
Using the COBRA toolbox with cobrapy
====================================

This example demonstrates using COBRA toolbox commands in MATLAB from
python through
`pymatbridge <http://arokem.github.io/python-matlab-bridge/>`__.

.. code:: python

    %load_ext pymatbridge


.. parsed-literal::

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


.. code:: python

    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.

.. code:: python

    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.

.. code:: python

    %%matlab
    model



.. parsed-literal::

    
    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.

.. code:: python

    %%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

.. code:: python

    %%matlab
    optimizeCbModel(model)



.. parsed-literal::

    
    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

.. code:: python

    %time
    m.optimize().f


.. parsed-literal::

    CPU times: user 5 µs, sys: 0 ns, total: 5 µs
    Wall time: 10 µs




.. parsed-literal::

    0.8739215069684305


