Using the COBRA toolbox with cobrapy

This example demonstrates using COBRA toolbox commands in MATLAB from python through pymatbridge.


In [1]:
%load_ext pymatbridge


Starting MATLAB on ZMQ socket ipc:///tmp/pymatbridge-39fd5b7f-475a-40d3-b831-3adf4da6edd3
Send 'exit' command to kill the server
....MATLAB started and connected!

In [2]:
import cobra.test
m = cobra.test.create_test_model("textbook")

The model_to_pymatbridge function will send the model to the workspace with the given variable name.


In [3]:
from cobra.io.mat import model_to_pymatbridge
model_to_pymatbridge(m, variable_name="model")

Now in the MATLAB workspace, the variable name 'model' holds a COBRA toolbox struct encoding the model.


In [4]:
%%matlab
model


model = 

            rev: [95x1 double]
       metNames: {72x1 cell}
              b: [72x1 double]
              c: [95x1 double]
         csense: [72x1 char]
          genes: {137x1 cell}
    metFormulas: {72x1 cell}
           rxns: {95x1 cell}
        grRules: {95x1 cell}
       rxnNames: {95x1 cell}
    description: [8x1 char]
              S: [72x95 double]
             ub: [95x1 double]
             lb: [95x1 double]
           mets: {72x1 cell}
     subSystems: {95x1 cell}

First, we have to initialize the COBRA toolbox in MATLAB.


In [5]:
%%matlab --silent
warning('off'); % this works around a pymatbridge bug
addpath(genpath('~/cobratoolbox/'));
initCobraToolbox();

Commands from the COBRA toolbox can now be run on the model


In [6]:
%%matlab
optimizeCbModel(model)


ans = 

           x: [95x1 double]
           f: 0.8739
           y: [71x1 double]
           w: [95x1 double]
        stat: 1
    origStat: 5
      solver: 'glpk'
        time: 0.2327

FBA in the COBRA toolbox should give the same result as cobrapy


In [7]:
%time
m.optimize().f


CPU times: user 5 µs, sys: 0 ns, total: 5 µs
Wall time: 10 µs
Out[7]:
0.8739215069684305