Documentation for COBRApy¶
For installation instructions, please see INSTALL.rst.
Many of the examples below are viewable as IPython notebooks, which can be viewed at nbviewer.
- {
- “cells”: [
- {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“# Getting Started”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“## Loading a model and inspecting it”
]
}, {
}, {
“cell_type”: “code”, “execution_count”: 1, “metadata”: {}, “outputs”: [], “source”: [
“from __future__ import print_functionn”, “n”, “import cobran”, “import cobra.testn”, “n”, “# “ecoli” and “salmonella” are also valid argumentsn”, “model = cobra.test.create_test_model(“textbook”)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The reactions, metabolites, and genes attributes of the cobrapy model are a special type of list called a cobra.DictList, and each one is made up of cobra.Reaction, cobra.Metabolite and cobra.Gene objects respectively.”
]
}, {
“cell_type”: “code”, “execution_count”: 2, “metadata”: {
“scrolled”: true
}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“95n”, “72n”, “137n”
]
}
], “source”: [
“print(len(model.reactions))n”, “print(len(model.metabolites))n”, “print(len(model.genes))”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“When using [Jupyter notebook](https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/) this type of information is rendered as a table.”
]
}, {
“cell_type”: “code”, “execution_count”: 3, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Name</strong></td>n”, ” <td>e_coli_core</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x01158878d0</td>n”,
” </tr><tr>n”, ” <td><strong>Number of metabolites</strong></td>n”, ” <td>72</td>n”, ” </tr><tr>n”, ” <td><strong>Number of reactions</strong></td>n”, ” <td>95</td>n”, ” </tr><tr>n”, ” <td><strong>Objective expression</strong></td>n”, ” <td>1.0*Biomass_Ecoli_core - 1.0*Biomass_Ecoli_core_reverse_2cdba</td>n”, ” </tr><tr>n”, ” <td><strong>Compartments</strong></td>n”, ” <td>cytosol, extracellular</td>n”, ” </tr>n”, ” </table>”
], “text/plain”: [
- <<<<<<< HEAD
“<Model e_coli_core at 0x1158878d0>”
]
}, “execution_count”: 3, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Just like a regular list, objects in the DictList can be retrieved by index. For example, to get the 30th reaction in the model (at index 29 because of [0-indexing](https://en.wikipedia.org/wiki/Zero-based_numbering)):”
]
}, {
“cell_type”: “code”, “execution_count”: 4, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Reaction identifier</strong></td><td>EX_glu__L_e</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td>L-Glutamate exchange</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x011615e2e8</td>n”,
” </tr><tr>n”, ” <td><strong>Stoichiometry</strong></td>n”, ” <td>n”, ” <p style=’text-align:right’>glu__L_e –> </p>n”, ” <p style=’text-align:right’>L-Glutamate –> </p>n”, ” </td>n”, ” </tr><tr>n”, ” <td><strong>GPR</strong></td><td></td>n”, ” </tr><tr>n”, ” <td><strong>Lower bound</strong></td><td>0.0</td>n”, ” </tr><tr>n”, ” <td><strong>Upper bound</strong></td><td>1000.0</td>n”, ” </tr>n”, ” </table>n”, ” “
], “text/plain”: [
- <<<<<<< HEAD
“<Reaction EX_glu__L_e at 0x11615e2e8>”
]
}, “execution_count”: 4, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model.reactions[29]”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Additionally, items can be retrieved by their id using the DictList.get_by_id() function. For example, to get the cytosolic atp metabolite object (the id is “atp_c”), we can do the following:”
]
}, {
“cell_type”: “code”, “execution_count”: 5, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Metabolite identifier</strong></td><td>atp_c</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td>ATP</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x01160d4630</td>n”,
” </tr><tr>n”, ” <td><strong>Formula</strong></td><td>C10H12N5O13P3</td>n”, ” </tr><tr>n”, ” <td><strong>Compartment</strong></td><td>c</td>n”, ” </tr><tr>n”, ” <td><strong>In 13 reaction(s)</strong></td><td>n”,
- <<<<<<< HEAD
” PPS, ADK1, ATPS4r, GLNS, SUCOAS, GLNabc, PGK, ATPM, PPCK, ACKr, PFK, Biomass_Ecoli_core, PYK</td>n”,
” </tr>n”, ” </table>”
], “text/plain”: [
- <<<<<<< HEAD
“<Metabolite atp_c at 0x1160d4630>”
]
}, “execution_count”: 5, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model.metabolites.get_by_id(“atp_c”)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“As an added bonus, users with an interactive shell such as IPython will be able to tab-complete to list elements inside a list. While this is not recommended behavior for most code because of the possibility for characters like “-” inside ids, this is very useful while in an interactive prompt:”
]
}, {
“cell_type”: “code”, “execution_count”: 6, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“(-10.0, 1000.0)”
]
}, “execution_count”: 6, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model.reactions.EX_glc__D_e.bounds”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“## Reactions”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We will consider the reaction glucose 6-phosphate isomerase, which interconverts glucose 6-phosphate and fructose 6-phosphate. The reaction id for this reaction in our test model is PGI.”
]
}, {
“cell_type”: “code”, “execution_count”: 7, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Reaction identifier</strong></td><td>PGI</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td>glucose-6-phosphate isomerase</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x0116188e48</td>n”,
” </tr><tr>n”, ” <td><strong>Stoichiometry</strong></td>n”, ” <td>n”, ” <p style=’text-align:right’>g6p_c <=> f6p_c</p>n”, ” <p style=’text-align:right’>D-Glucose 6-phosphate <=> D-Fructose 6-phosphate</p>n”, ” </td>n”, ” </tr><tr>n”, ” <td><strong>GPR</strong></td><td>b4025</td>n”, ” </tr><tr>n”, ” <td><strong>Lower bound</strong></td><td>-1000.0</td>n”, ” </tr><tr>n”, ” <td><strong>Upper bound</strong></td><td>1000.0</td>n”, ” </tr>n”, ” </table>n”, ” “
], “text/plain”: [
- <<<<<<< HEAD
“<Reaction PGI at 0x116188e48>”
]
}, “execution_count”: 7, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi = model.reactions.get_by_id(“PGI”)n”, “pgi”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can view the full name and reaction catalyzed as strings”
]
}, {
“cell_type”: “code”, “execution_count”: 8, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“glucose-6-phosphate isomerasen”, “g6p_c <=> f6p_cn”
]
}
], “source”: [
“print(pgi.name)n”, “print(pgi.reaction)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can also view reaction upper and lower bounds. Because the pgi.lower_bound < 0, and pgi.upper_bound > 0, pgi is reversible.”
]
}, {
“cell_type”: “code”, “execution_count”: 9, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“-1000.0 < pgi < 1000.0n”, “Truen”
]
}
], “source”: [
“print(pgi.lower_bound, “< pgi <”, pgi.upper_bound)n”, “print(pgi.reversibility)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The lower and upper bound of reactions can also be modified, and the reversibility attribute will automatically be updated. The preferred method for manipulating bounds is using reaction.bounds, e.g.”
]
}, {
“cell_type”: “code”, “execution_count”: 10, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“0 < pgi < 1000.0n”, “Reversibility after modification: Falsen”, “Reversibility after resetting: Truen”
]
}
], “source”: [
“old_bounds = pgi.boundsn”, “pgi.bounds = (0, 1000.0)n”, “print(pgi.lower_bound, “< pgi <”, pgi.upper_bound)n”, “print(“Reversibility after modification:”, pgi.reversibility)n”, “pgi.bounds = old_boundsn”, “print(“Reversibility after resetting:”, pgi.reversibility)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Bounds can also be modified one-at-a-time using reaction.lower_bound or reaction.upper_bound. This approach is less desirable than setting both bounds simultaneously with reaction.bounds because a user might accidently set a lower bound higher than an upper bound (or vice versa). Currently, cobrapy will automatically adjust the other bound (e.g. the bound the user didn’t manually adjust) so that this violation doesn’t occur, but this feature may be removed in the near future. “
]
}, {
“cell_type”: “code”, “execution_count”: 11, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“Upper bound prior to setting new lower bound: 1000.0n”, “Upper bound after setting new lower bound: 1100n”
]
}
], “source”: [
“old_bounds = pgi.boundsn”, “print(‘Upper bound prior to setting new lower bound:’, pgi.upper_bound)n”, “pgi.lower_bound = 1100n”, “print(‘Upper bound after setting new lower bound:’, pgi.upper_bound)n”, “pgi.bounds = old_bounds”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can also ensure the reaction is mass balanced. This function will return elements which violate mass balance. If it comes back empty, then the reaction is mass balanced.”
]
}, {
“cell_type”: “code”, “execution_count”: 12, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“{}”
]
}, “execution_count”: 12, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.check_mass_balance()”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“In order to add a metabolite, we pass in a dict with the metabolite object and its coefficient”
]
}, {
“cell_type”: “code”, “execution_count”: 13, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“‘g6p_c + h_c <=> f6p_c’”
]
}, “execution_count”: 13, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.add_metabolites({model.metabolites.get_by_id(“h_c”): -1})n”, “pgi.reaction”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The reaction is no longer mass balanced”
]
}, {
“cell_type”: “code”, “execution_count”: 14, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“{‘charge’: -1.0, ‘H’: -1.0}”
]
}, “execution_count”: 14, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.check_mass_balance()”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can remove the metabolite, and the reaction will be balanced once again.”
]
}, {
“cell_type”: “code”, “execution_count”: 15, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“g6p_c <=> f6p_cn”, “{}n”
]
}
], “source”: [
“pgi.subtract_metabolites({model.metabolites.get_by_id(“h_c”): -1})n”, “print(pgi.reaction)n”, “print(pgi.check_mass_balance())”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“It is also possible to build the reaction from a string. However, care must be taken when doing this to ensure reaction id’s match those in the model. The direction of the arrow is also used to update the upper and lower bounds.”
]
}, {
“cell_type”: “code”, “execution_count”: 16, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“unknown metabolite ‘green_eggs’ createdn”, “unknown metabolite ‘ham’ createdn”
]
}
], “source”: [
“pgi.reaction = “g6p_c –> f6p_c + h_c + green_eggs + ham””
]
}, {
“cell_type”: “code”, “execution_count”: 17, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“‘g6p_c –> f6p_c + green_eggs + h_c + ham’”
]
}, “execution_count”: 17, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.reaction”
]
}, {
“cell_type”: “code”, “execution_count”: 18, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“‘g6p_c <=> f6p_c’”
]
}, “execution_count”: 18, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.reaction = “g6p_c <=> f6p_c”n”, “pgi.reaction”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“## Metabolites”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We will consider cytosolic atp as our metabolite, which has the id “atp_c” in our test model.”
]
}, {
“cell_type”: “code”, “execution_count”: 19, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Metabolite identifier</strong></td><td>atp_c</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td>ATP</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x01160d4630</td>n”,
” </tr><tr>n”, ” <td><strong>Formula</strong></td><td>C10H12N5O13P3</td>n”, ” </tr><tr>n”, ” <td><strong>Compartment</strong></td><td>c</td>n”, ” </tr><tr>n”, ” <td><strong>In 13 reaction(s)</strong></td><td>n”,
- <<<<<<< HEAD
” PPS, ADK1, ATPS4r, GLNS, SUCOAS, GLNabc, PGK, ATPM, PPCK, ACKr, PFK, Biomass_Ecoli_core, PYK</td>n”,
” </tr>n”, ” </table>”
], “text/plain”: [
- <<<<<<< HEAD
“<Metabolite atp_c at 0x1160d4630>”
]
}, “execution_count”: 19, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“atp = model.metabolites.get_by_id(“atp_c”)n”, “atp”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can print out the metabolite name and compartment (cytosol in this case) directly as string.”
]
}, {
“cell_type”: “code”, “execution_count”: 20, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“ATPn”, “cn”
]
}
], “source”: [
“print(atp.name)n”, “print(atp.compartment)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can see that ATP is a charged molecule in our model.”
]
}, {
“cell_type”: “code”, “execution_count”: 21, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“-4”
]
}, “execution_count”: 21, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“atp.charge”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“We can see the chemical formula for the metabolite as well.”
]
}, {
“cell_type”: “code”, “execution_count”: 22, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“C10H12N5O13P3n”
]
}
], “source”: [
“print(atp.formula)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The reactions attribute gives a frozenset of all reactions using the given metabolite. We can use this to count the number of reactions which use atp.”
]
}, {
“cell_type”: “code”, “execution_count”: 23, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“13”
]
}, “execution_count”: 23, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“len(atp.reactions)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“A metabolite like glucose 6-phosphate will participate in fewer reactions.”
]
}, {
“cell_type”: “code”, “execution_count”: 24, “metadata”: {}, “outputs”: [
- {
- “data”: {
“text/plain”: [
- <<<<<<< HEAD
“frozenset({<Reaction Biomass_Ecoli_core at 0x1161337b8>,n”, ” <Reaction G6PDH2r at 0x1160a3a20>,n”, ” <Reaction GLCpts at 0x1160a3da0>,n”, ” <Reaction PGI at 0x116188e48>})”
” <Reaction GLCpts at 0x117a9d0f0>,n”, ” <Reaction PGI at 0x117afacc0>})”
- >>>>>>> origin/devel
]
}, “execution_count”: 24, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model.metabolites.get_by_id(“g6p_c”).reactions”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“## Genes”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The gene_reaction_rule is a boolean representation of the gene requirements for this reaction to be active as described in [Schellenberger et al 2011 Nature Protocols 6(9):1290-307](http://dx.doi.org/doi:10.1038/nprot.2011.308).n”, “n”, “The GPR is stored as the gene_reaction_rule for a Reaction object as a string.”
]
}, {
“cell_type”: “code”, “execution_count”: 25, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“‘b4025’”
]
}, “execution_count”: 25, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“gpr = pgi.gene_reaction_rulen”, “gpr”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Corresponding gene objects also exist. These objects are tracked by the reactions itself, as well as by the model”
]
}, {
“cell_type”: “code”, “execution_count”: 26, “metadata”: {}, “outputs”: [
- {
- “data”: {
“text/plain”: [
- <<<<<<< HEAD
“frozenset({<Gene b4025 at 0x11610a2b0>})”
]
}, “execution_count”: 26, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.genes”
]
}, {
“cell_type”: “code”, “execution_count”: 27, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Gene identifier</strong></td><td>b4025</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td>pgi</td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x011610a2b0</td>n”,
” </tr><tr>n”, ” <td><strong>Functional</strong></td><td>True</td>n”, ” </tr><tr>n”, ” <td><strong>In 1 reaction(s)</strong></td><td>n”, ” PGI</td>n”, ” </tr>n”, ” </table>”
], “text/plain”: [
- <<<<<<< HEAD
“<Gene b4025 at 0x11610a2b0>”
]
}, “execution_count”: 27, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi_gene = model.genes.get_by_id(“b4025”)n”, “pgi_gene”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Each gene keeps track of the reactions it catalyzes”
]
}, {
“cell_type”: “code”, “execution_count”: 28, “metadata”: {}, “outputs”: [
- {
- “data”: {
“text/plain”: [
- <<<<<<< HEAD
“frozenset({<Reaction PGI at 0x116188e48>})”
]
}, “execution_count”: 28, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi_gene.reactions”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Altering the gene_reaction_rule will create new gene objects if necessary and update all relationships.”
]
}, {
“cell_type”: “code”, “execution_count”: 29, “metadata”: {}, “outputs”: [
- {
- “data”: {
“text/plain”: [
- <<<<<<< HEAD
“frozenset({<Gene eggs at 0x1160245c0>, <Gene spam at 0x116024080>})”
]
}, “execution_count”: 29, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi.gene_reaction_rule = “(spam or eggs)”n”, “pgi.genes”
]
}, {
“cell_type”: “code”, “execution_count”: 30, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“frozenset()”
]
}, “execution_count”: 30, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“pgi_gene.reactions”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Newly created genes are also added to the model”
]
}, {
“cell_type”: “code”, “execution_count”: 31, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/html”: [
“n”, ” <table>n”, ” <tr>n”, ” <td><strong>Gene identifier</strong></td><td>spam</td>n”, ” </tr><tr>n”, ” <td><strong>Name</strong></td><td></td>n”, ” </tr><tr>n”, ” <td><strong>Memory address</strong></td>n”,
- <<<<<<< HEAD
” <td>0x0116024080</td>n”,
” </tr><tr>n”, ” <td><strong>Functional</strong></td><td>True</td>n”, ” </tr><tr>n”, ” <td><strong>In 1 reaction(s)</strong></td><td>n”, ” PGI</td>n”, ” </tr>n”, ” </table>”
], “text/plain”: [
- <<<<<<< HEAD
“<Gene spam at 0x116024080>”
]
}, “execution_count”: 31, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“model.genes.get_by_id(“spam”)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The delete_model_genes function will evaluate the GPR and set the upper and lower bounds to 0 if the reaction is knocked out. This function can preserve existing deletions or reset them using the cumulative_deletions flag.”
]
}, {
“cell_type”: “code”, “execution_count”: 32, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“after 1 KO: -1000 < flux_PGI < 1000n”, “after 2 KO: 0 < flux_PGI < 0n”
]
}
], “source”: [
“cobra.manipulation.delete_model_genes(n”, ” model, [“spam”], cumulative_deletions=True)n”, “print(“after 1 KO: %4d < flux_PGI < %4d” % (pgi.lower_bound, pgi.upper_bound))n”, “n”, “cobra.manipulation.delete_model_genes(n”, ” model, [“eggs”], cumulative_deletions=True)n”, “print(“after 2 KO: %4d < flux_PGI < %4d” % (pgi.lower_bound, pgi.upper_bound))”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“The undelete_model_genes can be used to reset a gene deletion”
]
}, {
“cell_type”: “code”, “execution_count”: 33, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“-1000 < pgi < 1000n”
]
}
], “source”: [
“cobra.manipulation.undelete_model_genes(model)n”, “print(pgi.lower_bound, “< pgi <”, pgi.upper_bound)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“## Making changes reversibly using models as contexts”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Quite often, one wants to make small changes to a model and evaluate the impacts of these. For example, we may want to knock-out all reactions sequentially, and see what the impact of this is on the objective function. One way of doing this would be to create a new copy of the model before each knock-out with model.copy(). However, even with small models, this is a very slow approach as models are quite complex objects. Better then would be to do the knock-out, optimizing and then manually resetting the reaction bounds before proceeding with the next reaction. Since this is such a common scenario however, cobrapy allows us to use the model as a context, to have changes reverted automatically.”
]
}, {
“cell_type”: “code”, “execution_count”: 34, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“ACALD blocked (bounds: (0, 0)), new growth rate 0.873922n”, “ACALDt blocked (bounds: (0, 0)), new growth rate 0.873922n”, “ACKr blocked (bounds: (0, 0)), new growth rate 0.873922n”, “ACONTa blocked (bounds: (0, 0)), new growth rate -0.000000n”, “ACONTb blocked (bounds: (0, 0)), new growth rate -0.000000n”
]
}
], “source”: [
“model = cobra.test.create_test_model(‘textbook’)n”, “for reaction in model.reactions[:5]:n”, ” with model as model:n”, ” reaction.knock_out()n”, ” model.optimize()n”, ” print(‘%s blocked (bounds: %s), new growth rate %f’ %n”, ” (reaction.id, str(reaction.bounds), model.objective.value))”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“If we look at those knocked reactions, see that their bounds have all been reverted.”
]
}, {
“cell_type”: “code”, “execution_count”: 35, “metadata”: {}, “outputs”: [
- {
- “data”: {
- “text/plain”: [
“[(-1000.0, 1000.0),n”, ” (-1000.0, 1000.0),n”, ” (-1000.0, 1000.0),n”, ” (-1000.0, 1000.0),n”, ” (-1000.0, 1000.0)]”
]
}, “execution_count”: 35, “metadata”: {}, “output_type”: “execute_result”
}
], “source”: [
“[reaction.bounds for reaction in model.reactions[:5]]”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Nested contexts are also supported”
]
}, {
“cell_type”: “code”, “execution_count”: 36, “metadata”: {}, “outputs”: [
- {
“name”: “stdout”, “output_type”: “stream”, “text”: [
“original objective: 1.0*Biomass_Ecoli_core - 1.0*Biomass_Ecoli_core_reverse_2cdban”, “print objective in first context: -1.0*ATPM_reverse_5b752 + 1.0*ATPMn”, “print objective in second context: 1.0*ACALD - 1.0*ACALD_reverse_fda2bn”, “objective after exiting second context: -1.0*ATPM_reverse_5b752 + 1.0*ATPMn”, “back to original objective: 1.0*Biomass_Ecoli_core - 1.0*Biomass_Ecoli_core_reverse_2cdban”
]
}
], “source”: [
“print(‘original objective: ‘, model.objective.expression)n”, “with model:n”, ” model.objective = ‘ATPM’n”, ” print(‘print objective in first context:’, model.objective.expression)n”, ” with model:n”, ” model.objective = ‘ACALD’n”, ” print(‘print objective in second context:’, model.objective.expression)n”, ” print(‘objective after exiting second context:’,n”, ” model.objective.expression)n”, “print(‘back to original objective:’, model.objective.expression)”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“Most methods that modify the model are supported like this including adding and removing reactions and metabolites and setting the objective. Supported methods and functions mention this in the corresponding documentation.”
]
}, {
“cell_type”: “markdown”, “metadata”: {}, “source”: [
“While it does not have any actual effect, for syntactic convenience it is also possible to refer to the model by a different name than outside the context. Such as”
]
}, {
“cell_type”: “code”, “execution_count”: 37, “metadata”: {}, “outputs”: [], “source”: [
“with model as inner:n”, ” inner.reactions.PFK.knock_out”
]
}
], “metadata”: {
- “kernelspec”: {
“display_name”: “Python 3”, “language”: “python”, “name”: “python3”
}, “language_info”: {
- “codemirror_mode”: {
“name”: “ipython”, “version”: 3
}, “file_extension”: “.py”, “mimetype”: “text/x-python”, “name”: “python”, “nbconvert_exporter”: “python”, “pygments_lexer”: “ipython3”, “version”: “3.6.5”
}
}, “nbformat”: 4, “nbformat_minor”: 1
}
Global Configuration¶
With cobra > 0.13.4, we introduce a global configuration object. For now, you can configure default reaction bounds and optimization solver which will be respected by newly created reactions and models.
The configuration object¶
You can get a configuration object1 in the following way:
[1]:
import cobra
[2]:
cobra_config = cobra.Configuration()
1The configuration object is a singleton. That means only one instance can exist and it is respected everywhere in COBRApy.
Reaction bounds¶
The object has the following attributes which you can inspect but also change as desired.
[3]:
cobra_config.lower_bound
[3]:
-1000.0
[4]:
cobra_config.upper_bound
[4]:
1000.0
[5]:
cobra_config.bounds
[5]:
(-1000.0, 1000.0)
Changing bounds¶
If you modify the above values before creating a reaction they will be used.
[6]:
cobra_config.bounds = -10, 20
[7]:
cobra.Reaction("R1")
[7]:
Reaction identifier | R1 |
Name | |
Memory address | 0x07f0426135fd0 |
Stoichiometry |
--> --> |
GPR | |
Lower bound | 0.0 |
Upper bound | 20 |
Please note that by default reactions are irreversible. You can change this behavior by unsetting the lower bound argument.
[8]:
cobra.Reaction("R2", lower_bound=None)
[8]:
Reaction identifier | R2 |
Name | |
Memory address | 0x07f04260d4438 |
Stoichiometry |
<=> <=> |
GPR | |
Lower bound | -10 |
Upper bound | 20 |
N.B.: Most models define reaction bounds explicitly which takes precedence over the configured values.
[9]:
from cobra.test import create_test_model
[10]:
model = create_test_model("textbook")
[11]:
model.reactions.ACt2r
[11]:
Reaction identifier | ACt2r |
Name | R acetate reversible transport via proton - symport |
Memory address | 0x07f042607c780 |
Stoichiometry |
ac_e + h_e <=> ac_c + h_c Acetate + H+ <=> Acetate + H+ |
GPR | |
Lower bound | -1000.0 |
Upper bound | 1000.0 |
Solver¶
You can define the default solver used by newly instantiated models. The default solver depends on your environment. In order we test for the availability of Gurobi, CPLEX, and GLPK. GLPK is assumed to always be present in the environment.
[12]:
model.solver
[12]:
<optlang.cplex_interface.Model at 0x7f04260d4b00>
Changing solver¶
[13]:
cobra_config.solver = "glpk_exact"
[14]:
new_model = create_test_model("textbook")
[15]:
new_model.solver
[15]:
<optlang.glpk_exact_interface.Model at 0x7f04260d47b8>
Changing global configuration values is mostly useful at the beginning of a work session.
Building a Model¶
Model, Reactions and Metabolites¶
This simple example demonstrates how to create a model, create a reaction, and then add the reaction to the model.
We’ll use the ‘3OAS140’ reaction from the STM_1.0 model:
1.0 malACP[c] + 1.0 h[c] + 1.0 ddcaACP[c] \(\rightarrow\) 1.0 co2[c] + 1.0 ACP[c] + 1.0 3omrsACP[c]
First, create the model and reaction.
[1]:
from cobra import Model, Reaction, Metabolite
[2]:
model = Model('example_model')
reaction = Reaction('R_3OAS140')
reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
reaction.subsystem = 'Cell Envelope Biosynthesis'
reaction.lower_bound = 0. # This is the default
reaction.upper_bound = 1000. # This is the default
We need to create metabolites as well. If we were using an existing model, we could use Model.get_by_id
to get the appropriate Metabolite objects instead.
[3]:
ACP_c = Metabolite(
'ACP_c',
formula='C11H21N2O7PRS',
name='acyl-carrier-protein',
compartment='c')
omrsACP_c = Metabolite(
'M3omrsACP_c',
formula='C25H45N2O9PRS',
name='3-Oxotetradecanoyl-acyl-carrier-protein',
compartment='c')
co2_c = Metabolite('co2_c', formula='CO2', name='CO2', compartment='c')
malACP_c = Metabolite(
'malACP_c',
formula='C14H22N2O10PRS',
name='Malonyl-acyl-carrier-protein',
compartment='c')
h_c = Metabolite('h_c', formula='H', name='H', compartment='c')
ddcaACP_c = Metabolite(
'ddcaACP_c',
formula='C23H43N2O8PRS',
name='Dodecanoyl-ACP-n-C120ACP',
compartment='c')
Side note: SId
It is highly recommended that the ids for reactions, metabolites and genes are valid SBML identifiers (SId
). SId
is a data type derived from the basic XML typestring, but with restrictions about the characters permitted and the sequences in which those characters may appear.
letter ::= ’a’..’z’,’A’..’Z’
digit ::= ’0’..’9’
idChar ::= letter | digit | ’_’
SId ::= ( letter | ’_’ ) idChar*
The main limitation is that ids cannot start with numbers. Using SId
s allows serialization to SBML. In addition features such as code completion and object access via the dot syntax will work in cobrapy
.
Adding metabolites to a reaction uses a dictionary of the metabolites and their stoichiometric coefficients. A group of metabolites can be added all at once, or they can be added one at a time.
[4]:
reaction.add_metabolites({
malACP_c: -1.0,
h_c: -1.0,
ddcaACP_c: -1.0,
co2_c: 1.0,
ACP_c: 1.0,
omrsACP_c: 1.0
})
reaction.reaction # This gives a string representation of the reaction
[4]:
'ddcaACP_c + h_c + malACP_c --> ACP_c + M3omrsACP_c + co2_c'
The gene_reaction_rule is a boolean representation of the gene requirements for this reaction to be active as described in Schellenberger et al 2011 Nature Protocols 6(9):1290-307. We will assign the gene reaction rule string, which will automatically create the corresponding gene objects.
[5]:
reaction.gene_reaction_rule = '( STM2378 or STM1197 )'
reaction.genes
[5]:
frozenset({<Gene STM1197 at 0x7fef047474c0>, <Gene STM2378 at 0x7fef04747dc0>})
At this point in time, the model is still empty
[6]:
print(f'{len(model.reactions)} reactions initially')
print(f'{len(model.metabolites)} metabolites initially')
print(f'{len(model.genes)} genes initially')
0 reactions initially
0 metabolites initially
0 genes initially
We will add the reaction to the model, which will also add all associated metabolites and genes
[7]:
model.add_reactions([reaction])
# The objects have been added to the model
print(f'{len(model.reactions)} reactions')
print(f'{len(model.metabolites)} metabolites')
print(f'{len(model.genes)} genes')
1 reactions
6 metabolites
2 genes
We can iterate through the model objects to observe the contents
[8]:
# Iterate through the the objects in the model
print("Reactions")
print("---------")
for x in model.reactions:
print("%s : %s" % (x.id, x.reaction))
print("")
print("Metabolites")
print("-----------")
for x in model.metabolites:
print('%9s : %s' % (x.id, x.formula))
print("")
print("Genes")
print("-----")
for x in model.genes:
associated_ids = (i.id for i in x.reactions)
print("%s is associated with reactions: %s" %
(x.id, "{" + ", ".join(associated_ids) + "}"))
Reactions
---------
R_3OAS140 : ddcaACP_c + h_c + malACP_c --> ACP_c + M3omrsACP_c + co2_c
Metabolites
-----------
malACP_c : C14H22N2O10PRS
h_c : H
ddcaACP_c : C23H43N2O8PRS
co2_c : CO2
ACP_c : C11H21N2O7PRS
M3omrsACP_c : C25H45N2O9PRS
Genes
-----
STM2378 is associated with reactions: {R_3OAS140}
STM1197 is associated with reactions: {R_3OAS140}
Objective¶
Last we need to set the objective of the model. Here, we just want this to be the maximization of the flux in the single reaction we added and we do this by assigning the reaction’s identifier to the objective
property of the model.
[9]:
model.objective = 'R_3OAS140'
The created objective is a symbolic algebraic expression and we can examine it by printing it
[10]:
print(model.objective.expression)
print(model.objective.direction)
1.0*R_3OAS140 - 1.0*R_3OAS140_reverse_60acb
max
which here shows that the solver will maximize the flux in the forward direction.
Model Validation¶
For exchange with other tools you can validate and export the model to SBML. For more information on serialization and available formats see the section “Reading and Writing Models”
[11]:
import tempfile
from pprint import pprint
from cobra.io import write_sbml_model, validate_sbml_model
with tempfile.NamedTemporaryFile(suffix='.xml') as f_sbml:
write_sbml_model(model, filename=f_sbml.name)
report = validate_sbml_model(filename=f_sbml.name)
pprint(report)
(<Model example_model at 0x7fef046eb160>,
{'COBRA_CHECK': [],
'COBRA_ERROR': [],
'COBRA_FATAL': [],
'COBRA_WARNING': [],
'SBML_ERROR': [],
'SBML_FATAL': [],
'SBML_SCHEMA_ERROR': [],
'SBML_WARNING': []})
The model is valid with no COBRA or SBML errors or warnings.
Exchanges, Sinks and Demands¶
Boundary reactions can be added using the model’s method add_boundary
. There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. All of them are unbalanced pseudo reactions, that means they fulfill a function for modeling by adding to or removing metabolites from the model system but are not based on real biology. An exchange reaction is a reversible reaction that adds to or removes an extracellular metabolite from the extracellular compartment.
A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites, i.e., a reversible reaction that adds or removes an intracellular metabolite.
[12]:
print("exchanges", model.exchanges)
print("demands", model.demands)
print("sinks", model.sinks)
There are no boundary reactions in this model. Therefore specific types of boundary reactions such as 'exchanges', 'demands' or 'sinks' cannot be identified.
There are no boundary reactions in this model. Therefore specific types of boundary reactions such as 'exchanges', 'demands' or 'sinks' cannot be identified.
There are no boundary reactions in this model. Therefore specific types of boundary reactions such as 'exchanges', 'demands' or 'sinks' cannot be identified.
exchanges []
demands []
sinks []
Boundary reactions are defined on metabolites. First we add two metabolites to the model then we define the boundary reactions. We add glycogen to the cytosolic compartment c
and CO2 to the external compartment e
.
[13]:
model.add_metabolites([
Metabolite(
'glycogen_c',
name='glycogen',
compartment='c'
),
Metabolite(
'co2_e',
name='CO2',
compartment='e'
),
])
[14]:
# create exchange reaction
model.add_boundary(model.metabolites.get_by_id("co2_e"), type="exchange")
[14]:
Reaction identifier | EX_co2_e |
Name | CO2 exchange |
Memory address | 0x07fef04703d90 |
Stoichiometry |
co2_e <=> CO2 <=> |
GPR | |
Lower bound | -1000.0 |
Upper bound | 1000.0 |
[15]:
# create exchange reaction
model.add_boundary(model.metabolites.get_by_id("glycogen_c"), type="sink")
[15]:
Reaction identifier | SK_glycogen_c |
Name | glycogen sink |
Memory address | 0x07fef046eb2e0 |
Stoichiometry |
glycogen_c <=> glycogen <=> |
GPR | |
Lower bound | -1000.0 |
Upper bound | 1000.0 |
[16]:
# Now we have an additional exchange and sink reaction in the model
print("exchanges", model.exchanges)
print("sinks", model.sinks)
print("demands", model.demands)
exchanges [<Reaction EX_co2_e at 0x7fef04703d90>]
sinks [<Reaction SK_glycogen_c at 0x7fef046eb2e0>]
demands []
To create a demand reaction instead of a sink use type demand
instead of sink
.
Information on all boundary reactions is available via the model’s property boundary
.
[17]:
# boundary reactions
model.boundary
[17]:
[<Reaction EX_co2_e at 0x7fef04703d90>,
<Reaction SK_glycogen_c at 0x7fef046eb2e0>]
A neat trick to get all metabolic reactions is
[18]:
# metabolic reactions
set(model.reactions) - set(model.boundary)
[18]:
{<Reaction R_3OAS140 at 0x7fef04737d00>}
Reading and Writing Models¶
Cobrapy supports reading and writing models in SBML (with and without FBC), JSON, YAML, MAT, and pickle formats. Generally, SBML with FBC version 2 is the preferred format for general use. The JSON format may be more useful for cobrapy-specific functionality.
The package also ships with test models in various formats for testing purposes.
[1]:
import cobra.test
import os
from os.path import join
data_dir = cobra.test.data_dir
print("mini test files: ")
print(", ".join(i for i in os.listdir(data_dir) if i.startswith("mini")))
textbook_model = cobra.test.create_test_model("textbook")
ecoli_model = cobra.test.create_test_model("ecoli")
salmonella_model = cobra.test.create_test_model("salmonella")
mini test files:
mini.json, mini.mat, mini.pickle, mini.yml, mini_cobra.xml, mini_fbc1.xml, mini_fbc2.xml, mini_fbc2.xml.bz2, mini_fbc2.xml.gz
SBML¶
The Systems Biology Markup Language is an XML-based standard format for distributing models which has support for COBRA models through the FBC extension version 2.
Cobrapy has native support for reading and writing SBML with FBCv2. Please note that all id’s in the model must conform to the SBML SID requirements in order to generate a valid SBML file.
[2]:
cobra.io.read_sbml_model(join(data_dir, "mini_fbc2.xml"))
[2]:
Name | mini_textbook |
Memory address | 0x01074fd080 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | cytosol, extracellular |
[3]:
cobra.io.write_sbml_model(textbook_model, "test_fbc2.xml")
There are other dialects of SBML prior to FBC 2 which have previously been use to encode COBRA models. The primary ones is the “COBRA” dialect which used the “notes” fields in SBML files.
Cobrapy can use libsbml, which must be installed separately (see installation instructions) to read and write these files. When reading in a model, it will automatically detect whether FBC was used or not. When writing a model, the use_fbc_package flag can be used can be used to write files in this legacy “cobra” format.
Consider having the lxml package installed as it can speed up parsing considerably.
[4]:
cobra.io.read_sbml_model(join(data_dir, "mini_cobra.xml"))
[4]:
Name | mini_textbook |
Memory address | 0x0112fa6b38 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | cytosol, extracellular |
[5]:
cobra.io.write_sbml_model(
textbook_model, "test_cobra.xml", use_fbc_package=False)
JSON¶
Cobrapy models have a JSON (JavaScript Object Notation) representation. This format was created for interoperability with escher.
[6]:
cobra.io.load_json_model(join(data_dir, "mini.json"))
[6]:
Name | mini_textbook |
Memory address | 0x0113061080 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | cytosol, extracellular |
[7]:
cobra.io.save_json_model(textbook_model, "test.json")
YAML¶
Cobrapy models have a YAML (YAML Ain’t Markup Language) representation. This format was created for more human readable model representations and automatic diffs between models.
[8]:
cobra.io.load_yaml_model(join(data_dir, "mini.yml"))
[8]:
Name | mini_textbook |
Memory address | 0x0113013390 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | extracellular, cytosol |
[9]:
cobra.io.save_yaml_model(textbook_model, "test.yml")
MATLAB¶
Often, models may be imported and exported solely for the purposes of working with the same models in cobrapy and the MATLAB cobra toolbox. MATLAB has its own “.mat” format for storing variables. Reading and writing to these mat files from python requires scipy.
A mat file can contain multiple MATLAB variables. Therefore, the variable name of the model in the MATLAB file can be passed into the reading function:
[10]:
cobra.io.load_matlab_model(
join(data_dir, "mini.mat"), variable_name="mini_textbook")
[10]:
Name | mini_textbook |
Memory address | 0x0113000b70 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | c, e |
If the mat file contains only a single model, cobra can figure out which variable to read from, and the variable_name parameter is unnecessary.
[11]:
cobra.io.load_matlab_model(join(data_dir, "mini.mat"))
[11]:
Name | mini_textbook |
Memory address | 0x0113758438 |
Number of metabolites | 23 |
Number of reactions | 18 |
Objective expression | -1.0*ATPM_reverse_5b752 - 1.0*PFK_reverse_d24a6 + 1.0*PFK + 1.0*ATPM |
Compartments | c, e |
Saving models to mat files is also relatively straightforward
[12]:
cobra.io.save_matlab_model(textbook_model, "test.mat")
Pickle¶
Cobra models can be serialized using the python serialization format, pickle.
Please note that use of the pickle format is generally not recommended for most use cases. JSON, SBML, and MAT are generally the preferred formats.
Simulating with FBA¶
Simulations using flux balance analysis can be solved using Model.optimize()
. This will maximize or minimize (maximizing is the default) flux through the objective reactions.
[1]:
import cobra.test
model = cobra.test.create_test_model("textbook")
Running FBA¶
[2]:
solution = model.optimize()
print(solution)
<Solution 0.874 at 0x7f920c907d60>
The Model.optimize() function will return a Solution object. A solution object has several attributes:
objective_value
: the objective valuestatus
: the status from the linear programming solverfluxes
: a pandas series with flux indexed by reaction identifier. The flux for a reaction variable is the difference of the primal values for the forward and reverse reaction variables.shadow_prices
: a pandas series with shadow price indexed by the metabolite identifier.
For example, after the last call to model.optimize()
, if the optimization succeeds it’s status will be optimal. In case the model is infeasible an error is raised.
[3]:
solution.objective_value
[3]:
0.8739215069684307
The solvers that can be used with cobrapy are so fast that for many small to mid-size models computing the solution can be even faster than it takes to collect the values from the solver and convert to them python objects. With model.optimize
, we gather values for all reactions and metabolites and that can take a significant amount of time if done repeatedly. If we are only interested in the flux value of a single reaction or the objective, it is faster to instead use model.slim_optimize
which only does the optimization and returns the objective value leaving it up to you to fetch other values that you may need.
[4]:
%%time
model.optimize().objective_value
CPU times: user 590 µs, sys: 642 µs, total: 1.23 ms
Wall time: 1.24 ms
[4]:
0.8739215069684307
[5]:
%%time
model.slim_optimize()
CPU times: user 85 µs, sys: 91 µs, total: 176 µs
Wall time: 180 µs
[5]:
0.8739215069684307
Analyzing FBA solutions¶
Models solved using FBA can be further analyzed by using summary methods, which output printed text to give a quick representation of model behavior. Calling the summary method on the entire model displays information on the input and output behavior of the model, along with the optimized objective.
[6]:
model.summary()
[6]:
Objective
1.0 Biomass_Ecoli_core = 0.8739215069684306
Uptake
Metabolite | Reaction | Flux | C-Number | C-Flux |
---|---|---|---|---|
glc__D_e | EX_glc__D_e | 10 | 6 | 100.00% |
nh4_e | EX_nh4_e | 4.765 | 0 | 0.00% |
o2_e | EX_o2_e | 21.8 | 0 | 0.00% |
pi_e | EX_pi_e | 3.215 | 0 | 0.00% |
Secretion
Metabolite | Reaction | Flux | C-Number | C-Flux |
---|---|---|---|---|
co2_e | EX_co2_e | -22.81 | 1 | 100.00% |
h2o_e | EX_h2o_e | -29.18 | 0 | 0.00% |
h_e | EX_h_e | -17.53 | 0 | 0.00% |
In addition, the input-output behavior of individual metabolites can also be inspected using summary methods. For instance, the following commands can be used to examine the overall redox balance of the model
[7]:
model.metabolites.nadh_c.summary()
[7]:
nadh_c
C21H27N7O14P2
Producing Reactions
Percent | Flux | Reaction | Definition |
---|---|---|---|
13.14% | 5.064 | AKGDH | akg_c + coa_c + nad_c --> co2_c + nadh_c + succoa_c |
8.04% | 3.1 | Biomass_Ecoli_core | 1.496 3pg_c + 3.7478 accoa_c + 59.81 atp_c + 0.361 e4p_c + 0.0709 f6p_c + 0.129 g3p_c + 0.205 g6p_c + 0.2557 gln__L_c + 4.9414 glu__L_c + 59.81 h2o_c + 3.547 nad_c + 13.0279 nadph_c + 1.7867 oaa_c + 0.5191 pep_c + 2.8328 pyr_c + 0.8977 r5p_c --> 59.81 adp_c + 4.1182 akg_c + 3.7478 coa_c + 59.81 h_c + 3.547 nadh_c + 13.0279 nadp_c + 59.81 pi_c |
41.58% | 16.02 | GAPD | g3p_c + nad_c + pi_c <=> 13dpg_c + h_c + nadh_c |
13.14% | 5.064 | MDH | mal__L_c + nad_c <=> h_c + nadh_c + oaa_c |
24.09% | 9.283 | PDH | coa_c + nad_c + pyr_c --> accoa_c + co2_c + nadh_c |
Consuming Reactions
Percent | Flux | Reaction | Definition |
---|---|---|---|
100.00% | -38.53 | NADH16 | 4.0 h_c + nadh_c + q8_c --> 3.0 h_e + nad_c + q8h2_c |
Or to get a sense of the main energy production and consumption reactions
[8]:
model.metabolites.atp_c.summary()
[8]:
atp_c
C10H12N5O13P3
Producing Reactions
Percent | Flux | Reaction | Definition |
---|---|---|---|
66.58% | 45.51 | ATPS4r | adp_c + 4.0 h_e + pi_c <=> atp_c + h2o_c + 3.0 h_c |
23.44% | 16.02 | PGK | 3pg_c + atp_c <=> 13dpg_c + adp_c |
2.57% | 1.758 | PYK | adp_c + h_c + pep_c --> atp_c + pyr_c |
7.41% | 5.064 | SUCOAS | atp_c + coa_c + succ_c <=> adp_c + pi_c + succoa_c |
Consuming Reactions
Percent | Flux | Reaction | Definition |
---|---|---|---|
12.27% | -8.39 | ATPM | atp_c + h2o_c --> adp_c + h_c + pi_c |
76.46% | -52.27 | Biomass_Ecoli_core | 1.496 3pg_c + 3.7478 accoa_c + 59.81 atp_c + 0.361 e4p_c + 0.0709 f6p_c + 0.129 g3p_c + 0.205 g6p_c + 0.2557 gln__L_c + 4.9414 glu__L_c + 59.81 h2o_c + 3.547 nad_c + 13.0279 nadph_c + 1.7867 oaa_c + 0.5191 pep_c + 2.8328 pyr_c + 0.8977 r5p_c --> 59.81 adp_c + 4.1182 akg_c + 3.7478 coa_c + 59.81 h_c + 3.547 nadh_c + 13.0279 nadp_c + 59.81 pi_c |
0.33% | -0.2235 | GLNS | atp_c + glu__L_c + nh4_c --> adp_c + gln__L_c + h_c + pi_c |
10.94% | -7.477 | PFK | atp_c + f6p_c --> adp_c + fdp_c + h_c |
Changing the Objectives¶
The objective function is determined from the objective_coefficient attribute of the objective reaction(s). Generally, a “biomass” function which describes the composition of metabolites which make up a cell is used.
[9]:
biomass_rxn = model.reactions.get_by_id("Biomass_Ecoli_core")
Currently in the model, there is only one reaction in the objective (the biomass reaction), with an linear coefficient of 1.
[10]:
from cobra.util.solver import linear_reaction_coefficients
linear_reaction_coefficients(model)
[10]:
{<Reaction Biomass_Ecoli_core at 0x7f90db4d2d90>: 1.0}
The objective function can be changed by assigning Model.objective, which can be a reaction object (or just it’s name), or a dict
of {Reaction: objective_coefficient}
.
[11]:
# change the objective to ATPM
model.objective = "ATPM"
# The upper bound should be 1000, so that we get
# the actual optimal value
model.reactions.get_by_id("ATPM").upper_bound = 1000.
linear_reaction_coefficients(model)
[11]:
{<Reaction ATPM at 0x7f90db4d2c40>: 1.0}
[12]:
model.optimize().objective_value
[12]:
174.99999999999983
We can also have more complicated objectives including quadratic terms.
Running FVA¶
FBA will not give always give unique solution, because multiple flux states can achieve the same optimum. FVA (or flux variability analysis) finds the ranges of each metabolic flux at the optimum.
[13]:
from cobra.flux_analysis import flux_variability_analysis
[14]:
flux_variability_analysis(model, model.reactions[:10])
[14]:
minimum | maximum | |
---|---|---|
ACALD | -2.623542e-14 | 0.000000e+00 |
ACALDt | -2.623542e-14 | 0.000000e+00 |
ACKr | -4.012477e-14 | 0.000000e+00 |
ACONTa | 2.000000e+01 | 2.000000e+01 |
ACONTb | 2.000000e+01 | 2.000000e+01 |
ACt2r | -4.012477e-14 | 0.000000e+00 |
ADK1 | 0.000000e+00 | 1.705303e-13 |
AKGDH | 2.000000e+01 | 2.000000e+01 |
AKGt2r | -1.586328e-14 | 0.000000e+00 |
ALCD2x | -2.273737e-14 | 0.000000e+00 |
Setting parameter fraction_of_optimium=0.90
would give the flux ranges for reactions at 90% optimality.
[15]:
cobra.flux_analysis.flux_variability_analysis(
model, model.reactions[:10], fraction_of_optimum=0.9)
[15]:
minimum | maximum | |
---|---|---|
ACALD | -2.692308 | 0.0 |
ACALDt | -2.692308 | 0.0 |
ACKr | -4.117647 | 0.0 |
ACONTa | 8.461538 | 20.0 |
ACONTb | 8.461538 | 20.0 |
ACt2r | -4.117647 | 0.0 |
ADK1 | 0.000000 | 17.5 |
AKGDH | 2.500000 | 20.0 |
AKGt2r | -1.489362 | 0.0 |
ALCD2x | -2.333333 | 0.0 |
The standard FVA may contain loops, i.e. high absolute flux values that only can be high if they are allowed to participate in loops (a mathematical artifact that cannot happen in vivo). Use the loopless
argument to avoid such loops. Below, we can see that FRD7 and SUCDi reactions can participate in loops but that this is avoided when using the looplesss FVA.
[16]:
loop_reactions = [model.reactions.FRD7, model.reactions.SUCDi]
flux_variability_analysis(model, reaction_list=loop_reactions, loopless=False)
[16]:
minimum | maximum | |
---|---|---|
FRD7 | 0.0 | 980.0 |
SUCDi | 20.0 | 1000.0 |
[17]:
flux_variability_analysis(model, reaction_list=loop_reactions, loopless=True)
[17]:
minimum | maximum | |
---|---|---|
FRD7 | 0.0 | 0.0 |
SUCDi | 20.0 | 20.0 |
Running FVA in summary methods¶
Flux variability analysis can also be embedded in calls to summary methods. For instance, the expected variability in substrate consumption and product formation can be quickly found by
[18]:
model.optimize()
model.summary(fva=0.95)
[18]:
Objective
1.0 ATPM = 175.0
Uptake
Metabolite | Reaction | Flux | Range | C-Number | C-Flux |
---|---|---|---|---|---|
glc__D_e | EX_glc__D_e | 10 | [9.5; 10] | 6 | 100.00% |
o2_e | EX_o2_e | 60 | [55.88; 60] | 0 | 0.00% |
Secretion
Metabolite | Reaction | Flux | Range | C-Number | C-Flux |
---|---|---|---|---|---|
ac_e | EX_ac_e | 0 | [-2.059; 0] | 2 | 0.00% |
acald_e | EX_acald_e | 0 | [-1.346; 0] | 2 | 0.00% |
akg_e | EX_akg_e | 0 | [-0.7447; 0] | 5 | 0.00% |
co2_e | EX_co2_e | -60 | [-60; -54.17] | 1 | 100.00% |
etoh_e | EX_etoh_e | 0 | [-1.167; 0] | 2 | 0.00% |
for_e | EX_for_e | 0 | [-5.833; 0] | 1 | 0.00% |
glu__L_e | EX_glu__L_e | 0 | [-0.6731; 0] | 5 | 0.00% |
h2o_e | EX_h2o_e | -60 | [-60; -54.17] | 0 | 0.00% |
h_e | EX_h_e | 0 | [-5.833; 0] | 0 | 0.00% |
lac__D_e | EX_lac__D_e | 0 | [-1.129; 0] | 3 | 0.00% |
nh4_e | EX_nh4_e | 0 | [0; 0.6731] | 0 | 0.00% |
pi_e | EX_pi_e | 0 | [0; 0.171] | 0 | 0.00% |
pyr_e | EX_pyr_e | 0 | [-1.346; 0] | 3 | 0.00% |
succ_e | EX_succ_e | 0 | [-0.875; 0] | 4 | 0.00% |
Similarly, variability in metabolite mass balances can also be checked with flux variability analysis.
[19]:
model.metabolites.pyr_c.summary(fva=0.95)
[19]:
pyr_c
C3H3O3
Producing Reactions
Percent | Flux | Range | Reaction | Definition |
---|---|---|---|---|
50.00% | 10 | [9.5; 10] | GLCpts | glc__D_e + pep_c --> g6p_c + pyr_c |
0.00% | 0 | [-1.129; 0] | LDH_D | lac__D_c + nad_c <=> h_c + nadh_c + pyr_c |
0.00% | 0 | [0; 8.75] | ME1 | mal__L_c + nad_c --> co2_c + nadh_c + pyr_c |
0.00% | 0 | [0; 8.75] | ME2 | mal__L_c + nadp_c --> co2_c + nadph_c + pyr_c |
50.00% | 10 | [1.25; 18.75] | PYK | adp_c + h_c + pep_c --> atp_c + pyr_c |
0.00% | 0 | [-1.346; 0] | PYRt2 | h_e + pyr_e <=> h_c + pyr_c |
Consuming Reactions
Percent | Flux | Range | Reaction | Definition |
---|---|---|---|---|
0.00% | 0 | [-0.1316; 0] | Biomass_Ecoli_core | 1.496 3pg_c + 3.7478 accoa_c + 59.81 atp_c + 0.361 e4p_c + 0.0709 f6p_c + 0.129 g3p_c + 0.205 g6p_c + 0.2557 gln__L_c + 4.9414 glu__L_c + 59.81 h2o_c + 3.547 nad_c + 13.0279 nadph_c + 1.7867 oaa_c + 0.5191 pep_c + 2.8328 pyr_c + 0.8977 r5p_c --> 59.81 adp_c + 4.1182 akg_c + 3.7478 coa_c + 59.81 h_c + 3.547 nadh_c + 13.0279 nadp_c + 59.81 pi_c |
100.00% | -20 | [-28.75; -13] | PDH | coa_c + nad_c + pyr_c --> accoa_c + co2_c + nadh_c |
0.00% | 0 | [-5.833; 0] | PFL | coa_c + pyr_c --> accoa_c + for_c |
0.00% | 0 | [-8.75; 0] | PPS | atp_c + h2o_c + pyr_c --> amp_c + 2.0 h_c + pep_c + pi_c |
In these summary methods, the values are reported as a the center point +/- the range of the FVA solution, calculated from the maximum and minimum values.
Running pFBA¶
Parsimonious FBA (often written pFBA) finds a flux distribution which gives the optimal growth rate, but minimizes the total sum of flux. This involves solving two sequential linear programs, but is handled transparently by cobrapy. For more details on pFBA, please see Lewis et al. (2010).
[20]:
model.objective = 'Biomass_Ecoli_core'
fba_solution = model.optimize()
pfba_solution = cobra.flux_analysis.pfba(model)
These functions will likely give completely different objective values, because the objective value shown from pFBA is defined as sum(abs(pfba_solution.fluxes.values))
, while the objective value for standard FBA is defined as the weighted flux through the reactions being optimized for (e.g. fba_solution.fluxes["Biomass_Ecoli_core"]
).
Both pFBA and FBA should return identical results within solver tolerances for the objective being optimized. E.g. for a FBA problem which maximizes the reaction Biomass_Ecoli_core
:
[21]:
abs(fba_solution.fluxes["Biomass_Ecoli_core"] - pfba_solution.fluxes[
"Biomass_Ecoli_core"])
[21]:
8.881784197001252e-16
[22]:
import numpy as np
np.isclose(
fba_solution.fluxes["Biomass_Ecoli_core"],
pfba_solution.fluxes["Biomass_Ecoli_core"]
)
[22]:
True
Running geometric FBA¶
Geometric FBA finds a unique optimal flux distribution which is central to the range of possible fluxes. For more details on geometric FBA, please see K Smallbone, E Simeonidis (2009).
[23]:
geometric_fba_sol = cobra.flux_analysis.geometric_fba(model)
geometric_fba_sol
[23]:
fluxes | reduced_costs | |
---|---|---|
ACALD | 0.000000e+00 | 0.0 |
ACALDt | 0.000000e+00 | 0.0 |
ACKr | 7.454685e-15 | 0.0 |
ACONTa | 6.007250e+00 | 0.0 |
ACONTb | 6.007250e+00 | 0.0 |
... | ... | ... |
TALA | 1.496984e+00 | 0.0 |
THD2 | 0.000000e+00 | 0.0 |
TKT1 | 1.496984e+00 | 0.0 |
TKT2 | 1.181498e+00 | 0.0 |
TPI | 7.477382e+00 | 0.0 |
95 rows × 2 columns
Simulating Deletions¶
[2]:
import pandas
from time import time
import cobra.test
from cobra.flux_analysis import (
single_gene_deletion, single_reaction_deletion, double_gene_deletion,
double_reaction_deletion)
cobra_model = cobra.test.create_test_model("textbook")
ecoli_model = cobra.test.create_test_model("ecoli")
Knocking out single genes and reactions¶
A commonly asked question when analyzing metabolic models is what will happen if a certain reaction was not allowed to have any flux at all. This can tested using cobrapy by
[3]:
print('complete model: ', cobra_model.optimize())
with cobra_model:
cobra_model.reactions.PFK.knock_out()
print('pfk knocked out: ', cobra_model.optimize())
complete model: <Solution 0.874 at 0x7f8130c3c760>
pfk knocked out: <Solution 0.704 at 0x7f8130c3c070>
For evaluating genetic manipulation strategies, it is more interesting to examine what happens if given genes are knocked out as doing so can affect no reactions in case of redundancy, or more reactions if gene when is participating in more than one reaction.
[4]:
print('complete model: ', cobra_model.optimize())
with cobra_model:
cobra_model.genes.b1723.knock_out()
print('pfkA knocked out: ', cobra_model.optimize())
cobra_model.genes.b3916.knock_out()
print('pfkB knocked out: ', cobra_model.optimize())
complete model: <Solution 0.874 at 0x7f8131dbc7c0>
pfkA knocked out: <Solution 0.874 at 0x7f816ddee820>
pfkB knocked out: <Solution 0.704 at 0x7f8130c3cf40>
Single Deletions¶
Perform all single gene deletions on a model
[5]:
deletion_results = single_gene_deletion(cobra_model)
These can also be done for only a subset of genes
[6]:
single_gene_deletion(cobra_model, cobra_model.genes[:20])
[6]:
ids | growth | status | |
---|---|---|---|
0 | {b0351} | 0.873922 | optimal |
1 | {b0727} | 0.858307 | optimal |
2 | {b2587} | 0.873922 | optimal |
3 | {b0474} | 0.873922 | optimal |
4 | {b3734} | 0.374230 | optimal |
5 | {b0726} | 0.858307 | optimal |
6 | {b3735} | 0.374230 | optimal |
7 | {b1241} | 0.873922 | optimal |
8 | {b1276} | 0.873922 | optimal |
9 | {b1849} | 0.873922 | optimal |
10 | {b3732} | 0.374230 | optimal |
11 | {s0001} | 0.211141 | optimal |
12 | {b0118} | 0.873922 | optimal |
13 | {b0356} | 0.873922 | optimal |
14 | {b2296} | 0.873922 | optimal |
15 | {b0116} | 0.782351 | optimal |
16 | {b1478} | 0.873922 | optimal |
17 | {b3115} | 0.873922 | optimal |
18 | {b3736} | 0.374230 | optimal |
19 | {b3733} | 0.374230 | optimal |
This can also be done for reactions
[7]:
single_reaction_deletion(cobra_model, cobra_model.reactions[:20])
[7]:
ids | growth | status | |
---|---|---|---|
0 | {ACALDt} | 0.873922 | optimal |
1 | {ATPS4r} | 0.374230 | optimal |
2 | {EX_ac_e} | 0.873922 | optimal |
3 | {AKGDH} | 0.858307 | optimal |
4 | {ACKr} | 0.873922 | optimal |
5 | {ETOHt2r} | 0.873922 | optimal |
6 | {CS} | 0.000000 | optimal |
7 | {ALCD2x} | 0.873922 | optimal |
8 | {ACONTa} | 0.000000 | optimal |
9 | {D_LACt2} | 0.873922 | optimal |
10 | {ADK1} | 0.873922 | optimal |
11 | {Biomass_Ecoli_core} | 0.000000 | optimal |
12 | {ATPM} | 0.916647 | optimal |
13 | {CYTBD} | 0.211663 | optimal |
14 | {ACt2r} | 0.873922 | optimal |
15 | {CO2t} | 0.461670 | optimal |
16 | {ACALD} | 0.873922 | optimal |
17 | {ENO} | 0.000000 | optimal |
18 | {AKGt2r} | 0.873922 | optimal |
19 | {ACONTb} | 0.000000 | optimal |
Double Deletions¶
Double deletions run in a similar way.
[8]:
double_gene_deletion(
cobra_model, cobra_model.genes[-5:]).round(4)
[8]:
ids | growth | status | |
---|---|---|---|
0 | {b2935} | 0.8739 | optimal |
1 | {b2465, b2464} | 0.8739 | optimal |
2 | {b0008, b2464} | 0.8739 | optimal |
3 | {b0008, b3919} | 0.7040 | optimal |
4 | {b3919, b2465} | 0.7040 | optimal |
5 | {b0008, b2935} | 0.8739 | optimal |
6 | {b3919} | 0.7040 | optimal |
7 | {b2465, b2935} | 0.8739 | optimal |
8 | {b0008, b2465} | 0.8739 | optimal |
9 | {b3919, b2464} | 0.7040 | optimal |
10 | {b2464} | 0.8739 | optimal |
11 | {b0008} | 0.8739 | optimal |
12 | {b3919, b2935} | 0.7040 | optimal |
13 | {b2935, b2464} | 0.8739 | optimal |
14 | {b2465} | 0.8739 | optimal |
By default, the double deletion function will automatically use multiprocessing, splitting the task over up to 4 cores if they are available. The number of cores can be manually specified as well. Setting use of a single core will disable use of the multiprocessing library, which often aids debugging.
[9]:
start = time() # start timer()
double_gene_deletion(
ecoli_model, ecoli_model.genes[:25], processes=2)
t1 = time() - start
print("Double gene deletions for 200 genes completed in "
"%.2f sec with 2 cores" % t1)
start = time() # start timer()
double_gene_deletion(
ecoli_model, ecoli_model.genes[:25], processes=1)
t2 = time() - start
print("Double gene deletions for 200 genes completed in "
"%.2f sec with 1 core" % t2)
print("Speedup of %.2fx" % (t2 / t1))
Double gene deletions for 200 genes completed in 9.02 sec with 2 cores
Double gene deletions for 200 genes completed in 15.48 sec with 1 core
Speedup of 1.72x
Double deletions can also be run for reactions.
[10]:
double_reaction_deletion(
cobra_model, cobra_model.reactions[2:7]).round(4)
[10]:
ids | growth | status | |
---|---|---|---|
0 | {ACt2r, ACKr} | 0.8739 | optimal |
1 | {ACONTa, ACKr} | 0.0000 | optimal |
2 | {ACONTa, ACONTb} | 0.0000 | optimal |
3 | {ACONTa} | 0.0000 | optimal |
4 | {ACONTb, ACt2r} | 0.0000 | optimal |
5 | {ACt2r} | 0.8739 | optimal |
6 | {ACONTa, ADK1} | 0.0000 | optimal |
7 | {ACONTa, ACt2r} | 0.0000 | optimal |
8 | {ADK1, ACt2r} | 0.8739 | optimal |
9 | {ACONTb, ACKr} | 0.0000 | optimal |
10 | {ADK1} | 0.8739 | optimal |
11 | {ACONTb, ADK1} | 0.0000 | optimal |
12 | {ADK1, ACKr} | 0.8739 | optimal |
13 | {ACKr} | 0.8739 | optimal |
14 | {ACONTb} | 0.0000 | optimal |
Accessing individual deletion results¶
Note that the indices for deletions are python set objects. This is the appropriate type since the order of deletions does not matter. Deleting reaction 1 and reaction 2 will have the same effect as deleting reaction 2 and reaction 1.
To make it easier to access results all DataFrames returned by COBRAPpy deletion functions have a knockout
indexer that makes that a bit simpler. Each entry in the indexer is treated as a single deletion entry. So you need to pass sets for double deletions.
[11]:
single = single_reaction_deletion(cobra_model)
double = double_reaction_deletion(cobra_model)
print(single.knockout["ATPM"])
print(double.knockout[{"ATPM", "TKT1"}])
ids growth status
89 {ATPM} 0.916647 optimal
ids growth status
2238 {ATPM, TKT1} 0.90584 optimal
This can be used to get several deletions at once and will also work for Reaction or Gene objects (depending on what you deleted) directly.
[12]:
atpm = cobra_model.reactions.ATPM
tkt1 = cobra_model.reactions.TKT1
pfk = cobra_model.reactions.PFK
print(single.knockout[atpm, tkt1, pfk])
print(double.knockout[{atpm, tkt1}, {atpm, pfk}, {atpm}])
ids growth status
15 {PFK} 0.704037 optimal
17 {TKT1} 0.864759 optimal
89 {ATPM} 0.916647 optimal
ids growth status
762 {ATPM} 0.916647 optimal
2238 {ATPM, TKT1} 0.905840 optimal
2533 {PFK, ATPM} 0.704037 optimal
[ ]:
Production envelopes¶
Production envelopes (aka phenotype phase planes) will show distinct phases of optimal growth with different use of two different substrates. For more information, see Edwards et al.
Cobrapy supports calculating these production envelopes and they can easily be plotted using your favorite plotting package. Here, we will make one for the “textbook” E. coli core model and demonstrate plotting using matplotlib.
[1]:
import cobra.test
from cobra.flux_analysis import production_envelope
model = cobra.test.create_test_model("textbook")
We want to make a phenotype phase plane to evaluate uptakes of Glucose and Oxygen.
[2]:
prod_env = production_envelope(model, ["EX_glc__D_e", "EX_o2_e"])
[3]:
prod_env.head()
[3]:
carbon_source | carbon_yield_maximum | carbon_yield_minimum | flux_maximum | flux_minimum | mass_yield_maximum | mass_yield_minimum | EX_glc__D_e | EX_o2_e | |
---|---|---|---|---|---|---|---|---|---|
0 | EX_glc__D_e | 1.442300e-13 | 0.0 | 0.000000 | 0.0 | NaN | NaN | -10.0 | -60.000000 |
1 | EX_glc__D_e | 1.310050e+00 | 0.0 | 0.072244 | 0.0 | NaN | NaN | -10.0 | -56.842105 |
2 | EX_glc__D_e | 2.620100e+00 | 0.0 | 0.144488 | 0.0 | NaN | NaN | -10.0 | -53.684211 |
3 | EX_glc__D_e | 3.930150e+00 | 0.0 | 0.216732 | 0.0 | NaN | NaN | -10.0 | -50.526316 |
4 | EX_glc__D_e | 5.240200e+00 | 0.0 | 0.288975 | 0.0 | NaN | NaN | -10.0 | -47.368421 |
If we specify the carbon source, we can also get the carbon and mass yield. For example, temporarily setting the objective to produce acetate instead we could get production envelope as follows and pandas to quickly plot the results.
[4]:
prod_env = production_envelope(
model, ["EX_o2_e"], objective="EX_ac_e", carbon_sources="EX_glc__D_e")
[5]:
prod_env.head()
[5]:
carbon_source | carbon_yield_maximum | carbon_yield_minimum | flux_maximum | flux_minimum | mass_yield_maximum | mass_yield_minimum | EX_o2_e | |
---|---|---|---|---|---|---|---|---|
0 | EX_glc__D_e | 2.385536e-15 | 0.0 | 0.000000 | 0.0 | 2.345496e-15 | 0.0 | -60.000000 |
1 | EX_glc__D_e | 5.263158e-02 | 0.0 | 1.578947 | 0.0 | 5.174819e-02 | 0.0 | -56.842105 |
2 | EX_glc__D_e | 1.052632e-01 | 0.0 | 3.157895 | 0.0 | 1.034964e-01 | 0.0 | -53.684211 |
3 | EX_glc__D_e | 1.578947e-01 | 0.0 | 4.736842 | 0.0 | 1.552446e-01 | 0.0 | -50.526316 |
4 | EX_glc__D_e | 2.105263e-01 | 0.0 | 6.315789 | 0.0 | 2.069927e-01 | 0.0 | -47.368421 |
[6]:
%matplotlib inline
[7]:
prod_env.plot(
kind='line', x='EX_o2_e', y='carbon_yield_maximum');

Previous versions of cobrapy included more tailored plots for phase planes which have now been dropped in order to improve maintainability and enhance the focus of cobrapy. Plotting for cobra models is intended for another package.
Flux sampling¶
Basic usage¶
The easiest way to get started with flux sampling is using the sample
function in the flux_analysis
submodule. sample
takes at least two arguments: a cobra model and the number of samples you want to generate.
[1]:
from cobra.test import create_test_model
from cobra.sampling import sample
model = create_test_model("textbook")
s = sample(model, 100)
s.head()
[1]:
ACALD | ACALDt | ACKr | ACONTa | ACONTb | ACt2r | ADK1 | AKGDH | AKGt2r | ALCD2x | ... | RPI | SUCCt2_2 | SUCCt3 | SUCDi | SUCOAS | TALA | THD2 | TKT1 | TKT2 | TPI | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | -2.060626 | -0.766231 | -1.746726 | 6.136642 | 6.136642 | -1.746726 | 13.915541 | 2.174506 | -0.242290 | -1.294395 | ... | -6.117270 | 33.457990 | 34.319917 | 704.483302 | -2.174506 | 6.109618 | 0.230408 | 6.109618 | 6.106540 | 3.122076 |
1 | -1.518217 | -1.265778 | -0.253608 | 9.081331 | 9.081331 | -0.253608 | 7.194475 | 5.979050 | -0.225992 | -0.252439 | ... | -5.072733 | 39.902893 | 40.343192 | 718.488475 | -5.979050 | 4.991843 | 0.137019 | 4.991843 | 4.959315 | 4.172389 |
2 | -3.790368 | -1.292543 | -0.457502 | 9.340755 | 9.340755 | -0.457502 | 23.435794 | 1.652395 | -0.333891 | -2.497825 | ... | -0.674220 | 0.153276 | 1.506968 | 844.889698 | -1.652395 | 0.673601 | 9.198001 | 0.673601 | 0.673352 | 7.770955 |
3 | -5.173189 | -4.511308 | -2.333962 | 7.364836 | 7.364836 | -2.333962 | 11.725401 | 2.504044 | -0.051420 | -0.661881 | ... | -0.681200 | 7.506732 | 9.110446 | 885.755585 | -2.504044 | 0.656561 | 7.514520 | 0.656561 | 0.646653 | 8.450394 |
4 | -6.787036 | -5.645414 | -1.521566 | 6.373250 | 6.373250 | -1.521566 | 4.823373 | 3.452123 | -0.126943 | -1.141621 | ... | -0.510598 | 9.307459 | 10.941500 | 749.854462 | -3.452123 | 0.474878 | 6.235982 | 0.474878 | 0.460514 | 8.908012 |
5 rows × 95 columns
By default sample uses the optgp
method based on the method presented here as it is suited for larger models and can run in parallel. By default the sampler uses a single process. This can be changed by using the processes
argument.
[2]:
print("One process:")
%time s = sample(model, 1000)
print("Two processes:")
%time s = sample(model, 1000, processes=2)
One process:
CPU times: user 19.7 s, sys: 918 ms, total: 20.6 s
Wall time: 16.1 s
Two processes:
CPU times: user 1.31 s, sys: 154 ms, total: 1.46 s
Wall time: 8.76 s
Alternatively you can also user Artificial Centering Hit-and-Run for sampling by setting the method to achr
. achr
does not support parallel execution but has good convergence and is almost Markovian.
[3]:
s = sample(model, 100, method="achr")
In general setting up the sampler is expensive since initial search directions are generated by solving many linear programming problems. Thus, we recommend to generate as many samples as possible in one go. However, this might require finer control over the sampling procedure as described in the following section.
Advanced usage¶
Sampler objects¶
The sampling process can be controlled on a lower level by using the sampler classes directly.
[4]:
from cobra.sampling import OptGPSampler, ACHRSampler
Both sampler classes have standardized interfaces and take some additional argument. For instance the thinning
factor. “Thinning” means only recording samples every n iterations. A higher thinning factors mean less correlated samples but also larger computation times. By default the samplers use a thinning factor of 100 which creates roughly uncorrelated samples. If you want less samples but better mixing feel free to increase this parameter. If you want to study convergence for your own
model you might want to set it to 1 to obtain all iterates.
[5]:
achr = ACHRSampler(model, thinning=10)
OptGPSampler
has an additional processes
argument specifying how many processes are used to create parallel sampling chains. This should be in the order of your CPU cores for maximum efficiency. As noted before class initialization can take up to a few minutes due to generation of initial search directions. Sampling on the other hand is quick.
[6]:
optgp = OptGPSampler(model, processes=4)
Sampling and validation¶
Both samplers have a sample function that generates samples from the initialized object and act like the sample
function described above, only that this time it will only accept a single argument, the number of samples. For OptGPSampler
the number of samples should be a multiple of the number of processes, otherwise it will be increased to the nearest multiple automatically.
[7]:
s1 = achr.sample(100)
s2 = optgp.sample(100)
You can call sample
repeatedly and both samplers are optimized to generate large amount of samples without falling into “numerical traps”. All sampler objects have a validate
function in order to check if a set of points are feasible and give detailed information about feasibility violations in a form of a short code denoting feasibility. Here the short code is a combination of any of the following letters:
“v” - valid point
“l” - lower bound violation
“u” - upper bound violation
“e” - equality violation (meaning the point is not a steady state)
For instance for a random flux distribution (should not be feasible):
[8]:
import numpy as np
bad = np.random.uniform(-1000, 1000, size=len(model.reactions))
achr.validate(np.atleast_2d(bad))
[8]:
array(['le'], dtype='<U3')
And for our generated samples:
[9]:
achr.validate(s1)
[9]:
array(['v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v'], dtype='<U3')
Even though most models are numerically stable enought that the sampler should only generate valid samples we still urge to check this. validate
is pretty fast and works quickly even for large models and many samples. If you find invalid samples you do not necessarily have to rerun the entire sampling but can exclude them from the sample DataFrame.
[10]:
s1_valid = s1[achr.validate(s1) == "v"]
len(s1_valid)
[10]:
100
Batch sampling¶
Sampler objects are made for generating billions of samples, however using the sample
function might quickly fill up your RAM when working with genome-scale models. Here, the batch
method of the sampler objects might come in handy. batch
takes two arguments, the number of samples in each batch and the number of batches. This will make sense with a small example.
Let’s assume we want to quantify what proportion of our samples will grow. For that we might want to generate 10 batches of 50 samples each and measure what percentage of the individual 100 samples show a growth rate larger than 0.1. Finally, we want to calculate the mean and standard deviation of those individual percentages.
[11]:
counts = [np.mean(s.Biomass_Ecoli_core > 0.1) for s in optgp.batch(100, 10)]
print("Usually {:.2f}% +- {:.2f}% grow...".format(
np.mean(counts) * 100.0, np.std(counts) * 100.0))
Usually 14.50% +- 2.16% grow...
Adding constraints¶
Flux sampling will respect additional contraints defined in the model. For instance we can add a constraint enforcing growth in asimilar manner as the section before.
[12]:
co = model.problem.Constraint(model.reactions.Biomass_Ecoli_core.flux_expression, lb=0.1)
model.add_cons_vars([co])
Note that this is only for demonstration purposes. usually you could set the lower bound of the reaction directly instead of creating a new constraint.
[13]:
s = sample(model, 10)
print(s.Biomass_Ecoli_core)
0 0.124471
1 0.151331
2 0.108145
3 0.144076
4 0.110480
5 0.109024
6 0.111399
7 0.139682
8 0.103511
9 0.116880
Name: Biomass_Ecoli_core, dtype: float64
As we can see our new constraint was respected.
Loopless FBA¶
The goal of this procedure is identification of a thermodynamically consistent flux state without loops, as implied by the name. You can find a more detailed description in the method section at the end of the notebook.
[1]:
%matplotlib inline
import plot_helper
import cobra.test
from cobra import Reaction, Metabolite, Model
from cobra.flux_analysis.loopless import add_loopless, loopless_solution
from cobra.flux_analysis import pfba
Loopless solution¶
Classical loopless approaches as described below are computationally expensive to solve due to the added mixed-integer constraints. A much faster, and pragmatic approach is instead to post-process flux distributions to simply set fluxes to zero wherever they can be zero without changing the fluxes of any exchange reactions in the model. CycleFreeFlux is an algorithm that can be used to achieve this and in cobrapy it is implemented in the
cobra.flux_analysis.loopless_solution
function. loopless_solution
will identify the closest flux distribution (using only loopless elementary flux modes) to the original one. Note that this will not remove loops which you explicitly requested, for instance by forcing a loop reaction to carry non-zero flux.
Using a larger model than the simple example above, this can be demonstrated as follows
[2]:
salmonella = cobra.test.create_test_model('salmonella')
nominal = salmonella.optimize()
loopless = loopless_solution(salmonella)
[3]:
import pandas
df = pandas.DataFrame(dict(loopless=loopless.fluxes, nominal=nominal.fluxes))
[4]:
df.plot.scatter(x='loopless', y='nominal')
[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x10f7cb3c8>

This functionality can also be used in FVA by using the loopless=True
argument to avoid getting high flux ranges for reactions that essentially only can reach high fluxes if they are allowed to participate in loops (see the simulation notebook) leading to much narrower flux ranges.
Loopless model¶
Cobrapy also includes the “classical” loopless formulation by Schellenberger et. al. implemented in cobra.flux_analysis.add_loopless
modify the model with additional mixed-integer constraints that make thermodynamically infeasible loops impossible. This is much slower than the strategy provided above and should only be used if one of the two following cases applies:
You want to combine a non-linear (e.g. quadratic) objective with the loopless condition
You want to force the model to be infeasible in the presence of loops independent of the set reaction bounds.
We will demonstrate this with a toy model which has a simple loop cycling A \(\rightarrow\) B \(\rightarrow\) C \(\rightarrow\) A, with A allowed to enter the system and C allowed to leave. A graphical view of the system is drawn below:
[5]:
plot_helper.plot_loop()

[6]:
model = Model()
model.add_metabolites([Metabolite(i) for i in "ABC"])
model.add_reactions([Reaction(i) for i in ["EX_A", "DM_C", "v1", "v2", "v3"]])
model.reactions.EX_A.add_metabolites({"A": 1})
model.reactions.DM_C.add_metabolites({"C": -1})
model.reactions.v1.add_metabolites({"A": -1, "B": 1})
model.reactions.v2.add_metabolites({"B": -1, "C": 1})
model.reactions.v3.add_metabolites({"C": -1, "A": 1})
model.objective = 'DM_C'
While this model contains a loop, a flux state exists which has no flux through reaction v\(_3\), and is identified by loopless FBA.
[7]:
with model:
add_loopless(model)
solution = model.optimize()
print("loopless solution: status = " + solution.status)
print("loopless solution flux: v3 = %.1f" % solution.fluxes["v3"])
loopless solution: status = optimal
loopless solution flux: v3 = 0.0
If there is no forced flux through a loopless reaction, parsimonious FBA will also have no flux through the loop.
[8]:
solution = pfba(model)
print("parsimonious solution: status = " + solution.status)
print("loopless solution flux: v3 = %.1f" % solution.fluxes["v3"])
parsimonious solution: status = optimal
loopless solution flux: v3 = 0.0
However, if flux is forced through v\(_3\), then there is no longer a feasible loopless solution, but the parsimonious solution will still exist.
[9]:
model.reactions.v3.lower_bound = 1
with model:
add_loopless(model)
try:
solution = model.optimize()
except:
print('model is infeasible')
model is infeasible
cobra/util/solver.py:398 UserWarning: solver status is 'infeasible'
[10]:
solution = pfba(model)
print("parsimonious solution: status = " + solution.status)
print("loopless solution flux: v3 = %.1f" % solution.fluxes["v3"])
parsimonious solution: status = optimal
loopless solution flux: v3 = 1.0
Method¶
loopless_solution
is based on a given reference flux distribution. It will look for a new flux distribution with the following requirements:
The objective value is the same as in the reference fluxes.
All exchange fluxes have the same value as in the reference distribution.
All non-exchange fluxes have the same sign (flow in the same direction) as the reference fluxes.
The sum of absolute non-exchange fluxes is minimized.
As proven in the original publication this will identify the “least-loopy” solution closest to the reference fluxes.
If you are using add_loopless
this will use the method described here. In summary, it will add \(G \approx \Delta G\) proxy variables and make loops thermodynamically infeasible. This is achieved by the following formulation.
Here the index j runs over all reactions and the index i only over internal ones. \(a_i\) are indicator variables which equal one if the reaction flux flows in hte forward direction and 0 otherwise. They are used to force the G proxies to always carry the opposite sign of the flux (as it is the case for the “real” \(\Delta G\) values). \(N_{int}\) is the nullspace matrix for internal reactions and is used to find thermodinamically “correct” values for G.
Consistency testing¶
For most problems, multiple flux states can achieve the same optimum and thus we try to obtain a consistent network. By this, we mean that there will be mulitple blocked reactions in the network, which gives rise to this inconsistency. To solve this problem, we use algorithms which can detect all the blocked reactions and also give us consistent networks.
Let us take a toy network, like so:
Here, \(v_{x}\), where \(x \in \{1, 2, \ldots, 6\}\) represent the flux carried by the reactions as shown above.
[1]:
import cobra
[2]:
test_model = cobra.Model("test_model")
v1 = cobra.Reaction("v1")
v2 = cobra.Reaction("v2")
v3 = cobra.Reaction("v3")
v4 = cobra.Reaction("v4")
v5 = cobra.Reaction("v5")
v6 = cobra.Reaction("v6")
test_model.add_reactions([v1, v2, v3, v4, v5, v6])
v1.reaction = "-> 2 A"
v2.reaction = "A <-> B"
v3.reaction = "A -> D"
v4.reaction = "A -> C"
v5.reaction = "C -> D"
v6.reaction = "D ->"
v1.bounds = (0.0, 3.0)
v2.bounds = (-3.0, 3.0)
v3.bounds = (0.0, 3.0)
v4.bounds = (0.0, 3.0)
v5.bounds = (0.0, 3.0)
v6.bounds = (0.0, 3.0)
test_model.objective = v6
unknown metabolite 'A' created
unknown metabolite 'B' created
unknown metabolite 'D' created
unknown metabolite 'C' created
Using FVA¶
The first approach we can follow is to use FVA (Flux Variability Analysis) which among many other applications, is used to detect blocked reactions. The cobra.flux_analysis.find_blocked_reactions()
function will return a list of all the blocked reactions obtained using FVA.
[3]:
cobra.flux_analysis.find_blocked_reactions(test_model)
[3]:
['v2']
As we see above, we are able to obtain the blocked reaction, which in this case is \(v_2\).
Using FASTCC¶
The second approach to obtaining consistent network in cobrapy
is to use FASTCC. Using this method, you can expect to efficiently obtain an accurate consistent network. For more details regarding the algorithm, please see Vlassis N, Pacheco MP, Sauter T (2014).
[4]:
consistent_model = cobra.flux_analysis.fastcc(test_model)
consistent_model.reactions
[4]:
[<Reaction v1 at 0x7fc71ddea5c0>,
<Reaction v3 at 0x7fc71ddea630>,
<Reaction v4 at 0x7fc71ddea668>,
<Reaction v5 at 0x7fc71ddea6a0>,
<Reaction v6 at 0x7fc71ddea6d8>]
Similar to the FVA approach, we are able to identify that \(v_2\) is indeed the blocked reaction.
Gapfillling¶
Model gap filling is the task of figuring out which reactions have to be added to a model to make it feasible. Several such algorithms have been reported e.g. Kumar et al. 2009 and Reed et al. 2006. Cobrapy has a gap filling implementation that is very similar to that of Reed et al. where we use a mixed-integer linear program to figure out the smallest number of reactions that need to be added for a user-defined collection of reactions, i.e. a universal model. Briefly, the problem that we try to solve is
Minimize:
subject to
Where l, u are lower and upper bounds for reaction i and z is an indicator variable that is zero if the reaction is not used and otherwise 1, c is a user-defined cost associated with using the ith reaction, \(v^\star\) is the flux of the objective and t a lower bound for that objective. To demonstrate, let’s take a model and remove some essential reactions from it.
[1]:
import cobra.test
from cobra.flux_analysis import gapfill
model = cobra.test.create_test_model("salmonella")
In this model D-Fructose-6-phosphate is an essential metabolite. We will remove all the reactions using it, and at them to a separate model.
[2]:
universal = cobra.Model("universal_reactions")
for i in [i.id for i in model.metabolites.f6p_c.reactions]:
reaction = model.reactions.get_by_id(i)
universal.add_reaction(reaction.copy())
model.remove_reactions([reaction])
Now, because of these gaps, the model won’t grow.
[3]:
model.optimize().objective_value
[3]:
0.0
We will use can use the model’s original objective, growth, to figure out which of the removed reactions are required for the model be feasible again. This is very similar to making the ‘no-growth but growth (NGG)’ predictions of Kumar et al. 2009.
[4]:
solution = gapfill(model, universal, demand_reactions=False)
for reaction in solution[0]:
print(reaction.id)
GF6PTA
F6PP
TKT2
FBP
MAN6PI
We can obtain multiple possible reaction sets by having the algorithm go through multiple iterations.
[5]:
result = gapfill(model, universal, demand_reactions=False, iterations=4)
for i, entries in enumerate(result):
print("---- Run %d ----" % (i + 1))
for e in entries:
print(e.id)
---- Run 1 ----
GF6PTA
F6PP
TKT2
FBP
MAN6PI
---- Run 2 ----
GF6PTA
TALA
PGI
F6PA
MAN6PI
---- Run 3 ----
GF6PTA
F6PP
TKT2
FBP
MAN6PI
---- Run 4 ----
GF6PTA
TALA
PGI
F6PA
MAN6PI
We can also instead of using the original objective, specify a given metabolite that we want the model to be able to produce.
[6]:
with model:
model.objective = model.add_boundary(model.metabolites.f6p_c, type='demand')
solution = gapfill(model, universal)
for reaction in solution[0]:
print(reaction.id)
FBP
Finally, note that using mixed-integer linear programming is computationally quite expensive and for larger models you may want to consider alternative gap filling methods and reconstruction methods.
Growth media¶
The availability of nutrients has a major impact on metabolic fluxes and cobrapy
provides some helpers to manage the exchanges between the external environment and your metabolic model. In experimental settings the “environment” is usually constituted by the growth medium, ergo the concentrations of all metabolites and co-factors available to the modeled organism. However, constraint-based metabolic models only consider fluxes. Thus, you can not simply use concentrations since fluxes have
the unit mmol / [gDW h]
(concentration per gram dry weight of cells and hour).
Also, you are setting an upper bound for the particular import flux and not the flux itself. There are some crude approximations. For instance, if you supply 1 mol of glucose every 24h to 1 gram of bacteria you might set the upper exchange flux for glucose to 1 mol / [1 gDW * 24 h]
since that is the nominal maximum that can be imported. There is no guarantee however that glucose will be consumed with that flux. Thus, the preferred data for exchange fluxes are direct flux measurements as the
ones obtained from timecourse exa-metabolome measurements for instance.
So how does that look in COBRApy? The current growth medium of a model is managed by the medium
attribute.
[1]:
from cobra.test import create_test_model
model = create_test_model("textbook")
model.medium
[1]:
{'EX_co2_e': 1000.0,
'EX_glc__D_e': 10.0,
'EX_h_e': 1000.0,
'EX_h2o_e': 1000.0,
'EX_nh4_e': 1000.0,
'EX_o2_e': 1000.0,
'EX_pi_e': 1000.0}
This will return a dictionary that contains the upper flux bounds for all active exchange fluxes (the ones having non-zero flux bounds). Right now we see that we have enabled aerobic growth. You can modify a growth medium of a model by assigning a dictionary to model.medium
that maps exchange reactions to their respective upper import bounds. For now let us enforce anaerobic growth by shutting off the oxygen import.
[2]:
medium = model.medium
medium["EX_o2_e"] = 0.0
model.medium = medium
model.medium
[2]:
{'EX_co2_e': 1000.0,
'EX_glc__D_e': 10.0,
'EX_h_e': 1000.0,
'EX_h2o_e': 1000.0,
'EX_nh4_e': 1000.0,
'EX_pi_e': 1000.0}
As we can see oxygen import is now removed from the list of active exchanges and we can verify that this also leads to a lower growth rate.
[3]:
model.slim_optimize()
[3]:
0.21166294973530736
There is a small trap here. model.medium
can not be assigned to directly. So the following will not work:
[4]:
model.medium["EX_co2_e"] = 0.0
model.medium
[4]:
{'EX_co2_e': 1000.0,
'EX_glc__D_e': 10.0,
'EX_h_e': 1000.0,
'EX_h2o_e': 1000.0,
'EX_nh4_e': 1000.0,
'EX_pi_e': 1000.0}
As you can see EX_co2_e
is not set to zero. This is because model.medium is just a copy of the current exchange fluxes. Assigning to it directly with model.medium[...] = ...
will not change the model. You have to assign an entire dictionary with the changed import flux upper bounds:
[5]:
medium = model.medium
medium["EX_co2_e"] = 0.0
model.medium = medium
model.medium # now it worked
[5]:
{'EX_glc__D_e': 10.0,
'EX_h_e': 1000.0,
'EX_h2o_e': 1000.0,
'EX_nh4_e': 1000.0,
'EX_pi_e': 1000.0}
Setting the growth medium also connects to the context manager, so you can set a specific growth medium in a reversible manner.
[6]:
model = create_test_model("textbook")
with model:
medium = model.medium
medium["EX_o2_e"] = 0.0
model.medium = medium
print(model.slim_optimize())
print(model.slim_optimize())
model.medium
0.21166294973530736
0.8739215069684102
[6]:
{'EX_co2_e': 1000.0,
'EX_glc__D_e': 10.0,
'EX_h_e': 1000.0,
'EX_h2o_e': 1000.0,
'EX_nh4_e': 1000.0,
'EX_o2_e': 1000.0,
'EX_pi_e': 1000.0}
So the medium change is only applied within the with
block and reverted automatically.
Minimal media¶
In some cases you might be interested in the smallest growth medium that can maintain a specific growth rate, the so called “minimal medium”. For this we provide the function minimal_medium
which by default obtains the medium with the lowest total import flux. This function needs two arguments: the model and the minimum growth rate (or other objective) the model has to achieve.
[7]:
from cobra.medium import minimal_medium
max_growth = model.slim_optimize()
minimal_medium(model, max_growth)
[7]:
EX_glc__D_e 10.000000
EX_nh4_e 4.765319
EX_o2_e 21.799493
EX_pi_e 3.214895
dtype: float64
So we see that growth is actually limited by glucose import.
Alternatively you might be interested in a minimal medium with the smallest number of active imports. This can be achieved by using the minimize_components
argument (note that this uses a MIP formulation and will therefore be much slower).
[8]:
minimal_medium(model, 0.1, minimize_components=True)
[8]:
EX_glc__D_e 10.000000
EX_nh4_e 1.042503
EX_pi_e 0.703318
dtype: float64
When minimizing the number of import fluxes there may be many alternative solutions. To obtain several of those you can also pass a positive integer to minimize_components
which will give you at most that many alternative solutions. Let us try that with our model and also use the open_exchanges
argument which will assign a large upper bound to all import reactions in the model. The return type will be a pandas.DataFrame
.
[9]:
minimal_medium(model, 0.8, minimize_components=8, open_exchanges=True)
[9]:
0 | 1 | 2 | 3 | |
---|---|---|---|---|
EX_fru_e | 0.000000 | 521.357767 | 0.000000 | 0.000000 |
EX_glc__D_e | 0.000000 | 0.000000 | 0.000000 | 519.750758 |
EX_gln__L_e | 0.000000 | 40.698058 | 18.848678 | 0.000000 |
EX_glu__L_e | 348.101944 | 0.000000 | 0.000000 | 0.000000 |
EX_mal__L_e | 0.000000 | 0.000000 | 1000.000000 | 0.000000 |
EX_nh4_e | 0.000000 | 0.000000 | 0.000000 | 81.026921 |
EX_o2_e | 500.000000 | 0.000000 | 0.000000 | 0.000000 |
EX_pi_e | 66.431529 | 54.913419 | 12.583458 | 54.664344 |
So there are 4 alternative solutions in total. One aerobic and three anaerobic ones using different carbon sources.
Boundary reactions¶
Apart from exchange reactions there are other types of boundary reactions such as demand or sink reactions. cobrapy
uses various heuristics to identify those and they can be accessed by using the appropriate attribute.
For exchange reactions:
[10]:
ecoli = create_test_model("ecoli")
ecoli.exchanges[0:5]
[10]:
[<Reaction EX_12ppd__R_e at 0x131b4a58d0>,
<Reaction EX_12ppd__S_e at 0x131b471c50>,
<Reaction EX_14glucan_e at 0x131b471e10>,
<Reaction EX_15dap_e at 0x131b471e48>,
<Reaction EX_23camp_e at 0x131b471f98>]
For demand reactions:
[11]:
ecoli.demands
[11]:
[<Reaction DM_4CRSOL at 0x131b3162b0>,
<Reaction DM_5DRIB at 0x131b4712e8>,
<Reaction DM_AACALD at 0x131b471400>,
<Reaction DM_AMOB at 0x131b4714e0>,
<Reaction DM_MTHTHF at 0x131b4715f8>,
<Reaction DM_OXAM at 0x131b4716d8>]
For sink reactions:
[12]:
ecoli.sinks
[12]:
[]
All boundary reactions (any reaction that consumes or introduces mass into the system) can be obtained with the boundary
attribute:
[13]:
ecoli.boundary[0:10]
[13]:
[<Reaction DM_4CRSOL at 0x131b3162b0>,
<Reaction DM_5DRIB at 0x131b4712e8>,
<Reaction DM_AACALD at 0x131b471400>,
<Reaction DM_AMOB at 0x131b4714e0>,
<Reaction DM_MTHTHF at 0x131b4715f8>,
<Reaction DM_OXAM at 0x131b4716d8>,
<Reaction EX_12ppd__R_e at 0x131b4a58d0>,
<Reaction EX_12ppd__S_e at 0x131b471c50>,
<Reaction EX_14glucan_e at 0x131b471e10>,
<Reaction EX_15dap_e at 0x131b471e48>]
Solvers¶
A constraint-based reconstruction and analysis model for biological systems is actually just an application of a class of discrete optimization problems typically solved with linear, mixed integer or quadratic programming techniques. Cobrapy does not implement any algorithm to find solutions to such problems but rather creates a biologically motivated abstraction to these techniques to make it easier to think of how metabolic systems work without paying much attention to how that formulates to an optimization problem.
The actual solving is instead done by tools such as the free software glpk or commercial tools gurobi and cplex which are all made available as a common programmers interface via the optlang package.
When you have defined your model, you can switch solver backend by simply assigning to the model.solver
property.
[1]:
import cobra.test
model = cobra.test.create_test_model('textbook')
[2]:
model.solver = 'glpk'
# or if you have cplex installed
model.solver = 'cplex'
For information on how to configure and tune the solver, please see the documentation for optlang project and note that model.solver
is simply an optlang object of class Model
.
[3]:
type(model.solver)
[3]:
optlang.cplex_interface.Model
Internal solver interfaces¶
Cobrapy also contains its own solver interfaces but these are now deprecated and will be removed completely in the near future. For documentation of how to use these, please refer to older documentation.
Tailored constraints, variables and objectives¶
Thanks to the use of symbolic expressions via the optlang mathematical modeling package, it is relatively straight-forward to add new variables, constraints and advanced objectives that cannot be easily formulated as a combination of different reaction and their corresponding upper and lower bounds. Here we demonstrate this optlang functionality which is exposed via the model.solver.interface
.
Constraints¶
Suppose we want to ensure that two reactions have the same flux in our model. We can add this criteria as constraint to our model using the optlang solver interface by simply defining the relevant expression as follows.
[1]:
import cobra.test
model = cobra.test.create_test_model('textbook')
[2]:
same_flux = model.problem.Constraint(
model.reactions.FBA.flux_expression - model.reactions.NH4t.flux_expression,
lb=0,
ub=0)
model.add_cons_vars(same_flux)
The flux for our reaction of interest is obtained by the model.reactions.FBA.flux_expression
which is simply the sum of the forward and reverse flux, i.e.,
[3]:
model.reactions.FBA.flux_expression
[3]:
1.0*FBA - 1.0*FBA_reverse_84806
Now I can maximize growth rate whilst the fluxes of reactions ‘FBA’ and ‘NH4t’ are constrained to be (near) identical.
[4]:
solution = model.optimize()
print(solution.fluxes['FBA'], solution.fluxes['NH4t'],
solution.objective_value)
4.66274904774 4.66274904774 0.855110960926157
It is also possible to add many constraints at once. For large models, with constraints involving many reactions, the efficient way to do this is to first build a dictionary of the linear coefficients for every flux, and then add the constraint at once. For example, suppose we want to add a constrain on the sum of the absolute values of every flux in the network to be less than 100:
[5]:
coefficients = dict()
for rxn in model.reactions:
coefficients[rxn.forward_variable] = 1.
coefficients[rxn.reverse_variable] = 1.
constraint = model.problem.Constraint(0, lb=0, ub=100)
model.add_cons_vars(constraint)
model.solver.update()
constraint.set_linear_coefficients(coefficients=coefficients)
Objectives¶
Simple objective such as the maximization of the flux through one or more reactions can conveniently be done by simply assigning to the model.objective
property as we have seen in previous chapters, e.g.,
[5]:
model = cobra.test.create_test_model('textbook')
with model:
model.objective = {model.reactions.Biomass_Ecoli_core: 1}
model.optimize()
print(model.reactions.Biomass_Ecoli_core.flux)
0.8739215069684307
The objectives mathematical expression is seen by
[6]:
model.objective.expression
[6]:
-1.0*Biomass_Ecoli_core_reverse_2cdba + 1.0*Biomass_Ecoli_core
But suppose we need a more complicated objective, such as minimizing the Euclidean distance of the solution to the origin minus another variable, while subject to additional linear constraints. This is an objective function with both linear and quadratic components.
Consider the example problem:
min \(\frac{1}{2}\left(x^2 + y^2 \right) - y\)
subject to
\(x + y = 2\)
\(x \ge 0\)
\(y \ge 0\)
This (admittedly very artificial) problem can be visualized graphically where the optimum is indicated by the blue dot on the line of feasible solutions.
[7]:
%matplotlib inline
import plot_helper
plot_helper.plot_qp2()

We return to the textbook model and set the solver to one that can handle quadratic objectives such as cplex. We then add the linear constraint that the sum of our x and y reactions, that we set to FBA and NH4t, must equal 2.
[8]:
model.solver = 'cplex'
sum_two = model.problem.Constraint(
model.reactions.FBA.flux_expression + model.reactions.NH4t.flux_expression,
lb=2,
ub=2)
model.add_cons_vars(sum_two)
Next we add the quadratic objective
[9]:
quadratic_objective = model.problem.Objective(
0.5 * model.reactions.NH4t.flux_expression**2 + 0.5 *
model.reactions.FBA.flux_expression**2 -
model.reactions.FBA.flux_expression,
direction='min')
model.objective = quadratic_objective
solution = model.optimize(objective_sense=None)
[10]:
print(solution.fluxes['NH4t'], solution.fluxes['FBA'])
0.5 1.5
Variables¶
We can also create additional variables to facilitate studying the effects of new constraints and variables. Suppose we want to study the difference in flux between nitrogen and carbon uptake whilst we block other reactions. For this it will may help to add another variable representing this difference.
[11]:
model = cobra.test.create_test_model('textbook')
difference = model.problem.Variable('difference')
We use constraints to define what values this variable shall take
[12]:
constraint = model.problem.Constraint(
model.reactions.EX_glc__D_e.flux_expression -
model.reactions.EX_nh4_e.flux_expression - difference,
lb=0,
ub=0)
model.add_cons_vars([difference, constraint])
Now we can access that difference directly during our knock-out exploration by looking at its primal value.
[13]:
for reaction in model.reactions[:5]:
with model:
reaction.knock_out()
model.optimize()
print(model.solver.variables.difference.primal)
-5.234680806802543
-5.2346808068025386
-5.234680806802525
-1.8644444444444337
-1.8644444444444466
Dynamic Flux Balance Analysis (dFBA) in COBRApy¶
The following notebook shows a simple, but slow example of implementing dFBA using COBRApy and scipy.integrate.solve_ivp. This notebook shows a static optimization approach (SOA) implementation and should not be considered production ready.
The model considers only basic Michaelis-Menten limited growth on glucose.
[1]:
import numpy as np
from tqdm import tqdm
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
%matplotlib inline
Create or load a cobrapy model. Here, we use the ‘textbook’ e-coli core model.
[2]:
import cobra
from cobra.test import create_test_model
model = create_test_model('textbook')
Set up the dynamic system¶
Dynamic flux balance analysis couples a dynamic system in external cellular concentrations to a pseudo-steady state metabolic model.
In this notebook, we define the function add_dynamic_bounds(model, y)
to convert the external metabolite concentrations into bounds on the boundary fluxes in the metabolic model.
[7]:
def add_dynamic_bounds(model, y):
"""Use external concentrations to bound the uptake flux of glucose."""
biomass, glucose = y # expand the boundary species
glucose_max_import = -10 * glucose / (5 + glucose)
model.reactions.EX_glc__D_e.lower_bound = glucose_max_import
def dynamic_system(t, y):
"""Calculate the time derivative of external species."""
biomass, glucose = y # expand the boundary species
# Calculate the specific exchanges fluxes at the given external concentrations.
with model:
add_dynamic_bounds(model, y)
cobra.util.add_lp_feasibility(model)
feasibility = cobra.util.fix_objective_as_constraint(model)
lex_constraints = cobra.util.add_lexicographic_constraints(
model, ['Biomass_Ecoli_core', 'EX_glc__D_e'], ['max', 'max'])
# Since the calculated fluxes are specific rates, we multiply them by the
# biomass concentration to get the bulk exchange rates.
fluxes = lex_constraints.values
fluxes *= biomass
# This implementation is **not** efficient, so I display the current
# simulation time using a progress bar.
if dynamic_system.pbar is not None:
dynamic_system.pbar.update(1)
dynamic_system.pbar.set_description('t = {:.3f}'.format(t))
return fluxes
dynamic_system.pbar = None
def infeasible_event(t, y):
"""
Determine solution feasibility.
Avoiding infeasible solutions is handled by solve_ivp's built-in event detection.
This function re-solves the LP to determine whether or not the solution is feasible
(and if not, how far it is from feasibility). When the sign of this function changes
from -epsilon to positive, we know the solution is no longer feasible.
"""
with model:
add_dynamic_bounds(model, y)
cobra.util.add_lp_feasibility(model)
feasibility = cobra.util.fix_objective_as_constraint(model)
return feasibility - infeasible_event.epsilon
infeasible_event.epsilon = 1E-6
infeasible_event.direction = 1
infeasible_event.terminal = True
Run the dynamic FBA simulation¶
[4]:
ts = np.linspace(0, 15, 100) # Desired integration resolution and interval
y0 = [0.1, 10]
with tqdm() as pbar:
dynamic_system.pbar = pbar
sol = solve_ivp(
fun=dynamic_system,
events=[infeasible_event],
t_span=(ts.min(), ts.max()),
y0=y0,
t_eval=ts,
rtol=1e-6,
atol=1e-8,
method='BDF'
)
t = 5.804: : 185it [00:16, 11.27it/s]
Because the culture runs out of glucose, the simulation terminates early. The exact time of this ‘cell death’ is recorded in sol.t_events
.
[5]:
sol
[5]:
message: 'A termination event occurred.'
nfev: 179
njev: 2
nlu: 14
sol: None
status: 1
success: True
t: array([0. , 0.15151515, 0.3030303 , 0.45454545, 0.60606061,
0.75757576, 0.90909091, 1.06060606, 1.21212121, 1.36363636,
1.51515152, 1.66666667, 1.81818182, 1.96969697, 2.12121212,
2.27272727, 2.42424242, 2.57575758, 2.72727273, 2.87878788,
3.03030303, 3.18181818, 3.33333333, 3.48484848, 3.63636364,
3.78787879, 3.93939394, 4.09090909, 4.24242424, 4.39393939,
4.54545455, 4.6969697 , 4.84848485, 5. , 5.15151515,
5.3030303 , 5.45454545, 5.60606061, 5.75757576])
t_events: [array([5.80191035])]
y: array([[ 0.1 , 0.10897602, 0.11871674, 0.12927916, 0.14072254,
0.15310825, 0.16649936, 0.18095988, 0.19655403, 0.21334507,
0.23139394, 0.25075753, 0.27148649, 0.29362257, 0.31719545,
0.34221886, 0.36868605, 0.3965646 , 0.42579062, 0.4562623 ,
0.48783322, 0.52030582, 0.55342574, 0.58687742, 0.62028461,
0.65321433, 0.685188 , 0.71570065, 0.74425054, 0.77037369,
0.79368263, 0.81390289, 0.83089676, 0.84467165, 0.85535715,
0.8631722 , 0.86843813, 0.8715096 , 0.8727423 ],
[10. , 9.8947027 , 9.78040248, 9.65642157, 9.52205334,
9.37656372, 9.21919615, 9.04917892, 8.86573366, 8.6680879 ,
8.45549026, 8.22722915, 7.98265735, 7.72122137, 7.442497 ,
7.14623236, 6.83239879, 6.50124888, 6.15338213, 5.78981735,
5.41206877, 5.02222068, 4.62299297, 4.21779303, 3.81071525,
3.40650104, 3.01042208, 2.6280723 , 2.26504645, 1.92656158,
1.61703023, 1.33965598, 1.09616507, 0.88670502, 0.70995892,
0.56344028, 0.44387781, 0.34762375, 0.27100065]])
Plot timelines of biomass and glucose¶
[6]:
ax = plt.subplot(111)
ax.plot(sol.t, sol.y.T[:, 0])
ax2 = plt.twinx(ax)
ax2.plot(sol.t, sol.y.T[:, 1], color='r')
ax.set_ylabel('Biomass', color='b')
ax2.set_ylabel('Glucose', color='r')
[6]:
Text(0, 0.5, 'Glucose')

Using the COBRA toolbox with cobrapy¶
This example demonstrates using COBRA toolbox commands in MATLAB from python through pymatbridge.
[1]:
%load_ext pymatbridge
Starting MATLAB on ZMQ socket ipc:///tmp/pymatbridge-57ff5429-02d9-4e1a-8ed0-44e391fb0df7
Send 'exit' command to kill the server
....MATLAB started and connected!
[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.
[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.
[4]:
%%matlab
model
model =
rev: [95x1 double]
metNames: {72x1 cell}
b: [72x1 double]
metCharge: [72x1 double]
c: [95x1 double]
csense: [72x1 char]
genes: {137x1 cell}
metFormulas: {72x1 cell}
rxns: {95x1 cell}
grRules: {95x1 cell}
rxnNames: {95x1 cell}
description: [11x1 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.
[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
[6]:
%%matlab
optimizeCbModel(model)
ans =
x: [95x1 double]
f: 0.8739
y: [71x1 double]
w: [95x1 double]
stat: 1
origStat: 5
solver: 'glpk'
time: 3.2911
FBA in the COBRA toolbox should give the same result as cobrapy (but maybe just a little bit slower :))
[7]:
%time
m.optimize().f
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 5.48 µs
[7]:
0.8739215069684909
FAQ¶
This document will address frequently asked questions not addressed in other pages of the documentation.
How do I install cobrapy?¶
Please see the INSTALL.rst file.
How do I cite cobrapy?¶
Please cite the 2013 publication: 10.1186/1752-0509-7-74
How do I rename reactions or metabolites?¶
TL;DR Use Model.repair
afterwards
When renaming metabolites or reactions, there are issues because cobra indexes based off of ID’s, which can cause errors. For example:
[1]:
from __future__ import print_function
import cobra.test
model = cobra.test.create_test_model()
for metabolite in model.metabolites:
metabolite.id = "test_" + metabolite.id
try:
model.metabolites.get_by_id(model.metabolites[0].id)
except KeyError as e:
print(repr(e))
The Model.repair function will rebuild the necessary indexes
[2]:
model.repair()
model.metabolites.get_by_id(model.metabolites[0].id)
[2]:
Metabolite identifier | test_dcaACP_c |
Name | Decanoyl-ACP-n-C100ACP |
Memory address | 0x0110f09630 |
Formula | C21H39N2O8PRS |
How do I delete a gene?¶
That depends on what precisely you mean by delete a gene.
If you want to simulate the model with a gene knockout, use the cobra.manipulation.delete_model_genes
function. The effects of this function are reversed by cobra.manipulation.undelete_model_genes
.
[3]:
model = cobra.test.create_test_model()
PGI = model.reactions.get_by_id("PGI")
print("bounds before knockout:", (PGI.lower_bound, PGI.upper_bound))
cobra.manipulation.delete_model_genes(model, ["STM4221"])
print("bounds after knockouts", (PGI.lower_bound, PGI.upper_bound))
bounds before knockout: (-1000.0, 1000.0)
bounds after knockouts (0.0, 0.0)
If you want to actually remove all traces of a gene from a model, this is more difficult because this will require changing all the gene_reaction_rule
strings for reactions involving the gene.
How do I change the reversibility of a Reaction?¶
Reaction.reversibility
is a property in cobra which is computed when it is requested from the lower and upper bounds.
[4]:
model = cobra.test.create_test_model()
model.reactions.get_by_id("PGI").reversibility
[4]:
True
Trying to set it directly will result in an error or warning:
[5]:
try:
model.reactions.get_by_id("PGI").reversibility = False
except Exception as e:
print(repr(e))
cobra/core/reaction.py:501 UserWarning: Setting reaction reversibility is ignored
The way to change the reversibility is to change the bounds to make the reaction irreversible.
[6]:
model.reactions.get_by_id("PGI").lower_bound = 10
model.reactions.get_by_id("PGI").reversibility
[6]:
False
How do I generate an LP file from a COBRA model?¶
For optlang based solvers¶
With optlang solvers, the LP formulation of a model is obtained by it’s string representation. All solvers behave the same way.
[7]:
with open('test.lp', 'w') as out:
out.write(str(model.solver))
For cobrapy’s internal solvers¶
With the internal solvers, we first create the problem and use functions bundled with the solver.
Please note that unlike the LP file format, the MPS file format does not specify objective direction and is always a minimization. Some (but not all) solvers will rewrite the maximization as a minimization.
[8]:
model = cobra.test.create_test_model()
# glpk through cglpk
glpk = cobra.solvers.cglpk.create_problem(model)
glpk.write("test.lp")
glpk.write("test.mps") # will not rewrite objective
# cplex
cplex = cobra.solvers.cplex_solver.create_problem(model)
cplex.write("test.lp")
cplex.write("test.mps") # rewrites objective
How do I visualize my flux solutions?¶
Please browse the visualization packages on our website for the most recent list of tools.
API Reference¶
This page contains auto-generated API reference documentation 1.
cobra
¶
Subpackages¶
cobra.core
¶
Submodules¶
cobra.core.configuration
¶Provide a global configuration object.
Define a global configuration object. |
-
class
cobra.core.configuration.
Configuration
(**kwargs)[source]¶ Define a global configuration object.
The attributes of this singleton object are used as default values by cobra functions.
-
solver
[source]¶ The default solver for new models. The solver choices are the ones provided by optlang and depend on solvers installed in your environment.
- Type
{“glpk”, “cplex”, “gurobi”, “glpk_exact”}
-
lower_bound
¶ The standard lower bound for reversible reactions (default -1000).
- Type
float, optional
-
bounds
[source]¶ The default reaction bounds for newly created reactions. The bounds are in the form of lower_bound, upper_bound (default -1000.0, 1000.0).
- Type
tuple of floats
-
processes
¶ A default number of processes to use where multiprocessing is possible. The default number corresponds to the number of available cores (hyperthreads) minus one.
- Type
-
cache_directory
[source]¶ A path where the model cache should reside if caching is desired. The default directory depends on the operating system.
- Type
pathlib.Path or str, optional
-
max_cache_size
¶ The allowed maximum size of the model cache in bytes (default 1 GB).
- Type
int, optional
-
cache_expiration
¶ The expiration time in seconds for the model cache if any (default None).
- Type
int, optional
-
_set_default_cache_directory
(self) → None[source]¶ Set the platform-dependent default cache directory.
-
property
solver
(self) → types.ModuleType[source] Return the optlang solver interface.
-
property
bounds
(self) → Tuple[Optional[Number], Optional[Number]][source] Return the lower, upper reaction bound pair.
-
property
cache_directory
(self) → pathlib.Path[source] Return the model cache directory.
-
cobra.core.dictlist
¶A combined dict and list |
-
class
cobra.core.dictlist.
DictList
(*args)[source]¶ Bases:
list
A combined dict and list
This object behaves like a list, but has the O(1) speed benefits of a dict when looking up elements by their id.
-
_check
(self, id)[source]¶ make sure duplicate id’s are not added. This function is called before adding in elements.
-
query
(self, search_function, attribute=None)[source]¶ Query the list
- Parameters
search_function (a string, regular expression or function) – Used to find the matching elements in the list. - a regular expression (possibly compiled), in which case the given attribute of the object should match the regular expression. - a function which takes one argument and returns True for desired values
attribute (string or None) – the name attribute of the object to passed as argument to the search_function. If this is None, the object itself is used.
- Returns
a new list of objects which match the query
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model('textbook') >>> model.reactions.query(lambda x: x.boundary) >>> import re >>> regex = re.compile('^g', flags=re.IGNORECASE) >>> model.metabolites.query(regex, attribute='name')
-
_extend_nocheck
(self, iterable)[source]¶ extends without checking for uniqueness
This function should only be used internally by DictList when it can guarantee elements are already unique (as in when coming from self or other DictList). It will be faster because it skips these checks.
-
__sub__
(self, other)[source]¶ x.__sub__(y) <==> x - y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__isub__
(self, other)[source]¶ x.__sub__(y) <==> x -= y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__add__
(self, other)[source]¶ x.__add__(y) <==> x + y
- Parameters
other (iterable) – other must contain only unique id’s which do not intersect with self
-
__iadd__
(self, other)[source]¶ x.__iadd__(y) <==> x += y
- Parameters
other (iterable) – other must contain only unique id’s whcih do not intersect with self
-
__getstate__
(self)[source]¶ gets internal state
This is only provided for backwards compatibility so older versions of cobrapy can load pickles generated with cobrapy. In reality, the “_dict” state is ignored when loading a pickle
-
__setstate__
(self, state)[source]¶ sets internal state
Ignore the passed in state and recalculate it. This is only for compatibility with older pickles which did not correctly specify the initialization class
-
cobra.core.formula
¶Describes a Chemical Formula |
-
class
cobra.core.formula.
Formula
(formula=None)[source]¶ Bases:
cobra.core.object.Object
Describes a Chemical Formula
- Parameters
formula (string) – A legal formula string contains only letters and numbers.
cobra.core.gene
¶Parses compiled ast of a gene_reaction_rule and identifies genes |
|
A Gene in a cobra model |
|
convert compiled ast to gene_reaction_rule str |
|
evaluate compiled ast of gene_reaction_rule with knockouts |
|
parse gpr into AST |
-
cobra.core.gene.
replacements
= [['.', '__COBRA_DOT__'], ["'", '__COBRA_SQUOTE__'], ['"', '__COBRA_DQUOTE__'], [':', '__COBRA_COLON__'], ['/', '__COBRA_FSLASH__'], ['\\', '__COBRA_BSLASH'], ['-', '__COBRA_DASH__'], ['=', '__COBRA_EQ__']][source]¶
-
cobra.core.gene.
ast2str
(expr, level=0, names=None)[source]¶ convert compiled ast to gene_reaction_rule str
- Parameters
expr (str) – string for a gene reaction rule, e.g “a and b”
level (int) – internal use only
names (dict) – Dict where each element id a gene identifier and the value is the gene name. Use this to get a rule str which uses names instead. This should be done for display purposes only. All gene_reaction_rule strings which are computed with should use the id.
- Returns
The gene reaction rule
- Return type
string
-
cobra.core.gene.
eval_gpr
(expr, knockouts)[source]¶ evaluate compiled ast of gene_reaction_rule with knockouts
-
class
cobra.core.gene.
GPRCleaner
[source]¶ Bases:
ast.NodeTransformer
Parses compiled ast of a gene_reaction_rule and identifies genes
Parts of the tree are rewritten to allow periods in gene ID’s and bitwise boolean operations
-
cobra.core.gene.
parse_gpr
(str_expr)[source]¶ parse gpr into AST
- Parameters
str_expr (string) – string with the gene reaction rule to parse
- Returns
elements ast_tree and gene_ids as a set
- Return type
-
class
cobra.core.gene.
Gene
(id=None, name='', functional=True)[source]¶ Bases:
cobra.core.species.Species
A Gene in a cobra model
- Parameters
id (string) – The identifier to associate the gene with
name (string) – A longer human readable name for the gene
functional (bool) – Indicates whether the gene is functional. If it is not functional then it cannot be used in an enzyme complex nor can its products be used.
-
property
functional
(self)[source]¶ A flag indicating if the gene is functional.
Changing the flag is reverted upon exit if executed within the model as context.
-
knock_out
(self)[source]¶ Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as context.
-
remove_from_model
(self, model=None, make_dependent_reactions_nonfunctional=True)[source]¶ Removes the association
- Parameters
model (cobra model) – The model to remove the gene from
make_dependent_reactions_nonfunctional (bool) – If True then replace the gene with ‘False’ in the gene association, else replace the gene with ‘True’
Deprecated since version 0.4: Use cobra.manipulation.delete_model_genes to simulate knockouts and cobra.manipulation.remove_genes to remove genes from the model.
cobra.core.group
¶Define the group class.
Manage groups via this implementation of the SBML group specification. |
-
class
cobra.core.group.
Group
(id, name='', members=None, kind=None)[source]¶ Bases:
cobra.core.object.Object
Manage groups via this implementation of the SBML group specification.
Group is a class for holding information regarding a pathways, subsystems, or other custom groupings of objects within a cobra.Model object.
- Parameters
id (str) – The identifier to associate with this group
name (str, optional) – A human readable name for the group
members (iterable, optional) – A DictList containing references to cobra.Model-associated objects that belong to the group.
kind ({"collection", "classification", "partonomy"}, optional) – The kind of group, as specified for the Groups feature in the SBML level 3 package specification. Can be any of “classification”, “partonomy”, or “collection”. The default is “collection”. Please consult the SBML level 3 package specification to ensure you are using the proper value for kind. In short, members of a “classification” group should have an “is-a” relationship to the group (e.g. member is-a polar compound, or member is-a transporter). Members of a “partonomy” group should have a “part-of” relationship (e.g. member is part-of glycolysis). Members of a “collection” group do not have an implied relationship between the members, so use this value for kind when in doubt (e.g. member is a gap-filled reaction, or member is involved in a disease phenotype).
cobra.core.metabolite
¶Define the Metabolite class.
Metabolite is a class for holding information regarding |
-
class
cobra.core.metabolite.
Metabolite
(id=None, formula=None, name='', charge=None, compartment=None)[source]¶ Bases:
cobra.core.species.Species
Metabolite is a class for holding information regarding a metabolite in a cobra.Reaction object.
- Parameters
-
property
constraint
(self)[source]¶ Get the constraints associated with this metabolite from the solve
- Returns
the optlang constraint for this metabolite
- Return type
optlang.<interface>.Constraint
-
property
elements
(self)[source]¶ Dictionary of elements as keys and their count in the metabolite as integer. When set, the formula property is update accordingly
-
property
y
(self)[source]¶ The shadow price for the metabolite in the most recent solution
Shadow prices are computed from the dual values of the bounds in the solution.
-
property
shadow_price
(self)[source]¶ The shadow price in the most recent solution.
Shadow price is the dual value of the corresponding constraint in the model.
Warning
Accessing shadow prices through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Shadow price is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the metabolite is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra >>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.metabolites.glc__D_e.shadow_price -0.09166474637510488 >>> solution.shadow_prices.glc__D_e -0.091664746375104883
-
remove_from_model
(self, destructive=False)[source]¶ Removes the association from self.model
The change is reverted upon exit when using the model as a context.
- Parameters
destructive (bool) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model.
-
summary
(self, solution=None, fva=None)[source]¶ Create a summary of the producing and consuming fluxes.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
See also
Reaction.summary()
,Model.summary()
cobra.core.model
¶Define the Model class.
Class representation for a cobra model |
-
class
cobra.core.model.
Model
(id_or_model=None, name=None)[source]¶ Bases:
cobra.core.object.Object
Class representation for a cobra model
- Parameters
id_or_model (Model, string) – Either an existing Model object in which case a new model object is instantiated with the same properties as the original model, or an identifier to associate with the model as a string.
name (string) – Human readable name for the model
-
reactions
¶ A DictList where the key is the reaction identifier and the value a Reaction
- Type
-
metabolites
¶ A DictList where the key is the metabolite identifier and the value a Metabolite
- Type
-
__getstate__
(self)[source]¶ Get state for serialization.
Ensures that the context stack is cleared prior to serialization, since partial functions cannot be pickled reliably.
-
property
solver
(self)[source]¶ Get or set the attached solver instance.
The associated the solver object, which manages the interaction with the associated solver, e.g. glpk.
This property is useful for accessing the optimization problem directly and to define additional non-metabolic constraints.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> new = model.problem.Constraint(model.objective.expression, >>> lb=0.99) >>> model.solver.add(new)
-
__add__
(self, other_model)[source]¶ Add the content of another model to this model (+).
The model is copied as a new object, with a new model identifier, and copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
__iadd__
(self, other_model)[source]¶ Incrementally add the content of another model to this model (+=).
Copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
copy
(self)[source]¶ Provides a partial ‘deepcopy’ of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy
-
add_metabolites
(self, metabolite_list)[source]¶ Will add a list of metabolites to the model object and add new constraints accordingly.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolite_list (A list of cobra.core.Metabolite objects) –
-
remove_metabolites
(self, metabolite_list, destructive=False)[source]¶ Remove a list of metabolites from the the object.
The change is reverted upon exit when using the model as a context.
-
add_reaction
(self, reaction)[source]¶ Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions.
- Parameters
reaction (cobra.Reaction) – The reaction to add
(0.6) Use ~cobra.Model.add_reactions instead (Deprecated) –
-
add_boundary
(self, metabolite, type='exchange', reaction_id=None, lb=None, ub=None, sbo_term=None)[source]¶ Add a boundary reaction for a given metabolite.
There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, unbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites, i.e., a reversible reaction that adds or removes an intracellular metabolite.
If you set the reaction type to something else, you must specify the desired identifier of the created reaction along with its upper and lower bound. The name will be given by the metabolite name and the given type.
- Parameters
metabolite (cobra.Metabolite) – Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks.
type (str, {"exchange", "demand", "sink"}) – Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., ‘my-boundary’.
reaction_id (str, optional) – The ID of the resulting reaction. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using model.boundary or specifically model.exchanges etc.
lb (float, optional) – The lower bound of the resulting reaction.
ub (float, optional) – The upper bound of the resulting reaction.
sbo_term (str, optional) – A correct SBO term is set for the available types. If a custom type is chosen, a suitable SBO term should also be set.
- Returns
The created boundary reaction.
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> demand = model.add_boundary(model.metabolites.atp_c, type="demand") >>> demand.id 'DM_atp_c' >>> demand.name 'ATP demand' >>> demand.bounds (0, 1000.0) >>> demand.build_reaction_string() 'atp_c --> '
-
add_reactions
(self, reaction_list)[source]¶ Add reactions to the model.
Reactions with identifiers identical to a reaction already in the model are ignored.
The change is reverted upon exit when using the model as a context.
- Parameters
reaction_list (list) – A list of cobra.Reaction objects
-
remove_reactions
(self, reactions, remove_orphans=False)[source]¶ Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
-
add_groups
(self, group_list)[source]¶ Add groups to the model.
Groups with identifiers identical to a group already in the model are ignored.
If any group contains members that are not in the model, these members are added to the model as well. Only metabolites, reactions, and genes can have groups.
- Parameters
group_list (list) – A list of cobra.Group objects to add to the model.
-
remove_groups
(self, group_list)[source]¶ Remove groups from the model.
Members of each group are not removed from the model (i.e. metabolites, reactions, and genes in the group stay in the model after any groups containing them are removed).
- Parameters
group_list (list) – A list of cobra.Group objects to remove from the model.
-
get_associated_groups
(self, element)[source]¶ Returns a list of groups that an element (reaction, metabolite, gene) is associated with.
- Parameters
element (cobra.Reaction, cobra.Metabolite, or cobra.Gene) –
- Returns
All groups that the provided object is a member of
- Return type
list of cobra.Group
-
add_cons_vars
(self, what, **kwargs)[source]¶ Add constraints and variables to the model’s mathematical problem.
Useful for variables and constraints that can not be expressed with reactions and simple lower and upper bounds.
Additions are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
**kwargs (keyword arguments) – Passed to solver.add()
-
remove_cons_vars
(self, what)[source]¶ Remove variables and constraints from the model’s mathematical problem.
Remove variables and constraints that were added directly to the model’s underlying mathematical problem. Removals are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
-
property
problem
(self)[source]¶ The interface to the model’s underlying mathematical problem.
Solutions to cobra models are obtained by formulating a mathematical problem and solving it. Cobrapy uses the optlang package to accomplish that and with this property you can get access to the problem interface directly.
- Returns
The problem interface that defines methods for interacting with the problem and associated solver directly.
- Return type
optlang.interface
-
property
variables
(self)[source]¶ The mathematical variables in the cobra model.
In a cobra model, most variables are reactions. However, for specific use cases, it may also be useful to have other types of variables. This property defines all variables currently associated with the model’s problem.
- Returns
A container with all associated variables.
- Return type
optlang.container.Container
-
property
constraints
(self)[source]¶ The constraints in the cobra model.
In a cobra model, most constraints are metabolites and their stoichiometries. However, for specific use cases, it may also be useful to have other types of constraints. This property defines all constraints currently associated with the model’s problem.
- Returns
A container with all associated constraints.
- Return type
optlang.container.Container
-
property
boundary
(self)[source]¶ Boundary reactions in the model. Reactions that either have no substrate or product.
-
property
exchanges
(self)[source]¶ Exchange reactions in model. Reactions that exchange mass with the exterior. Uses annotations and heuristics to exclude non-exchanges such as sink reactions.
-
property
demands
(self)[source]¶ Demand reactions in model. Irreversible reactions that accumulate or consume a metabolite in the inside of the model.
-
property
sinks
(self)[source]¶ Sink reactions in model. Reversible reactions that accumulate or consume a metabolite in the inside of the model.
-
_populate_solver
(self, reaction_list, metabolite_list=None)[source]¶ Populate attached solver with constraints and variables that model the provided reactions.
-
slim_optimize
(self, error_value=float('nan'), message=None)[source]¶ Optimize model without creating a solution object.
Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and in cases where only one or two values are of interest, it is recommended to instead use this function which does not create a solution object returning only the value of the objective. Note however that the optimize() function uses efficient means to fetch values so if you need fluxes/shadow prices for more than say 4 reactions/metabolites, then the total speed increase of slim_optimize versus optimize is expected to be small or even negative depending on how you fetch the values after optimization.
-
optimize
(self, objective_sense=None, raise_error=False)[source]¶ Optimize the model using flux balance analysis.
- Parameters
objective_sense ({None, 'maximize' 'minimize'}, optional) – Whether fluxes should be maximized or minimized. In case of None, the previous direction is used.
raise_error (bool) –
- If true, raise an OptimizationError if solver status is not
optimal.
Notes
Only the most commonly used parameters are presented here. Additional parameters for cobra.solvers may be available and specified with the appropriate keyword argument.
-
repair
(self, rebuild_index=True, rebuild_relationships=True)[source]¶ Update all indexes and pointers in a model
-
property
objective
(self)[source]¶ Get or set the solver objective
Before introduction of the optlang based problems, this function returned the objective reactions as a list. With optlang, the objective is not limited a simple linear summation of individual reaction fluxes, making that return value ambiguous. Henceforth, use cobra.util.solver.linear_reaction_coefficients to get a dictionary of reactions with their linear coefficients (empty if there are none)
The set value can be dictionary (reactions as keys, linear coefficients as values), string (reaction identifier), int (reaction index), Reaction or problem.Objective or sympy expression directly interpreted as objectives.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
objective_direction
(self)[source]¶ Get or set the objective direction.
When using a HistoryManager context, this attribute can be set temporarily, reversed when exiting the context.
-
summary
(self, solution=None, fva=None)[source]¶ Create a summary of the exchange fluxes of the model.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.ModelSummary
See also
Reaction.summary()
,Metabolite.summary()
-
__enter__
(self)[source]¶ Record all future changes to the model, undoing them when a call to __exit__ is received
-
__exit__
(self, type, value, traceback)[source]¶ Pop the top context manager and trigger the undo functions
-
merge
(self, right, prefix_existing=None, inplace=True, objective='left')[source]¶ Merge two models to create a model with the reactions from both models.
Custom constraints and variables from right models are also copied to left model, however note that, constraints and variables are assumed to be the same if they have the same name.
- rightcobra.Model
The model to add reactions from
- prefix_existingstring
Prefix the reaction identifier in the right that already exist in the left model with this string.
- inplacebool
Add reactions from right directly to left model object. Otherwise, create a new model leaving the left model untouched. When done within the model as context, changes to the models are reverted upon exit.
- objectivestring
One of ‘left’, ‘right’ or ‘sum’ for setting the objective of the resulting model to that of the corresponding model or the sum of both.
cobra.core.object
¶Defines common behavior of object in cobra.core |
cobra.core.reaction
¶Define the Reaction class.
Reaction is a class for holding information regarding |
-
class
cobra.core.reaction.
Reaction
(id=None, name='', subsystem='', lower_bound=0.0, upper_bound=None)[source]¶ Bases:
cobra.core.object.Object
Reaction is a class for holding information regarding a biochemical reaction in a cobra.Model object.
Reactions are by default irreversible with bounds (0.0, cobra.Configuration().upper_bound) if no bounds are provided on creation. To create an irreversible reaction use lower_bound=None, resulting in reaction bounds of (cobra.Configuration().lower_bound, cobra.Configuration().upper_bound).
- Parameters
-
property
flux_expression
(self)[source]¶ Forward flux expression
- Returns
The expression representing the the forward flux (if associated with model), otherwise None. Representing the net flux if model.reversible_encoding == ‘unsplit’ or None if reaction is not associated with a model
- Return type
sympy expression
-
property
forward_variable
(self)[source]¶ An optlang variable representing the forward flux
- Returns
An optlang variable for the forward flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
reverse_variable
(self)[source]¶ An optlang variable representing the reverse flux
- Returns
An optlang variable for the reverse flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
objective_coefficient
(self)[source]¶ Get the coefficient for this reaction in a linear objective (float)
Assuming that the objective of the associated model is summation of fluxes from a set of reactions, the coefficient for each reaction can be obtained individually using this property. A more general way is to use the model.objective property directly.
-
property
lower_bound
(self)[source]¶ Get or set the lower bound
Setting the lower bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a lower bound higher than the current upper bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
upper_bound
(self)[source]¶ Get or set the upper bound
Setting the upper bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a upper bound lower than the current lower bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
bounds
(self)[source]¶ Get or set the bounds directly from a tuple
Convenience method for setting upper and lower bounds in one line using a tuple of lower and upper bound. Invalid bounds will raise an AssertionError.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
flux
(self)[source]¶ The flux value in the most recent solution.
Flux is the primal value of the corresponding variable in the model.
Warning
Accessing reaction fluxes through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reaction flux is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
AssertionError – If the flux value is not within the bounds.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.flux 7.477381962160283 >>> solution.fluxes.PFK 7.4773819621602833
-
property
reduced_cost
(self)[source]¶ The reduced cost in the most recent solution.
Reduced cost is the dual value of the corresponding variable in the model.
Warning
Accessing reduced costs through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reduced cost is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.reduced_cost -8.673617379884035e-18 >>> solution.reduced_costs.PFK -8.6736173798840355e-18
-
property
gene_name_reaction_rule
(self)[source]¶ Display gene_reaction_rule with names intead.
Do NOT use this string for computation. It is intended to give a representation of the rule using more familiar gene names instead of the often cryptic ids.
-
property
functional
(self)[source]¶ All required enzymes for reaction are functional.
- Returns
True if the gene-protein-reaction (GPR) rule is fulfilled for this reaction, or if reaction is not associated to a model, otherwise False.
- Return type
-
property
x
(self)[source]¶ The flux through the reaction in the most recent solution.
Flux values are computed from the primal values of the variables in the solution.
-
property
y
(self)[source]¶ The reduced cost of the reaction in the most recent solution.
Reduced costs are computed from the dual values of the variables in the solution.
-
property
reversibility
(self)[source]¶ Whether the reaction can proceed in both directions (reversible)
This is computed from the current upper and lower bounds.
-
property
boundary
(self)[source]¶ Whether or not this reaction is an exchange reaction.
Returns True if the reaction has either no products or reactants.
-
_update_awareness
(self)[source]¶ Make sure all metabolites and genes that are associated with this reaction are aware of it.
-
remove_from_model
(self, remove_orphans=False)[source]¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
delete
(self, remove_orphans=False)[source]¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Deprecated, use reaction.remove_from_model instead.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
__setstate__
(self, state)[source]¶ Probably not necessary to set _model as the cobra.Model that contains self sets the _model attribute for all metabolites and genes in the reaction.
However, to increase performance speed we do want to let the metabolite and gene know that they are employed in this reaction
-
__add__
(self, other)[source]¶ Add two reactions
The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction
-
__imul__
(self, coefficient)[source]¶ Scale coefficients in a reaction by a given value
E.g. A -> B becomes 2A -> 2B.
If coefficient is less than zero, the reaction is reversed and the bounds are swapped.
-
get_coefficient
(self, metabolite_id)[source]¶ Return the stoichiometric coefficient of a metabolite.
- Parameters
metabolite_id (str or cobra.Metabolite) –
-
get_coefficients
(self, metabolite_ids)[source]¶ Return the stoichiometric coefficients for a list of metabolites.
- Parameters
metabolite_ids (iterable) – Containing
str
or ``cobra.Metabolite``s.
-
add_metabolites
(self, metabolites_to_add, combine=True, reversibly=True)[source]¶ Add metabolites and stoichiometric coefficients to the reaction. If the final coefficient for a metabolite is 0 then it is removed from the reaction.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites_to_add (dict) – Dictionary with metabolite objects or metabolite identifiers as keys and coefficients as values. If keys are strings (name of a metabolite) the reaction must already be part of a model and a metabolite with the given name must exist in the model.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
subtract_metabolites
(self, metabolites, combine=True, reversibly=True)[source]¶ Subtract metabolites from a reaction.
That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction.
Notes
A final coefficient < 0 implies a reactant.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites (dict) – Dictionary where the keys are of class Metabolite and the values are the coefficients. These metabolites will be added to the reaction.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
build_reaction_string
(self, use_metabolite_names=False)[source]¶ Generate a human readable reaction string
-
check_mass_balance
(self)[source]¶ Compute mass and charge balance for the reaction
returns a dict of {element: amount} for unbalanced elements. “charge” is treated as an element in this dict This should be empty for balanced reactions.
-
_associate_gene
(self, cobra_gene)[source]¶ Associates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
_dissociate_gene
(self, cobra_gene)[source]¶ Dissociates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
build_reaction_from_string
(self, reaction_str, verbose=True, fwd_arrow=None, rev_arrow=None, reversible_arrow=None, term_split='+')[source]¶ Builds reaction from reaction equation reaction_str using parser
Takes a string and using the specifications supplied in the optional arguments infers a set of metabolites, metabolite compartments and stoichiometries for the reaction. It also infers the reversibility of the reaction from the reaction arrow.
Changes to the associated model are reverted upon exit when using the model as a context.
- Parameters
reaction_str (string) – a string containing a reaction formula (equation)
verbose (bool) – setting verbosity of function
fwd_arrow (re.compile) – for forward irreversible reaction arrows
rev_arrow (re.compile) – for backward irreversible reaction arrows
reversible_arrow (re.compile) – for reversible reaction arrows
term_split (string) – dividing individual metabolite entries
-
summary
(self, solution=None, fva=None)[source]¶ Create a summary of the reaction flux.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.summary.ReactionSummary
See also
Metabolite.summary()
,Model.summary()
cobra.core.singleton
¶Define the singleton meta class.
Implementation of the singleton pattern as a meta class. |
cobra.core.solution
¶Provide unified interfaces to optimization solutions.
A unified interface to a cobra.Model optimization solution. |
|
Legacy support for an interface to a cobra.Model optimization solution. |
|
Generate a solution representation of the current solver state. |
-
class
cobra.core.solution.
Solution
(objective_value, status, fluxes, reduced_costs=None, shadow_prices=None, **kwargs)[source]¶ Bases:
object
A unified interface to a cobra.Model optimization solution.
Notes
Solution is meant to be constructed by get_solution please look at that function to fully understand the Solution class.
-
fluxes
¶ Contains the reaction fluxes (primal values of variables).
- Type
pandas.Series
-
reduced_costs
¶ Contains reaction reduced costs (dual values of variables).
- Type
pandas.Series
-
shadow_prices
¶ Contains metabolite shadow prices (dual values of constraints).
- Type
pandas.Series
-
-
class
cobra.core.solution.
LegacySolution
(f, x=None, x_dict=None, y=None, y_dict=None, solver=None, the_time=0, status='NA', **kwargs)[source]¶ Bases:
object
Legacy support for an interface to a cobra.Model optimization solution.
-
x
¶ List or Array of the fluxes (primal values).
- Type
iterable
-
y
¶ List or Array of the dual values.
- Type
iterable
Warning
The LegacySolution class and its interface is deprecated.
-
-
cobra.core.solution.
get_solution
(model, reactions=None, metabolites=None, raise_error=False)[source]¶ Generate a solution representation of the current solver state.
- Parameters
model (cobra.Model) – The model whose reactions to retrieve values for.
reactions (list, optional) – An iterable of cobra.Reaction objects. Uses model.reactions by default.
metabolites (list, optional) – An iterable of cobra.Metabolite objects. Uses model.metabolites by default.
raise_error (bool) – If true, raise an OptimizationError if solver status is not optimal.
- Returns
- Return type
Note
This is only intended for the optlang solver interfaces and not the legacy solvers.
cobra.core.species
¶Species is a class for holding information regarding |
-
class
cobra.core.species.
Species
(id=None, name=None)[source]¶ Bases:
cobra.core.object.Object
Species is a class for holding information regarding a chemical Species
- Parameters
id (string) – An identifier for the chemical species
name (string) – A human readable name.
-
__getstate__
(self)[source]¶ Remove the references to container reactions when serializing to avoid problems associated with recursion.
Package Contents¶
Define a global configuration object. |
|
A combined dict and list |
|
A Gene in a cobra model |
|
Metabolite is a class for holding information regarding |
|
Class representation for a cobra model |
|
Defines common behavior of object in cobra.core |
|
Reaction is a class for holding information regarding |
|
Manage groups via this implementation of the SBML group specification. |
|
A unified interface to a cobra.Model optimization solution. |
|
Legacy support for an interface to a cobra.Model optimization solution. |
|
Species is a class for holding information regarding |
|
Generate a solution representation of the current solver state. |
-
class
cobra.core.
Configuration
(**kwargs)[source]¶ Define a global configuration object.
The attributes of this singleton object are used as default values by cobra functions.
-
solver
¶ The default solver for new models. The solver choices are the ones provided by optlang and depend on solvers installed in your environment.
- Type
{“glpk”, “cplex”, “gurobi”, “glpk_exact”}
-
lower_bound
¶ The standard lower bound for reversible reactions (default -1000).
- Type
float, optional
-
bounds
¶ The default reaction bounds for newly created reactions. The bounds are in the form of lower_bound, upper_bound (default -1000.0, 1000.0).
- Type
tuple of floats
-
processes
¶ A default number of processes to use where multiprocessing is possible. The default number corresponds to the number of available cores (hyperthreads) minus one.
- Type
-
cache_directory
¶ A path where the model cache should reside if caching is desired. The default directory depends on the operating system.
- Type
pathlib.Path or str, optional
-
max_cache_size
¶ The allowed maximum size of the model cache in bytes (default 1 GB).
- Type
int, optional
-
cache_expiration
¶ The expiration time in seconds for the model cache if any (default None).
- Type
int, optional
-
_set_default_solver
(self) → None¶ Set the default solver from a preferred order.
-
_set_default_processes
(self) → None¶ Set the default number of processes.
-
_set_default_cache_directory
(self) → None¶ Set the platform-dependent default cache directory.
-
property
solver
(self) → types.ModuleType Return the optlang solver interface.
-
property
bounds
(self) → Tuple[Optional[Number], Optional[Number]] Return the lower, upper reaction bound pair.
-
property
cache_directory
(self) → pathlib.Path Return the model cache directory.
-
__repr__
(self) → str¶ Return a string representation of the current configuration values.
-
_repr_html_
(self) → str¶ Return a rich HTML representation of the current configuration values.
Notes
This special method is used automatically in Jupyter notebooks to display a result from a cell.
-
-
class
cobra.core.
DictList
(*args)[source]¶ Bases:
list
A combined dict and list
This object behaves like a list, but has the O(1) speed benefits of a dict when looking up elements by their id.
-
has_id
(self, id)¶
-
_check
(self, id)¶ make sure duplicate id’s are not added. This function is called before adding in elements.
-
_generate_index
(self)¶ rebuild the _dict index
-
get_by_id
(self, id)¶ return the element with a matching id
-
list_attr
(self, attribute)¶ return a list of the given attribute for every object
-
get_by_any
(self, iterable)¶ Get a list of members using several different ways of indexing
-
query
(self, search_function, attribute=None)¶ Query the list
- Parameters
search_function (a string, regular expression or function) – Used to find the matching elements in the list. - a regular expression (possibly compiled), in which case the given attribute of the object should match the regular expression. - a function which takes one argument and returns True for desired values
attribute (string or None) – the name attribute of the object to passed as argument to the search_function. If this is None, the object itself is used.
- Returns
a new list of objects which match the query
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model('textbook') >>> model.reactions.query(lambda x: x.boundary) >>> import re >>> regex = re.compile('^g', flags=re.IGNORECASE) >>> model.metabolites.query(regex, attribute='name')
-
_replace_on_id
(self, new_object)¶ Replace an object by another with the same id.
-
append
(self, object)¶ append object to end
-
union
(self, iterable)¶ adds elements with id’s not already in the model
-
extend
(self, iterable)¶ extend list by appending elements from the iterable
-
_extend_nocheck
(self, iterable)¶ extends without checking for uniqueness
This function should only be used internally by DictList when it can guarantee elements are already unique (as in when coming from self or other DictList). It will be faster because it skips these checks.
-
__sub__
(self, other)¶ x.__sub__(y) <==> x - y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__isub__
(self, other)¶ x.__sub__(y) <==> x -= y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__add__
(self, other)¶ x.__add__(y) <==> x + y
- Parameters
other (iterable) – other must contain only unique id’s which do not intersect with self
-
__iadd__
(self, other)¶ x.__iadd__(y) <==> x += y
- Parameters
other (iterable) – other must contain only unique id’s whcih do not intersect with self
-
__reduce__
(self)¶ Helper for pickle.
-
__getstate__
(self)¶ gets internal state
This is only provided for backwards compatibility so older versions of cobrapy can load pickles generated with cobrapy. In reality, the “_dict” state is ignored when loading a pickle
-
__setstate__
(self, state)¶ sets internal state
Ignore the passed in state and recalculate it. This is only for compatibility with older pickles which did not correctly specify the initialization class
-
index
(self, id, *args)¶ Determine the position in the list
id: A string or a
Object
-
__contains__
(self, object)¶ DictList.__contains__(object) <==> object in DictList
object: str or
Object
-
__copy__
(self)¶
-
insert
(self, index, object)¶ insert object before index
-
pop
(self, *args)¶ remove and return item at index (default last).
-
add
(self, x)¶ Opposite of remove. Mirrors set.add
-
remove
(self, x)¶ Warning
Internal use only
-
reverse
(self)¶ reverse IN PLACE
-
sort
(self, cmp=None, key=None, reverse=False)¶ stable sort IN PLACE
cmp(x, y) -> -1, 0, 1
-
__getitem__
(self, i)¶ x.__getitem__(y) <==> x[y]
-
__setitem__
(self, i, y)¶ Set self[key] to value.
-
__delitem__
(self, index)¶ Delete self[key].
-
__getslice__
(self, i, j)¶
-
__setslice__
(self, i, j, y)¶
-
__delslice__
(self, i, j)¶
-
__getattr__
(self, attr)¶
-
__dir__
(self)¶ Default dir() implementation.
-
-
class
cobra.core.
Gene
(id=None, name='', functional=True)[source]¶ Bases:
cobra.core.species.Species
A Gene in a cobra model
- Parameters
id (string) – The identifier to associate the gene with
name (string) – A longer human readable name for the gene
functional (bool) – Indicates whether the gene is functional. If it is not functional then it cannot be used in an enzyme complex nor can its products be used.
-
property
functional
(self)¶ A flag indicating if the gene is functional.
Changing the flag is reverted upon exit if executed within the model as context.
-
knock_out
(self)¶ Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as context.
-
remove_from_model
(self, model=None, make_dependent_reactions_nonfunctional=True)¶ Removes the association
- Parameters
model (cobra model) – The model to remove the gene from
make_dependent_reactions_nonfunctional (bool) – If True then replace the gene with ‘False’ in the gene association, else replace the gene with ‘True’
Deprecated since version 0.4: Use cobra.manipulation.delete_model_genes to simulate knockouts and cobra.manipulation.remove_genes to remove genes from the model.
-
_repr_html_
(self)¶
-
class
cobra.core.
Metabolite
(id=None, formula=None, name='', charge=None, compartment=None)[source]¶ Bases:
cobra.core.species.Species
Metabolite is a class for holding information regarding a metabolite in a cobra.Reaction object.
- Parameters
-
_set_id_with_model
(self, value)¶
-
property
constraint
(self)¶ Get the constraints associated with this metabolite from the solve
- Returns
the optlang constraint for this metabolite
- Return type
optlang.<interface>.Constraint
-
property
elements
(self)¶ Dictionary of elements as keys and their count in the metabolite as integer. When set, the formula property is update accordingly
-
property
formula_weight
(self)¶ Calculate the formula weight
-
property
y
(self)¶ The shadow price for the metabolite in the most recent solution
Shadow prices are computed from the dual values of the bounds in the solution.
-
property
shadow_price
(self)¶ The shadow price in the most recent solution.
Shadow price is the dual value of the corresponding constraint in the model.
Warning
Accessing shadow prices through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Shadow price is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the metabolite is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra >>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.metabolites.glc__D_e.shadow_price -0.09166474637510488 >>> solution.shadow_prices.glc__D_e -0.091664746375104883
-
remove_from_model
(self, destructive=False)¶ Removes the association from self.model
The change is reverted upon exit when using the model as a context.
- Parameters
destructive (bool) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model.
-
summary
(self, solution=None, fva=None)¶ Create a summary of the producing and consuming fluxes.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
See also
-
_repr_html_
(self)¶
-
class
cobra.core.
Model
(id_or_model=None, name=None)[source]¶ Bases:
cobra.core.object.Object
Class representation for a cobra model
- Parameters
id_or_model (Model, string) – Either an existing Model object in which case a new model object is instantiated with the same properties as the original model, or an identifier to associate with the model as a string.
name (string) – Human readable name for the model
-
reactions
¶ A DictList where the key is the reaction identifier and the value a Reaction
- Type
-
metabolites
¶ A DictList where the key is the metabolite identifier and the value a Metabolite
- Type
-
__setstate__
(self, state)¶ Make sure all cobra.Objects in the model point to the model.
-
__getstate__
(self)¶ Get state for serialization.
Ensures that the context stack is cleared prior to serialization, since partial functions cannot be pickled reliably.
-
property
solver
(self)¶ Get or set the attached solver instance.
The associated the solver object, which manages the interaction with the associated solver, e.g. glpk.
This property is useful for accessing the optimization problem directly and to define additional non-metabolic constraints.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> new = model.problem.Constraint(model.objective.expression, >>> lb=0.99) >>> model.solver.add(new)
-
property
tolerance
(self)¶
-
property
description
(self)¶
-
get_metabolite_compartments
(self)¶ Return all metabolites’ compartments.
-
property
compartments
(self)¶
-
property
medium
(self)¶
-
__add__
(self, other_model)¶ Add the content of another model to this model (+).
The model is copied as a new object, with a new model identifier, and copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
__iadd__
(self, other_model)¶ Incrementally add the content of another model to this model (+=).
Copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
copy
(self)¶ Provides a partial ‘deepcopy’ of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy
-
add_metabolites
(self, metabolite_list)¶ Will add a list of metabolites to the model object and add new constraints accordingly.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolite_list (A list of cobra.core.Metabolite objects) –
-
remove_metabolites
(self, metabolite_list, destructive=False)¶ Remove a list of metabolites from the the object.
The change is reverted upon exit when using the model as a context.
-
add_reaction
(self, reaction)¶ Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions.
- Parameters
reaction (cobra.Reaction) – The reaction to add
(0.6) Use ~cobra.Model.add_reactions instead (Deprecated) –
-
add_boundary
(self, metabolite, type='exchange', reaction_id=None, lb=None, ub=None, sbo_term=None)¶ Add a boundary reaction for a given metabolite.
There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, unbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites, i.e., a reversible reaction that adds or removes an intracellular metabolite.
If you set the reaction type to something else, you must specify the desired identifier of the created reaction along with its upper and lower bound. The name will be given by the metabolite name and the given type.
- Parameters
metabolite (cobra.Metabolite) – Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks.
type (str, {"exchange", "demand", "sink"}) – Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., ‘my-boundary’.
reaction_id (str, optional) – The ID of the resulting reaction. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using model.boundary or specifically model.exchanges etc.
lb (float, optional) – The lower bound of the resulting reaction.
ub (float, optional) – The upper bound of the resulting reaction.
sbo_term (str, optional) – A correct SBO term is set for the available types. If a custom type is chosen, a suitable SBO term should also be set.
- Returns
The created boundary reaction.
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> demand = model.add_boundary(model.metabolites.atp_c, type="demand") >>> demand.id 'DM_atp_c' >>> demand.name 'ATP demand' >>> demand.bounds (0, 1000.0) >>> demand.build_reaction_string() 'atp_c --> '
-
add_reactions
(self, reaction_list)¶ Add reactions to the model.
Reactions with identifiers identical to a reaction already in the model are ignored.
The change is reverted upon exit when using the model as a context.
- Parameters
reaction_list (list) – A list of cobra.Reaction objects
-
remove_reactions
(self, reactions, remove_orphans=False)¶ Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
-
add_groups
(self, group_list)¶ Add groups to the model.
Groups with identifiers identical to a group already in the model are ignored.
If any group contains members that are not in the model, these members are added to the model as well. Only metabolites, reactions, and genes can have groups.
- Parameters
group_list (list) – A list of cobra.Group objects to add to the model.
-
remove_groups
(self, group_list)¶ Remove groups from the model.
Members of each group are not removed from the model (i.e. metabolites, reactions, and genes in the group stay in the model after any groups containing them are removed).
- Parameters
group_list (list) – A list of cobra.Group objects to remove from the model.
-
get_associated_groups
(self, element)¶ Returns a list of groups that an element (reaction, metabolite, gene) is associated with.
- Parameters
element (cobra.Reaction, cobra.Metabolite, or cobra.Gene) –
- Returns
All groups that the provided object is a member of
- Return type
list of cobra.Group
-
add_cons_vars
(self, what, **kwargs)¶ Add constraints and variables to the model’s mathematical problem.
Useful for variables and constraints that can not be expressed with reactions and simple lower and upper bounds.
Additions are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
**kwargs (keyword arguments) – Passed to solver.add()
-
remove_cons_vars
(self, what)¶ Remove variables and constraints from the model’s mathematical problem.
Remove variables and constraints that were added directly to the model’s underlying mathematical problem. Removals are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
-
property
problem
(self)¶ The interface to the model’s underlying mathematical problem.
Solutions to cobra models are obtained by formulating a mathematical problem and solving it. Cobrapy uses the optlang package to accomplish that and with this property you can get access to the problem interface directly.
- Returns
The problem interface that defines methods for interacting with the problem and associated solver directly.
- Return type
optlang.interface
-
property
variables
(self)¶ The mathematical variables in the cobra model.
In a cobra model, most variables are reactions. However, for specific use cases, it may also be useful to have other types of variables. This property defines all variables currently associated with the model’s problem.
- Returns
A container with all associated variables.
- Return type
optlang.container.Container
-
property
constraints
(self)¶ The constraints in the cobra model.
In a cobra model, most constraints are metabolites and their stoichiometries. However, for specific use cases, it may also be useful to have other types of constraints. This property defines all constraints currently associated with the model’s problem.
- Returns
A container with all associated constraints.
- Return type
optlang.container.Container
-
property
boundary
(self)¶ Boundary reactions in the model. Reactions that either have no substrate or product.
-
property
exchanges
(self)¶ Exchange reactions in model. Reactions that exchange mass with the exterior. Uses annotations and heuristics to exclude non-exchanges such as sink reactions.
-
property
demands
(self)¶ Demand reactions in model. Irreversible reactions that accumulate or consume a metabolite in the inside of the model.
-
property
sinks
(self)¶ Sink reactions in model. Reversible reactions that accumulate or consume a metabolite in the inside of the model.
-
_populate_solver
(self, reaction_list, metabolite_list=None)¶ Populate attached solver with constraints and variables that model the provided reactions.
-
slim_optimize
(self, error_value=float('nan'), message=None)¶ Optimize model without creating a solution object.
Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and in cases where only one or two values are of interest, it is recommended to instead use this function which does not create a solution object returning only the value of the objective. Note however that the optimize() function uses efficient means to fetch values so if you need fluxes/shadow prices for more than say 4 reactions/metabolites, then the total speed increase of slim_optimize versus optimize is expected to be small or even negative depending on how you fetch the values after optimization.
-
optimize
(self, objective_sense=None, raise_error=False)¶ Optimize the model using flux balance analysis.
- Parameters
objective_sense ({None, 'maximize' 'minimize'}, optional) – Whether fluxes should be maximized or minimized. In case of None, the previous direction is used.
raise_error (bool) –
- If true, raise an OptimizationError if solver status is not
optimal.
Notes
Only the most commonly used parameters are presented here. Additional parameters for cobra.solvers may be available and specified with the appropriate keyword argument.
-
repair
(self, rebuild_index=True, rebuild_relationships=True)¶ Update all indexes and pointers in a model
-
property
objective
(self)¶ Get or set the solver objective
Before introduction of the optlang based problems, this function returned the objective reactions as a list. With optlang, the objective is not limited a simple linear summation of individual reaction fluxes, making that return value ambiguous. Henceforth, use cobra.util.solver.linear_reaction_coefficients to get a dictionary of reactions with their linear coefficients (empty if there are none)
The set value can be dictionary (reactions as keys, linear coefficients as values), string (reaction identifier), int (reaction index), Reaction or problem.Objective or sympy expression directly interpreted as objectives.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
objective_direction
(self)¶ Get or set the objective direction.
When using a HistoryManager context, this attribute can be set temporarily, reversed when exiting the context.
-
summary
(self, solution=None, fva=None)¶ Create a summary of the exchange fluxes of the model.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.ModelSummary
See also
-
__enter__
(self)¶ Record all future changes to the model, undoing them when a call to __exit__ is received
-
__exit__
(self, type, value, traceback)¶ Pop the top context manager and trigger the undo functions
-
merge
(self, right, prefix_existing=None, inplace=True, objective='left')¶ Merge two models to create a model with the reactions from both models.
Custom constraints and variables from right models are also copied to left model, however note that, constraints and variables are assumed to be the same if they have the same name.
- rightcobra.Model
The model to add reactions from
- prefix_existingstring
Prefix the reaction identifier in the right that already exist in the left model with this string.
- inplacebool
Add reactions from right directly to left model object. Otherwise, create a new model leaving the left model untouched. When done within the model as context, changes to the models are reverted upon exit.
- objectivestring
One of ‘left’, ‘right’ or ‘sum’ for setting the objective of the resulting model to that of the corresponding model or the sum of both.
-
_repr_html_
(self)¶
-
class
cobra.core.
Object
(id=None, name='')[source]¶ Bases:
object
Defines common behavior of object in cobra.core
-
property
id
(self)¶
-
_set_id_with_model
(self, value)¶
-
property
annotation
(self)¶
-
__getstate__
(self)¶ To prevent excessive replication during deepcopy.
-
__repr__
(self)¶ Return repr(self).
-
__str__
(self)¶ Return str(self).
-
property
-
class
cobra.core.
Reaction
(id=None, name='', subsystem='', lower_bound=0.0, upper_bound=None)[source]¶ Bases:
cobra.core.object.Object
Reaction is a class for holding information regarding a biochemical reaction in a cobra.Model object.
Reactions are by default irreversible with bounds (0.0, cobra.Configuration().upper_bound) if no bounds are provided on creation. To create an irreversible reaction use lower_bound=None, resulting in reaction bounds of (cobra.Configuration().lower_bound, cobra.Configuration().upper_bound).
- Parameters
-
__radd__
¶
-
_set_id_with_model
(self, value)¶
-
property
reverse_id
(self)¶ Generate the id of reverse_variable from the reaction’s id.
-
property
flux_expression
(self)¶ Forward flux expression
- Returns
The expression representing the the forward flux (if associated with model), otherwise None. Representing the net flux if model.reversible_encoding == ‘unsplit’ or None if reaction is not associated with a model
- Return type
sympy expression
-
property
forward_variable
(self)¶ An optlang variable representing the forward flux
- Returns
An optlang variable for the forward flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
reverse_variable
(self)¶ An optlang variable representing the reverse flux
- Returns
An optlang variable for the reverse flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
objective_coefficient
(self)¶ Get the coefficient for this reaction in a linear objective (float)
Assuming that the objective of the associated model is summation of fluxes from a set of reactions, the coefficient for each reaction can be obtained individually using this property. A more general way is to use the model.objective property directly.
-
__copy__
(self)¶
-
__deepcopy__
(self, memo)¶
-
static
_check_bounds
(lb, ub)¶
-
update_variable_bounds
(self)¶
-
property
lower_bound
(self)¶ Get or set the lower bound
Setting the lower bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a lower bound higher than the current upper bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
upper_bound
(self)¶ Get or set the upper bound
Setting the upper bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a upper bound lower than the current lower bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
bounds
(self)¶ Get or set the bounds directly from a tuple
Convenience method for setting upper and lower bounds in one line using a tuple of lower and upper bound. Invalid bounds will raise an AssertionError.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
flux
(self)¶ The flux value in the most recent solution.
Flux is the primal value of the corresponding variable in the model.
Warning
Accessing reaction fluxes through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reaction flux is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
AssertionError – If the flux value is not within the bounds.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.flux 7.477381962160283 >>> solution.fluxes.PFK 7.4773819621602833
-
property
reduced_cost
(self)¶ The reduced cost in the most recent solution.
Reduced cost is the dual value of the corresponding variable in the model.
Warning
Accessing reduced costs through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reduced cost is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.reduced_cost -8.673617379884035e-18 >>> solution.reduced_costs.PFK -8.6736173798840355e-18
-
property
metabolites
(self)¶
-
property
genes
(self)¶
-
property
gene_reaction_rule
(self)¶
-
property
gene_name_reaction_rule
(self)¶ Display gene_reaction_rule with names intead.
Do NOT use this string for computation. It is intended to give a representation of the rule using more familiar gene names instead of the often cryptic ids.
-
property
functional
(self)¶ All required enzymes for reaction are functional.
- Returns
True if the gene-protein-reaction (GPR) rule is fulfilled for this reaction, or if reaction is not associated to a model, otherwise False.
- Return type
-
property
x
(self)¶ The flux through the reaction in the most recent solution.
Flux values are computed from the primal values of the variables in the solution.
-
property
y
(self)¶ The reduced cost of the reaction in the most recent solution.
Reduced costs are computed from the dual values of the variables in the solution.
-
property
reversibility
(self)¶ Whether the reaction can proceed in both directions (reversible)
This is computed from the current upper and lower bounds.
-
property
boundary
(self)¶ Whether or not this reaction is an exchange reaction.
Returns True if the reaction has either no products or reactants.
-
property
model
(self)¶ returns the model the reaction is a part of
-
_update_awareness
(self)¶ Make sure all metabolites and genes that are associated with this reaction are aware of it.
-
remove_from_model
(self, remove_orphans=False)¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
delete
(self, remove_orphans=False)¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Deprecated, use reaction.remove_from_model instead.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
__setstate__
(self, state)¶ Probably not necessary to set _model as the cobra.Model that contains self sets the _model attribute for all metabolites and genes in the reaction.
However, to increase performance speed we do want to let the metabolite and gene know that they are employed in this reaction
-
copy
(self)¶ Copy a reaction
The referenced metabolites and genes are also copied.
-
__add__
(self, other)¶ Add two reactions
The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction
-
__iadd__
(self, other)¶
-
__sub__
(self, other)¶
-
__isub__
(self, other)¶
-
__imul__
(self, coefficient)¶ Scale coefficients in a reaction by a given value
E.g. A -> B becomes 2A -> 2B.
If coefficient is less than zero, the reaction is reversed and the bounds are swapped.
-
__mul__
(self, coefficient)¶
-
property
reactants
(self)¶ Return a list of reactants for the reaction.
-
property
products
(self)¶ Return a list of products for the reaction
-
get_coefficient
(self, metabolite_id)¶ Return the stoichiometric coefficient of a metabolite.
- Parameters
metabolite_id (str or cobra.Metabolite) –
-
get_coefficients
(self, metabolite_ids)¶ Return the stoichiometric coefficients for a list of metabolites.
- Parameters
metabolite_ids (iterable) – Containing
str
or ``cobra.Metabolite``s.
-
add_metabolites
(self, metabolites_to_add, combine=True, reversibly=True)¶ Add metabolites and stoichiometric coefficients to the reaction. If the final coefficient for a metabolite is 0 then it is removed from the reaction.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites_to_add (dict) – Dictionary with metabolite objects or metabolite identifiers as keys and coefficients as values. If keys are strings (name of a metabolite) the reaction must already be part of a model and a metabolite with the given name must exist in the model.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
subtract_metabolites
(self, metabolites, combine=True, reversibly=True)¶ Subtract metabolites from a reaction.
That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction.
Notes
A final coefficient < 0 implies a reactant.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites (dict) – Dictionary where the keys are of class Metabolite and the values are the coefficients. These metabolites will be added to the reaction.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
property
reaction
(self)¶ Human readable reaction string
-
build_reaction_string
(self, use_metabolite_names=False)¶ Generate a human readable reaction string
-
check_mass_balance
(self)¶ Compute mass and charge balance for the reaction
returns a dict of {element: amount} for unbalanced elements. “charge” is treated as an element in this dict This should be empty for balanced reactions.
-
property
compartments
(self)¶ lists compartments the metabolites are in
-
get_compartments
(self)¶ lists compartments the metabolites are in
-
_associate_gene
(self, cobra_gene)¶ Associates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
_dissociate_gene
(self, cobra_gene)¶ Dissociates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
knock_out
(self)¶ Knockout reaction by setting its bounds to zero.
-
build_reaction_from_string
(self, reaction_str, verbose=True, fwd_arrow=None, rev_arrow=None, reversible_arrow=None, term_split='+')¶ Builds reaction from reaction equation reaction_str using parser
Takes a string and using the specifications supplied in the optional arguments infers a set of metabolites, metabolite compartments and stoichiometries for the reaction. It also infers the reversibility of the reaction from the reaction arrow.
Changes to the associated model are reverted upon exit when using the model as a context.
- Parameters
reaction_str (string) – a string containing a reaction formula (equation)
verbose (bool) – setting verbosity of function
fwd_arrow (re.compile) – for forward irreversible reaction arrows
rev_arrow (re.compile) – for backward irreversible reaction arrows
reversible_arrow (re.compile) – for reversible reaction arrows
term_split (string) – dividing individual metabolite entries
-
summary
(self, solution=None, fva=None)¶ Create a summary of the reaction flux.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.summary.ReactionSummary
See also
-
__str__
(self)¶ Return str(self).
-
_repr_html_
(self)¶
-
class
cobra.core.
Group
(id, name='', members=None, kind=None)[source]¶ Bases:
cobra.core.object.Object
Manage groups via this implementation of the SBML group specification.
Group is a class for holding information regarding a pathways, subsystems, or other custom groupings of objects within a cobra.Model object.
- Parameters
id (str) – The identifier to associate with this group
name (str, optional) – A human readable name for the group
members (iterable, optional) – A DictList containing references to cobra.Model-associated objects that belong to the group.
kind ({"collection", "classification", "partonomy"}, optional) – The kind of group, as specified for the Groups feature in the SBML level 3 package specification. Can be any of “classification”, “partonomy”, or “collection”. The default is “collection”. Please consult the SBML level 3 package specification to ensure you are using the proper value for kind. In short, members of a “classification” group should have an “is-a” relationship to the group (e.g. member is-a polar compound, or member is-a transporter). Members of a “partonomy” group should have a “part-of” relationship (e.g. member is part-of glycolysis). Members of a “collection” group do not have an implied relationship between the members, so use this value for kind when in doubt (e.g. member is a gap-filled reaction, or member is involved in a disease phenotype).
-
KIND_TYPES
= ['collection', 'classification', 'partonomy']¶
-
__len__
(self)¶
-
property
members
(self)¶
-
property
kind
(self)¶
-
class
cobra.core.
Solution
(objective_value, status, fluxes, reduced_costs=None, shadow_prices=None, **kwargs)[source]¶ Bases:
object
A unified interface to a cobra.Model optimization solution.
Notes
Solution is meant to be constructed by get_solution please look at that function to fully understand the Solution class.
-
fluxes
¶ Contains the reaction fluxes (primal values of variables).
- Type
pandas.Series
-
reduced_costs
¶ Contains reaction reduced costs (dual values of variables).
- Type
pandas.Series
-
shadow_prices
¶ Contains metabolite shadow prices (dual values of constraints).
- Type
pandas.Series
-
get_primal_by_id
¶
-
__repr__
(self)¶ String representation of the solution instance.
-
_repr_html_
(self)¶
-
__getitem__
(self, reaction_id)¶ Return the flux of a reaction.
- Parameters
reaction (str) – A model reaction ID.
-
to_frame
(self)¶ Return the fluxes and reduced costs as a data frame
-
-
class
cobra.core.
LegacySolution
(f, x=None, x_dict=None, y=None, y_dict=None, solver=None, the_time=0, status='NA', **kwargs)[source]¶ Bases:
object
Legacy support for an interface to a cobra.Model optimization solution.
-
x
¶ List or Array of the fluxes (primal values).
- Type
iterable
-
y
¶ List or Array of the dual values.
- Type
iterable
Warning
The LegacySolution class and its interface is deprecated.
-
__repr__
(self)¶ String representation of the solution instance.
-
__getitem__
(self, reaction_id)¶ Return the flux of a reaction.
- Parameters
reaction_id (str) – A reaction ID.
-
dress_results
(self, model)¶ Method could be intended as a decorator.
Warning
deprecated
-
-
cobra.core.
get_solution
(model, reactions=None, metabolites=None, raise_error=False)[source]¶ Generate a solution representation of the current solver state.
- Parameters
model (cobra.Model) – The model whose reactions to retrieve values for.
reactions (list, optional) – An iterable of cobra.Reaction objects. Uses model.reactions by default.
metabolites (list, optional) – An iterable of cobra.Metabolite objects. Uses model.metabolites by default.
raise_error (bool) – If true, raise an OptimizationError if solver status is not optimal.
- Returns
- Return type
Note
This is only intended for the optlang solver interfaces and not the legacy solvers.
-
class
cobra.core.
Species
(id=None, name=None)[source]¶ Bases:
cobra.core.object.Object
Species is a class for holding information regarding a chemical Species
- Parameters
id (string) – An identifier for the chemical species
name (string) – A human readable name.
-
property
reactions
(self)¶
-
__getstate__
(self)¶ Remove the references to container reactions when serializing to avoid problems associated with recursion.
-
copy
(self)¶ When copying a reaction, it is necessary to deepcopy the components so the list references aren’t carried over.
Additionally, a copy of a reaction is no longer in a cobra.Model.
This should be fixed with self.__deepcopy__ if possible
-
property
model
(self)¶
cobra.flux_analysis
¶
Submodules¶
cobra.flux_analysis.deletion
¶Provide functions for reaction and gene deletions.
Access unique combinations of reactions in deletion results. |
|
Return the growth from the model. |
|
Perform reaction deletion. |
|
Perform reaction deletions on worker process. |
|
Perform gene deletions. |
|
Perform gene deletions on worker process. |
|
Initialize worker process. |
|
Provide a common interface for single or multiple knockouts. |
|
Return the IDs of the entities. |
|
Return the elements. |
|
Knock out each reaction from reaction_list. |
|
Knock out each gene from gene_list. |
|
Knock out each reaction pair from the combinations of two given lists. |
|
Knock out each gene pair from the combination of two given lists. |
-
cobra.flux_analysis.deletion.
_get_growth
(model: Model) → Tuple[float, str][source]¶ Return the growth from the model.
- Parameters
model (cobra.Model) – The model to obtain growth for.
- Returns
The obtained growth value. Returns nan if there is some error while optimizing.
- Return type
-
cobra.flux_analysis.deletion.
_reaction_deletion
(model: Model, reaction_ids: List[str]) → Tuple[List[str], float, str][source]¶ Perform reaction deletion.
- Parameters
model (cobra.Model) – The model to perform reaction deletion on.
ids (list of str) – The reaction IDs to knock-out.
- Returns
A tuple containing reaction IDs knocked out, growth of the model and the solver status.
- Return type
-
cobra.flux_analysis.deletion.
_reaction_deletion_worker
(ids: List[str]) → Tuple[List[str], float, str][source]¶ Perform reaction deletions on worker process.
-
cobra.flux_analysis.deletion.
_gene_deletion
(model: Model, gene_ids: List[str]) → Tuple[List[str], float, str][source]¶ Perform gene deletions.
- Parameters
model (cobra.Model) – The model to perform gene deletion on.
ids (list of str) – The gene IDs to knock-out.
- Returns
A tuple containing gene IDs knocked out, growth of the model and the solver status.
- Return type
-
cobra.flux_analysis.deletion.
_gene_deletion_worker
(ids: List[str]) → Tuple[List[str], float, str][source]¶ Perform gene deletions on worker process.
-
cobra.flux_analysis.deletion.
_multi_deletion
(model: Model, entity: str, element_lists: List[Union[Gene, Reaction]], method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Provide a common interface for single or multiple knockouts.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
entity ({"gene", "reaction"}) – The entity to knockout.
element_lists (list of cobra.Gene or cobra.Reaction) – List of cobra.Gene or cobra.Reaction to be deleted.
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Passed on to underlying simulation functions.
- Returns
A representation of all combinations of entity deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The gene or reaction identifiers that were knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.deletion.
_entities_ids
(entities: List[Union[str, Gene, Reaction]]) → List[str][source]¶ Return the IDs of the entities.
- Parameters
entities (list of str or cobra.Gene or cobra.Reaction) – The list of entities whose IDs need to be returned.
- Returns
The IDs of the entities.
- Return type
list of str
-
cobra.flux_analysis.deletion.
_element_lists
(entities: List[Union[str, Gene, Reaction]], *ids: List[str]) → List[str][source]¶ Return the elements.
- Parameters
entities (list of str or cobra.Gene or cobra.Reaction) – The list of entities.
*ids (list of str) – The list of IDs.
- Returns
The list of IDs.
- Return type
list of str
-
cobra.flux_analysis.deletion.
single_reaction_deletion
(model: Model, reaction_list: Optional[List[Union[Reaction, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each reaction from reaction_list.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
reaction_list (list of cobra.Reaction or str, optional) – The reactions be knocked out. If not passed, all the reactions from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all single reaction deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The reaction identifier that was knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.deletion.
single_gene_deletion
(model: Model, gene_list: Optional[List[Union[Gene, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each gene from gene_list.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
gene_list (list of cobra.Gene or str, optional) – The gene objects to be deleted. If not passed, all the genes from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all single gene deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The gene identifier that was knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.deletion.
double_reaction_deletion
(model: Model, reaction_list1: Optional[List[Union[Reaction, str]]] = None, reaction_list2: Optional[List[Union[Reaction, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each reaction pair from the combinations of two given lists.
We say ‘pair’ here but the order order does not matter.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
reaction_list1 (list of cobra.Reaction or str, optional) – The first reaction list to be deleted. If not passed, all the reactions from the model are used (default None).
reaction_list2 (list of cobra.Reaction or str, optional) – The second reaction list to be deleted. If not passed, all the reactions from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all combinations of reaction deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The reaction identifiers that were knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.deletion.
double_gene_deletion
(model: Model, gene_list1: Optional[List[Union[Gene, str]]] = None, gene_list2: Optional[List[Union[Gene, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each gene pair from the combination of two given lists.
We say ‘pair’ here but the order order does not matter.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
gene_list1 (list of cobra.Gene or str, optional) – The first gene list to be deleted. If not passed, all the genes from the model are used (default None).
gene_list2 (list of cobra.Gene or str, optional) – The second gene list to be deleted. If not passed, all the genes from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default None).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all combinations of gene deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The gene identifiers that were knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
class
cobra.flux_analysis.deletion.
KnockoutAccessor
(pandas_obj: Union[pd.DataFrame, pd.Series])[source]¶ Access unique combinations of reactions in deletion results.
This allows acces in the form of results.knockout[rxn1] or results.knockout[“rxn1_id”]. Each individual entry will return a deletion so results.knockout[rxn1, rxn2] will return two deletions (for individual knockouts of rxn1 and rxn2 respectively). Multi-deletions can be accessed by passing in sets like results.knockout[{rxn1, rxn2}] which denotes the double deletion of both reactions. Thus, the following are allowed index elements:
single reactions or genes (depending on whether it is a gene or reaction deletion)
single reaction IDs or gene IDs
lists of single single reaction IDs or gene IDs (will return one row for each element in the list)
sets of reactions or genes (for multi-deletions)
sets of reactions IDs or gene IDs
list of sets of objects or IDs (to get several multi-deletions)
- pandas_objpandas.DataFrame or pandas.Series
A result from one of the deletion methods.
-
static
_validate
(obj: pd.DataFrame) → None[source]¶ Validate the object given.
- Parameters
obj (pandas.DataFrame) – The object to validate.
- Raises
AttributeError – If the object supplied is not a DataFrame.
-
__getitem__
(self, args: Union[Gene, List[Gene], Set[Gene], List[Set[Gene]], Reaction, List[Reaction], Set[Reaction], List[Set[Reaction]], str, List[str], Set[str], List[Set[str]]]) → pd.DataFrame[source]¶ Return the deletion result for a particular set of knocked entities.
- Parameters
args (cobra.Reaction, cobra.Gene, str, set, or list) – The deletions to be returned. Accepts: - single reactions or genes - single reaction IDs or gene IDs - lists of single single reaction IDs or gene IDs - sets of reactions or genes - sets of reactions IDs or gene IDs - list of sets of objects or IDs See the docs for usage examples.
- Returns
The deletion result where the chosen entities have been deleted. Each row denotes a deletion.
- Return type
pandas.DataFrame
- Raises
ValueError – If any other object is used as index for lookup.
cobra.flux_analysis.fastcc
¶Provide an implementation of FASTCC.
|
Perform the LP required for FASTCC. |
|
Flip the coefficients for optimizing in reverse direction. |
|
Check consistency of a metabolic network using FASTCC 1. |
-
cobra.flux_analysis.fastcc.
_find_sparse_mode
(model: Model, rxns: List['Reaction'], flux_threshold: float, zero_cutoff: float) → List['Reaction'][source]¶ Perform the LP required for FASTCC.
- Parameters
model (cobra.Model) – The model to perform FASTCC on.
rxns (list of cobra.Reaction) – The reactions to use for LP.
flux_threshold (float) – The upper threshold an auxiliary variable can have.
zero_cutoff (float) – The cutoff below which flux is considered zero.
- Returns
The list of reactions to consider as consistent.
- Return type
list of cobra.Reaction
-
cobra.flux_analysis.fastcc.
_flip_coefficients
(model: Model, rxns: List['Reaction']) → None[source]¶ Flip the coefficients for optimizing in reverse direction.
- Parameters
model (cobra.Model) – The model to operate on.
rxns (list of cobra.Reaction) – The list of reactions whose coefficients will be flipped.
-
cobra.flux_analysis.fastcc.
fastcc
(model: Model, flux_threshold: float = 1.0, zero_cutoff: Optional[float] = None) → 'Model'[source]¶ Check consistency of a metabolic network using FASTCC 1.
FASTCC (Fast Consistency Check) is an algorithm for rapid and efficient consistency check in metabolic networks. FASTCC is a pure LP implementation and is low on computation resource demand. FASTCC also circumvents the problem associated with reversible reactions for the purpose. Given a global model, it will generate a consistent global model i.e., remove blocked reactions. For more details on FASTCC, please check 1.
- Parameters
model (cobra.Model) – The model to operate on.
flux_threshold (float, optional) – The flux threshold to consider (default 1.0).
zero_cutoff (float, optional) – The cutoff to consider for zero flux (default model.tolerance).
- Returns
The consistent model.
- Return type
Notes
The LP used for FASTCC is like so: maximize: sum_{i in J} z_i s.t. : z_i in [0, varepsilon] forall i in J, z_i in mathbb{R}_+
v_i ge z_i forall i in J Sv = 0 v in B
References
cobra.flux_analysis.gapfilling
¶Provide the base class and utility function for gap filling.
The base class for performing gap filling. |
|
Perform gap filling on a model. |
-
class
cobra.flux_analysis.gapfilling.
GapFiller
(model: Model, universal: Optional[Model] = None, lower_bound: float = 0.05, penalties: Optional[Dict[str, 'Reaction']] = None, exchange_reactions: bool = False, demand_reactions: bool = True, integer_threshold: float = 1e-06, **kwargs)[source]¶ The base class for performing gap filling.
This class implements gap filling based on a mixed-integer approach, very similar to that described in 1 and the ‘no-growth but growth’ part of 2 but with minor adjustments. In short, we add indicator variables for using the reactions in the universal model, z_i and then solve problem
minimize: sum_i c_i * z_i s.t. : Sv = 0
v_o ge t lb_i le v_i le ub_i v_i = 0 if z_i = 0
where lb, ub are respectively the upper, lower flux bounds for reaction i, c_i is a cost parameter and the objective v_o is greater than the lower bound t. The default costs are 1 for reactions from the universal model, 100 for exchange (uptake) reactions added and 1 for added demand reactions.
Note that this is a mixed-integer linear program and as such will be expensive to solve for large models. Consider using alternatives 3 such as CORDA instead [4,5]_ .
- Parameters
model (cobra.Model) – The model to perform gap filling on.
universal (cobra.Model, optional) – A universal model with reactions that can be used to complete the model (default None).
lower_bound (float, optional) – The minimally accepted flux for the objective in the filled model (default 0.05).
penalties (dict, optional) – A dictionary with keys being ‘universal’ (all reactions included in the universal model), ‘exchange’ and ‘demand’ (all additionally added exchange and demand reactions) for the three reaction types. Can also have reaction identifiers for reaction specific costs. Defaults are 1, 100 and 1 respectively (default None).
exchange_reactions (bool, optional) – Consider adding exchange (uptake) reactions for all metabolites in the model (default False).
demand_reactions (bool, optional) – Consider adding demand reactions for all metabolites (default True).
integer_threshold (float, optional) – The threshold at which a value is considered non-zero (aka integrality threshold). If gapfilled models fail to validate, you may want to lower this value (default 1E-6).
-
indicators
¶ The list of symbolic indicator variables.
- Type
list of optlang.interface.Variable
-
costs
¶ The dictionary with symbolic variables as keys and their cost as values.
- Type
dict of {optlang.interface.Variable: float}
References
- 1
Reed, Jennifer L., Trina R. Patel, Keri H. Chen, Andrew R. Joyce, Margaret K. Applebee, Christopher D. Herring, Olivia T. Bui, Eric M. Knight, Stephen S. Fong, and Bernhard O. Palsson. “Systems Approach to Refining Genome Annotation.” Proceedings of the National Academy of Sciences 103, no. 46 (2006): 17480–17484.
- 2
Kumar, Vinay Satish, and Costas D. Maranas. “GrowMatch: An Automated Method for Reconciling In Silico/In Vivo Growth Predictions.” Edited by Christos A. Ouzounis. PLoS Computational Biology 5, no. 3 (March 13, 2009): e1000308. doi:10.1371/journal.pcbi.1000308.
- 3
- 4
Schultz, André, and Amina A. Qutub. “Reconstruction of Tissue-Specific Metabolic Networks Using CORDA.” Edited by Costas D. Maranas. PLOS Computational Biology 12, no. 3 (March 4, 2016): e1004808. doi:10.1371/journal.pcbi.1004808.
- 5
Diener, Christian https://github.com/cdiener/corda
-
extend_model
(self, exchange_reactions: bool = False, demand_reactions: bool = True) → None[source]¶ Extend gap filling model.
Add reactions from universal model and optionally exchange and demand reactions for all metabolites in the model to perform gap filling on.
-
update_costs
(self) → None[source]¶ Update coefficients for the indicator variables in the objective.
Done incrementally so that second time the function is called, active indicators in the current solutions gets higher cost than the unused indicators.
-
add_switches_and_objective
(self) → None[source]¶ Update gap filling model with switches and indicator objective.
-
fill
(self, iterations: int = 1) → List[List['Reaction']][source]¶ Perform the gap filling.
With every iteration, it solves the model, updates the costs and records the used reactions.
- Parameters
iterations (int, optional) – The number of rounds of gap filling to perform. For every iteration, the penalty for every used reaction increases linearly. This way, the algorithm is encouraged to search for alternative solutions which may include previously used reactions i.e., with enough iterations pathways including 10 steps will eventually be reported even if the shortest pathway is a single reaction (default 1).
- Returns
A list of lists where each element is a list of reactions that were used to gap fill the model.
- Return type
list of list of cobra.Reaction
- Raises
RuntimeError – If the model fails to be validated (i.e. the original model with the proposed reactions added, still cannot get the required flux through the objective).
-
cobra.flux_analysis.gapfilling.
gapfill
(model: Model, universal: Optional[Model] = None, lower_bound: float = 0.05, penalties: Optional[Dict[str, 'Reaction']] = None, demand_reactions: bool = True, exchange_reactions: bool = False, iterations: int = 1)[source]¶ Perform gap filling on a model.
- Parameters
model (cobra.Model) – The model to perform gap filling on.
universal (cobra.Model, optional) – A universal model with reactions that can be used to complete the model. Only gapfill considering demand and exchange reactions if left missing (default None).
lower_bound (float, optional) – The minimally accepted flux for the objective in the filled model. (default 0.05).
penalties (dict, optional) – A dictionary with keys being ‘universal’ (all reactions included in the universal model), ‘exchange’ and ‘demand’ (all additionally added exchange and demand reactions) for the three reaction types. Can also have reaction identifiers for reaction specific costs. Defaults are 1, 100 and 1 respectively (default None).
exchange_reactions (bool, optional) – Consider adding exchange (uptake) reactions for all metabolites in the model (default False).
demand_reactions (bool, optional) – Consider adding demand reactions for all metabolites (default True).
iterations (int, optional) – The number of rounds of gap filling to perform. For every iteration, the penalty for every used reaction increases linearly. This way, the algorithm is encouraged to search for alternative solutions which may include previously used reactions i.e., with enough iterations pathways including 10 steps will eventually be reported even if the shortest pathway is a single reaction (default 1).
- Returns
A list of lists with on set of reactions that completes the model per requested iteration.
- Return type
list of list of cobra.Reaction
Examples
>>> import cobra.test as ct >>> from cobra import Model >>> from cobra.flux_analysis import gapfill >>> model = ct.create_test_model("salmonella") >>> universal = Model("universal") >>> universal.add_reactions([model.reactions.GF6PTA.copy()]) >>> model.remove_reactions([model.reactions.GF6PTA]) >>> gapfill(model, universal) [[<Reaction GF6PTA at 0x12206a280>]]
cobra.flux_analysis.geometric
¶Provide an implementation of geometric FBA.
|
Perform geometric FBA to obtain a unique, centered flux distribution. |
-
cobra.flux_analysis.geometric.
geometric_fba
(model: Model, epsilon: float = 1e-06, max_tries: int = 200, processes: Optional[int] = None) → 'Solution'[source]¶ Perform geometric FBA to obtain a unique, centered flux distribution.
Geometric FBA 1 formulates the problem as a polyhedron and then solves it by bounding the convex hull of the polyhedron. The bounding forms a box around the convex hull which reduces with every iteration and extracts a unique solution in this way.
- Parameters
model (cobra.Model) – The model to perform geometric FBA on.
epsilon (float, optional) – The convergence tolerance of the model (default 1E-06).
max_tries (int, optional) – Maximum number of iterations (default 200).
processes (int, optional) – The number of parallel processes to run. If not explicitly passed, will be set from the global configuration singleton (default None).
- Returns
The solution object containing all the constraints required for geometric FBA.
- Return type
- Raises
RuntimeError – If iteration count becomes equal to max_tries.
References
- 1
Smallbone, Kieran & Simeonidis, Vangelis. (2009). Flux balance analysis: A geometric perspective. Journal of theoretical biology.258. 311-5. 10.1016/j.jtbi.2009.01.027.
cobra.flux_analysis.helpers
¶Helper functions for all flux analysis methods.
|
Return a valid zero cutoff value. |
-
cobra.flux_analysis.helpers.
normalize_cutoff
(model: Model, zero_cutoff: Optional[float] = None) → float[source]¶ Return a valid zero cutoff value.
- Parameters
model (cobra.Model) – The model to operate on.
zero_cutoff (positive float, optional) – The zero cutoff value. If not specified, defaults to model.tolerance (default None).
- Returns
The normalized zero cutoff value.
- Return type
- Raises
ValueError – If the specified zero_cutoff is lesser than model.tolerance.
cobra.flux_analysis.loopless
¶Provide functions to remove thermodynamically infeasible loops.
|
Modify a model so all feasible flux distributions are loopless. |
|
Add constraints for CycleFreeFlux. |
|
Convert an existing solution to a loopless one. |
|
Plugin to get a loopless FVA solution from single FVA iteration. |
-
cobra.flux_analysis.loopless.
add_loopless
(model: Model, zero_cutoff: Optional[float] = None) → None[source]¶ Modify a model so all feasible flux distributions are loopless.
It adds variables and constraints to a model which will disallow flux distributions with loops. The used formulation is described in [1]_. This function will modify your model.
In most cases you probably want to use the much faster loopless_solution. May be used in cases where you want to add complex constraints and objecives (for instance quadratic objectives) to the model afterwards or use an approximation of Gibbs free energy directions in your model.
- Parameters
model (cobra.Model) – The model to which to add the constraints.
zero_cutoff (positive float, optional) – Cutoff used for null space. Coefficients with an absolute value smaller than zero_cutoff are considered to be zero. The default uses the model.tolerance (default None).
References
- 1
Elimination of thermodynamically infeasible loops in steady-state metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J. 2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum in: Biophys J. 2011 Mar 2;100(5):1381.
-
cobra.flux_analysis.loopless.
_add_cycle_free
(model: Model, fluxes: Dict[str, float]) → None[source]¶ Add constraints for CycleFreeFlux.
- Parameters
model (cobra.Model) – The model to operate on.
fluxes (dict of {str: float}) – A dictionary having keys as reaction IDs and values as their flux values.
-
cobra.flux_analysis.loopless.
loopless_solution
(model: Model, fluxes: Optional[Dict[str, float]] = None) → 'Solution'[source]¶ Convert an existing solution to a loopless one.
Removes as many loops as possible (see Notes).
Uses the method from CycleFreeFlux [1]_ and is much faster than add_loopless and should therefore be the preferred option to get loopless flux distributions.
- Parameters
model (cobra.Model) – The model to which to add the constraints.
fluxes (dict of {str, float}, optional) – A dictionary having keys as reaction IDs and values as their flux values. If not None will use the provided flux values to obtain a close loopless solution (default None).
- Returns
A solution object containing the fluxes with the least amount of loops possible or None if the optimization failed (usually happening if the flux distribution in fluxes is infeasible).
- Return type
Notes
The returned flux solution has the following properties:
It contains the minimal number of loops possible and no loops at all if all flux bounds include zero.
It has an objective value close to the original one and the same objective value id the objective expression can not form a cycle (which is usually true since it consumes metabolites).
It has the same exact exchange fluxes as the previous solution.
All fluxes have the same sign (flow in the same direction) as the previous solution.
References
- 1
CycleFreeFlux: efficient removal of thermodynamically infeasible loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi: 10.1093/bioinformatics/btv096.
-
cobra.flux_analysis.loopless.
loopless_fva_iter
(model: Model, reaction: Reaction, solution: bool = False, zero_cutoff: Optional[float] = None) → Union[float, Dict[str, float]][source]¶ Plugin to get a loopless FVA solution from single FVA iteration.
Assumes the following about model and reaction: 1. The model objective is set to be reaction. 2. The model has been optimized and contains the minimum/maximum flux
for reaction.
The model contains an auxiliary variable called “fva_old_objective” denoting the previous objective.
- Parameters
model (cobra.Model) – The model to be used.
reaction (cobra.Reaction) – The reaction currently minimized/maximized.
solution (bool, optional) – Whether to return the entire solution or only the minimum/maximum for reaction (default False).
zero_cutoff (positive float, optional) – Cutoff used for loop removal. Fluxes with an absolute value smaller than zero_cutoff are considered to be zero. The default is to use model.tolerance (default None).
- Returns
single float or dict of {str – Returns the minimized/maximized flux through reaction if solution is False. Otherwise, returns a loopless flux solution object containing the minimum/maximum flux for reaction.
- Return type
float}
cobra.flux_analysis.moma
¶Provide minimization of metabolic adjustment (MOMA).
|
Compute a single solution based on (linear) MOMA. |
|
Add MOMA constraints and objective representing to the model. |
-
cobra.flux_analysis.moma.
moma
(model: Model, solution: Optional['Solution'] = None, linear: bool = True) → 'Solution'[source]¶ Compute a single solution based on (linear) MOMA.
Compute a new flux distribution that is at a minimal distance to a previous reference solution solution. Minimization of metabolic adjustment (MOMA) is generally used to assess the impact of knock-outs. Thus, the typical usage is to provide a wild-type flux distribution as reference and a model in knock-out state.
- Parameters
model (cobra.Model) – The model state to compute a MOMA-based solution for.
solution (cobra.Solution, optional) – A (wild-type) reference solution (default None).
linear (bool, optional) – Whether to use the linear MOMA formulation or not (default True).
- Returns
A flux distribution that is at a minimal distance compared to the reference solution.
- Return type
See also
add_moma()
add MOMA constraints and objective
-
cobra.flux_analysis.moma.
add_moma
(model: Model, solution: Optional['Solution'] = None, linear: bool = True) → None[source]¶ Add MOMA constraints and objective representing to the model.
This adds variables and constraints for the minimization of metabolic adjustment (MOMA) to the model.
- Parameters
model (cobra.Model) – The model to add MOMA constraints and objective to.
solution (cobra.Solution, optional) – A previous solution to use as a reference. If no solution is given, one will be computed using pFBA (default None).
linear (bool, optional) – Whether to use the linear MOMA formulation or not (default True).
Notes
In the original MOMA 1 specification, one looks for the flux distribution of the deletion (v^d) closest to the fluxes without the deletion (v). In math this means:
minimize: sum_i (v^d_i - v_i)^2 s.t. : Sv^d = 0
lb_i le v^d_i le ub_i
Here, we use a variable transformation v^t := v^d_i - v_i. Substituting and using the fact that Sv = 0 gives:
minimize: sum_i (v^t_i)^2 s.t. : Sv^d = 0
v^t = v^d_i - v_i lb_i le v^d_i le ub_i
So, basically we just re-center the flux space at the old solution and then find the flux distribution closest to the new zero (center). This is the same strategy as used in cameo.
In the case of linear MOMA 2, we instead minimize sum_i abs(v^t_i). The linear MOMA is typically significantly faster. Also, quadratic MOMA tends to give flux distributions in which all fluxes deviate from the reference fluxes a little bit whereas linear MOMA tends to give flux distributions where the majority of fluxes are the same reference with few fluxes deviating a lot (typical effect of L2 norm vs L1 norm).
The former objective function is saved in the optlang solver interface as
"moma_old_objective"
and this can be used to immediately extract the value of the former objective after MOMA optimization.See also
pfba()
parsimonious FBA
References
- 1
Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of Optimality in Natural and Perturbed Metabolic Networks.” Proceedings of the National Academy of Sciences 99, no. 23 (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.
- 2
Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum, Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative Prediction of Cellular Metabolism with Constraint-Based Models: The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727.
cobra.flux_analysis.parsimonious
¶Provide parsimonious FBA implementation.
|
Perform basic pFBA to minimize total flux. |
|
Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis). |
|
Add pFBA objective to the model. |
-
cobra.flux_analysis.parsimonious.
optimize_minimal_flux
(*args, **kwargs) → Callable[['Model', float, Union[Dict, 'Objective'], List['Reaction']], 'Solution'][source]¶ Perform basic pFBA to minimize total flux.
Deprecated since version 0.6.0a4: optimize_minimal_flux will be removed in cobrapy 1.0.0, it is replaced by pfba.
- Parameters
*args (Any) – Non-keyword variable-length arguments.
**kwargs (Any) – Keyword-only variable-length arguments.
- Returns
- Return type
A function performing the parsimonious FBA.
-
cobra.flux_analysis.parsimonious.
pfba
(model: Model, fraction_of_optimum: float = 1.0, objective: Union[Dict, 'Objective', None] = None, reactions: Optional[List['Reaction']] = None) → 'Solution'[source]¶ Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis).
pFBA [1] adds the minimization of all fluxes the the objective of the model. This approach is motivated by the idea that high fluxes have a higher enzyme turn-over and that since producing enzymes is costly, the cell will try to minimize overall flux while still maximizing the original objective function, e.g. the growth rate.
- Parameters
model (cobra.Model) – The model to perform pFBA on.
fraction_of_optimum (float, optional) – The fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal value times the fraction_of_optimum (default 1.0).
objective (dict or cobra.Model.objective, optional) – A desired objective to use during optimization in addition to the pFBA objective. Dictionaries (reaction as key, coefficient as value) can be used for linear objectives (default None).
reactions (list of cobra.Reaction, optional) – List of cobra.Reaction. Implies return_frame to be true. Only return fluxes for the given reactions. Faster than fetching all fluxes if only a few are needed (default None).
- Returns
The solution object to the optimized model with pFBA constraints added.
- Return type
References
- 1
Lewis, N. E., Hixson, K. K., Conrad, T. M., Lerman, J. A., Charusanti, P., Polpitiya, A. D., Palsson, B. O. (2010). Omic data from evolved E. coli are consistent with computed optimal growth from genome-scale models. Molecular Systems Biology, 6, 390. doi:10.1038/msb.2010.47
-
cobra.flux_analysis.parsimonious.
add_pfba
(model: Model, objective: Union[Dict, 'Objective', None] = None, fraction_of_optimum: float = 1.0) → None[source]¶ Add pFBA objective to the model.
This adds objective to minimize the summed flux of all reactions to the current objective.
- Parameters
model (cobra.Model) – The model to add the objective to.
objective (dict or cobra.Model.objective, optional) – A desired objective to use during optimization in addition to the pFBA objective. Dictionaries (reaction as key, coefficient as value) can be used for linear objectives (default None).
fraction_of_optimum (float, optional) – Fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal value times the fraction_of_optimum.
See also
cobra.flux_analysis.phenotype_phase_plane
¶Provide functions for phenotype phase plane analysis.
|
Calculate the objective value conditioned on all flux combinations. |
|
Add a production envelope based on the parameters provided. |
|
Compute total output per input unit. |
|
Split metabolites into atoms times their stoichiometric coefficients. |
|
Return the metabolite weight times its stoichiometric coefficient. |
|
Compute the total components consumption or production flux. |
|
Find all active carbon source reactions. |
-
cobra.flux_analysis.phenotype_phase_plane.
production_envelope
(model: Model, reactions: List['Reaction'], objective: Union[Dict, 'Objective', None] = None, carbon_sources: Optional[List['Reaction']] = None, points: int = 20, threshold: Optional[float] = None) → pd.DataFrame[source]¶ Calculate the objective value conditioned on all flux combinations.
The production envelope can be used to analyze a model’s ability to produce a given compound conditional on the fluxes for another set of reactions, such as the uptake rates. The model is alternately optimized with respect to minimizing and maximizing the objective and the obtained fluxes are recorded. Ranges to compute production is set to the effective bounds, i.e., the minimum / maximum fluxes that can be obtained given current reaction bounds.
- Parameters
model (cobra.Model) – The model to compute the production envelope for.
reactions (list of cobra.Reaction) – A list of reaction objects.
objective (dict or cobra.Model.objective, optional) – The objective (reaction) to use for the production envelope. Use the model’s current objective if left missing (default None).
carbon_sources (list of cobra.Reaction, optional) – One or more reactions that are the source of carbon for computing carbon (mol carbon in output over mol carbon in input) and mass yield (gram product over gram output). Only objectives with a carbon containing input and output metabolite is supported. Will identify active carbon sources in the medium if none are specified (default None).
points (int, optional) – The number of points to calculate production for (default 20).
threshold (float, optional) – A cut-off under which flux values will be considered to be zero. If not specified, it defaults to model.tolerance (default None).
- Returns
A DataFrame with fixed columns as: - carbon_source : identifiers of carbon exchange reactions - flux_maximum : maximum objective flux - flux_minimum : minimum objective flux - carbon_yield_maximum : maximum yield of a carbon source - carbon_yield_minimum : minimum yield of a carbon source - mass_yield_maximum : maximum mass yield of a carbon source - mass_yield_minimum : minimum mass yield of a carbon source
and variable columns (for each input reactions) as: - reaction_id : flux at each given point
- Return type
pandas.DataFrame
- Raises
ValueError – If model’s objective is comprised of multiple reactions.
Examples
>>> import cobra.test >>> from cobra.flux_analysis import production_envelope >>> model = cobra.test.create_test_model("textbook") >>> production_envelope(model, ["EX_glc__D_e", "EX_o2_e"]) carbon_source flux_minimum carbon_yield_minimum mass_yield_minimum ... 0 EX_glc__D_e 0.0 0.0 NaN ... 1 EX_glc__D_e 0.0 0.0 NaN ... 2 EX_glc__D_e 0.0 0.0 NaN ... 3 EX_glc__D_e 0.0 0.0 NaN ... 4 EX_glc__D_e 0.0 0.0 NaN ... .. ... ... ... ... ... 395 EX_glc__D_e NaN NaN NaN ... 396 EX_glc__D_e NaN NaN NaN ... 397 EX_glc__D_e NaN NaN NaN ... 398 EX_glc__D_e NaN NaN NaN ... 399 EX_glc__D_e NaN NaN NaN ...
[400 rows x 9 columns]
-
cobra.flux_analysis.phenotype_phase_plane.
_add_envelope
(model: Model, reactions: List['Reaction'], grid: pd.DataFrame, c_input: List['Reaction'], c_output: List['Reaction'], threshold: float) → None[source]¶ Add a production envelope based on the parameters provided.
- Parameters
model (cobra.Model) – The model to operate on.
reactions (list of cobra.Reaction) – The input reaction objects.
grid (pandas.DataFrame) – The DataFrame containing all the data regarding the operation.
c_input (list of cobra.Reaction) – The list of reaction objects acting as carbon inputs.
c_output (list of cobra.Reaction) – The list of reaction objects acting as carbon outputs.
-
cobra.flux_analysis.phenotype_phase_plane.
_total_yield
(input_fluxes: List[float], input_elements: List[float], output_flux: List[float], output_elements: List[float]) → float[source]¶ Compute total output per input unit.
Units are typically mol carbon atoms or gram of source and product.
- Parameters
input_fluxes (list of float) – A list of input reaction fluxes in the same order as the input_components.
input_elements (list of float) – A list of reaction components which are in turn list of numbers.
output_flux (float) – The output flux value.
output_elements (list) – A list of stoichiometrically weighted output reaction components.
- Returns
The ratio between output (mol carbon atoms or grams of product) and input (mol carbon atoms or grams of source compounds). If input flux of carbon sources is zero then numpy.nan is returned.
- Return type
-
cobra.flux_analysis.phenotype_phase_plane.
_reaction_elements
(reaction: Reaction) → List[float][source]¶ Split metabolites into atoms times their stoichiometric coefficients.
- Parameters
reaction (cobra.Reaction) – The reaction whose metabolite components are desired.
- Returns
Each of the reaction’s metabolites’ desired carbon elements (if any) times that metabolite’s stoichiometric coefficient.
- Return type
list of float
-
cobra.flux_analysis.phenotype_phase_plane.
_reaction_weight
(reaction: Reaction) → List[float][source]¶ Return the metabolite weight times its stoichiometric coefficient.
- Parameters
reaction (cobra.Reaction) – The reaction whose metabolite component weights is desired.
- Returns
Each of reaction’s metabolite components’ weights.
- Return type
list of float
- Raises
ValueError – If more than one metabolite comprises the reaction.
-
cobra.flux_analysis.phenotype_phase_plane.
_total_components_flux
(flux: float, components: List[float], consumption: bool = True) → float[source]¶ Compute the total components consumption or production flux.
- Parameters
- Returns
The total consumption or production flux of components.
- Return type
-
cobra.flux_analysis.phenotype_phase_plane.
_find_carbon_sources
(model: Model) → List['Reaction'][source]¶ Find all active carbon source reactions.
- Parameters
model (Model) – The model whose active carbon sources need to found.
- Returns
The medium reactions with carbon input flux.
- Return type
list of cobra.Reaction
cobra.flux_analysis.reaction
¶Provide functions for analyzing / creating objective functions.
|
Assess production capacity. |
|
Assess production capacity of components. |
|
Perform quick optimization and return the objective value. |
|
Assess production capacity of precursors. |
|
Assesses absorption capacity of products. |
-
cobra.flux_analysis.reaction.
assess
(model: Model, reaction: Union[Reaction, str], flux_coefficient_cutoff: float = 0.001, solver: str = None) → Union[bool, Dict][source]¶ Assess production capacity.
Assess the capacity of the model to produce the precursors for the reaction and absorb the production of the reaction while the reaction is operating at, or above, the specified flux_coefficient_cutoff.
Deprecated since version 0.10.0a1: solver argument will be removed in cobrapy 1.0.0, it is replaced by globally setting the solver via cobra.Configuration .
- Parameters
model (cobra.Model) – The cobra model to assess production capacity for.
reaction (str or cobra.Reaction) – The reaction to assess.
flux_coefficient_cutoff (float, optional) – The minimum flux that reaction must carry to be considered active (default 0.001).
solver (str, optional) – The solver name. If None, the default solver will be used (default None).
- Returns
True if the model can produce the precursors and absorb the products for the reaction operating at, or above, flux_coefficient_cutoff. Otherwise, a dictionary of {‘precursor’: Status, ‘product’: Status}, where ‘Status’ is the results from assess_precursors and assess_products, respectively.
- Return type
-
cobra.flux_analysis.reaction.
assess_component
(model: Model, reaction: Union[Reaction, str], side: str, flux_coefficient_cutoff: float = 0.001, solver: str = None) → Union[bool, Dict][source]¶ Assess production capacity of components.
Assess the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified flux_coefficient_cutoff.
Deprecated since version 0.10.0a1: solver argument will be removed in cobrapy 1.0.0, it is replaced by globally setting the solver via cobra.Configuration .
- Parameters
model (cobra.Model) – The cobra model to assess production capacity for.
reaction (str or cobra.Reaction) – The reaction to assess.
side ({"products", "reactants"}) – The side of the reaction to assess.
flux_coefficient_cutoff (float, optional) – The minimum flux that reaction must carry to be considered active (default 0.001).
solver (str, optional) – The solver name. If None, the default solver will be used (default None).
- Returns
True if the precursors can be simultaneously produced at the specified cutoff. False, if the model has the capacity to produce each individual precursor at the specified threshold but not all precursors at the required level simultaneously. Otherwise, a dictionary of the required and the produced fluxes for each reactant that is not produced in sufficient quantities.
- Return type
-
cobra.flux_analysis.reaction.
_optimize_or_value
(model: Model, value: float = 0.0) → float[source]¶ Perform quick optimization and return the objective value.
The objective value is returned at value error value.
Deprecated since version 0.22.0: _optimize_or_value will be removed in cobrapy 1.0.0, its functionality can be achieved by using cobra.Model.slim_optimize.
- Parameters
model (cobra.Model) – The model to optimize.
value (float) – The error value to consider.
- Returns
The optimized value of the model’s objective.
- Return type
-
cobra.flux_analysis.reaction.
assess_precursors
(model: Model, reaction: Reaction, flux_coefficient_cutoff: float = 0.001, solver: str = None) → Union[bool, Dict][source]¶ Assess production capacity of precursors.
Assess the ability of the model to provide sufficient precursors for a reaction operating at, or beyond, the flux_coefficient_cutoff.
Deprecated since version 0.7.0: assess_precursors will be removed in cobrapy 1.0.0, it is replaced by assess_component.
- Parameters
model (cobra.Model) – The cobra model to assess production capacity for.
reaction (str or cobra.Reaction) – The reaction to assess.
flux_coefficient_cutoff (float, optional) – The minimum flux that reaction must carry to be considered active (default 0.001).
solver (str, optional) – The solver name. If None, the default solver will be used (default None).
- Returns
True if the precursors can be simultaneously produced at the specified cutoff. False, if the model has the capacity to produce each individual precursor at the specified threshold but not all precursors at the required level simultaneously. Otherwise, a dictionary of the required and the produced fluxes for each reactant that is not produced in sufficient quantities.
- Return type
-
cobra.flux_analysis.reaction.
assess_products
(model: Model, reaction: Reaction, flux_coefficient_cutoff: float = 0.001, solver: str = None) → Union[bool, Dict][source]¶ Assesses absorption capacity of products.
Assess the ability of the model to to absorb the products of a reaction at a given flux rate. Useful for identifying which components might be blocking a reaction from achieving a specific flux rate.
Deprecated since version 0.7.0: assess_products will be removed in cobrapy 1.0.0, it is replaced by assess_component.
- Parameters
model (cobra.Model) – The cobra model to assess production capacity for.
reaction (str or cobra.Reaction) – The reaction to assess.
flux_coefficient_cutoff (float, optional) – The minimum flux that reaction must carry to be considered active (default 0.001).
solver (str, optional) – The solver name. If None, the default solver will be used (default None).
- Returns
True if the model has the capacity to absorb all the reaction products being simultaneously given the specified cutoff. False, if the model has the capacity to absorb each individual product but not all products at the required level simultaneously. Otherwise, a dictionary of the required and the capacity fluxes for each product that is not absorbed in sufficient quantities.
- Return type
cobra.flux_analysis.room
¶Provide regulatory on/off minimization (ROOM).
|
Compute a solution based on regulatory on/off minimization (ROOM). |
|
Add constraints and objective for ROOM. |
-
cobra.flux_analysis.room.
room
(model: Model, solution: Optional['Solution'] = None, linear: bool = False, delta: float = 0.03, epsilon: float = 0.001) → 'Solution'[source]¶ Compute a solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active reactions needed to accommodate a previous reference solution. Regulatory on/off minimization (ROOM) is generally used to assess the impact of knock-outs. Thus, the typical usage is to provide a wild-type flux distribution as reference and a model in knock-out state.
- Parameters
model (cobra.Model) – The model state to compute a ROOM-based solution for.
solution (cobra.Solution, optional) – A (wild-type) reference solution (default None).
linear (bool, optional) – Whether to use the linear ROOM formulation or not (default False).
delta (float, optional) – The relative tolerance range (additive) (default 0.03).
epsilon (float, optional) – The absolute tolerance range (multiplicative) (default 0.001).
- Returns
A flux distribution with minimal active reaction changes compared to the reference.
- Return type
See also
add_room()
add ROOM constraints and objective
-
cobra.flux_analysis.room.
add_room
(model: Model, solution: Optional['Solution'] = None, linear: bool = False, delta: float = 0.03, epsilon: float = 0.001) → None[source]¶ Add constraints and objective for ROOM.
This function adds variables and constraints for applying regulatory on/off minimization (ROOM) to the model.
- Parameters
model (cobra.Model) – The model to add ROOM constraints and objective to.
solution (cobra.Solution, optional) – A previous solution to use as a reference. If no solution is given, one will be computed using pFBA (default None).
linear (bool, optional) – Whether to use the linear ROOM formulation or not (default False).
delta (float, optional) – The relative tolerance range which is additive in nature (default 0.03).
epsilon (float, optional) – The absolute range of tolerance which is multiplicative (default 0.001).
Notes
The formulation used here is the same as stated in the original paper 1. The mathematical expression is given below:
minimize: sum_{i=1}^m y^i s.t. : Sv = 0
v_min le v le v_max v_j = 0 j in A for 1 le i le m v_i - y_i(v_{max,i} - w_i^u) le w_i^u (1) v_i - y_i(v_{min,i} - w_i^l) le w_i^l (2) y_i in {0,1} (3) w_i^u = w_i + delta|w_i| + epsilon w_i^l = w_i - delta|w_i| - epsilon
So, for the linear version of the ROOM , constraint (3) is relaxed to 0 le y_i le 1.
See also
pfba()
parsimonious FBA
References
- 1
Tomer Shlomi, Omer Berkman and Eytan Ruppin, “Regulatory on/off minimization of metabolic flux changes after genetic perturbations”, PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102
cobra.flux_analysis.variability
¶Provide variability based methods such as flux variability or gene essentiality.
|
Initialize a global model object for multiprocessing. |
|
Take a step for calculating FVA. |
|
Determine the minimum and maximum flux value for each reaction. |
|
Find reactions that cannot carry any flux. |
|
Return a set of essential genes. |
|
Return a set of essential reactions. |
-
cobra.flux_analysis.variability.
_init_worker
(model: Model, loopless: bool, sense: str) → None[source]¶ Initialize a global model object for multiprocessing.
- Parameters
model (cobra.Model) – The model to operate on.
loopless (bool) – Whether to use loopless version.
sense ({"max", "min"}) – Whether to maximise or minimise objective.
-
cobra.flux_analysis.variability.
_fva_step
(reaction_id: str) → Tuple[str, float][source]¶ Take a step for calculating FVA.
-
cobra.flux_analysis.variability.
flux_variability_analysis
(model: Model, reaction_list: Optional[List[Union['Reaction', str]]] = None, loopless: bool = False, fraction_of_optimum: float = 1.0, pfba_factor: Optional[float] = None, processes: Optional[int] = None) → pd.DataFrame[source]¶ Determine the minimum and maximum flux value for each reaction.
- Parameters
model (cobra.Model) – The model for which to run the analysis. It will not be modified.
reaction_list (list of cobra.Reaction or str, optional) – The reactions for which to obtain min/max fluxes. If None will use all reactions in the model (default None).
loopless (bool, optional) – Whether to return only loopless solutions. This is significantly slower. Please also refer to the notes (default False).
fraction_of_optimum (float, optional) – Must be <= 1.0. Requires that the objective value is at least the fraction times maximum objective value. A value of 0.85 for instance means that the objective has to be at least at 85% percent of its maximum (default 1.0).
pfba_factor (float, optional) – Add an additional constraint to the model that requires the total sum of absolute fluxes must not be larger than this value times the smallest possible sum of absolute fluxes, i.e., by setting the value to 1.1 the total sum of absolute fluxes must not be more than 10% larger than the pFBA solution. Since the pFBA solution is the one that optimally minimizes the total flux sum, the pfba_factor should, if set, be larger than one. Setting this value may lead to more realistic predictions of the effective flux bounds (default None).
processes (int, optional) – The number of parallel processes to run. If not explicitly passed, will be set from the global configuration singleton (default None).
- Returns
A data frame with reaction identifiers as the index and two columns: - maximum: indicating the highest possible flux - minimum: indicating the lowest possible flux
- Return type
pandas.DataFrame
Notes
This implements the fast version as described in 1. Please note that the flux distribution containing all minimal/maximal fluxes does not have to be a feasible solution for the model. Fluxes are minimized/maximized individually and a single minimal flux might require all others to be sub-optimal.
Using the loopless option will lead to a significant increase in computation time (about a factor of 100 for large models). However, the algorithm used here (see 2) is still more than 1000x faster than the “naive” version using add_loopless(model). Also note that if you have included constraints that force a loop (for instance by setting all fluxes in a loop to be non-zero) this loop will be included in the solution.
References
- 1
Computationally efficient flux variability analysis. Gudmundsson S, Thiele I. BMC Bioinformatics. 2010 Sep 29;11:489. doi: 10.1186/1471-2105-11-489, PMID: 20920235
- 2
CycleFreeFlux: efficient removal of thermodynamically infeasible loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi: 10.1093/bioinformatics/btv096.
-
cobra.flux_analysis.variability.
find_blocked_reactions
(model: Model, reaction_list: Optional[List[Union['Reaction', str]]] = None, zero_cutoff: Optional[float] = None, open_exchanges: bool = False, processes: Optional[int] = None) → List['Reaction'][source]¶ Find reactions that cannot carry any flux.
The question whether or not a reaction is blocked is highly dependent on the current exchange reaction settings for a COBRA model. Hence an argument is provided to open all exchange reactions.
- Parameters
model (cobra.Model) – The model to analyze.
reaction_list (list of cobra.Reaction or str, optional) – List of reactions to consider, the default includes all model reactions (default None).
zero_cutoff (float, optional) – Flux value which is considered to effectively be zero. The default is set to use model.tolerance (default None).
open_exchanges (bool, optional) – Whether or not to open all exchange reactions to very high flux ranges (default False).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of reactions is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
List with the identifiers of blocked reactions.
- Return type
list of cobra.Reaction
Notes
Sink and demand reactions are left untouched. Please modify them manually.
-
cobra.flux_analysis.variability.
find_essential_genes
(model: Model, threshold: Optional[float] = None, processes: Optional[int] = None) → Set['Gene'][source]¶ Return a set of essential genes.
A gene is considered essential if restricting the flux of all reactions that depend on it to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible.
- Parameters
model (cobra.Model) – The model to find the essential genes for.
threshold (float, optional) – Minimal objective flux to be considered viable. By default this is 1% of the maximal objective (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
Set of essential genes.
- Return type
set of cobra.Gene
-
cobra.flux_analysis.variability.
find_essential_reactions
(model: Model, threshold: Optional[float] = None, processes: Optional[int] = None) → Set['Reaction'][source]¶ Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible.
- Parameters
model (cobra.Model) – The model to find the essential reactions for.
threshold (float, optional) – Minimal objective flux to be considered viable. By default this is 1% of the maximal objective (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
Set of essential reactions.
- Return type
set of cobra.Reaction
Package Contents¶
|
Knock out each gene pair from the combination of two given lists. |
|
Knock out each reaction pair from the combinations of two given lists. |
|
Knock out each gene from gene_list. |
|
Knock out each reaction from reaction_list. |
|
Check consistency of a metabolic network using FASTCC [1]_. |
|
Perform gap filling on a model. |
|
Perform geometric FBA to obtain a unique, centered flux distribution. |
|
Convert an existing solution to a loopless one. |
|
Modify a model so all feasible flux distributions are loopless. |
|
Add MOMA constraints and objective representing to the model. |
|
Compute a single solution based on (linear) MOMA. |
|
Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis). |
|
Find reactions that cannot carry any flux. |
|
Return a set of essential genes. |
|
Return a set of essential reactions. |
|
Determine the minimum and maximum flux value for each reaction. |
|
Calculate the objective value conditioned on all flux combinations. |
|
Add constraints and objective for ROOM. |
|
Compute a solution based on regulatory on/off minimization (ROOM). |
-
cobra.flux_analysis.
double_gene_deletion
(model: Model, gene_list1: Optional[List[Union[Gene, str]]] = None, gene_list2: Optional[List[Union[Gene, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each gene pair from the combination of two given lists.
We say ‘pair’ here but the order order does not matter.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
gene_list1 (list of cobra.Gene or str, optional) – The first gene list to be deleted. If not passed, all the genes from the model are used (default None).
gene_list2 (list of cobra.Gene or str, optional) – The second gene list to be deleted. If not passed, all the genes from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default None).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all combinations of gene deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The gene identifiers that were knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.
double_reaction_deletion
(model: Model, reaction_list1: Optional[List[Union[Reaction, str]]] = None, reaction_list2: Optional[List[Union[Reaction, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each reaction pair from the combinations of two given lists.
We say ‘pair’ here but the order order does not matter.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
reaction_list1 (list of cobra.Reaction or str, optional) – The first reaction list to be deleted. If not passed, all the reactions from the model are used (default None).
reaction_list2 (list of cobra.Reaction or str, optional) – The second reaction list to be deleted. If not passed, all the reactions from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all combinations of reaction deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The reaction identifiers that were knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.
single_gene_deletion
(model: Model, gene_list: Optional[List[Union[Gene, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each gene from gene_list.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
gene_list (list of cobra.Gene or str, optional) – The gene objects to be deleted. If not passed, all the genes from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all single gene deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The gene identifier that was knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.
single_reaction_deletion
(model: Model, reaction_list: Optional[List[Union[Reaction, str]]] = None, method: str = 'fba', solution: Optional['Solution'] = None, processes: Optional[int] = None, **kwargs) → pd.DataFrame[source]¶ Knock out each reaction from reaction_list.
- Parameters
model (cobra.Model) – The metabolic model to perform deletions in.
reaction_list (list of cobra.Reaction or str, optional) – The reactions be knocked out. If not passed, all the reactions from the model are used (default None).
method ({"fba", "moma", "linear moma", "room", "linear room"}, optional) – Method used to predict the growth rate (default “fba”).
solution (cobra.Solution, optional) – A previous solution to use as a reference for (linear) MOMA or ROOM (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not passed, will be set to configuration.processes (default None).
**kwargs – Keyword arguments are passed on to underlying simulation functions such as add_room.
- Returns
A representation of all single reaction deletions. The columns are ‘growth’ and ‘status’, where
- indextuple(str)
The reaction identifier that was knocked out.
- growthfloat
The growth rate of the adjusted model.
- statusstr
The solution’s status.
- Return type
pandas.DataFrame
-
cobra.flux_analysis.
fastcc
(model: Model, flux_threshold: float = 1.0, zero_cutoff: Optional[float] = None) → 'Model'[source]¶ Check consistency of a metabolic network using FASTCC [1]_.
FASTCC (Fast Consistency Check) is an algorithm for rapid and efficient consistency check in metabolic networks. FASTCC is a pure LP implementation and is low on computation resource demand. FASTCC also circumvents the problem associated with reversible reactions for the purpose. Given a global model, it will generate a consistent global model i.e., remove blocked reactions. For more details on FASTCC, please check [1]_.
- Parameters
model (cobra.Model) – The model to operate on.
flux_threshold (float, optional) – The flux threshold to consider (default 1.0).
zero_cutoff (float, optional) – The cutoff to consider for zero flux (default model.tolerance).
- Returns
The consistent model.
- Return type
Notes
The LP used for FASTCC is like so: maximize: sum_{i in J} z_i s.t. : z_i in [0, varepsilon] forall i in J, z_i in mathbb{R}_+
v_i ge z_i forall i in J Sv = 0 v in B
References
- 1
Vlassis N, Pacheco MP, Sauter T (2014) Fast Reconstruction of Compact Context-Specific Metabolic Network Models. PLoS Comput Biol 10(1): e1003424. doi:10.1371/journal.pcbi.1003424
-
cobra.flux_analysis.
gapfill
(model: Model, universal: Optional[Model] = None, lower_bound: float = 0.05, penalties: Optional[Dict[str, 'Reaction']] = None, demand_reactions: bool = True, exchange_reactions: bool = False, iterations: int = 1)[source]¶ Perform gap filling on a model.
- Parameters
model (cobra.Model) – The model to perform gap filling on.
universal (cobra.Model, optional) – A universal model with reactions that can be used to complete the model. Only gapfill considering demand and exchange reactions if left missing (default None).
lower_bound (float, optional) – The minimally accepted flux for the objective in the filled model. (default 0.05).
penalties (dict, optional) – A dictionary with keys being ‘universal’ (all reactions included in the universal model), ‘exchange’ and ‘demand’ (all additionally added exchange and demand reactions) for the three reaction types. Can also have reaction identifiers for reaction specific costs. Defaults are 1, 100 and 1 respectively (default None).
exchange_reactions (bool, optional) – Consider adding exchange (uptake) reactions for all metabolites in the model (default False).
demand_reactions (bool, optional) – Consider adding demand reactions for all metabolites (default True).
iterations (int, optional) – The number of rounds of gap filling to perform. For every iteration, the penalty for every used reaction increases linearly. This way, the algorithm is encouraged to search for alternative solutions which may include previously used reactions i.e., with enough iterations pathways including 10 steps will eventually be reported even if the shortest pathway is a single reaction (default 1).
- Returns
A list of lists with on set of reactions that completes the model per requested iteration.
- Return type
list of list of cobra.Reaction
Examples
>>> import cobra.test as ct >>> from cobra import Model >>> from cobra.flux_analysis import gapfill >>> model = ct.create_test_model("salmonella") >>> universal = Model("universal") >>> universal.add_reactions([model.reactions.GF6PTA.copy()]) >>> model.remove_reactions([model.reactions.GF6PTA]) >>> gapfill(model, universal) [[<Reaction GF6PTA at 0x12206a280>]]
-
cobra.flux_analysis.
geometric_fba
(model: Model, epsilon: float = 1e-06, max_tries: int = 200, processes: Optional[int] = None) → 'Solution'[source]¶ Perform geometric FBA to obtain a unique, centered flux distribution.
Geometric FBA [1]_ formulates the problem as a polyhedron and then solves it by bounding the convex hull of the polyhedron. The bounding forms a box around the convex hull which reduces with every iteration and extracts a unique solution in this way.
- Parameters
model (cobra.Model) – The model to perform geometric FBA on.
epsilon (float, optional) – The convergence tolerance of the model (default 1E-06).
max_tries (int, optional) – Maximum number of iterations (default 200).
processes (int, optional) – The number of parallel processes to run. If not explicitly passed, will be set from the global configuration singleton (default None).
- Returns
The solution object containing all the constraints required for geometric FBA.
- Return type
- Raises
RuntimeError – If iteration count becomes equal to max_tries.
References
- 1
Smallbone, Kieran & Simeonidis, Vangelis. (2009). Flux balance analysis: A geometric perspective. Journal of theoretical biology.258. 311-5. 10.1016/j.jtbi.2009.01.027.
-
cobra.flux_analysis.
loopless_solution
(model: Model, fluxes: Optional[Dict[str, float]] = None) → 'Solution'[source]¶ Convert an existing solution to a loopless one.
Removes as many loops as possible (see Notes).
Uses the method from CycleFreeFlux [1]_ and is much faster than add_loopless and should therefore be the preferred option to get loopless flux distributions.
- Parameters
model (cobra.Model) – The model to which to add the constraints.
fluxes (dict of {str, float}, optional) – A dictionary having keys as reaction IDs and values as their flux values. If not None will use the provided flux values to obtain a close loopless solution (default None).
- Returns
A solution object containing the fluxes with the least amount of loops possible or None if the optimization failed (usually happening if the flux distribution in fluxes is infeasible).
- Return type
Notes
The returned flux solution has the following properties:
It contains the minimal number of loops possible and no loops at all if all flux bounds include zero.
It has an objective value close to the original one and the same objective value id the objective expression can not form a cycle (which is usually true since it consumes metabolites).
It has the same exact exchange fluxes as the previous solution.
All fluxes have the same sign (flow in the same direction) as the previous solution.
References
- 1
CycleFreeFlux: efficient removal of thermodynamically infeasible loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi: 10.1093/bioinformatics/btv096.
-
cobra.flux_analysis.
add_loopless
(model: Model, zero_cutoff: Optional[float] = None) → None[source]¶ Modify a model so all feasible flux distributions are loopless.
It adds variables and constraints to a model which will disallow flux distributions with loops. The used formulation is described in [1]_. This function will modify your model.
In most cases you probably want to use the much faster loopless_solution. May be used in cases where you want to add complex constraints and objecives (for instance quadratic objectives) to the model afterwards or use an approximation of Gibbs free energy directions in your model.
- Parameters
model (cobra.Model) – The model to which to add the constraints.
zero_cutoff (positive float, optional) – Cutoff used for null space. Coefficients with an absolute value smaller than zero_cutoff are considered to be zero. The default uses the model.tolerance (default None).
References
- 1
Elimination of thermodynamically infeasible loops in steady-state metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J. 2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum in: Biophys J. 2011 Mar 2;100(5):1381.
-
cobra.flux_analysis.
add_moma
(model: Model, solution: Optional['Solution'] = None, linear: bool = True) → None[source]¶ Add MOMA constraints and objective representing to the model.
This adds variables and constraints for the minimization of metabolic adjustment (MOMA) to the model.
- Parameters
model (cobra.Model) – The model to add MOMA constraints and objective to.
solution (cobra.Solution, optional) – A previous solution to use as a reference. If no solution is given, one will be computed using pFBA (default None).
linear (bool, optional) – Whether to use the linear MOMA formulation or not (default True).
Notes
In the original MOMA [1]_ specification, one looks for the flux distribution of the deletion (v^d) closest to the fluxes without the deletion (v). In math this means:
minimize: sum_i (v^d_i - v_i)^2 s.t. : Sv^d = 0
lb_i le v^d_i le ub_i
Here, we use a variable transformation v^t := v^d_i - v_i. Substituting and using the fact that Sv = 0 gives:
minimize: sum_i (v^t_i)^2 s.t. : Sv^d = 0
v^t = v^d_i - v_i lb_i le v^d_i le ub_i
So, basically we just re-center the flux space at the old solution and then find the flux distribution closest to the new zero (center). This is the same strategy as used in cameo.
In the case of linear MOMA [2]_, we instead minimize sum_i abs(v^t_i). The linear MOMA is typically significantly faster. Also, quadratic MOMA tends to give flux distributions in which all fluxes deviate from the reference fluxes a little bit whereas linear MOMA tends to give flux distributions where the majority of fluxes are the same reference with few fluxes deviating a lot (typical effect of L2 norm vs L1 norm).
The former objective function is saved in the optlang solver interface as
"moma_old_objective"
and this can be used to immediately extract the value of the former objective after MOMA optimization.See also
pfba()
parsimonious FBA
References
- 1
Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of Optimality in Natural and Perturbed Metabolic Networks.” Proceedings of the National Academy of Sciences 99, no. 23 (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.
- 2
Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum, Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative Prediction of Cellular Metabolism with Constraint-Based Models: The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727.
-
cobra.flux_analysis.
moma
(model: Model, solution: Optional['Solution'] = None, linear: bool = True) → 'Solution'[source]¶ Compute a single solution based on (linear) MOMA.
Compute a new flux distribution that is at a minimal distance to a previous reference solution solution. Minimization of metabolic adjustment (MOMA) is generally used to assess the impact of knock-outs. Thus, the typical usage is to provide a wild-type flux distribution as reference and a model in knock-out state.
- Parameters
model (cobra.Model) – The model state to compute a MOMA-based solution for.
solution (cobra.Solution, optional) – A (wild-type) reference solution (default None).
linear (bool, optional) – Whether to use the linear MOMA formulation or not (default True).
- Returns
A flux distribution that is at a minimal distance compared to the reference solution.
- Return type
See also
add_moma()
add MOMA constraints and objective
-
cobra.flux_analysis.
pfba
(model: Model, fraction_of_optimum: float = 1.0, objective: Union[Dict, 'Objective', None] = None, reactions: Optional[List['Reaction']] = None) → 'Solution'[source]¶ Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis).
pFBA [1] adds the minimization of all fluxes the the objective of the model. This approach is motivated by the idea that high fluxes have a higher enzyme turn-over and that since producing enzymes is costly, the cell will try to minimize overall flux while still maximizing the original objective function, e.g. the growth rate.
- Parameters
model (cobra.Model) – The model to perform pFBA on.
fraction_of_optimum (float, optional) – The fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal value times the fraction_of_optimum (default 1.0).
objective (dict or cobra.Model.objective, optional) – A desired objective to use during optimization in addition to the pFBA objective. Dictionaries (reaction as key, coefficient as value) can be used for linear objectives (default None).
reactions (list of cobra.Reaction, optional) – List of cobra.Reaction. Implies return_frame to be true. Only return fluxes for the given reactions. Faster than fetching all fluxes if only a few are needed (default None).
- Returns
The solution object to the optimized model with pFBA constraints added.
- Return type
References
- 1
Lewis, N. E., Hixson, K. K., Conrad, T. M., Lerman, J. A., Charusanti, P., Polpitiya, A. D., Palsson, B. O. (2010). Omic data from evolved E. coli are consistent with computed optimal growth from genome-scale models. Molecular Systems Biology, 6, 390. doi:10.1038/msb.2010.47
-
cobra.flux_analysis.
find_blocked_reactions
(model: Model, reaction_list: Optional[List[Union['Reaction', str]]] = None, zero_cutoff: Optional[float] = None, open_exchanges: bool = False, processes: Optional[int] = None) → List['Reaction'][source]¶ Find reactions that cannot carry any flux.
The question whether or not a reaction is blocked is highly dependent on the current exchange reaction settings for a COBRA model. Hence an argument is provided to open all exchange reactions.
- Parameters
model (cobra.Model) – The model to analyze.
reaction_list (list of cobra.Reaction or str, optional) – List of reactions to consider, the default includes all model reactions (default None).
zero_cutoff (float, optional) – Flux value which is considered to effectively be zero. The default is set to use model.tolerance (default None).
open_exchanges (bool, optional) – Whether or not to open all exchange reactions to very high flux ranges (default False).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of reactions is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
List with the identifiers of blocked reactions.
- Return type
list of cobra.Reaction
Notes
Sink and demand reactions are left untouched. Please modify them manually.
-
cobra.flux_analysis.
find_essential_genes
(model: Model, threshold: Optional[float] = None, processes: Optional[int] = None) → Set['Gene'][source]¶ Return a set of essential genes.
A gene is considered essential if restricting the flux of all reactions that depend on it to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible.
- Parameters
model (cobra.Model) – The model to find the essential genes for.
threshold (float, optional) – Minimal objective flux to be considered viable. By default this is 1% of the maximal objective (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
Set of essential genes.
- Return type
set of cobra.Gene
-
cobra.flux_analysis.
find_essential_reactions
(model: Model, threshold: Optional[float] = None, processes: Optional[int] = None) → Set['Reaction'][source]¶ Return a set of essential reactions.
A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible.
- Parameters
model (cobra.Model) – The model to find the essential reactions for.
threshold (float, optional) – Minimal objective flux to be considered viable. By default this is 1% of the maximal objective (default None).
processes (int, optional) – The number of parallel processes to run. Can speed up the computations if the number of knockouts to perform is large. If not explicitly passed, it will be set from the global configuration singleton (default None).
- Returns
Set of essential reactions.
- Return type
set of cobra.Reaction
-
cobra.flux_analysis.
flux_variability_analysis
(model: Model, reaction_list: Optional[List[Union['Reaction', str]]] = None, loopless: bool = False, fraction_of_optimum: float = 1.0, pfba_factor: Optional[float] = None, processes: Optional[int] = None) → pd.DataFrame[source]¶ Determine the minimum and maximum flux value for each reaction.
- Parameters
model (cobra.Model) – The model for which to run the analysis. It will not be modified.
reaction_list (list of cobra.Reaction or str, optional) – The reactions for which to obtain min/max fluxes. If None will use all reactions in the model (default None).
loopless (bool, optional) – Whether to return only loopless solutions. This is significantly slower. Please also refer to the notes (default False).
fraction_of_optimum (float, optional) – Must be <= 1.0. Requires that the objective value is at least the fraction times maximum objective value. A value of 0.85 for instance means that the objective has to be at least at 85% percent of its maximum (default 1.0).
pfba_factor (float, optional) – Add an additional constraint to the model that requires the total sum of absolute fluxes must not be larger than this value times the smallest possible sum of absolute fluxes, i.e., by setting the value to 1.1 the total sum of absolute fluxes must not be more than 10% larger than the pFBA solution. Since the pFBA solution is the one that optimally minimizes the total flux sum, the pfba_factor should, if set, be larger than one. Setting this value may lead to more realistic predictions of the effective flux bounds (default None).
processes (int, optional) – The number of parallel processes to run. If not explicitly passed, will be set from the global configuration singleton (default None).
- Returns
A data frame with reaction identifiers as the index and two columns: - maximum: indicating the highest possible flux - minimum: indicating the lowest possible flux
- Return type
pandas.DataFrame
Notes
This implements the fast version as described in [1]_. Please note that the flux distribution containing all minimal/maximal fluxes does not have to be a feasible solution for the model. Fluxes are minimized/maximized individually and a single minimal flux might require all others to be sub-optimal.
Using the loopless option will lead to a significant increase in computation time (about a factor of 100 for large models). However, the algorithm used here (see [2]_) is still more than 1000x faster than the “naive” version using add_loopless(model). Also note that if you have included constraints that force a loop (for instance by setting all fluxes in a loop to be non-zero) this loop will be included in the solution.
References
- 1
Computationally efficient flux variability analysis. Gudmundsson S, Thiele I. BMC Bioinformatics. 2010 Sep 29;11:489. doi: 10.1186/1471-2105-11-489, PMID: 20920235
- 2
CycleFreeFlux: efficient removal of thermodynamically infeasible loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi: 10.1093/bioinformatics/btv096.
-
cobra.flux_analysis.
production_envelope
(model: Model, reactions: List['Reaction'], objective: Union[Dict, 'Objective', None] = None, carbon_sources: Optional[List['Reaction']] = None, points: int = 20, threshold: Optional[float] = None) → pd.DataFrame[source]¶ Calculate the objective value conditioned on all flux combinations.
The production envelope can be used to analyze a model’s ability to produce a given compound conditional on the fluxes for another set of reactions, such as the uptake rates. The model is alternately optimized with respect to minimizing and maximizing the objective and the obtained fluxes are recorded. Ranges to compute production is set to the effective bounds, i.e., the minimum / maximum fluxes that can be obtained given current reaction bounds.
- Parameters
model (cobra.Model) – The model to compute the production envelope for.
reactions (list of cobra.Reaction) – A list of reaction objects.
objective (dict or cobra.Model.objective, optional) – The objective (reaction) to use for the production envelope. Use the model’s current objective if left missing (default None).
carbon_sources (list of cobra.Reaction, optional) – One or more reactions that are the source of carbon for computing carbon (mol carbon in output over mol carbon in input) and mass yield (gram product over gram output). Only objectives with a carbon containing input and output metabolite is supported. Will identify active carbon sources in the medium if none are specified (default None).
points (int, optional) – The number of points to calculate production for (default 20).
threshold (float, optional) – A cut-off under which flux values will be considered to be zero. If not specified, it defaults to model.tolerance (default None).
- Returns
A DataFrame with fixed columns as: - carbon_source : identifiers of carbon exchange reactions - flux_maximum : maximum objective flux - flux_minimum : minimum objective flux - carbon_yield_maximum : maximum yield of a carbon source - carbon_yield_minimum : minimum yield of a carbon source - mass_yield_maximum : maximum mass yield of a carbon source - mass_yield_minimum : minimum mass yield of a carbon source
and variable columns (for each input reactions) as: - reaction_id : flux at each given point
- Return type
pandas.DataFrame
- Raises
ValueError – If model’s objective is comprised of multiple reactions.
Examples
>>> import cobra.test >>> from cobra.flux_analysis import production_envelope >>> model = cobra.test.create_test_model("textbook") >>> production_envelope(model, ["EX_glc__D_e", "EX_o2_e"]) carbon_source flux_minimum carbon_yield_minimum mass_yield_minimum ... 0 EX_glc__D_e 0.0 0.0 NaN ... 1 EX_glc__D_e 0.0 0.0 NaN ... 2 EX_glc__D_e 0.0 0.0 NaN ... 3 EX_glc__D_e 0.0 0.0 NaN ... 4 EX_glc__D_e 0.0 0.0 NaN ... .. ... ... ... ... ... 395 EX_glc__D_e NaN NaN NaN ... 396 EX_glc__D_e NaN NaN NaN ... 397 EX_glc__D_e NaN NaN NaN ... 398 EX_glc__D_e NaN NaN NaN ... 399 EX_glc__D_e NaN NaN NaN ...
[400 rows x 9 columns]
-
cobra.flux_analysis.
add_room
(model: Model, solution: Optional['Solution'] = None, linear: bool = False, delta: float = 0.03, epsilon: float = 0.001) → None[source]¶ Add constraints and objective for ROOM.
This function adds variables and constraints for applying regulatory on/off minimization (ROOM) to the model.
- Parameters
model (cobra.Model) – The model to add ROOM constraints and objective to.
solution (cobra.Solution, optional) – A previous solution to use as a reference. If no solution is given, one will be computed using pFBA (default None).
linear (bool, optional) – Whether to use the linear ROOM formulation or not (default False).
delta (float, optional) – The relative tolerance range which is additive in nature (default 0.03).
epsilon (float, optional) – The absolute range of tolerance which is multiplicative (default 0.001).
Notes
The formulation used here is the same as stated in the original paper [1]_. The mathematical expression is given below:
minimize: sum_{i=1}^m y^i s.t. : Sv = 0
v_min le v le v_max v_j = 0 j in A for 1 le i le m v_i - y_i(v_{max,i} - w_i^u) le w_i^u (1) v_i - y_i(v_{min,i} - w_i^l) le w_i^l (2) y_i in {0,1} (3) w_i^u = w_i + delta|w_i| + epsilon w_i^l = w_i - delta|w_i| - epsilon
So, for the linear version of the ROOM , constraint (3) is relaxed to 0 le y_i le 1.
See also
pfba()
parsimonious FBA
References
- 1
Tomer Shlomi, Omer Berkman and Eytan Ruppin, “Regulatory on/off minimization of metabolic flux changes after genetic perturbations”, PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102
-
cobra.flux_analysis.
room
(model: Model, solution: Optional['Solution'] = None, linear: bool = False, delta: float = 0.03, epsilon: float = 0.001) → 'Solution'[source]¶ Compute a solution based on regulatory on/off minimization (ROOM).
Compute a new flux distribution that minimizes the number of active reactions needed to accommodate a previous reference solution. Regulatory on/off minimization (ROOM) is generally used to assess the impact of knock-outs. Thus, the typical usage is to provide a wild-type flux distribution as reference and a model in knock-out state.
- Parameters
model (cobra.Model) – The model state to compute a ROOM-based solution for.
solution (cobra.Solution, optional) – A (wild-type) reference solution (default None).
linear (bool, optional) – Whether to use the linear ROOM formulation or not (default False).
delta (float, optional) – The relative tolerance range (additive) (default 0.03).
epsilon (float, optional) – The absolute tolerance range (multiplicative) (default 0.001).
- Returns
A flux distribution with minimal active reaction changes compared to the reference.
- Return type
See also
add_room()
add ROOM constraints and objective
cobra.io
¶
Provide functions for loading and saving metabolic models.
Subpackages¶
cobra.io.web
¶Provide functionality to access remote model repositories.
cobra.io.web.abstract_model_repository
¶Provide an abstract base class that describes a remote model repository.
Define an abstract base class that describes a remote model repository. |
-
class
cobra.io.web.abstract_model_repository.
AbstractModelRepository
(*, url: Union[httpx.URL, str], **kwargs)[source]¶ Bases:
abc.ABC
Define an abstract base class that describes a remote model repository.
-
name
:str = Abstract[source]
-
cobra.io.web.bigg_models_repository
¶Provide a concrete implementation of the BioModels repository interface.
Define a concrete implementation of the BiGG Models repository. |
-
class
cobra.io.web.bigg_models_repository.
BiGGModels
(**kwargs)[source]¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BiGG Models repository.
-
name
:str = BiGG Models[source]
-
cobra.io.web.biomodels_repository
¶Provide functions for loading metabolic models over the wire.
Define a single BioModels file description. |
|
Define the BioModels files JSON response. |
|
Define a concrete implementation of the BioModels repository. |
-
class
cobra.io.web.biomodels_repository.
BioModelsFile
(__pydantic_self__, **data: Any)[source]¶ Bases:
pydantic.BaseModel
Define a single BioModels file description.
-
class
cobra.io.web.biomodels_repository.
BioModelsFilesResponse
(__pydantic_self__, **data: Any)[source]¶ Bases:
pydantic.BaseModel
Define the BioModels files JSON response.
-
class
cobra.io.web.biomodels_repository.
BioModels
(**kwargs)[source]¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BioModels repository.
-
name
:str = BioModels[source]
-
cobra.io.web.load
¶Provide a function load_model
to access remote model repositories.
|
Download an SBML model from a remote repository. |
|
Attempt to load a gzip-compressed SBML document from the cache. |
|
Attempt to load a gzip-compressed SBML document from the given repositories. |
|
Generate a model instance from a gzip-compressed, UTF-8 encoded SBML document. |
-
cobra.io.web.load.
load_model
(model_id: str, repositories: Iterable[AbstractModelRepository] = (BiGGModels(), BioModels()), cache: bool = True) → 'Model'[source]¶ Download an SBML model from a remote repository.
Downloaded SBML documents are by default stored in a cache on disk such that future access is much faster. By default, models can be loaded from the following repositories:
BiGG Models
BioModels
You can use the
AbstractModelRepository
class as a parent to implement your own repository accessor which you pass to theload_model
function. In case you implement a new interface, please consider submitting a pull request to COBRApy.- Parameters
model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.
repositories (iterable, optional) – An iterable of repository accessor instances. The model_id is searched in order.
cache (bool, optional) – Whether or not to use the local caching mechanism (default yes).
- Returns
A model instance generated from the SBML document.
- Return type
- Raises
RuntimeError – As with any internet connection, there are multiple errors that can occur.
Examples
# Most of the time calling load_model with an identifier should be enough. >>> print(load_model(“e_coli_core”)) e_coli_core >>> print(load_model(“MODEL1510010000”)) MODEL1510010000
See also
BiGGModels()
,BioModels()
-
cobra.io.web.load.
_cached_load
(model_id: str, repositories: Iterable[AbstractModelRepository]) → bytes[source]¶ Attempt to load a gzip-compressed SBML document from the cache.
If the given model identifier is not in the cache, the remote repositories are searched.
-
cobra.io.web.load.
_fetch_model
(model_id: str, repositories: Iterable[AbstractModelRepository]) → bytes[source]¶ Attempt to load a gzip-compressed SBML document from the given repositories.
Define an abstract base class that describes a remote model repository. |
|
Define a concrete implementation of the BiGG Models repository. |
|
Define a concrete implementation of the BioModels repository. |
|
Download an SBML model from a remote repository. |
-
class
cobra.io.web.
AbstractModelRepository
(*, url: Union[httpx.URL, str], **kwargs)[source]¶ Bases:
abc.ABC
Define an abstract base class that describes a remote model repository.
-
_progress
¶
-
name
:str = Abstract
-
property
url
(self) → httpx.URL¶ Return the repository’s URL.
-
-
class
cobra.io.web.
BiGGModels
(**kwargs)[source]¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BiGG Models repository.
-
name
:str = BiGG Models
-
get_sbml
(self, model_id: str) → bytes¶ Attempt to download an SBML document from the repository.
-
-
class
cobra.io.web.
BioModels
(**kwargs)[source]¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BioModels repository.
-
name
:str = BioModels
-
get_sbml
(self, model_id: str) → bytes¶ Attempt to download an SBML document from the repository.
-
-
cobra.io.web.
load_model
(model_id: str, repositories: Iterable[AbstractModelRepository] = (BiGGModels(), BioModels()), cache: bool = True) → 'Model'[source]¶ Download an SBML model from a remote repository.
Downloaded SBML documents are by default stored in a cache on disk such that future access is much faster. By default, models can be loaded from the following repositories:
BiGG Models
BioModels
You can use the
AbstractModelRepository
class as a parent to implement your own repository accessor which you pass to theload_model
function. In case you implement a new interface, please consider submitting a pull request to COBRApy.- Parameters
model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.
repositories (iterable, optional) – An iterable of repository accessor instances. The model_id is searched in order.
cache (bool, optional) – Whether or not to use the local caching mechanism (default yes).
- Returns
A model instance generated from the SBML document.
- Return type
- Raises
RuntimeError – As with any internet connection, there are multiple errors that can occur.
Examples
# Most of the time calling load_model with an identifier should be enough. >>> print(load_model(“e_coli_core”)) e_coli_core >>> print(load_model(“MODEL1510010000”)) MODEL1510010000
See also
Submodules¶
cobra.io.dict
¶
|
convert possible types to str, float, and bool |
|
update new_dict with optional attributes from cobra_object |
|
|
|
|
|
|
|
|
|
|
|
|
|
Convert model to a dict. |
|
Build a model from a dict. |
-
cobra.io.dict.
_REQUIRED_REACTION_ATTRIBUTES
= ['id', 'name', 'metabolites', 'lower_bound', 'upper_bound', 'gene_reaction_rule'][source]¶
-
cobra.io.dict.
_ORDERED_OPTIONAL_REACTION_KEYS
= ['objective_coefficient', 'subsystem', 'notes', 'annotation'][source]¶
-
cobra.io.dict.
_ORDERED_OPTIONAL_METABOLITE_KEYS
= ['charge', 'formula', '_bound', 'notes', 'annotation'][source]¶
-
cobra.io.dict.
_ORDERED_OPTIONAL_MODEL_KEYS
= ['name', 'compartments', 'notes', 'annotation'][source]¶
-
cobra.io.dict.
_update_optional
(cobra_object, new_dict, optional_attribute_dict, ordered_keys)[source]¶ update new_dict with optional attributes from cobra_object
-
cobra.io.dict.
model_to_dict
(model, sort=False)[source]¶ Convert model to a dict.
- Parameters
model (cobra.Model) – The model to reformulate as a dict.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
A dictionary with elements, ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists with dictionaries holding all attributes to form the corresponding object.
- Return type
OrderedDict
See also
-
cobra.io.dict.
model_from_dict
(obj)[source]¶ Build a model from a dict.
Models stored in json are first formulated as a dict that can be read to cobra model using this function.
- Parameters
obj (dict) – A dictionary with elements, ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists with dictionaries holding all attributes to form the corresponding object.
- Returns
The generated model.
- Return type
cora.core.Model
See also
cobra.io.json
¶
|
Return the model as a JSON document. |
|
Load a cobra model from a JSON document. |
|
Write the cobra model to a file in JSON format. |
|
Load a cobra model from a file in JSON format. |
-
cobra.io.json.
to_json
(model, sort=False, **kwargs)[source]¶ Return the model as a JSON document.
kwargs
are passed on tojson.dumps
.- Parameters
model (cobra.Model) – The cobra model to represent.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
String representation of the cobra model as a JSON document.
- Return type
See also
save_json_model()
Write directly to a file.
json.dumps()
Base function.
-
cobra.io.json.
from_json
(document)[source]¶ Load a cobra model from a JSON document.
- Parameters
document (str) – The JSON document representation of a cobra model.
- Returns
The cobra model as represented in the JSON document.
- Return type
See also
load_json_model()
Load directly from a file.
-
cobra.io.json.
save_json_model
(model, filename, sort=False, pretty=False, **kwargs)[source]¶ Write the cobra model to a file in JSON format.
kwargs
are passed on tojson.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
filename (str or file-like) – File path or descriptor that the JSON representation should be written to.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
pretty (bool, optional) – Whether to format the JSON more compactly (default) or in a more verbose but easier to read fashion. Can be partially overwritten by the
kwargs
.
See also
to_json()
Return a string representation.
json.dump()
Base function.
-
cobra.io.json.
load_json_model
(filename)[source]¶ Load a cobra model from a file in JSON format.
- Parameters
filename (str or file-like) – File path or descriptor that contains the JSON document describing the cobra model.
- Returns
The cobra model as represented in the JSON document.
- Return type
See also
from_json()
Load from a string.
cobra.io.mat
¶Helpers to interface with Matlab models.
Extract the compartment from the id string. |
|
|
Translate an array x into a MATLAB cell array. |
|
Load a cobra model stored as a .mat file. |
|
Save the cobra model as a .mat file. |
|
Obtain a metabolite id from a Matlab model. |
|
Create a dict mapping model attributes to arrays. |
|
Create a model from the COBRA toolbox struct. |
|
Ensure success of a pymatbridge operation. |
|
Send the model to a MATLAB workspace through pymatbridge. |
-
cobra.io.mat.
load_matlab_model
(infile_path, variable_name=None, inf=inf)[source]¶ Load a cobra model stored as a .mat file.
- Parameters
infile_path (str) – path to the file to to read
variable_name (str, optional) – The variable name of the model in the .mat file. If this is not specified, then the first MATLAB variable which looks like a COBRA model will be used
inf (value) – The value to use for infinite bounds. Some solvers do not handle infinite values so for using those, set this to a high numeric value.
- Returns
The resulting cobra model
- Return type
cobra.core.Model.Model
-
cobra.io.mat.
save_matlab_model
(model, file_name, varname=None)[source]¶ Save the cobra model as a .mat file.
This .mat file can be used directly in the MATLAB version of COBRA.
- Parameters
model (cobra.core.Model.Model object) – The model to save
file_name (str or file-like object) – The file to save to
varname (string) – The name of the variable within the workspace
-
cobra.io.mat.
from_mat_struct
(mat_struct, model_id=None, inf=inf)[source]¶ Create a model from the COBRA toolbox struct.
The struct will be a dict read in by scipy.io.loadmat
cobra.io.sbml
¶SBML import and export using python-libsbml.
The SBML importer supports all versions of SBML and the fbc package.
The SBML exporter writes SBML L3 models.
Annotation information is stored on the cobrapy objects
Information from the group package is read
Parsing of fbc models was implemented as efficient as possible, whereas (discouraged) fallback solutions are not optimized for efficiency.
Notes are only supported in a minimal way relevant for constraint-based models. I.e., structured information from notes in the form
<p>key: value</p>
is read into the Object.notes dictionary when reading SBML files. On writing the Object.notes dictionary is serialized to the SBML notes information.
Annotations are read in the Object.annotation fields.
Some SBML related issues are still open, please refer to the respective issue: - update annotation format and support qualifiers (depends on decision
for new annotation format; https://github.com/opencobra/cobrapy/issues/684)
- write compartment annotations and notes (depends on updated first-class
compartments; see https://github.com/opencobra/cobrapy/issues/760)
- support compression on file handles (depends on solution for
|
converts a non alphanumeric character to a string representation of |
|
converts an ascii number to a character |
|
Clips a prefix from the beginning of a string if it exists. |
|
Clips gene prefix from id. |
|
Adds gene prefix to id. |
|
Clips specie/metabolite prefix from id. |
|
Adds specie/metabolite prefix to id. |
|
Clips reaction prefix from id. |
|
Adds reaction prefix to id. |
|
Clips group prefix from id. |
|
Adds group prefix to id. |
|
Reads SBML model from given filename. |
|
Get SBMLDocument from given filename. |
|
Creates cobra model from SBMLDocument. |
|
Writes cobra model to filename. |
|
Convert Cobra model to SBMLDocument. |
|
Creates bound in model for given reaction. |
|
Create parameter in SBML model. |
|
Get required attribute from SBase. |
|
Checks the libsbml return value and logs error messages. |
|
Creates dictionary of COBRA notes. |
|
Set SBase notes based on dictionary. |
|
Parses cobra annotations from a given SBase object. |
Parses provider and term from given identifiers annotation uri. |
|
|
Set SBase annotations based on cobra annotations. |
|
Validate SBML model and returns the model along with a list of errors. |
|
String representation of SBMLError. |
-
cobra.io.sbml.
_escape_non_alphanum
(nonASCII)[source]¶ converts a non alphanumeric character to a string representation of its ascii number
-
cobra.io.sbml.
_clip
(sid, prefix)[source]¶ Clips a prefix from the beginning of a string if it exists.
-
cobra.io.sbml.
read_sbml_model
(filename, number=float, f_replace=F_REPLACE, **kwargs)[source]¶ Reads SBML model from given filename.
If the given filename ends with the suffix ‘’.gz’’ (for example, ‘’myfile.xml.gz’),’ the file is assumed to be compressed in gzip format and will be automatically decompressed upon reading. Similarly, if the given filename ends with ‘’.zip’’ or ‘’.bz2’,’ the file is assumed to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be read uncompressed. Note that if the file is in zip format but the archive contains more than one file, only the first file in the archive will be read and the rest ignored.
To read a gzip/zip file, libSBML needs to be configured and linked with the zlib library at compile time. It also needs to be linked with the bzip2 library to read files in bzip2 format. (Both of these are the default configurations for libSBML.)
This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models are converted to FBC-v2 models before reading.
The parser tries to fall back to information in notes dictionaries if information is not available in the FBC packages, e.g., CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.
- Parameters
filename (path to SBML file, or SBML string, or SBML file handle) – SBML which is read into cobra model
number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.
f_replace (dict of replacement functions for id replacement) – Dictionary of replacement functions for gene, specie, and reaction. By default the following id changes are performed on import: clip G_ from genes, clip M_ from species, clip R_ from reactions If no replacements should be performed, set f_replace={}, None
- Returns
- Return type
Notes
- Provided file handles cannot be opened in binary mode, i.e., use
- with open(path, “r” as f):
read_sbml_model(f)
File handles to compressed files are not supported yet.
-
cobra.io.sbml.
_get_doc_from_filename
(filename)[source]¶ Get SBMLDocument from given filename.
- Parameters
filename (path to SBML, or SBML string, or filehandle) –
- Returns
- Return type
libsbml.SBMLDocument
-
cobra.io.sbml.
_sbml_to_model
(doc, number=float, f_replace=F_REPLACE, set_missing_bounds=False, **kwargs)[source]¶ Creates cobra model from SBMLDocument.
- Parameters
doc (libsbml.SBMLDocument) –
number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.
f_replace (dict of replacement functions for id replacement) –
set_missing_bounds (flag to set missing bounds) –
- Returns
- Return type
-
cobra.io.sbml.
write_sbml_model
(cobra_model, filename, f_replace=F_REPLACE, **kwargs)[source]¶ Writes cobra model to filename.
The created model is SBML level 3 version 1 (L1V3) with fbc package v2 (fbc-v2).
If the given filename ends with the suffix “.gz” (for example, “myfile.xml.gz”), libSBML assumes the caller wants the file to be written compressed in gzip format. Similarly, if the given filename ends with “.zip” or “.bz2”, libSBML assumes the caller wants the file to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be written uncompressed. Special considerations for the zip format: If the given filename ends with “.zip”, the file placed in the zip archive will have the suffix “.xml” or “.sbml”. For example, the file in the zip archive will be named “test.xml” if the given filename is “test.xml.zip” or “test.zip”. Similarly, the filename in the archive will be “test.sbml” if the given filename is “test.sbml.zip”.
- Parameters
cobra_model (cobra.core.Model) – Model instance which is written to SBML
filename (string) – path to which the model is written
f_replace (dict of replacement functions for id replacement) –
-
cobra.io.sbml.
_model_to_sbml
(cobra_model, f_replace=None, units=True)[source]¶ Convert Cobra model to SBMLDocument.
- Parameters
cobra_model (cobra.core.Model) – Cobra model instance
f_replace (dict of replacement functions) – Replacement to apply on identifiers.
units (boolean) – Should the FLUX_UNITS be written in the SBMLDocument.
- Returns
- Return type
libsbml.SBMLDocument
-
cobra.io.sbml.
_create_bound
(model, reaction, bound_type, f_replace, units=None, flux_udef=None)[source]¶ Creates bound in model for given reaction.
Adds the parameters for the bounds to the SBML model.
- Parameters
model (libsbml.Model) – SBML model instance
reaction (cobra.core.Reaction) – Cobra reaction instance from which the bounds are read.
bound_type ({LOWER_BOUND, UPPER_BOUND}) – Type of bound
f_replace (dict of id replacement functions) –
units (flux units) –
- Returns
- Return type
Id of bound parameter.
-
cobra.io.sbml.
_create_parameter
(model, pid, value, sbo=None, constant=True, units=None, flux_udef=None)[source]¶ Create parameter in SBML model.
-
cobra.io.sbml.
_check_required
(sbase, value, attribute)[source]¶ Get required attribute from SBase.
- Parameters
sbase (libsbml.SBase) –
value (existing value) –
attribute (name of attribute) –
- Returns
- Return type
attribute value (or value if already set)
-
cobra.io.sbml.
_check
(value, message)[source]¶ Checks the libsbml return value and logs error messages.
- If ‘value’ is None, logs an error message constructed using
‘message’ and then exits with status code 1. If ‘value’ is an integer, it assumes it is a libSBML return status code. If the code value is LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not, prints an error message constructed using ‘message’ along with text from libSBML explaining the meaning of the code, and exits with status code 1.
-
cobra.io.sbml.
_parse_notes_dict
(sbase)[source]¶ Creates dictionary of COBRA notes.
- Parameters
sbase (libsbml.SBase) –
- Returns
- Return type
dict of notes
-
cobra.io.sbml.
_sbase_notes_dict
(sbase, notes)[source]¶ Set SBase notes based on dictionary.
- Parameters
sbase (libsbml.SBase) – SBML object to set notes on
notes (notes object) – notes information from cobra object
-
cobra.io.sbml.
_parse_annotations
(sbase)[source]¶ Parses cobra annotations from a given SBase object.
Annotations are dictionaries with the providers as keys.
- Parameters
sbase (libsbml.SBase) – SBase from which the SBML annotations are read
- Returns
dict (annotation dictionary)
FIXME (annotation format must be updated (this is a big collection of) – fixes) - see: https://github.com/opencobra/cobrapy/issues/684)
-
cobra.io.sbml.
_parse_annotation_info
(uri)[source]¶ Parses provider and term from given identifiers annotation uri.
- Parameters
uri (str) – uri (identifiers.org url)
- Returns
- Return type
(provider, identifier) if resolvable, None otherwise
-
cobra.io.sbml.
_sbase_annotations
(sbase, annotation)[source]¶ Set SBase annotations based on cobra annotations.
- Parameters
sbase (libsbml.SBase) – SBML object to annotate
annotation (cobra annotation structure) – cobra object with annotation information
FIXME (annotation format must be updated) – (https://github.com/opencobra/cobrapy/issues/684)
-
cobra.io.sbml.
validate_sbml_model
(filename, check_model=True, internal_consistency=True, check_units_consistency=False, check_modeling_practice=False, **kwargs)[source]¶ Validate SBML model and returns the model along with a list of errors.
- Parameters
filename (str) – The filename (or SBML string) of the SBML model to be validated.
internal_consistency (boolean {True, False}) – Check internal consistency.
check_units_consistency (boolean {True, False}) – Check consistency of units.
check_modeling_practice (boolean {True, False}) – Check modeling practise.
check_model (boolean {True, False}) – Whether to also check some basic model properties such as reaction boundaries and compartment formulas.
- Returns
(model, errors)
model (
Model
object) – The cobra model if the file could be read successfully or None otherwise.errors (dict) – Warnings and errors grouped by their respective types.
- Raises
cobra.io.yaml
¶
|
Return the model as a YAML document. |
|
Load a cobra model from a YAML document. |
|
Write the cobra model to a file in YAML format. |
|
Load a cobra model from a file in YAML format. |
-
class
cobra.io.yaml.
MyYAML
(: Any, *, typ: Optional[Text] = None, pure: Any = False, output: Any = None, plug_ins: Any = None)[source]¶ Bases:
ruamel.yaml.main.YAML
-
cobra.io.yaml.
to_yaml
(model, sort=False, **kwargs)[source]¶ Return the model as a YAML document.
kwargs
are passed on toyaml.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
String representation of the cobra model as a YAML document.
- Return type
See also
save_yaml_model()
Write directly to a file.
ruamel.yaml.dump()
Base function.
-
cobra.io.yaml.
from_yaml
(document)[source]¶ Load a cobra model from a YAML document.
- Parameters
document (str) – The YAML document representation of a cobra model.
- Returns
The cobra model as represented in the YAML document.
- Return type
See also
load_yaml_model()
Load directly from a file.
-
cobra.io.yaml.
save_yaml_model
(model, filename, sort=False, **kwargs)[source]¶ Write the cobra model to a file in YAML format.
kwargs
are passed on toyaml.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
filename (str or file-like) – File path or descriptor that the YAML representation should be written to.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
See also
to_yaml()
Return a string representation.
ruamel.yaml.dump()
Base function.
-
cobra.io.yaml.
load_yaml_model
(filename)[source]¶ Load a cobra model from a file in YAML format.
- Parameters
filename (str or file-like) – File path or descriptor that contains the YAML document describing the cobra model.
- Returns
The cobra model as represented in the YAML document.
- Return type
See also
from_yaml()
Load from a string.
Package Contents¶
Define an abstract base class that describes a remote model repository. |
|
Define a concrete implementation of the BiGG Models repository. |
|
Define a concrete implementation of the BioModels repository. |
|
Build a model from a dict. |
|
Convert model to a dict. |
|
Load a cobra model from a JSON document. |
|
Load a cobra model from a file in JSON format. |
|
Write the cobra model to a file in JSON format. |
|
Return the model as a JSON document. |
|
Load a cobra model stored as a .mat file. |
|
Save the cobra model as a .mat file. |
|
Reads SBML model from given filename. |
|
Writes cobra model to filename. |
|
Validate SBML model and returns the model along with a list of errors. |
|
Load a cobra model from a YAML document. |
|
Load a cobra model from a file in YAML format. |
|
Write the cobra model to a file in YAML format. |
|
Return the model as a YAML document. |
|
Download an SBML model from a remote repository. |
-
cobra.io.
model_from_dict
(obj)[source]¶ Build a model from a dict.
Models stored in json are first formulated as a dict that can be read to cobra model using this function.
- Parameters
obj (dict) – A dictionary with elements, ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists with dictionaries holding all attributes to form the corresponding object.
- Returns
The generated model.
- Return type
cora.core.Model
See also
-
cobra.io.
model_to_dict
(model, sort=False)[source]¶ Convert model to a dict.
- Parameters
model (cobra.Model) – The model to reformulate as a dict.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
A dictionary with elements, ‘genes’, ‘compartments’, ‘id’, ‘metabolites’, ‘notes’ and ‘reactions’; where ‘metabolites’, ‘genes’ and ‘metabolites’ are in turn lists with dictionaries holding all attributes to form the corresponding object.
- Return type
OrderedDict
See also
-
cobra.io.
from_json
(document)[source]¶ Load a cobra model from a JSON document.
- Parameters
document (str) – The JSON document representation of a cobra model.
- Returns
The cobra model as represented in the JSON document.
- Return type
See also
load_json_model()
Load directly from a file.
-
cobra.io.
load_json_model
(filename)[source]¶ Load a cobra model from a file in JSON format.
- Parameters
filename (str or file-like) – File path or descriptor that contains the JSON document describing the cobra model.
- Returns
The cobra model as represented in the JSON document.
- Return type
See also
from_json()
Load from a string.
-
cobra.io.
save_json_model
(model, filename, sort=False, pretty=False, **kwargs)[source]¶ Write the cobra model to a file in JSON format.
kwargs
are passed on tojson.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
filename (str or file-like) – File path or descriptor that the JSON representation should be written to.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
pretty (bool, optional) – Whether to format the JSON more compactly (default) or in a more verbose but easier to read fashion. Can be partially overwritten by the
kwargs
.
See also
to_json()
Return a string representation.
json.dump()
Base function.
-
cobra.io.
to_json
(model, sort=False, **kwargs)[source]¶ Return the model as a JSON document.
kwargs
are passed on tojson.dumps
.- Parameters
model (cobra.Model) – The cobra model to represent.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
String representation of the cobra model as a JSON document.
- Return type
See also
save_json_model()
Write directly to a file.
json.dumps()
Base function.
-
cobra.io.
load_matlab_model
(infile_path, variable_name=None, inf=inf)[source]¶ Load a cobra model stored as a .mat file.
- Parameters
infile_path (str) – path to the file to to read
variable_name (str, optional) – The variable name of the model in the .mat file. If this is not specified, then the first MATLAB variable which looks like a COBRA model will be used
inf (value) – The value to use for infinite bounds. Some solvers do not handle infinite values so for using those, set this to a high numeric value.
- Returns
The resulting cobra model
- Return type
cobra.core.Model.Model
-
cobra.io.
save_matlab_model
(model, file_name, varname=None)[source]¶ Save the cobra model as a .mat file.
This .mat file can be used directly in the MATLAB version of COBRA.
- Parameters
model (cobra.core.Model.Model object) – The model to save
file_name (str or file-like object) – The file to save to
varname (string) – The name of the variable within the workspace
-
cobra.io.
read_sbml_model
(filename, number=float, f_replace=F_REPLACE, **kwargs)[source]¶ Reads SBML model from given filename.
If the given filename ends with the suffix ‘’.gz’’ (for example, ‘’myfile.xml.gz’),’ the file is assumed to be compressed in gzip format and will be automatically decompressed upon reading. Similarly, if the given filename ends with ‘’.zip’’ or ‘’.bz2’,’ the file is assumed to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be read uncompressed. Note that if the file is in zip format but the archive contains more than one file, only the first file in the archive will be read and the rest ignored.
To read a gzip/zip file, libSBML needs to be configured and linked with the zlib library at compile time. It also needs to be linked with the bzip2 library to read files in bzip2 format. (Both of these are the default configurations for libSBML.)
This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models are converted to FBC-v2 models before reading.
The parser tries to fall back to information in notes dictionaries if information is not available in the FBC packages, e.g., CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.
- Parameters
filename (path to SBML file, or SBML string, or SBML file handle) – SBML which is read into cobra model
number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.
f_replace (dict of replacement functions for id replacement) – Dictionary of replacement functions for gene, specie, and reaction. By default the following id changes are performed on import: clip G_ from genes, clip M_ from species, clip R_ from reactions If no replacements should be performed, set f_replace={}, None
- Returns
- Return type
Notes
- Provided file handles cannot be opened in binary mode, i.e., use
- with open(path, “r” as f):
read_sbml_model(f)
File handles to compressed files are not supported yet.
-
cobra.io.
write_sbml_model
(cobra_model, filename, f_replace=F_REPLACE, **kwargs)[source]¶ Writes cobra model to filename.
The created model is SBML level 3 version 1 (L1V3) with fbc package v2 (fbc-v2).
If the given filename ends with the suffix “.gz” (for example, “myfile.xml.gz”), libSBML assumes the caller wants the file to be written compressed in gzip format. Similarly, if the given filename ends with “.zip” or “.bz2”, libSBML assumes the caller wants the file to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be written uncompressed. Special considerations for the zip format: If the given filename ends with “.zip”, the file placed in the zip archive will have the suffix “.xml” or “.sbml”. For example, the file in the zip archive will be named “test.xml” if the given filename is “test.xml.zip” or “test.zip”. Similarly, the filename in the archive will be “test.sbml” if the given filename is “test.sbml.zip”.
- Parameters
cobra_model (cobra.core.Model) – Model instance which is written to SBML
filename (string) – path to which the model is written
f_replace (dict of replacement functions for id replacement) –
-
cobra.io.
validate_sbml_model
(filename, check_model=True, internal_consistency=True, check_units_consistency=False, check_modeling_practice=False, **kwargs)[source]¶ Validate SBML model and returns the model along with a list of errors.
- Parameters
filename (str) – The filename (or SBML string) of the SBML model to be validated.
internal_consistency (boolean {True, False}) – Check internal consistency.
check_units_consistency (boolean {True, False}) – Check consistency of units.
check_modeling_practice (boolean {True, False}) – Check modeling practise.
check_model (boolean {True, False}) – Whether to also check some basic model properties such as reaction boundaries and compartment formulas.
- Returns
(model, errors)
model (
Model
object) – The cobra model if the file could be read successfully or None otherwise.errors (dict) – Warnings and errors grouped by their respective types.
- Raises
-
cobra.io.
from_yaml
(document)[source]¶ Load a cobra model from a YAML document.
- Parameters
document (str) – The YAML document representation of a cobra model.
- Returns
The cobra model as represented in the YAML document.
- Return type
See also
load_yaml_model()
Load directly from a file.
-
cobra.io.
load_yaml_model
(filename)[source]¶ Load a cobra model from a file in YAML format.
- Parameters
filename (str or file-like) – File path or descriptor that contains the YAML document describing the cobra model.
- Returns
The cobra model as represented in the YAML document.
- Return type
See also
from_yaml()
Load from a string.
-
cobra.io.
save_yaml_model
(model, filename, sort=False, **kwargs)[source]¶ Write the cobra model to a file in YAML format.
kwargs
are passed on toyaml.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
filename (str or file-like) – File path or descriptor that the YAML representation should be written to.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
See also
to_yaml()
Return a string representation.
ruamel.yaml.dump()
Base function.
-
cobra.io.
to_yaml
(model, sort=False, **kwargs)[source]¶ Return the model as a YAML document.
kwargs
are passed on toyaml.dump
.- Parameters
model (cobra.Model) – The cobra model to represent.
sort (bool, optional) – Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model.
- Returns
String representation of the cobra model as a YAML document.
- Return type
See also
save_yaml_model()
Write directly to a file.
ruamel.yaml.dump()
Base function.
-
class
cobra.io.
AbstractModelRepository
(*, url: Union[httpx.URL, str], **kwargs)¶ Bases:
abc.ABC
Define an abstract base class that describes a remote model repository.
-
_progress
¶
-
name
:str = Abstract
-
property
url
(self) → httpx.URL¶ Return the repository’s URL.
-
-
class
cobra.io.
BiGGModels
(**kwargs)¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BiGG Models repository.
-
name
:str = BiGG Models
-
get_sbml
(self, model_id: str) → bytes¶ Attempt to download an SBML document from the repository.
-
-
class
cobra.io.
BioModels
(**kwargs)¶ Bases:
cobra.io.web.abstract_model_repository.AbstractModelRepository
Define a concrete implementation of the BioModels repository.
-
name
:str = BioModels
-
get_sbml
(self, model_id: str) → bytes¶ Attempt to download an SBML document from the repository.
-
-
cobra.io.
load_model
(model_id: str, repositories: Iterable[AbstractModelRepository] = (BiGGModels(), BioModels()), cache: bool = True) → 'Model'¶ Download an SBML model from a remote repository.
Downloaded SBML documents are by default stored in a cache on disk such that future access is much faster. By default, models can be loaded from the following repositories:
BiGG Models
BioModels
You can use the
AbstractModelRepository
class as a parent to implement your own repository accessor which you pass to theload_model
function. In case you implement a new interface, please consider submitting a pull request to COBRApy.- Parameters
model_id (str) – The identifier of the desired metabolic model. This is typically repository specific.
repositories (iterable, optional) – An iterable of repository accessor instances. The model_id is searched in order.
cache (bool, optional) – Whether or not to use the local caching mechanism (default yes).
- Returns
A model instance generated from the SBML document.
- Return type
- Raises
RuntimeError – As with any internet connection, there are multiple errors that can occur.
Examples
# Most of the time calling load_model with an identifier should be enough. >>> print(load_model(“e_coli_core”)) e_coli_core >>> print(load_model(“MODEL1510010000”)) MODEL1510010000
See also
cobra.manipulation
¶
Submodules¶
cobra.manipulation.annotate
¶Provide function for annotating demand and exchange reactions.
|
Add SBO terms for demands and exchanges. |
-
cobra.manipulation.annotate.
add_SBO
(model: Model) → None[source]¶ Add SBO terms for demands and exchanges.
This works for models which follow the standard convention for constructing and naming these reactions.
The reaction should only contain the single metabolite being exchanged, and the id should be EX_<met_id> or DM_<met_id> .
- Parameters
model (cobra.Model) – The model whose demand and exchange reactions need to be annotated.
cobra.manipulation.delete
¶Provide functions for pruning reactions, metabolites and genes.
Class to represent a gene set remover. |
|
Remove metabolites not involved in any reactions. |
|
Remove reactions with no assigned metabolites, returns pruned model. |
|
Undo the effects of a call to delete_model_genes in place. |
|
Generate a dictionary of compiled gene-reaction rules. |
|
Identify reactions which will be disabled when genes are knocked out. |
|
Temporarily remove the effect of genes in gene_list. |
|
Remove genes entirely from the model. |
-
cobra.manipulation.delete.
prune_unused_metabolites
(model: Model) → Tuple['Model', List['Metabolite']][source]¶ Remove metabolites not involved in any reactions.
- Parameters
model (cobra.Model) – The model to remove unused metabolites from.
- Returns
cobra.Model – Input model with unused metabolites removed.
list of cobra.Metabolite – List of metabolites that were removed.
-
cobra.manipulation.delete.
prune_unused_reactions
(model: Model) → Tuple['Model', List['Reaction']][source]¶ Remove reactions with no assigned metabolites, returns pruned model.
- Parameters
model (cobra.Model) – The model to remove unused reactions from.
- Returns
cobra.Model – Input model with unused reactions removed.
list of cobra.Reaction – List of reactions that were removed.
-
cobra.manipulation.delete.
undelete_model_genes
(model: Model) → None[source]¶ Undo the effects of a call to delete_model_genes in place.
- Parameters
model (cobra.Model) – The model which will be modified in place.
-
cobra.manipulation.delete.
get_compiled_gene_reaction_rules
(model: Model) → Dict['Reaction', Module][source]¶ Generate a dictionary of compiled gene-reaction rules.
Any gene-reaction rule expression which cannot be compiled or do not evaluate after compiling will be excluded. The result can be used in the find_gene_knockout_reactions function to speed up evaluation of these rules.
- Parameters
model (cobra.Model) – The model to get gene-reaction rules for.
- Returns
The dictionary of cobra.Reaction objects as keys and ast.Module objects as keys.
- Return type
dict of cobra.Reaction, ast.Module
-
cobra.manipulation.delete.
find_gene_knockout_reactions
(model: Model, gene_list: List['Gene'], compiled_gene_reaction_rules: Optional[Dict['Reaction', Module]] = None) → List['Reaction'][source]¶ Identify reactions which will be disabled when genes are knocked out.
- Parameters
model (cobra.Model) – The model for which to find gene knock-out reactions.
gene_list (list of cobra.Gene) – The list of genes to knock-out.
compiled_gene_reaction_rules (dict of {reaction: compiled_string},) – optional If provided, this gives pre-compiled gene-reaction rule strings. The compiled rule strings can be evaluated much faster. If a rule is not provided, the regular expression evaluation will be used. Because not all gene-reaction rule strings can be evaluated, this dict must exclude any rules which can not be used with eval (default None).
- Returns
list of cobra.Reaction – The list of cobra.Reaction objects which will be disabled.
.. deprecated:: 0.22.1 – Internal function that has outlived its purpose.
-
cobra.manipulation.delete.
delete_model_genes
(model: Model, gene_list: List['Gene'], cumulative_deletions: bool = True, disable_orphans: bool = False) → None[source]¶ Temporarily remove the effect of genes in gene_list.
It sets the bounds to “zero” for reactions catalysed by the genes in gene_list if deleting the genes stops the reactions from proceeding.
- Parameters
model (cobra.Model) – The model whose reaction bounds are to be set.
gene_list (list of cobra.Gene) – The list of genes to knock-out.
cumulative_deletions (bool, optional) – If True, then any previous deletions will be maintained in the model (default True).
disable_orphans (bool, optional) – If True, then orphan reactions will be disabled. Currently, this is not implemented (default False).
-
class
cobra.manipulation.delete.
_GeneRemover
(target_genes: List['Gene'], **kwargs)[source]¶ Bases:
ast.NodeTransformer
Class to represent a gene set remover.
- Parameters
target_genes (list of cobra.Gene) – A list of genes to be removed.
-
visit_Name
(self, node: Gene) → Optional['Gene'][source]¶ Remove a gene.
- Parameters
node (cobra.Gene) – The gene to remove.
- Returns
None if gene object is in target_genes.
- Return type
cobra.Gene or None
-
visit_BoolOp
(self, node: Gene) → Optional['Gene'][source]¶ Rules for boolean operations.
- Parameters
node (cobra.Gene) – The gene to apply rules to.
- Returns
None if size of node values is less after applying rule.
- Return type
cobra.Gene or None
-
cobra.manipulation.delete.
remove_genes
(model: Model, gene_list: List['Gene'], remove_reactions: bool = True) → None[source]¶ Remove genes entirely from the model.
This will also simplify all gene-reaction rules with the genes inactivated.
- Parameters
model (cobra.Model) – The model to remove genes from.
gene_list (list of cobra.Gene) – The list of gene objects to remove.
remove_reactions (bool, optional) – Whether to remove reactions associated with genes in gene_list (default True).
cobra.manipulation.modify
¶Provide functions to modify model components.
Class to represent a gene ID escaper. |
|
Class to represent a gene renamer. |
|
Make a single string ID SBML compliant. |
|
Make all model component object IDs SBML compliant. |
|
Rename genes in a model from the rename_dict. |
-
cobra.manipulation.modify.
_renames
= [['.', '_DOT_'], ['(', '_LPAREN_'], [')', '_RPAREN_'], ['-', '__'], ['[', '_LSQBKT'], [']', '_RSQBKT'], [',', '_COMMA_'], [':', '_COLON_'], ['>', '_GT_'], ['<', '_LT'], ['/', '_FLASH'], ['\\', '_BSLASH'], ['+', '_PLUS_'], ['=', '_EQ_'], [' ', '_SPACE_'], ["'", '_SQUOT_'], ['"', '_DQUOT_']][source]¶
-
cobra.manipulation.modify.
_escape_str_id
(id_str: str) → str[source]¶ Make a single string ID SBML compliant.
-
class
cobra.manipulation.modify.
_GeneEscaper
[source]¶ Bases:
ast.NodeTransformer
Class to represent a gene ID escaper.
-
visit_Name
(self, node: Gene) → 'Gene'[source]¶ Escape string ID.
- Parameters
node (cobra.Gene) – The gene object to work on.
- Returns
The gene object whose ID has been escaped.
- Return type
-
-
cobra.manipulation.modify.
escape_ID
(model: Model) → None[source]¶ Make all model component object IDs SBML compliant.
- Parameters
model (cobra.Model) – The model to operate on.
-
class
cobra.manipulation.modify.
_Renamer
(rename_dict: Dict[str, str], **kwargs)[source]¶ Bases:
ast.NodeTransformer
Class to represent a gene renamer.
- Parameters
rename_dict (dict of {str: str}) – The dictionary having keys as old gene names and value as new gene names.
-
visit_Name
(self, node: Gene) → 'Gene'[source]¶ Rename a gene.
- Parameters
node (cobra.Gene) – The gene to rename.
- Returns
The renamed gene object.
- Return type
-
cobra.manipulation.modify.
rename_genes
(model: Model, rename_dict: Dict[str, str]) → None[source]¶ Rename genes in a model from the rename_dict.
- Parameters
model (cobra.Model) – The model to operate on.
rename_dict (dict of {str: str}) – The dictionary having keys as old gene names and value as new gene names.
cobra.manipulation.validate
¶Provide functions for model component validations.
|
Check mass balance for reactions of model and return unbalanced ones. |
|
Check metabolite formulae of model. |
-
cobra.manipulation.validate.
check_mass_balance
(model: Model) → Dict['Reaction', Dict['Metabolite', float]][source]¶ Check mass balance for reactions of model and return unbalanced ones.
- Parameters
model (cobra.Model) – The model to perform check on.
- Returns
dict of {cobra.Reaction – Returns an empty dict if all components are balanced.
- Return type
dict of {cobra.Metabolite: float}}
-
cobra.manipulation.validate.
check_metabolite_compartment_formula
(model: Model) → List[str][source]¶ Check metabolite formulae of model.
- Parameters
model (cobra.Model) – The model to perform check on.
- Returns
Returns an empty list if no errors are found.
- Return type
list of str
Package Contents¶
|
Add SBO terms for demands and exchanges. |
|
Temporarily remove the effect of genes in gene_list. |
|
Identify reactions which will be disabled when genes are knocked out. |
|
Remove metabolites not involved in any reactions. |
|
Remove reactions with no assigned metabolites, returns pruned model. |
|
Remove genes entirely from the model. |
|
Undo the effects of a call to delete_model_genes in place. |
|
Make all model component object IDs SBML compliant. |
|
Generate a dictionary of compiled gene-reaction rules. |
|
Rename genes in a model from the rename_dict. |
|
Check mass balance for reactions of model and return unbalanced ones. |
|
Check metabolite formulae of model. |
-
cobra.manipulation.
add_SBO
(model: Model) → None[source]¶ Add SBO terms for demands and exchanges.
This works for models which follow the standard convention for constructing and naming these reactions.
The reaction should only contain the single metabolite being exchanged, and the id should be EX_<met_id> or DM_<met_id> .
- Parameters
model (cobra.Model) – The model whose demand and exchange reactions need to be annotated.
-
cobra.manipulation.
delete_model_genes
(model: Model, gene_list: List['Gene'], cumulative_deletions: bool = True, disable_orphans: bool = False) → None[source]¶ Temporarily remove the effect of genes in gene_list.
It sets the bounds to “zero” for reactions catalysed by the genes in gene_list if deleting the genes stops the reactions from proceeding.
- Parameters
model (cobra.Model) – The model whose reaction bounds are to be set.
gene_list (list of cobra.Gene) – The list of genes to knock-out.
cumulative_deletions (bool, optional) – If True, then any previous deletions will be maintained in the model (default True).
disable_orphans (bool, optional) – If True, then orphan reactions will be disabled. Currently, this is not implemented (default False).
-
cobra.manipulation.
find_gene_knockout_reactions
(model: Model, gene_list: List['Gene'], compiled_gene_reaction_rules: Optional[Dict['Reaction', Module]] = None) → List['Reaction'][source]¶ Identify reactions which will be disabled when genes are knocked out.
- Parameters
model (cobra.Model) – The model for which to find gene knock-out reactions.
gene_list (list of cobra.Gene) – The list of genes to knock-out.
compiled_gene_reaction_rules (dict of {reaction: compiled_string},) – optional If provided, this gives pre-compiled gene-reaction rule strings. The compiled rule strings can be evaluated much faster. If a rule is not provided, the regular expression evaluation will be used. Because not all gene-reaction rule strings can be evaluated, this dict must exclude any rules which can not be used with eval (default None).
- Returns
list of cobra.Reaction – The list of cobra.Reaction objects which will be disabled.
.. deprecated:: 0.22.1 – Internal function that has outlived its purpose.
-
cobra.manipulation.
prune_unused_metabolites
(model: Model) → Tuple['Model', List['Metabolite']][source]¶ Remove metabolites not involved in any reactions.
- Parameters
model (cobra.Model) – The model to remove unused metabolites from.
- Returns
cobra.Model – Input model with unused metabolites removed.
list of cobra.Metabolite – List of metabolites that were removed.
-
cobra.manipulation.
prune_unused_reactions
(model: Model) → Tuple['Model', List['Reaction']][source]¶ Remove reactions with no assigned metabolites, returns pruned model.
- Parameters
model (cobra.Model) – The model to remove unused reactions from.
- Returns
cobra.Model – Input model with unused reactions removed.
list of cobra.Reaction – List of reactions that were removed.
-
cobra.manipulation.
remove_genes
(model: Model, gene_list: List['Gene'], remove_reactions: bool = True) → None[source]¶ Remove genes entirely from the model.
This will also simplify all gene-reaction rules with the genes inactivated.
- Parameters
model (cobra.Model) – The model to remove genes from.
gene_list (list of cobra.Gene) – The list of gene objects to remove.
remove_reactions (bool, optional) – Whether to remove reactions associated with genes in gene_list (default True).
-
cobra.manipulation.
undelete_model_genes
(model: Model) → None[source]¶ Undo the effects of a call to delete_model_genes in place.
- Parameters
model (cobra.Model) – The model which will be modified in place.
-
cobra.manipulation.
escape_ID
(model: Model) → None[source]¶ Make all model component object IDs SBML compliant.
- Parameters
model (cobra.Model) – The model to operate on.
-
cobra.manipulation.
get_compiled_gene_reaction_rules
(model: Model) → Dict['Reaction', Module]¶ Generate a dictionary of compiled gene-reaction rules.
Any gene-reaction rule expression which cannot be compiled or do not evaluate after compiling will be excluded. The result can be used in the find_gene_knockout_reactions function to speed up evaluation of these rules.
- Parameters
model (cobra.Model) – The model to get gene-reaction rules for.
- Returns
The dictionary of cobra.Reaction objects as keys and ast.Module objects as keys.
- Return type
dict of cobra.Reaction, ast.Module
-
cobra.manipulation.
rename_genes
(model: Model, rename_dict: Dict[str, str]) → None[source]¶ Rename genes in a model from the rename_dict.
- Parameters
model (cobra.Model) – The model to operate on.
rename_dict (dict of {str: str}) – The dictionary having keys as old gene names and value as new gene names.
-
cobra.manipulation.
check_mass_balance
(model: Model) → Dict['Reaction', Dict['Metabolite', float]][source]¶ Check mass balance for reactions of model and return unbalanced ones.
- Parameters
model (cobra.Model) – The model to perform check on.
- Returns
dict of {cobra.Reaction – Returns an empty dict if all components are balanced.
- Return type
dict of {cobra.Metabolite: float}}
-
cobra.manipulation.
check_metabolite_compartment_formula
(model: Model) → List[str][source]¶ Check metabolite formulae of model.
- Parameters
model (cobra.Model) – The model to perform check on.
- Returns
Returns an empty list if no errors are found.
- Return type
list of str
cobra.medium
¶
Submodules¶
cobra.medium.annotations
¶Provide lists and annotations for compartment names and reactions.
Please send a PR if you want to add something here :)
cobra.medium.boundary_types
¶Provide functions to identify the type of boundary reactions.
This module uses various heuristics to decide whether a boundary reaction is an exchange, demand or sink reaction. It mostly orientates on the following paper:
Thiele, I., & Palsson, B. Ø. (2010, January). A protocol for generating a high-quality genome-scale metabolic reconstruction. Nature protocols. Nature Publishing Group. http://doi.org/10.1038/nprot.2009.203
|
Find the external compartment in the model. |
|
Check whether a reaction is an exchange reaction. |
|
Find specific boundary reactions. |
-
cobra.medium.boundary_types.
find_external_compartment
(model: Model) → str[source]¶ Find the external compartment in the model.
Uses a simple heuristic where the external compartment should be the one with the most exchange reactions.
- Parameters
model (cobra.Model) – The cobra model whose external compartments are to be identified.
- Returns
The putative external compartment.
- Return type
- Raises
RuntimeError – If several compartments are similar and thus difficult to identify, or, recognized names usually used for external compartment are absent.
-
cobra.medium.boundary_types.
is_boundary_type
(reaction: Reaction, boundary_type: str, external_compartment: str) → bool[source]¶ Check whether a reaction is an exchange reaction.
- Parameters
reaction (cobra.Reaction) – The reaction to check.
boundary_type ({"exchange", "demand", "sink"}) – Boundary type to check for.
external_compartment (str) – The ID for the external compartment.
- Returns
Whether the reaction looks like the requested type. Might be based on a heuristic.
- Return type
-
cobra.medium.boundary_types.
find_boundary_types
(model: Model, boundary_type: str, external_compartment: Optional[str] = None) → List['Reaction'][source]¶ Find specific boundary reactions.
- Parameters
model (cobra.Model) – The cobra model whose boundary reactions are to be found.
boundary_type ({"exchange", "demand", "sink"}) – Boundary type to check for.
external_compartment (str, optional) – The ID for the external compartment. If None, it will be detected automatically (default None).
- Returns
A list of likely boundary reactions of a user defined type.
- Return type
list of cobra.Reaction or an empty list
cobra.medium.minimal_medium
¶Provide functions and helpers to obtain minimal growth media.
|
Add a linear version of a minimal medium to the model solver. |
|
Add a mixed-integer version of a minimal medium to the model. |
|
Convert a solution to medium. |
|
Find the minimal growth medium for the model. |
-
cobra.medium.minimal_medium.
add_linear_obj
(model: Model) → None[source]¶ Add a linear version of a minimal medium to the model solver.
Changes the optimization objective to finding the growth medium requiring the smallest total import flux:
..math:: minimize sum_{r_i in import_reactions} |r_i|
- Parameters
model (cobra.Model) – The cobra model to modify.
-
cobra.medium.minimal_medium.
add_mip_obj
(model: Model) → None[source]¶ Add a mixed-integer version of a minimal medium to the model.
Changes the optimization objective to finding the medium with the least components:
minimize size(R) where R part of import_reactions
- Parameters
model (cobra.model) – The model to modify.
-
cobra.medium.minimal_medium.
_as_medium
(exchanges: Iterable['Reaction'], tolerance: float = 1e-06, exports: bool = False) → pd.Series[source]¶ Convert a solution to medium.
- Parameters
exchanges (list of cobra.reaction) – The exchange reactions to consider.
tolerance (float > 0, optional) – The absolute tolerance for fluxes. Fluxes with an absolute value smaller than this number will be ignored (default 1e-6).
exports (bool, optional) – Whether to return export fluxes as well (default False).
- Returns
The “medium”, meaning all active import fluxes in the solution.
- Return type
pandas.Series
-
cobra.medium.minimal_medium.
minimal_medium
(model: Model, min_objective_value: float = 0.1, exports: bool = False, minimize_components: Union[bool, int] = False, open_exchanges: bool = False) → Union[pd.Series, pd.DataFrame, None][source]¶ Find the minimal growth medium for the model.
Finds the minimal growth medium for the model which allows for model as well as individual growth. Here, a minimal medium can either be the medium requiring the smallest total import flux or the medium requiring the least components (ergo ingredients), which will be much slower due to being a mixed integer problem (MIP).
- Parameters
model (cobra.model) – The model to modify.
min_objective_value (float > 0 or array-like object, optional) – The minimum growth rate (objective) that has to be achieved (default 0.1).
exports (bool, optional) – Whether to include export fluxes in the returned medium. Defaults to False which will only return import fluxes (default False).
minimize_components (bool or int > 0, optional) – Whether to minimize the number of components instead of the total import flux. Might be more intuitive if set to True, but may also be slow to calculate for large communities. If set to a number n will return up to n alternative solutions all with the same number of components (default False).
open_exchanges (bool or number, optional) – Whether to ignore currently set bounds and make all exchange reactions in the model possible. If set to a number, all exchange reactions will be opened with (-number, number) as bounds (default False).
- Returns
A pandas.Series giving the import flux for each required import reaction and (optionally) the associated export fluxes. All exchange fluxes are oriented into the import reaction e.g. positive fluxes denote imports and negative fluxes exports. If minimize_components is a number larger than 1, may return a pandas.DataFrame where each column is a minimal medium. Returns None, if the minimization is infeasible (for instance if min_growth > maximum growth rate).
- Return type
pandas.Series, pandas.DataFrame or None
Notes
Due to numerical issues, the minimize_components option will usually only minimize the number of “large” import fluxes. Specifically, the detection limit is given by
integrality_tolerance * max_bound
wheremax_bound
is the largest bound on an import reaction. Thus, if you are interested in small import fluxes as well you may have to adjust the solver tolerance at first with model.tolerance = 1e-7 for instance. However, this will be very slow for large models especially with GLPK.
Package Contents¶
|
Find specific boundary reactions. |
|
Find the external compartment in the model. |
|
Check whether a reaction is an exchange reaction. |
|
Find the minimal growth medium for the model. |
-
cobra.medium.
find_boundary_types
(model: Model, boundary_type: str, external_compartment: Optional[str] = None) → List['Reaction'][source]¶ Find specific boundary reactions.
- Parameters
model (cobra.Model) – The cobra model whose boundary reactions are to be found.
boundary_type ({"exchange", "demand", "sink"}) – Boundary type to check for.
external_compartment (str, optional) – The ID for the external compartment. If None, it will be detected automatically (default None).
- Returns
A list of likely boundary reactions of a user defined type.
- Return type
list of cobra.Reaction or an empty list
-
cobra.medium.
find_external_compartment
(model: Model) → str[source]¶ Find the external compartment in the model.
Uses a simple heuristic where the external compartment should be the one with the most exchange reactions.
- Parameters
model (cobra.Model) – The cobra model whose external compartments are to be identified.
- Returns
The putative external compartment.
- Return type
- Raises
RuntimeError – If several compartments are similar and thus difficult to identify, or, recognized names usually used for external compartment are absent.
-
cobra.medium.
is_boundary_type
(reaction: Reaction, boundary_type: str, external_compartment: str) → bool[source]¶ Check whether a reaction is an exchange reaction.
- Parameters
reaction (cobra.Reaction) – The reaction to check.
boundary_type ({"exchange", "demand", "sink"}) – Boundary type to check for.
external_compartment (str) – The ID for the external compartment.
- Returns
Whether the reaction looks like the requested type. Might be based on a heuristic.
- Return type
-
cobra.medium.
sbo_terms
¶
-
cobra.medium.
minimal_medium
(model: Model, min_objective_value: float = 0.1, exports: bool = False, minimize_components: Union[bool, int] = False, open_exchanges: bool = False) → Union[pd.Series, pd.DataFrame, None][source]¶ Find the minimal growth medium for the model.
Finds the minimal growth medium for the model which allows for model as well as individual growth. Here, a minimal medium can either be the medium requiring the smallest total import flux or the medium requiring the least components (ergo ingredients), which will be much slower due to being a mixed integer problem (MIP).
- Parameters
model (cobra.model) – The model to modify.
min_objective_value (float > 0 or array-like object, optional) – The minimum growth rate (objective) that has to be achieved (default 0.1).
exports (bool, optional) – Whether to include export fluxes in the returned medium. Defaults to False which will only return import fluxes (default False).
minimize_components (bool or int > 0, optional) – Whether to minimize the number of components instead of the total import flux. Might be more intuitive if set to True, but may also be slow to calculate for large communities. If set to a number n will return up to n alternative solutions all with the same number of components (default False).
open_exchanges (bool or number, optional) – Whether to ignore currently set bounds and make all exchange reactions in the model possible. If set to a number, all exchange reactions will be opened with (-number, number) as bounds (default False).
- Returns
A pandas.Series giving the import flux for each required import reaction and (optionally) the associated export fluxes. All exchange fluxes are oriented into the import reaction e.g. positive fluxes denote imports and negative fluxes exports. If minimize_components is a number larger than 1, may return a pandas.DataFrame where each column is a minimal medium. Returns None, if the minimization is infeasible (for instance if min_growth > maximum growth rate).
- Return type
pandas.Series, pandas.DataFrame or None
Notes
Due to numerical issues, the minimize_components option will usually only minimize the number of “large” import fluxes. Specifically, the detection limit is given by
integrality_tolerance * max_bound
wheremax_bound
is the largest bound on an import reaction. Thus, if you are interested in small import fluxes as well you may have to adjust the solver tolerance at first with model.tolerance = 1e-7 for instance. However, this will be very slow for large models especially with GLPK.
cobra.sampling
¶
Submodules¶
cobra.sampling.achr
¶Provide the ACHR sampler class.
Artificial Centering Hit-and-Run sampler. |
-
class
cobra.sampling.achr.
ACHRSampler
(model: Model, thinning: int = 100, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
cobra.sampling.hr_sampler.HRSampler
Artificial Centering Hit-and-Run sampler.
A sampler with low memory footprint and good convergence.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps (default 100).
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
prev
¶ The current/last flux sample generated.
- Type
numpy.array
-
center
¶ The center of the sampling space as estimated by the mean of all previously generated samples.
- Type
numpy.array
Notes
ACHR generates samples by choosing new directions from the sampling space’s center and the warmup points. The implementation used here is the same as in the MATLAB COBRA Toolbox 2 and uses only the initial warmup points to generate new directions and not any other previous iterations. This usually gives better mixing, since the startup points are chosen to span the space in a wide manner. This also makes the generated sampling chain quasi-Markovian since the center converges rapidly.
Memory usage is roughly in the order of (2 * number of reactions) ^ 2 due to the required nullspace matrices and warmup points. So, large models easily take up a few GBs of RAM.
References
- 1
Direction Choice for Accelerated Convergence in Hit-and-Run Sampling David E. Kaufman, Robert L. Smith Operations Research 199846:1 , 84-95 https://doi.org/10.1287/opre.46.1.84
- 2
-
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame[source]¶ Generate a set of samples.
This is the basic sampling function for all hit-and-run samplers.
- Parameters
n (int) – The number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
Notes
Performance of this function linearly depends on the number of reactions in your model and the thinning factor.
cobra.sampling.core
¶Provide low-level sampling stepper functions and helpers.
|
Sample a new feasible point from the point x in direction delta. |
-
cobra.sampling.core.
step
(sampler: HRSampler, x: np.ndarray, delta: np.ndarray, fraction: Optional[float] = None, tries: int = 0) → np.ndarray[source]¶ Sample a new feasible point from the point x in direction delta.
This is the low-level sampling stepper for samplers derived from HRSampler. Currently, it’s used by ACHRSampler and OptGPSampler.
It’s declared outside of the base sampling class to facilitate use of multiprocessing.
- Parameters
sampler (cobra.sampling.HRSampler) – The sampler to sample a step for.
x (np.array) – A point in the sampling region.
delta (np.array) – The direction to take the step in.
fraction (float, optional) – A float controlling the part of alpha difference to contribute to the fraction of delta (default None). If None, alpha is obtained from a normal distribution.
tries (int, optional) – Total number of tries (default 0).
- Returns
The new numpy array obtained after a step of sampling.
- Return type
np.array
- Raises
RuntimeError – If tries exceeds MAX_TRIES.
cobra.sampling.hr_sampler
¶Provide the base class and associated functions for Hit-and-Run samplers.
The abstract base class for hit-and-run samplers. |
|
Create a new numpy array that resides in shared memory. |
-
cobra.sampling.hr_sampler.
Problem
[source]¶ Define the matrix representation of a sampling problem.
A named tuple consisting of 6 arrays, 1 matrix and 1 boolean.
-
cobra.sampling.hr_sampler.
equalities
¶ All equality constraints in the model.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
b
¶ The right side of the equality constraints.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
inequalities
¶ All inequality constraints in the model.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
bounds
¶ The lower and upper bounds for the inequality constraints.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
variable_fixed
¶ A boolean vector indicating whether the variable at that index is fixed i.e., whether variable.lower_bound == variable.upper_bound.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
variable_bounds
¶ The lower and upper bounds for the variables.
- Type
numpy.array
-
cobra.sampling.hr_sampler.
nullspace
¶ A matrix containing the nullspace of the equality constraints. Each column is one basis vector.
- Type
-
Create a new numpy array that resides in shared memory.
- Parameters
shape (tuple of int) – The shape of the new array.
data (numpy.array, optional) – Data to copy to the new array. Has to have the same shape (default None).
integer (bool, optional) – Whether to use an integer array. By default, float array is used (default False).
- Returns
The newly created shared numpy array.
- Return type
numpy.array
- Raises
ValueError – If the input data (if provided) size is not equal to the created array.
-
class
cobra.sampling.hr_sampler.
HRSampler
(model: Model, thinning: int, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
abc.ABC
The abstract base class for hit-and-run samplers.
New samplers should derive from this class where possible to provide a uniform interface.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
thinning (int) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps.
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
Problem
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
__build_problem
(self) → Problem[source]¶ Build the matrix representation of the sampling problem.
- Returns
The matrix representation in the form of a NamedTuple.
- Return type
Problem
-
generate_fva_warmup
(self) → None[source]¶ Generate the warmup points for the sampler.
Generates warmup points by setting each flux as the sole objective and minimizing/maximizing it. Also caches the projection of the warmup points into the nullspace for non-homogeneous problems (only if necessary).
- Raises
ValueError – If flux cone contains a single point or the problem is inhomogeneous.
-
_reproject
(self, p: np.ndarray) → np.ndarray[source]¶ Reproject a point into the feasibility region.
This function is guaranteed to return a new feasible point. However, no guarantee can be made in terms of proximity to the original point.
- Parameters
p (numpy.array) – The current sample point.
- Returns
A new feasible point. If p is feasible, it will return p.
- Return type
numpy.array
-
_is_redundant
(self, matrix: np.matrix, cutoff: Optional[float] = None) → bool[source]¶ Identify redundant rows in a matrix that can be removed.
-
_bounds_dist
(self, p: np.ndarray) → np.ndarray[source]¶ Get the lower and upper bound distances. Negative is bad.
-
abstract
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame[source]¶ Abstract sampling function.
Should be overwritten by child classes.
- Parameters
n (int) – The number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
-
batch
(self, batch_size: int, batch_num: int, fluxes: bool = True) → pd.DataFrame[source]¶ Create a batch generator.
This is useful to generate batch_num batches of batch_size samples each.
- Parameters
batch_size (int) – The number of samples contained in each batch.
batch_num (int) – The number of batches in the generator.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Yields
pandas.DataFrame – A DataFrame with dimensions (batch_size x n_r) containing a valid flux sample for a total of n_r reactions (or variables if fluxes=False) in each row.
-
validate
(self, samples: np.matrix) → np.ndarray[source]¶ Validate a set of samples for equality and inequality feasibility.
Can be used to check whether the generated samples and warmup points are feasible.
- Parameters
samples (numpy.matrix) – Must be of dimension (samples x n_reactions). Contains the samples to be validated. Samples must be from fluxes.
- Returns
A one-dimensional numpy array containing a code of 1 to 3 letters denoting the validation result: - ‘v’ means feasible in bounds and equality constraints - ‘l’ means a lower bound violation - ‘u’ means a lower bound validation - ‘e’ means and equality constraint violation
- Return type
numpy.array
- Raises
ValueError – If wrong number of columns.
cobra.sampling.optgp
¶Provide the OptGP sampler class and helper functions.
Improved Artificial Centering Hit-and-Run sampler. |
-
class
cobra.sampling.optgp.
OptGPSampler
(model: Model, thinning: int = 100, processes: Optional[int] = None, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
cobra.sampling.hr_sampler.HRSampler
Improved Artificial Centering Hit-and-Run sampler.
A parallel sampler with fast convergence and parallel execution. See 1 for details.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
processes (int, optional) – The number of processes used during sampling (default cobra.Configuration.processes).
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps (default 100).
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
prev
¶ The current/last flux sample generated.
- Type
numpy.array
-
center
¶ The center of the sampling space as estimated by the mean of all previously generated samples.
- Type
numpy.array
Notes
The sampler is very similar to artificial centering where each process samples its own chain. Initial points are chosen randomly from the warmup points followed by a linear transformation that pulls the points a little bit towards the center of the sampling space.
If the number of processes used is larger than the one requested, number of samples is adjusted to the smallest multiple of the number of processes larger than the requested sample number. For instance, if you have 3 processes and request 8 samples, you will receive 9.
Memory usage is roughly in the order of (2 * number of reactions)^2 due to the required nullspace matrices and warmup points. So, large models easily take up a few GBs of RAM. However, most of the large matrices are kept in shared memory. So the RAM usage is independent of the number of processes.
References
- 1
Megchelenbrink W, Huynen M, Marchiori E (2014) optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space of Genome-Scale Metabolic Networks. PLoS ONE 9(2): e86587. https://doi.org/10.1371/journal.pone.0086587
-
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame[source]¶ Generate a set of samples.
This is the basic sampling function for all hit-and-run samplers.
- Parameters
n (int) – The minimum number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
Notes
Performance of this function linearly depends on the number of reactions in your model and the thinning factor.
If the number of processes is larger than one, computation is split across the CPU cores of your machine. This may shorten computation time. However, there is also overhead in setting up parallel computation primitives so, we recommend to calculate large numbers of samples at once (n > 1000).
cobra.sampling.sampling
¶Provide a wrapper function for performing flux sampling of cobra models.
|
Sample valid flux distributions from a cobra model. |
-
cobra.sampling.sampling.
sample
(model: Model, n: int, method: str = 'optgp', thinning: int = 100, processes: int = 1, seed: Optional[int] = None) → pd.DataFrame[source]¶ Sample valid flux distributions from a cobra model.
Currently, two methods are supported:
- ‘optgp’ (default) which uses the OptGPSampler that supports parallel
sampling. Requires large numbers of samples to be performant (n > 1000). For smaller samples, ‘achr’ might be better suited. For details, refer 1 .
‘achr’ which uses artificial centering hit-and-run. This is a single process method with good convergence. For details, refer 2 .
- Parameters
model (cobra.Model) – The model from which to sample flux distributions.
n (int) – The number of samples to obtain. When using ‘optgp’, this must be a multiple of processes, otherwise a larger number of samples will be returned.
method ({"optgp", "achr"}, optional) – The sampling algorithm to use (default “optgp”).
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps. Defaults to 100 which in benchmarks gives approximately uncorrelated samples. If set to 1 will return all iterates (default 100).
processes (int, optional) – Only used for ‘optgp’. The number of processes used to generate samples (default 1).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
- Returns
The generated flux samples. Each row corresponds to a sample of the fluxes and the columns are the reactions.
- Return type
pandas.DataFrame
Notes
The samplers have a correction method to ensure equality feasibility for long-running chains, however this will only work for homogeneous models, meaning models with no non-zero fixed variables or constraints ( right-hand side of the equalities are zero).
References
- 1
Megchelenbrink W, Huynen M, Marchiori E (2014) optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space of Genome-Scale Metabolic Networks. PLoS ONE 9(2): e86587. https://doi.org/10.1371/journal.pone.0086587
- 2
Direction Choice for Accelerated Convergence in Hit-and-Run Sampling David E. Kaufman, Robert L. Smith Operations Research 199846:1 , 84-95 https://doi.org/10.1287/opre.46.1.84
Package Contents¶
The abstract base class for hit-and-run samplers. |
|
Artificial Centering Hit-and-Run sampler. |
|
Improved Artificial Centering Hit-and-Run sampler. |
|
Create a new numpy array that resides in shared memory. |
|
Sample a new feasible point from the point x in direction delta. |
|
Sample valid flux distributions from a cobra model. |
-
class
cobra.sampling.
HRSampler
(model: Model, thinning: int, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
abc.ABC
The abstract base class for hit-and-run samplers.
New samplers should derive from this class where possible to provide a uniform interface.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
thinning (int) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps.
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
Problem
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
__build_problem
(self) → Problem¶ Build the matrix representation of the sampling problem.
- Returns
The matrix representation in the form of a NamedTuple.
- Return type
Problem
-
generate_fva_warmup
(self) → None¶ Generate the warmup points for the sampler.
Generates warmup points by setting each flux as the sole objective and minimizing/maximizing it. Also caches the projection of the warmup points into the nullspace for non-homogeneous problems (only if necessary).
- Raises
ValueError – If flux cone contains a single point or the problem is inhomogeneous.
-
_reproject
(self, p: np.ndarray) → np.ndarray¶ Reproject a point into the feasibility region.
This function is guaranteed to return a new feasible point. However, no guarantee can be made in terms of proximity to the original point.
- Parameters
p (numpy.array) – The current sample point.
- Returns
A new feasible point. If p is feasible, it will return p.
- Return type
numpy.array
-
_random_point
(self) → np.ndarray¶ Find an approximately random point in the flux cone.
-
_is_redundant
(self, matrix: np.matrix, cutoff: Optional[float] = None) → bool¶ Identify redundant rows in a matrix that can be removed.
-
_bounds_dist
(self, p: np.ndarray) → np.ndarray¶ Get the lower and upper bound distances. Negative is bad.
-
abstract
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame¶ Abstract sampling function.
Should be overwritten by child classes.
- Parameters
n (int) – The number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
-
batch
(self, batch_size: int, batch_num: int, fluxes: bool = True) → pd.DataFrame¶ Create a batch generator.
This is useful to generate batch_num batches of batch_size samples each.
- Parameters
batch_size (int) – The number of samples contained in each batch.
batch_num (int) – The number of batches in the generator.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Yields
pandas.DataFrame – A DataFrame with dimensions (batch_size x n_r) containing a valid flux sample for a total of n_r reactions (or variables if fluxes=False) in each row.
-
validate
(self, samples: np.matrix) → np.ndarray¶ Validate a set of samples for equality and inequality feasibility.
Can be used to check whether the generated samples and warmup points are feasible.
- Parameters
samples (numpy.matrix) – Must be of dimension (samples x n_reactions). Contains the samples to be validated. Samples must be from fluxes.
- Returns
A one-dimensional numpy array containing a code of 1 to 3 letters denoting the validation result: - ‘v’ means feasible in bounds and equality constraints - ‘l’ means a lower bound violation - ‘u’ means a lower bound validation - ‘e’ means and equality constraint violation
- Return type
numpy.array
- Raises
ValueError – If wrong number of columns.
Create a new numpy array that resides in shared memory.
- Parameters
shape (tuple of int) – The shape of the new array.
data (numpy.array, optional) – Data to copy to the new array. Has to have the same shape (default None).
integer (bool, optional) – Whether to use an integer array. By default, float array is used (default False).
- Returns
The newly created shared numpy array.
- Return type
numpy.array
- Raises
ValueError – If the input data (if provided) size is not equal to the created array.
-
class
cobra.sampling.
ACHRSampler
(model: Model, thinning: int = 100, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
cobra.sampling.hr_sampler.HRSampler
Artificial Centering Hit-and-Run sampler.
A sampler with low memory footprint and good convergence.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps (default 100).
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
prev
¶ The current/last flux sample generated.
- Type
numpy.array
-
center
¶ The center of the sampling space as estimated by the mean of all previously generated samples.
- Type
numpy.array
Notes
ACHR generates samples by choosing new directions from the sampling space’s center and the warmup points. The implementation used here is the same as in the MATLAB COBRA Toolbox [2]_ and uses only the initial warmup points to generate new directions and not any other previous iterations. This usually gives better mixing, since the startup points are chosen to span the space in a wide manner. This also makes the generated sampling chain quasi-Markovian since the center converges rapidly.
Memory usage is roughly in the order of (2 * number of reactions) ^ 2 due to the required nullspace matrices and warmup points. So, large models easily take up a few GBs of RAM.
References
- 1
Direction Choice for Accelerated Convergence in Hit-and-Run Sampling David E. Kaufman, Robert L. Smith Operations Research 199846:1 , 84-95 https://doi.org/10.1287/opre.46.1.84
- 2
-
__single_iteration
(self) → None¶ Run a single iteration of the sampling.
-
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame¶ Generate a set of samples.
This is the basic sampling function for all hit-and-run samplers.
- Parameters
n (int) – The number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
Notes
Performance of this function linearly depends on the number of reactions in your model and the thinning factor.
-
cobra.sampling.
step
(sampler: HRSampler, x: np.ndarray, delta: np.ndarray, fraction: Optional[float] = None, tries: int = 0) → np.ndarray[source]¶ Sample a new feasible point from the point x in direction delta.
This is the low-level sampling stepper for samplers derived from HRSampler. Currently, it’s used by ACHRSampler and OptGPSampler.
It’s declared outside of the base sampling class to facilitate use of multiprocessing.
- Parameters
sampler (cobra.sampling.HRSampler) – The sampler to sample a step for.
x (np.array) – A point in the sampling region.
delta (np.array) – The direction to take the step in.
fraction (float, optional) – A float controlling the part of alpha difference to contribute to the fraction of delta (default None). If None, alpha is obtained from a normal distribution.
tries (int, optional) – Total number of tries (default 0).
- Returns
The new numpy array obtained after a step of sampling.
- Return type
np.array
- Raises
RuntimeError – If tries exceeds MAX_TRIES.
-
class
cobra.sampling.
OptGPSampler
(model: Model, thinning: int = 100, processes: Optional[int] = None, nproj: Optional[int] = None, seed: Optional[int] = None, **kwargs)[source]¶ Bases:
cobra.sampling.hr_sampler.HRSampler
Improved Artificial Centering Hit-and-Run sampler.
A parallel sampler with fast convergence and parallel execution. See [1]_ for details.
- Parameters
model (cobra.Model) – The cobra model from which to generate samples.
processes (int, optional) – The number of processes used during sampling (default cobra.Configuration.processes).
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps (default 100).
nproj (int > 0, optional) – How often to reproject the sampling point into the feasibility space. Avoids numerical issues at the cost of lower sampling. If you observe many equality constraint violations with sampler.validate you should lower this number (default None).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
-
problem
¶ A NamedTuple whose attributes define the entire sampling problem in matrix form.
- Type
-
warmup
¶ A numpy matrix with as many columns as reactions in the model and more than 3 rows containing a warmup sample in each row. None if no warmup points have been generated yet.
- Type
-
retries
¶ The overall of sampling retries the sampler has observed. Larger values indicate numerical instabilities.
- Type
-
fwd_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective forward variable.
- Type
numpy.array
-
rev_idx
¶ A numpy array having one entry for each reaction in the model, containing the index of the respective reverse variable.
- Type
numpy.array
-
prev
¶ The current/last flux sample generated.
- Type
numpy.array
-
center
¶ The center of the sampling space as estimated by the mean of all previously generated samples.
- Type
numpy.array
Notes
The sampler is very similar to artificial centering where each process samples its own chain. Initial points are chosen randomly from the warmup points followed by a linear transformation that pulls the points a little bit towards the center of the sampling space.
If the number of processes used is larger than the one requested, number of samples is adjusted to the smallest multiple of the number of processes larger than the requested sample number. For instance, if you have 3 processes and request 8 samples, you will receive 9.
Memory usage is roughly in the order of (2 * number of reactions)^2 due to the required nullspace matrices and warmup points. So, large models easily take up a few GBs of RAM. However, most of the large matrices are kept in shared memory. So the RAM usage is independent of the number of processes.
References
- 1
Megchelenbrink W, Huynen M, Marchiori E (2014) optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space of Genome-Scale Metabolic Networks. PLoS ONE 9(2): e86587. https://doi.org/10.1371/journal.pone.0086587
-
sample
(self, n: int, fluxes: bool = True) → pd.DataFrame¶ Generate a set of samples.
This is the basic sampling function for all hit-and-run samplers.
- Parameters
n (int) – The minimum number of samples that are generated at once.
fluxes (bool, optional) – Whether to return fluxes or the internal solver variables. If set to False, will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model (default True).
- Returns
Returns a pandas DataFrame with n rows, each containing a flux sample.
- Return type
pandas.DataFrame
Notes
Performance of this function linearly depends on the number of reactions in your model and the thinning factor.
If the number of processes is larger than one, computation is split across the CPU cores of your machine. This may shorten computation time. However, there is also overhead in setting up parallel computation primitives so, we recommend to calculate large numbers of samples at once (n > 1000).
-
__getstate__
(self) → Dict¶ Return the object for serialization.
-
cobra.sampling.
sample
(model: Model, n: int, method: str = 'optgp', thinning: int = 100, processes: int = 1, seed: Optional[int] = None) → pd.DataFrame[source]¶ Sample valid flux distributions from a cobra model.
Currently, two methods are supported:
- ‘optgp’ (default) which uses the OptGPSampler that supports parallel
sampling. Requires large numbers of samples to be performant (n > 1000). For smaller samples, ‘achr’ might be better suited. For details, refer [1]_ .
‘achr’ which uses artificial centering hit-and-run. This is a single process method with good convergence. For details, refer [2]_ .
- Parameters
model (cobra.Model) – The model from which to sample flux distributions.
n (int) – The number of samples to obtain. When using ‘optgp’, this must be a multiple of processes, otherwise a larger number of samples will be returned.
method ({"optgp", "achr"}, optional) – The sampling algorithm to use (default “optgp”).
thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps. Defaults to 100 which in benchmarks gives approximately uncorrelated samples. If set to 1 will return all iterates (default 100).
processes (int, optional) – Only used for ‘optgp’. The number of processes used to generate samples (default 1).
seed (int > 0, optional) – Sets the random number seed. Initialized to the current time stamp if None (default None).
- Returns
The generated flux samples. Each row corresponds to a sample of the fluxes and the columns are the reactions.
- Return type
pandas.DataFrame
Notes
The samplers have a correction method to ensure equality feasibility for long-running chains, however this will only work for homogeneous models, meaning models with no non-zero fixed variables or constraints ( right-hand side of the equalities are zero).
References
- 1
Megchelenbrink W, Huynen M, Marchiori E (2014) optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space of Genome-Scale Metabolic Networks. PLoS ONE 9(2): e86587. https://doi.org/10.1371/journal.pone.0086587
- 2
Direction Choice for Accelerated Convergence in Hit-and-Run Sampling David E. Kaufman, Robert L. Smith Operations Research 199846:1 , 84-95 https://doi.org/10.1287/opre.46.1.84
cobra.summary
¶
Submodules¶
cobra.summary.metabolite_summary
¶Provide the metabolite summary class.
Define the metabolite summary. |
-
class
cobra.summary.metabolite_summary.
MetaboliteSummary
(*, metabolite: Metabolite, model: Model, solution: Optional['Solution'] = None, fva: Optional[Union[float, pd.DataFrame]] = None, **kwargs)[source]¶ Bases:
cobra.summary.Summary
Define the metabolite summary.
-
producing_flux
¶ A pandas DataFrame of only the producing fluxes.
- Type
pandas.DataFrame
-
consuming_flux
¶ A pandas DataFrame of only the consuming fluxes.
- Type
pandas.DataFrame
See also
Summary
Parent that defines further attributes.
ReactionSummary
,ModelSummary
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None[source]¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
_display_flux
(self, frame: pd.DataFrame, names: bool, threshold: float) → pd.DataFrame[source]¶ Transform a flux data frame for display.
- Parameters
- Returns
The transformed pandas DataFrame with flux percentages and reaction definitions.
- Return type
pandas.DataFrame
-
static
_string_table
(frame: pd.DataFrame, float_format: str, column_width: int) → str[source]¶ Create a pretty string representation of the data frame.
-
static
_html_table
(frame: pd.DataFrame, float_format: str) → str[source]¶ Create an HTML representation of the data frame.
-
to_string
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str[source]¶ Return a pretty string representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
to_html
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G') → str[source]¶ Return a rich HTML representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
cobra.summary.model_summary
¶Provide the model summary class.
Define the model summary. |
-
class
cobra.summary.model_summary.
ModelSummary
(*, model: Model, solution: Optional['Solution'] = None, fva: Optional[Union[float, pd.DataFrame]] = None, **kwargs)[source]¶ Bases:
cobra.summary.Summary
Define the model summary.
-
uptake_flux
¶ A pandas DataFrame of only the uptake fluxes.
- Type
pandas.DataFrame
-
secretion_flux
¶ A pandas DataFrame of only the consuming fluxes.
- Type
pandas.DataFrame
See also
Summary
Parent that defines further attributes.
MetaboliteSummary
,ReactionSummary
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None[source]¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
_display_flux
(self, frame: pd.DataFrame, names: bool, element: str, threshold: float) → pd.DataFrame[source]¶ Transform a flux data frame for display.
- Parameters
- Returns
The transformed pandas DataFrame with flux percentages and reaction definitions.
- Return type
pandas.DataFrame
-
static
_string_table
(frame: pd.DataFrame, float_format: str, column_width: int) → str[source]¶ Create a pretty string representation of the data frame.
-
static
_html_table
(frame: pd.DataFrame, float_format: str) → str[source]¶ Create an HTML representation of the data frame.
-
_string_objective
(self, names: bool) → str[source]¶ Return a string representation of the objective.
-
to_string
(self, names: bool = False, element: str = 'C', threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str[source]¶ Return a pretty string representation of the model summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
element (str, optional) – The atomic element to summarize uptake and secretion for (default ‘C’).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
to_html
(self, names: bool = False, element: str = 'C', threshold: Optional[float] = None, float_format: str = '.4G') → str[source]¶ Return a rich HTML representation of the model summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
element (str, optional) – The atomic element to summarize uptake and secretion for (default ‘C’).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
cobra.summary.reaction_summary
¶Provide the reaction summary class.
Define the reaction summary. |
-
class
cobra.summary.reaction_summary.
ReactionSummary
(*, reaction: Reaction, model: Model, solution: Optional['Solution'] = None, fva: Optional[Union[float, pd.DataFrame]] = None, **kwargs)[source]¶ Bases:
cobra.summary.Summary
Define the reaction summary.
See also
Summary
Parent that defines further attributes.
MetaboliteSummary
,ModelSummary
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None[source]¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
_string_flux
(self, threshold: float, float_format: str) → str[source]¶ Transform a flux data frame to a string.
-
to_string
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str[source]¶ Return a pretty string representation of the reaction summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
to_html
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G') → str[source]¶ Return a rich HTML representation of the reaction summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
cobra.summary.summary
¶Provide the abstract base summary class.
Define the abstract base summary. |
-
class
cobra.summary.summary.
Summary
(**kwargs)[source]¶ Bases:
abc.ABC
Define the abstract base summary.
See also
MetaboliteSummary
,ReactionSummary
,ModelSummary
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None[source]¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
abstract
to_string
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str[source]¶ Return a pretty string representation of the summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
abstract
to_html
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G') → str[source]¶ Return a rich HTML representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
Package Contents¶
Define the abstract base summary. |
|
Define the metabolite summary. |
|
Define the model summary. |
-
class
cobra.summary.
Summary
(**kwargs)[source]¶ Bases:
abc.ABC
Define the abstract base summary.
See also
MetaboliteSummary
,ReactionSummary
,ModelSummary
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
__str__
(self) → str¶ Return a string representation of the summary.
-
_repr_html_
(self) → str¶ Return a rich HTML representation of the summary.
-
property
tolerance
(self) → float¶ Return the set threshold.
-
_normalize_threshold
(self, threshold: Optional[float])¶ Return a sensible threshold value.
-
abstract
to_string
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str¶ Return a pretty string representation of the summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
abstract
to_html
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G') → str¶ Return a rich HTML representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
to_frame
(self) → pd.DataFrame¶ Return the a data frame representation of the summary.
-
-
class
cobra.summary.
MetaboliteSummary
(*, metabolite: Metabolite, model: Model, solution: Optional['Solution'] = None, fva: Optional[Union[float, pd.DataFrame]] = None, **kwargs)[source]¶ Bases:
cobra.summary.Summary
Define the metabolite summary.
-
producing_flux
¶ A pandas DataFrame of only the producing fluxes.
- Type
pandas.DataFrame
-
consuming_flux
¶ A pandas DataFrame of only the consuming fluxes.
- Type
pandas.DataFrame
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
_display_flux
(self, frame: pd.DataFrame, names: bool, threshold: float) → pd.DataFrame¶ Transform a flux data frame for display.
- Parameters
- Returns
The transformed pandas DataFrame with flux percentages and reaction definitions.
- Return type
pandas.DataFrame
-
static
_string_table
(frame: pd.DataFrame, float_format: str, column_width: int) → str¶ Create a pretty string representation of the data frame.
-
static
_html_table
(frame: pd.DataFrame, float_format: str) → str¶ Create an HTML representation of the data frame.
-
to_string
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str¶ Return a pretty string representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
to_html
(self, names: bool = False, threshold: Optional[float] = None, float_format: str = '.4G') → str¶ Return a rich HTML representation of the metabolite summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
-
class
cobra.summary.
ModelSummary
(*, model: Model, solution: Optional['Solution'] = None, fva: Optional[Union[float, pd.DataFrame]] = None, **kwargs)[source]¶ Bases:
cobra.summary.Summary
Define the model summary.
-
uptake_flux
¶ A pandas DataFrame of only the uptake fluxes.
- Type
pandas.DataFrame
-
secretion_flux
¶ A pandas DataFrame of only the consuming fluxes.
- Type
pandas.DataFrame
-
_generate
(self, model: Model, solution: Optional['Solution'], fva: Optional[Union[float, pd.DataFrame]]) → None¶ Prepare the data for the summary instance.
- Parameters
model (cobra.Model) – The metabolic model for which to generate a metabolite summary.
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution.fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched.
-
_display_flux
(self, frame: pd.DataFrame, names: bool, element: str, threshold: float) → pd.DataFrame¶ Transform a flux data frame for display.
- Parameters
- Returns
The transformed pandas DataFrame with flux percentages and reaction definitions.
- Return type
pandas.DataFrame
-
static
_string_table
(frame: pd.DataFrame, float_format: str, column_width: int) → str¶ Create a pretty string representation of the data frame.
-
static
_html_table
(frame: pd.DataFrame, float_format: str) → str¶ Create an HTML representation of the data frame.
-
_string_objective
(self, names: bool) → str¶ Return a string representation of the objective.
-
to_string
(self, names: bool = False, element: str = 'C', threshold: Optional[float] = None, float_format: str = '.4G', column_width: int = 79) → str¶ Return a pretty string representation of the model summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
element (str, optional) – The atomic element to summarize uptake and secretion for (default ‘C’).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
column_width (int, optional) – The maximum column width for each row (default 79).
- Returns
The summary formatted as a pretty string.
- Return type
-
to_html
(self, names: bool = False, element: str = 'C', threshold: Optional[float] = None, float_format: str = '.4G') → str¶ Return a rich HTML representation of the model summary.
- Parameters
names (bool, optional) – Whether or not elements should be displayed by their common names (default False).
element (str, optional) – The atomic element to summarize uptake and secretion for (default ‘C’).
threshold (float, optional) – Hide fluxes below the threshold from being displayed. If no value is given, the model tolerance is used (default None).
float_format (str, optional) – Format string for floats (default ‘.4G’).
- Returns
The summary formatted as HTML.
- Return type
-
cobra.test
¶
Subpackages¶
cobra.test.test_manipulation
¶cobra.test.test_manipulation.test_annotate
¶Test functionalities of model component annotation functions.
|
Test SBO annotation function. |
cobra.test.test_manipulation.test_delete
¶Test functionalities of model component pruning functions.
|
Test the output type of unused metabolites pruning. |
|
Test the sanity of unused metabolites pruning. |
|
Test the output type of unused reactions pruning. |
|
Test the sanity of unused reactions pruning. |
|
Quickly find gene knockout reactions. |
|
Get trimmed reactions. |
|
Compute gene knockout. |
|
Test gene knockout. |
|
Test gene removal. |
-
cobra.test.test_manipulation.test_delete.
test_prune_unused_metabolites_output_type
(model: Model) → None[source]¶ Test the output type of unused metabolites pruning.
-
cobra.test.test_manipulation.test_delete.
test_prune_unused_metabolites_sanity
(model: Model) → None[source]¶ Test the sanity of unused metabolites pruning.
-
cobra.test.test_manipulation.test_delete.
test_prune_unused_reactions_output_type
(model: Model) → None[source]¶ Test the output type of unused reactions pruning.
-
cobra.test.test_manipulation.test_delete.
test_prune_unused_rxns_functionality
(model: Model) → None[source]¶ Test the sanity of unused reactions pruning.
-
cobra.test.test_manipulation.test_delete.
_find_gene_knockout_reactions_fast
(m: Model, gene_list: List[Gene]) → List[Reaction][source]¶ Quickly find gene knockout reactions.
-
cobra.test.test_manipulation.test_delete.
_get_removed
(m: Model) → Set[str][source]¶ Get trimmed reactions.
-
cobra.test.test_manipulation.test_delete.
_gene_knockout_computation
(m: Model, gene_ids: List[str], expected_reaction_ids: List[str]) → None[source]¶ Compute gene knockout.
cobra.test.test_manipulation.test_modify
¶Test functionalities of model component modifcations.
|
Test model component IDs’ SBML compliance. |
|
Test gene renaming functionality. |
cobra.test.test_manipulation.test_validate
¶Test functionalities of cobra component validation functions.
|
Test reaction mass balance validation. |
|
Test metabolite formulae validation. |
Submodules¶
cobra.test.conftest
¶Define global fixtures.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Package Contents¶
|
Reads SBML model from given filename. |
|
Returns a cobra model for testing |
|
alias for running all unit-tests on installed cobra |
-
cobra.test.
read_sbml_model
(filename, number=float, f_replace=F_REPLACE, **kwargs)¶ Reads SBML model from given filename.
If the given filename ends with the suffix ‘’.gz’’ (for example, ‘’myfile.xml.gz’),’ the file is assumed to be compressed in gzip format and will be automatically decompressed upon reading. Similarly, if the given filename ends with ‘’.zip’’ or ‘’.bz2’,’ the file is assumed to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be read uncompressed. Note that if the file is in zip format but the archive contains more than one file, only the first file in the archive will be read and the rest ignored.
To read a gzip/zip file, libSBML needs to be configured and linked with the zlib library at compile time. It also needs to be linked with the bzip2 library to read files in bzip2 format. (Both of these are the default configurations for libSBML.)
This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models are converted to FBC-v2 models before reading.
The parser tries to fall back to information in notes dictionaries if information is not available in the FBC packages, e.g., CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.
- Parameters
filename (path to SBML file, or SBML string, or SBML file handle) – SBML which is read into cobra model
number (data type of stoichiometry: {float, int}) – In which data type should the stoichiometry be parsed.
f_replace (dict of replacement functions for id replacement) – Dictionary of replacement functions for gene, specie, and reaction. By default the following id changes are performed on import: clip G_ from genes, clip M_ from species, clip R_ from reactions If no replacements should be performed, set f_replace={}, None
- Returns
- Return type
Notes
- Provided file handles cannot be opened in binary mode, i.e., use
- with open(path, “r” as f):
read_sbml_model(f)
File handles to compressed files are not supported yet.
cobra.util
¶
Submodules¶
cobra.util.array
¶Helper functions for array operations and sampling.
|
Return a stoichiometric array representation of the given model. |
|
Compute an approximate basis for the nullspace of A. |
|
Create a matrix representation of the problem. |
-
cobra.util.array.
create_stoichiometric_matrix
(model: Model, array_type: str = 'dense', dtype: Optional[np.dtype] = None) → Union[np.ndarray, dok_matrix, lil_matrix, pd.DataFrame][source]¶ Return a stoichiometric array representation of the given model.
The the columns represent the reactions and rows represent metabolites. S[i,j] therefore contains the quantity of metabolite i produced (negative for consumed) by reaction j.
- Parameters
model (cobra.Model) – The cobra model to construct the matrix for.
array_type ({"dense", "dok", "lil", "DataFrame"}) – The type of array to construct. “dense” will return a standard numpy.ndarray. “dok”, or “lil” will construct a sparse array using scipy of the corresponding type. “DataFrame” will give a pandas.DataFrame with metabolite as indices and reaction as columns.
dtype (numpy.dtype, optional) – The desired numpy data type for the array (default numpy.float64).
- Returns
The stoichiometric matrix for the given model.
- Return type
matrix of class dtype
- Raises
ValueError – If sparse matrix is used and scipy is not installed.
. deprecated: – 0.18.1: “DataFrame” option for array_type will be replaced with “frame” in future versions.
-
cobra.util.array.
nullspace
(A: np.ndarray, atol: float = 1e-13, rtol: float = 0.0) → np.ndarray[source]¶ Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the Singular Value Decomposition (SVD) of A.
- Parameters
A (numpy.ndarray) – A should be at most 2-D. 1-D array with length k will be treated as a 2-D with shape (1, k).
atol (float, optional) – The absolute tolerance for a zero singular value. Singular values smaller than atol are considered to be zero (default 1e-13).
rtol (float, optional) – The relative tolerance. Singular values less than rtol * smax are considered to be zero, where smax is the largest singular value (default 0.0).
- Returns
If A is an array with shape (m, k), then ns will be an array with shape (k, n), where n is the estimated dimension of the nullspace of A. The columns of ns are a basis for the nullspace; each element in numpy.dot(A, ns) will be approximately zero.
- Return type
Notes
This is taken from the numpy cookbook.
If both atol and rtol are positive, the combined tolerance is the maximum of the two; that is:
\[\mathtt{tol} = \max(\mathtt{atol}, \mathtt{rtol} * \mathtt{smax})\]Singular values smaller than tol are considered to be zero.
-
cobra.util.array.
constraint_matrices
(model: Model, array_type: str = 'dense', zero_tol: float = 1e-06) → NamedTuple[source]¶ Create a matrix representation of the problem.
This is used for alternative solution approaches that do not use “optlang”. The function will construct the equality matrix, inequality matrix and bounds for the complete problem.
- Parameters
model (cobra.Model) – The model from which to obtain the LP problem.
array_type ({"dense", "dok", "lil", "DataFrame"}) – The type of array to construct. “dense” will return a standard numpy.ndarray. “dok”, or “lil” will construct a sparse array using scipy of the corresponding type. “DataFrame” will give a pandas.DataFrame with metabolite as indices and reaction as columns.
zero_tol (float, optional) – The zero tolerance used to judge whether two bounds are the same (default 1e-6).
- Returns
A named tuple consisting of 6 matrices and 2 vectors: - “equalities” is a matrix S such that S * vars = b. It
includes a row for each constraint and one column for each variable.
”b” is the right side of the equality equation such that S * vars = b.
”inequalities” is a matrix M such that lb <= M * vars <= ub. It contains a row for each inequality and as many columns as variables.
”bounds” is a compound matrix [lb ub] containing the lower and upper bounds for the inequality constraints in M.
”variable_fixed” is a boolean vector indicating whether the variable at that index is fixed (lower bound == upper_bound) and is thus bounded by an equality constraint.
”variable_bounds” is a compound matrix [lb ub] containing the lower and upper bounds for all variables.
- Return type
NamedTuple
Notes
To accomodate non-zero equalities, the problem will add the variable “const_one” which is a variable that equals one.
Deprecated since version 0.18.1: “DataFrame” option for array_type will be replaced with “frame” in future versions.
cobra.util.context
¶Context manager for the package.
Define a base context manager. |
|
Search for a context manager. |
|
Simplify the context management of simple object attributes. |
-
class
cobra.util.context.
HistoryManager
(**kwargs)[source]¶ Define a base context manager.
It records a list of actions to be taken at a later time. This is used to implement context managers that allow temporary changes to a cobra.core.Model.
-
cobra.util.context.
get_context
(obj: Object) → Optional[HistoryManager][source]¶ Search for a context manager.
- Parameters
obj (cobra.Object) – The cobra.Object for which to search context manager.
- Returns
HistoryManager instance, or None if no context manager is found.
- Return type
- Raises
AttributeError – If no context manager is found.
IndexError – If no context manager is found.
-
cobra.util.context.
resettable
(func: Callable[[Any], Any]) → Callable[[Any], Any][source]¶ Simplify the context management of simple object attributes.
It gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the cobra.util.HistoryManager.
- Parameters
func (callable) – The function to decorate.
- Returns
The decorated function.
- Return type
callable
cobra.util.process_pool
¶Provide a process pool with enhanced performance on Windows.
Define a process pool that handles the Windows platform specially. |
-
class
cobra.util.process_pool.
ProcessPool
(processes: Optional[int] = None, initializer: Optional[Callable] = None, initargs: Tuple = (), maxtasksperchild: Optional[int] = None, **kwargs)[source]¶ Define a process pool that handles the Windows platform specially.
-
__exit__
(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) → Optional[bool][source]¶ Clean up resources when leaving a context.
-
cobra.util.solver
¶Additional helper functions for the optlang solvers.
All functions integrate well with the context manager, meaning that all operations defined here are automatically reverted when used in a with model: block.
The functions defined here together with the existing model functions should allow you to implement custom flux analysis methods with ease.
Define an object for adding absolute expressions. |
|
Retrieve coefficient for the reactions in a linear objective. |
|
Check whether a sympy expression references the correct variables. |
|
Set the model objective. |
|
Give a string representation for an optlang interface. |
|
Select a solver for a given optimization problem. |
|
Choose a solver given a solver name and model. |
|
Check whether the chosen solver is valid. |
|
Add variables and constraints to a model’s solver object. |
|
Remove variables and constraints from a model’s solver object. |
|
Add the absolute value of an expression to the model. |
|
Fix current objective as an additional constraint. |
|
Perform standard checks on a solver’s status. |
|
Assert model solver status is optimal. |
|
Add a new objective and variables to ensure a feasible solution. |
|
Successively optimize separate targets in a specific order. |
-
class
cobra.util.solver.
Components
[source]¶ Bases:
typing.NamedTuple
Define an object for adding absolute expressions.
-
cobra.util.solver.
linear_reaction_coefficients
(model: Model, reactions: Optional[List['Reaction']] = None) → Dict['Reaction', float][source]¶ Retrieve coefficient for the reactions in a linear objective.
- Parameters
model (cobra.Model) – The cobra model defining the linear objective.
reactions (list of cobra.Reaction, optional) – An optional list of the reactions to get the coefficients for. By default, all reactions are considered (default None).
- Returns
A dictionary where the keys are the reaction objects and the values are the corresponding coefficient. Empty dictionary if there are no linear terms in the objective.
- Return type
-
cobra.util.solver.
_valid_atoms
(model: Model, expression: optlang.symbolics.Basic) → bool[source]¶ Check whether a sympy expression references the correct variables.
- Parameters
model (cobra.Model) – The model in which to check for variables.
expression (sympy.Basic) – A sympy expression.
- Returns
True if all referenced variables are contained in model, False otherwise.
- Return type
-
cobra.util.solver.
set_objective
(model: Model, value: Union[optlang.interface.Objective, optlang.symbolics.Basic, Dict['Reaction', float]], additive: bool = False) → None[source]¶ Set the model objective.
- Parameters
model (cobra.Model) – The model to set the objective for.
value (optlang.interface.Objective, optlang.symbolics.Basic, dict) – If the model objective is linear, then the value can be a new optlang.interface.Objective or a dictionary with linear coefficients where each key is a reaction and the corresponding value is the new coefficient (float). If the objective is non-linear and additive is True, then only values of class optlang.interface.Objective, are accepted.
additive (bool) – If True, add the terms to the current objective, otherwise start with an empty objective.
- Raises
ValueError – If model objective is non-linear and the value is a dict.
TypeError – If the type of value is not one of the accepted ones.
-
cobra.util.solver.
interface_to_str
(interface: Union[str, ModuleType]) → str[source]¶ Give a string representation for an optlang interface.
-
cobra.util.solver.
get_solver_name
(mip: bool = False, qp: bool = False) → str[source]¶ Select a solver for a given optimization problem.
- Parameters
- Returns
The name of the feasible solver.
- Return type
- Raises
SolverNotFound – If no suitable solver could be found.
-
cobra.util.solver.
choose_solver
(model: Model, solver: Optional[str] = None, qp: bool = False) → ModuleType[source]¶ Choose a solver given a solver name and model.
This will choose a solver compatible with the model and required capabilities. Also respects model.solver where it can.
- Parameters
model (cobra.Model) – The model for which to choose the solver.
solver (str, optional) – The name of the solver to be used (default None).
qp (boolean, optional) – True if the solver needs quadratic programming capabilities (default False).
- Returns
Valid solver for the problem.
- Return type
optlang.interface
- Raises
SolverNotFound – If no suitable solver could be found.
-
cobra.util.solver.
check_solver
(obj)[source]¶ Check whether the chosen solver is valid.
Check whether chosen solver is valid and also warn when using a specialized solver. Will return the optlang interface for the requested solver.
- Parameters
obj (str or optlang.interface or optlang.interface.Model) – The chosen solver.
- Raises
SolverNotFound – If the solver is not valid.
-
cobra.util.solver.
add_cons_vars_to_problem
(model: Model, what: Union[List[CONS_VARS], Tuple[CONS_VARS], Components], **kwargs) → None[source]¶ Add variables and constraints to a model’s solver object.
Useful for variables and constraints that can not be expressed with reactions and lower/upper bounds. It will integrate with the model’s context manager in order to revert changes upon leaving the context.
- Parameters
model (cobra.Model) – The model to which to add the variables and constraints.
what (list or tuple of optlang.interface.Variable or) – optlang.interface.Constraint The variables and constraints to add to the model.
**kwargs (keyword arguments) – Keyword arguments passed to solver’s add() method.
-
cobra.util.solver.
remove_cons_vars_from_problem
(model: Model, what: Union[List[CONS_VARS], Tuple[CONS_VARS], Components]) → None[source]¶ Remove variables and constraints from a model’s solver object.
Useful to temporarily remove variables and constraints from a model’s solver object.
- Parameters
model (cobra.Model) – The model from which to remove the variables and constraints.
what (list or tuple of optlang.interface.Variable or) – optlang.interface.Constraint The variables and constraints to remove from the model.
-
cobra.util.solver.
add_absolute_expression
(model: Model, expression: str, name: str = 'abs_var', ub: Optional[float] = None, difference: float = 0.0, add: bool = True) → Components[source]¶ Add the absolute value of an expression to the model.
Also defines a variable for the absolute value that can be used in other objectives or constraints.
- Parameters
model (cobra.Model) – The model to which to add the absolute expression.
expression (str) – Must be a valid symbolic expression within the model’s solver object. The absolute value is applied automatically on the expression.
name (str, optional) – The name of the newly created variable (default “abs_var”).
ub (positive float, optional) – The upper bound for the variable (default None).
difference (positive float, optional) – The difference between the expression and the variable (default 0.0).
add (bool, optional) – Whether to add the variable to the model at once (default True).
- Returns
A named tuple with variable and two constraints (upper_constraint, lower_constraint) describing the new variable and the constraints that assign the absolute value of the expression to it.
- Return type
-
cobra.util.solver.
fix_objective_as_constraint
(model: Model, fraction: float = 1.0, bound: Optional[float] = None, name: str = 'fixed_objective_{}') → float[source]¶ Fix current objective as an additional constraint.
When adding constraints to a model, such as done in pFBA which minimizes total flux, these constraints can become too powerful, resulting in solutions that satisfy optimality but sacrifices too much for the original objective function. To avoid that, we can fix the current objective value as a constraint to ignore solutions that give a lower (or higher depending on the optimization direction) objective value than the original model.
When done with the model as a context, the modification to the objective will be reverted when exiting that context.
- Parameters
model (cobra.Model) – The model to operate on.
fraction (float, optional) – The fraction of the optimum the objective is allowed to reach (default 1.0).
bound (float, optional) – The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored (default None).
name (str, optional) – Name of the objective. May contain one “{}” placeholder which is filled with the name of the old objective (default “fixed_objective_{}”).
- Returns
The value of the optimized objective * fraction
- Return type
-
cobra.util.solver.
check_solver_status
(status: str = None, raise_error: bool = False) → None[source]¶ Perform standard checks on a solver’s status.
- Parameters
- Returns
- Return type
- Warns
UserWarning – If status is not optimal and raise_error is set to True.
- Raises
OptimizationError – If status is None or is not optimal and raise_error is set to True.
-
cobra.util.solver.
assert_optimal
(model: Model, message: str = 'Optimization failed') → None[source]¶ Assert model solver status is optimal.
Do nothing if model solver status is optimal, otherwise throw appropriate exception depending on the status.
- Parameters
model (cobra.Model) – The model to check the solver status for.
message (str, optional) – Message for the exception if solver status is not optimal (default “Optimization failed”).
- Returns
- Return type
- Raises
OptimizationError – If solver status is not optimal.
-
cobra.util.solver.
add_lp_feasibility
(model: Model) → None[source]¶ Add a new objective and variables to ensure a feasible solution.
The optimized objective will be zero for a feasible solution and otherwise represent the distance from feasibility (please see [1]_ for more information).
- Parameters
model (cobra.Model) – The model whose feasibility is to be tested.
- Returns
- Return type
References
- 1
Gomez, Jose A., Kai Höffner, and Paul I. Barton.
“DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8.
-
cobra.util.solver.
add_lexicographic_constraints
(model: Model, objectives: List['Reaction'], objective_direction: Union[str, List[str]] = 'max') → pd.Series[source]¶ Successively optimize separate targets in a specific order.
For each objective, optimize the model and set the optimal value as a constraint. Proceed in the order of the objectives given. Due to the specific order this is called lexicographic FBA [1]_. This procedure is useful for returning unique solutions for a set of important fluxes. Typically this is applied to exchange fluxes.
- Parameters
model (cobra.Model) – The model to be optimized.
objectives (list of cobra.Reaction) – A list of reactions (or objectives) in the model for which unique fluxes are to be determined.
objective_direction (str or list of str, optional) – The desired objective direction for each reaction (if a list) or the objective direction to use for all reactions (default “max”).
- Returns
A pandas Series containing the optimized fluxes for each of the given reactions in objectives.
- Return type
pandas.Series
References
- 1
Gomez, Jose A., Kai Höffner, and Paul I. Barton.
“DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8.
cobra.util.util
¶General utilities used across the package.
Implementation of Perl’s autovivification feature. |
|
Shorten long string into a small string with ellipsis. |
|
Print dependency information. |
-
cobra.util.util.
format_long_string
(string: str, max_length: int = 50) → str[source]¶ Shorten long string into a small string with ellipsis.
-
class
cobra.util.util.
AutoVivification
[source]¶ Bases:
dict
Implementation of Perl’s autovivification feature.
Notes
For more information, check https://stackoverflow.com/a/652284/280182 .
Package Contents¶
Define a base context manager. |
|
Define an object for adding absolute expressions. |
|
Implementation of Perl’s autovivification feature. |
|
Define a process pool that handles the Windows platform specially. |
|
Return a stoichiometric array representation of the given model. |
|
Compute an approximate basis for the nullspace of A. |
|
Create a matrix representation of the problem. |
|
Search for a context manager. |
|
Simplify the context management of simple object attributes. |
|
Search for a context manager. |
|
Retrieve coefficient for the reactions in a linear objective. |
|
Check whether a sympy expression references the correct variables. |
|
Set the model objective. |
|
Give a string representation for an optlang interface. |
|
Select a solver for a given optimization problem. |
|
Choose a solver given a solver name and model. |
|
Check whether the chosen solver is valid. |
|
Add variables and constraints to a model’s solver object. |
|
Remove variables and constraints from a model’s solver object. |
|
Add the absolute value of an expression to the model. |
|
Fix current objective as an additional constraint. |
|
Perform standard checks on a solver’s status. |
|
Assert model solver status is optimal. |
|
Add a new objective and variables to ensure a feasible solution. |
|
Successively optimize separate targets in a specific order. |
|
Shorten long string into a small string with ellipsis. |
|
Print dependency information. |
-
cobra.util.
create_stoichiometric_matrix
(model: Model, array_type: str = 'dense', dtype: Optional[np.dtype] = None) → Union[np.ndarray, dok_matrix, lil_matrix, pd.DataFrame][source]¶ Return a stoichiometric array representation of the given model.
The the columns represent the reactions and rows represent metabolites. S[i,j] therefore contains the quantity of metabolite i produced (negative for consumed) by reaction j.
- Parameters
model (cobra.Model) – The cobra model to construct the matrix for.
array_type ({"dense", "dok", "lil", "DataFrame"}) – The type of array to construct. “dense” will return a standard numpy.ndarray. “dok”, or “lil” will construct a sparse array using scipy of the corresponding type. “DataFrame” will give a pandas.DataFrame with metabolite as indices and reaction as columns.
dtype (numpy.dtype, optional) – The desired numpy data type for the array (default numpy.float64).
- Returns
The stoichiometric matrix for the given model.
- Return type
matrix of class dtype
- Raises
ValueError – If sparse matrix is used and scipy is not installed.
. deprecated: – 0.18.1: “DataFrame” option for array_type will be replaced with “frame” in future versions.
-
cobra.util.
nullspace
(A: np.ndarray, atol: float = 1e-13, rtol: float = 0.0) → np.ndarray[source]¶ Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the Singular Value Decomposition (SVD) of A.
- Parameters
A (numpy.ndarray) – A should be at most 2-D. 1-D array with length k will be treated as a 2-D with shape (1, k).
atol (float, optional) – The absolute tolerance for a zero singular value. Singular values smaller than atol are considered to be zero (default 1e-13).
rtol (float, optional) – The relative tolerance. Singular values less than rtol * smax are considered to be zero, where smax is the largest singular value (default 0.0).
- Returns
If A is an array with shape (m, k), then ns will be an array with shape (k, n), where n is the estimated dimension of the nullspace of A. The columns of ns are a basis for the nullspace; each element in numpy.dot(A, ns) will be approximately zero.
- Return type
Notes
This is taken from the numpy cookbook.
If both atol and rtol are positive, the combined tolerance is the maximum of the two; that is:
\[\mathtt{tol} = \max(\mathtt{atol}, \mathtt{rtol} * \mathtt{smax})\]Singular values smaller than tol are considered to be zero.
-
cobra.util.
constraint_matrices
(model: Model, array_type: str = 'dense', zero_tol: float = 1e-06) → NamedTuple[source]¶ Create a matrix representation of the problem.
This is used for alternative solution approaches that do not use “optlang”. The function will construct the equality matrix, inequality matrix and bounds for the complete problem.
- Parameters
model (cobra.Model) – The model from which to obtain the LP problem.
array_type ({"dense", "dok", "lil", "DataFrame"}) – The type of array to construct. “dense” will return a standard numpy.ndarray. “dok”, or “lil” will construct a sparse array using scipy of the corresponding type. “DataFrame” will give a pandas.DataFrame with metabolite as indices and reaction as columns.
zero_tol (float, optional) – The zero tolerance used to judge whether two bounds are the same (default 1e-6).
- Returns
A named tuple consisting of 6 matrices and 2 vectors: - “equalities” is a matrix S such that S * vars = b. It
includes a row for each constraint and one column for each variable.
”b” is the right side of the equality equation such that S * vars = b.
”inequalities” is a matrix M such that lb <= M * vars <= ub. It contains a row for each inequality and as many columns as variables.
”bounds” is a compound matrix [lb ub] containing the lower and upper bounds for the inequality constraints in M.
”variable_fixed” is a boolean vector indicating whether the variable at that index is fixed (lower bound == upper_bound) and is thus bounded by an equality constraint.
”variable_bounds” is a compound matrix [lb ub] containing the lower and upper bounds for all variables.
- Return type
NamedTuple
Notes
To accomodate non-zero equalities, the problem will add the variable “const_one” which is a variable that equals one.
Deprecated since version 0.18.1: “DataFrame” option for array_type will be replaced with “frame” in future versions.
-
class
cobra.util.
HistoryManager
(**kwargs)[source]¶ Define a base context manager.
It records a list of actions to be taken at a later time. This is used to implement context managers that allow temporary changes to a cobra.core.Model.
-
__call__
(self, operation: Callable[[Any], Any]) → None¶ Add the corresponding operation to the history stack.
- Parameters
operation (callable) – A function to be called at a later time.
-
reset
(self) → None¶ Trigger executions for all items in the stack in reverse order.
-
size
(self) → int¶ Calculate number of operations on the stack.
-
-
cobra.util.
get_context
(obj: Object) → Optional[HistoryManager][source]¶ Search for a context manager.
- Parameters
obj (cobra.Object) – The cobra.Object for which to search context manager.
- Returns
HistoryManager instance, or None if no context manager is found.
- Return type
- Raises
AttributeError – If no context manager is found.
IndexError – If no context manager is found.
-
cobra.util.
resettable
(func: Callable[[Any], Any]) → Callable[[Any], Any][source]¶ Simplify the context management of simple object attributes.
It gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the cobra.util.HistoryManager.
- Parameters
func (callable) – The function to decorate.
- Returns
The decorated function.
- Return type
callable
-
cobra.util.
OPTLANG_TO_EXCEPTIONS_DICT
¶
-
exception
cobra.util.
OptimizationError
(message)¶ Bases:
Exception
Exception for Optimization issues.
-
exception
cobra.util.
SolverNotFound
¶ Bases:
Exception
A simple Exception when a solver can not be found.
-
cobra.util.
get_context
(obj: Object) → Optional[HistoryManager][source] Search for a context manager.
- Parameters
obj (cobra.Object) – The cobra.Object for which to search context manager.
- Returns
HistoryManager instance, or None if no context manager is found.
- Return type
- Raises
AttributeError – If no context manager is found.
IndexError – If no context manager is found.
-
class
cobra.util.
Components
[source]¶ Bases:
typing.NamedTuple
Define an object for adding absolute expressions.
-
variable
:optlang.interface.Variable¶
-
upper_constraint
:optlang.interface.Constraint¶
-
lower_constraint
:optlang.interface.Constraint¶
-
-
cobra.util.
linear_reaction_coefficients
(model: Model, reactions: Optional[List['Reaction']] = None) → Dict['Reaction', float][source]¶ Retrieve coefficient for the reactions in a linear objective.
- Parameters
model (cobra.Model) – The cobra model defining the linear objective.
reactions (list of cobra.Reaction, optional) – An optional list of the reactions to get the coefficients for. By default, all reactions are considered (default None).
- Returns
A dictionary where the keys are the reaction objects and the values are the corresponding coefficient. Empty dictionary if there are no linear terms in the objective.
- Return type
-
cobra.util.
_valid_atoms
(model: Model, expression: optlang.symbolics.Basic) → bool[source]¶ Check whether a sympy expression references the correct variables.
- Parameters
model (cobra.Model) – The model in which to check for variables.
expression (sympy.Basic) – A sympy expression.
- Returns
True if all referenced variables are contained in model, False otherwise.
- Return type
-
cobra.util.
set_objective
(model: Model, value: Union[optlang.interface.Objective, optlang.symbolics.Basic, Dict['Reaction', float]], additive: bool = False) → None[source]¶ Set the model objective.
- Parameters
model (cobra.Model) – The model to set the objective for.
value (optlang.interface.Objective, optlang.symbolics.Basic, dict) – If the model objective is linear, then the value can be a new optlang.interface.Objective or a dictionary with linear coefficients where each key is a reaction and the corresponding value is the new coefficient (float). If the objective is non-linear and additive is True, then only values of class optlang.interface.Objective, are accepted.
additive (bool) – If True, add the terms to the current objective, otherwise start with an empty objective.
- Raises
ValueError – If model objective is non-linear and the value is a dict.
TypeError – If the type of value is not one of the accepted ones.
-
cobra.util.
interface_to_str
(interface: Union[str, ModuleType]) → str[source]¶ Give a string representation for an optlang interface.
-
cobra.util.
get_solver_name
(mip: bool = False, qp: bool = False) → str[source]¶ Select a solver for a given optimization problem.
- Parameters
- Returns
The name of the feasible solver.
- Return type
- Raises
SolverNotFound – If no suitable solver could be found.
-
cobra.util.
choose_solver
(model: Model, solver: Optional[str] = None, qp: bool = False) → ModuleType[source]¶ Choose a solver given a solver name and model.
This will choose a solver compatible with the model and required capabilities. Also respects model.solver where it can.
- Parameters
model (cobra.Model) – The model for which to choose the solver.
solver (str, optional) – The name of the solver to be used (default None).
qp (boolean, optional) – True if the solver needs quadratic programming capabilities (default False).
- Returns
Valid solver for the problem.
- Return type
optlang.interface
- Raises
SolverNotFound – If no suitable solver could be found.
-
cobra.util.
check_solver
(obj)[source]¶ Check whether the chosen solver is valid.
Check whether chosen solver is valid and also warn when using a specialized solver. Will return the optlang interface for the requested solver.
- Parameters
obj (str or optlang.interface or optlang.interface.Model) – The chosen solver.
- Raises
SolverNotFound – If the solver is not valid.
-
cobra.util.
add_cons_vars_to_problem
(model: Model, what: Union[List[CONS_VARS], Tuple[CONS_VARS], Components], **kwargs) → None[source]¶ Add variables and constraints to a model’s solver object.
Useful for variables and constraints that can not be expressed with reactions and lower/upper bounds. It will integrate with the model’s context manager in order to revert changes upon leaving the context.
- Parameters
model (cobra.Model) – The model to which to add the variables and constraints.
what (list or tuple of optlang.interface.Variable or) – optlang.interface.Constraint The variables and constraints to add to the model.
**kwargs (keyword arguments) – Keyword arguments passed to solver’s add() method.
-
cobra.util.
remove_cons_vars_from_problem
(model: Model, what: Union[List[CONS_VARS], Tuple[CONS_VARS], Components]) → None[source]¶ Remove variables and constraints from a model’s solver object.
Useful to temporarily remove variables and constraints from a model’s solver object.
- Parameters
model (cobra.Model) – The model from which to remove the variables and constraints.
what (list or tuple of optlang.interface.Variable or) – optlang.interface.Constraint The variables and constraints to remove from the model.
-
cobra.util.
add_absolute_expression
(model: Model, expression: str, name: str = 'abs_var', ub: Optional[float] = None, difference: float = 0.0, add: bool = True) → Components[source]¶ Add the absolute value of an expression to the model.
Also defines a variable for the absolute value that can be used in other objectives or constraints.
- Parameters
model (cobra.Model) – The model to which to add the absolute expression.
expression (str) – Must be a valid symbolic expression within the model’s solver object. The absolute value is applied automatically on the expression.
name (str, optional) – The name of the newly created variable (default “abs_var”).
ub (positive float, optional) – The upper bound for the variable (default None).
difference (positive float, optional) – The difference between the expression and the variable (default 0.0).
add (bool, optional) – Whether to add the variable to the model at once (default True).
- Returns
A named tuple with variable and two constraints (upper_constraint, lower_constraint) describing the new variable and the constraints that assign the absolute value of the expression to it.
- Return type
-
cobra.util.
fix_objective_as_constraint
(model: Model, fraction: float = 1.0, bound: Optional[float] = None, name: str = 'fixed_objective_{}') → float[source]¶ Fix current objective as an additional constraint.
When adding constraints to a model, such as done in pFBA which minimizes total flux, these constraints can become too powerful, resulting in solutions that satisfy optimality but sacrifices too much for the original objective function. To avoid that, we can fix the current objective value as a constraint to ignore solutions that give a lower (or higher depending on the optimization direction) objective value than the original model.
When done with the model as a context, the modification to the objective will be reverted when exiting that context.
- Parameters
model (cobra.Model) – The model to operate on.
fraction (float, optional) – The fraction of the optimum the objective is allowed to reach (default 1.0).
bound (float, optional) – The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored (default None).
name (str, optional) – Name of the objective. May contain one “{}” placeholder which is filled with the name of the old objective (default “fixed_objective_{}”).
- Returns
The value of the optimized objective * fraction
- Return type
-
cobra.util.
check_solver_status
(status: str = None, raise_error: bool = False) → None[source]¶ Perform standard checks on a solver’s status.
- Parameters
- Returns
- Return type
- Warns
UserWarning – If status is not optimal and raise_error is set to True.
- Raises
OptimizationError – If status is None or is not optimal and raise_error is set to True.
-
cobra.util.
assert_optimal
(model: Model, message: str = 'Optimization failed') → None[source]¶ Assert model solver status is optimal.
Do nothing if model solver status is optimal, otherwise throw appropriate exception depending on the status.
- Parameters
model (cobra.Model) – The model to check the solver status for.
message (str, optional) – Message for the exception if solver status is not optimal (default “Optimization failed”).
- Returns
- Return type
- Raises
OptimizationError – If solver status is not optimal.
-
cobra.util.
add_lp_feasibility
(model: Model) → None[source]¶ Add a new objective and variables to ensure a feasible solution.
The optimized objective will be zero for a feasible solution and otherwise represent the distance from feasibility (please see [1]_ for more information).
- Parameters
model (cobra.Model) – The model whose feasibility is to be tested.
- Returns
- Return type
References
- 1
Gomez, Jose A., Kai Höffner, and Paul I. Barton.
“DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8.
-
cobra.util.
add_lexicographic_constraints
(model: Model, objectives: List['Reaction'], objective_direction: Union[str, List[str]] = 'max') → pd.Series[source]¶ Successively optimize separate targets in a specific order.
For each objective, optimize the model and set the optimal value as a constraint. Proceed in the order of the objectives given. Due to the specific order this is called lexicographic FBA [1]_. This procedure is useful for returning unique solutions for a set of important fluxes. Typically this is applied to exchange fluxes.
- Parameters
model (cobra.Model) – The model to be optimized.
objectives (list of cobra.Reaction) – A list of reactions (or objectives) in the model for which unique fluxes are to be determined.
objective_direction (str or list of str, optional) – The desired objective direction for each reaction (if a list) or the objective direction to use for all reactions (default “max”).
- Returns
A pandas Series containing the optimized fluxes for each of the given reactions in objectives.
- Return type
pandas.Series
References
- 1
Gomez, Jose A., Kai Höffner, and Paul I. Barton.
“DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8.
-
cobra.util.
format_long_string
(string: str, max_length: int = 50) → str[source]¶ Shorten long string into a small string with ellipsis.
-
class
cobra.util.
AutoVivification
[source]¶ Bases:
dict
Implementation of Perl’s autovivification feature.
Notes
For more information, check https://stackoverflow.com/a/652284/280182 .
-
__getitem__
(self, item: Any) → Any¶ Retrieve if item is found, else add it.
- Parameters
item (Any) – The object to look for.
- Returns
The retrieved object.
- Return type
Any
-
-
class
cobra.util.
ProcessPool
(processes: Optional[int] = None, initializer: Optional[Callable] = None, initargs: Tuple = (), maxtasksperchild: Optional[int] = None, **kwargs)[source]¶ Define a process pool that handles the Windows platform specially.
-
__getattr__
(self, name: str, **kwargs) → Any¶ Defer attribute access to the pool instance.
-
__enter__
(self) → 'ProcessPool'¶ Enable context management.
-
__exit__
(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) → Optional[bool]¶ Clean up resources when leaving a context.
-
close
(self) → None¶ Close the process pool.
Prevent any more tasks from being submitted to the pool. Once all the tasks have been completed, the worker processes will exit.
-
_clean_up
(self) → None¶ Remove the dump file if it exists.
-
Submodules¶
cobra.exceptions
¶
Module for shared exceptions in the Cobra package.
Module Contents¶
-
exception
cobra.exceptions.
OptimizationError
(message)[source]¶ Bases:
Exception
Exception for Optimization issues.
-
exception
cobra.exceptions.
Infeasible
(message)[source]¶ Bases:
cobra.exceptions.OptimizationError
Exception for Infeasible issues.
-
exception
cobra.exceptions.
Unbounded
(message)[source]¶ Bases:
cobra.exceptions.OptimizationError
Exception for Unbounded issues.
-
exception
cobra.exceptions.
FeasibleButNotOptimal
(message)[source]¶ Bases:
cobra.exceptions.OptimizationError
Exception for Non-Optimal issues.
-
exception
cobra.exceptions.
UndefinedSolution
(message)[source]¶ Bases:
cobra.exceptions.OptimizationError
Exception for Undefined issues.
Package Contents¶
Classes¶
Define a global configuration object. |
|
A combined dict and list |
|
A Gene in a cobra model |
|
Metabolite is a class for holding information regarding |
|
Class representation for a cobra model |
|
Defines common behavior of object in cobra.core |
|
Reaction is a class for holding information regarding |
|
A unified interface to a cobra.Model optimization solution. |
|
Species is a class for holding information regarding |
Functions¶
|
Print dependency information. |
-
class
cobra.
Configuration
(**kwargs)¶ Define a global configuration object.
The attributes of this singleton object are used as default values by cobra functions.
-
solver
¶ The default solver for new models. The solver choices are the ones provided by optlang and depend on solvers installed in your environment.
- Type
{“glpk”, “cplex”, “gurobi”, “glpk_exact”}
-
lower_bound
¶ The standard lower bound for reversible reactions (default -1000).
- Type
float, optional
-
bounds
¶ The default reaction bounds for newly created reactions. The bounds are in the form of lower_bound, upper_bound (default -1000.0, 1000.0).
- Type
tuple of floats
-
processes
¶ A default number of processes to use where multiprocessing is possible. The default number corresponds to the number of available cores (hyperthreads) minus one.
- Type
-
cache_directory
¶ A path where the model cache should reside if caching is desired. The default directory depends on the operating system.
- Type
pathlib.Path or str, optional
-
max_cache_size
¶ The allowed maximum size of the model cache in bytes (default 1 GB).
- Type
int, optional
-
cache_expiration
¶ The expiration time in seconds for the model cache if any (default None).
- Type
int, optional
-
_set_default_solver
(self) → None¶ Set the default solver from a preferred order.
-
_set_default_processes
(self) → None¶ Set the default number of processes.
-
_set_default_cache_directory
(self) → None¶ Set the platform-dependent default cache directory.
-
property
solver
(self) → types.ModuleType Return the optlang solver interface.
-
property
bounds
(self) → Tuple[Optional[Number], Optional[Number]] Return the lower, upper reaction bound pair.
-
property
cache_directory
(self) → pathlib.Path Return the model cache directory.
-
__repr__
(self) → str¶ Return a string representation of the current configuration values.
-
_repr_html_
(self) → str¶ Return a rich HTML representation of the current configuration values.
Notes
This special method is used automatically in Jupyter notebooks to display a result from a cell.
-
-
class
cobra.
DictList
(*args)¶ Bases:
list
A combined dict and list
This object behaves like a list, but has the O(1) speed benefits of a dict when looking up elements by their id.
-
has_id
(self, id)¶
-
_check
(self, id)¶ make sure duplicate id’s are not added. This function is called before adding in elements.
-
_generate_index
(self)¶ rebuild the _dict index
-
get_by_id
(self, id)¶ return the element with a matching id
-
list_attr
(self, attribute)¶ return a list of the given attribute for every object
-
get_by_any
(self, iterable)¶ Get a list of members using several different ways of indexing
-
query
(self, search_function, attribute=None)¶ Query the list
- Parameters
search_function (a string, regular expression or function) – Used to find the matching elements in the list. - a regular expression (possibly compiled), in which case the given attribute of the object should match the regular expression. - a function which takes one argument and returns True for desired values
attribute (string or None) – the name attribute of the object to passed as argument to the search_function. If this is None, the object itself is used.
- Returns
a new list of objects which match the query
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model('textbook') >>> model.reactions.query(lambda x: x.boundary) >>> import re >>> regex = re.compile('^g', flags=re.IGNORECASE) >>> model.metabolites.query(regex, attribute='name')
-
_replace_on_id
(self, new_object)¶ Replace an object by another with the same id.
-
append
(self, object)¶ append object to end
-
union
(self, iterable)¶ adds elements with id’s not already in the model
-
extend
(self, iterable)¶ extend list by appending elements from the iterable
-
_extend_nocheck
(self, iterable)¶ extends without checking for uniqueness
This function should only be used internally by DictList when it can guarantee elements are already unique (as in when coming from self or other DictList). It will be faster because it skips these checks.
-
__sub__
(self, other)¶ x.__sub__(y) <==> x - y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__isub__
(self, other)¶ x.__sub__(y) <==> x -= y
- Parameters
other (iterable) – other must contain only unique id’s present in the list
-
__add__
(self, other)¶ x.__add__(y) <==> x + y
- Parameters
other (iterable) – other must contain only unique id’s which do not intersect with self
-
__iadd__
(self, other)¶ x.__iadd__(y) <==> x += y
- Parameters
other (iterable) – other must contain only unique id’s whcih do not intersect with self
-
__reduce__
(self)¶ Helper for pickle.
-
__getstate__
(self)¶ gets internal state
This is only provided for backwards compatibility so older versions of cobrapy can load pickles generated with cobrapy. In reality, the “_dict” state is ignored when loading a pickle
-
__setstate__
(self, state)¶ sets internal state
Ignore the passed in state and recalculate it. This is only for compatibility with older pickles which did not correctly specify the initialization class
-
index
(self, id, *args)¶ Determine the position in the list
id: A string or a
Object
-
__contains__
(self, object)¶ DictList.__contains__(object) <==> object in DictList
object: str or
Object
-
__copy__
(self)¶
-
insert
(self, index, object)¶ insert object before index
-
pop
(self, *args)¶ remove and return item at index (default last).
-
add
(self, x)¶ Opposite of remove. Mirrors set.add
-
remove
(self, x)¶ Warning
Internal use only
-
reverse
(self)¶ reverse IN PLACE
-
sort
(self, cmp=None, key=None, reverse=False)¶ stable sort IN PLACE
cmp(x, y) -> -1, 0, 1
-
__getitem__
(self, i)¶ x.__getitem__(y) <==> x[y]
-
__setitem__
(self, i, y)¶ Set self[key] to value.
-
__delitem__
(self, index)¶ Delete self[key].
-
__getslice__
(self, i, j)¶
-
__setslice__
(self, i, j, y)¶
-
__delslice__
(self, i, j)¶
-
__getattr__
(self, attr)¶
-
__dir__
(self)¶ Default dir() implementation.
-
-
class
cobra.
Gene
(id=None, name='', functional=True)¶ Bases:
cobra.core.species.Species
A Gene in a cobra model
- Parameters
id (string) – The identifier to associate the gene with
name (string) – A longer human readable name for the gene
functional (bool) – Indicates whether the gene is functional. If it is not functional then it cannot be used in an enzyme complex nor can its products be used.
-
property
functional
(self)¶ A flag indicating if the gene is functional.
Changing the flag is reverted upon exit if executed within the model as context.
-
knock_out
(self)¶ Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero.
The change is reverted upon exit if executed within the model as context.
-
remove_from_model
(self, model=None, make_dependent_reactions_nonfunctional=True)¶ Removes the association
- Parameters
model (cobra model) – The model to remove the gene from
make_dependent_reactions_nonfunctional (bool) – If True then replace the gene with ‘False’ in the gene association, else replace the gene with ‘True’
Deprecated since version 0.4: Use cobra.manipulation.delete_model_genes to simulate knockouts and cobra.manipulation.remove_genes to remove genes from the model.
-
_repr_html_
(self)¶
-
class
cobra.
Metabolite
(id=None, formula=None, name='', charge=None, compartment=None)¶ Bases:
cobra.core.species.Species
Metabolite is a class for holding information regarding a metabolite in a cobra.Reaction object.
- Parameters
-
_set_id_with_model
(self, value)¶
-
property
constraint
(self)¶ Get the constraints associated with this metabolite from the solve
- Returns
the optlang constraint for this metabolite
- Return type
optlang.<interface>.Constraint
-
property
elements
(self)¶ Dictionary of elements as keys and their count in the metabolite as integer. When set, the formula property is update accordingly
-
property
formula_weight
(self)¶ Calculate the formula weight
-
property
y
(self)¶ The shadow price for the metabolite in the most recent solution
Shadow prices are computed from the dual values of the bounds in the solution.
-
property
shadow_price
(self)¶ The shadow price in the most recent solution.
Shadow price is the dual value of the corresponding constraint in the model.
Warning
Accessing shadow prices through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Shadow price is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the metabolite is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra >>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.metabolites.glc__D_e.shadow_price -0.09166474637510488 >>> solution.shadow_prices.glc__D_e -0.091664746375104883
-
remove_from_model
(self, destructive=False)¶ Removes the association from self.model
The change is reverted upon exit when using the model as a context.
- Parameters
destructive (bool) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model.
-
summary
(self, solution=None, fva=None)¶ Create a summary of the producing and consuming fluxes.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
See also
-
_repr_html_
(self)¶
-
class
cobra.
Model
(id_or_model=None, name=None)¶ Bases:
cobra.core.object.Object
Class representation for a cobra model
- Parameters
id_or_model (Model, string) – Either an existing Model object in which case a new model object is instantiated with the same properties as the original model, or an identifier to associate with the model as a string.
name (string) – Human readable name for the model
-
reactions
¶ A DictList where the key is the reaction identifier and the value a Reaction
- Type
-
metabolites
¶ A DictList where the key is the metabolite identifier and the value a Metabolite
- Type
-
__setstate__
(self, state)¶ Make sure all cobra.Objects in the model point to the model.
-
__getstate__
(self)¶ Get state for serialization.
Ensures that the context stack is cleared prior to serialization, since partial functions cannot be pickled reliably.
-
property
solver
(self)¶ Get or set the attached solver instance.
The associated the solver object, which manages the interaction with the associated solver, e.g. glpk.
This property is useful for accessing the optimization problem directly and to define additional non-metabolic constraints.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> new = model.problem.Constraint(model.objective.expression, >>> lb=0.99) >>> model.solver.add(new)
-
property
tolerance
(self)¶
-
property
description
(self)¶
-
get_metabolite_compartments
(self)¶ Return all metabolites’ compartments.
-
property
compartments
(self)¶
-
property
medium
(self)¶
-
__add__
(self, other_model)¶ Add the content of another model to this model (+).
The model is copied as a new object, with a new model identifier, and copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
__iadd__
(self, other_model)¶ Incrementally add the content of another model to this model (+=).
Copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.
-
copy
(self)¶ Provides a partial ‘deepcopy’ of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy
-
add_metabolites
(self, metabolite_list)¶ Will add a list of metabolites to the model object and add new constraints accordingly.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolite_list (A list of cobra.core.Metabolite objects) –
-
remove_metabolites
(self, metabolite_list, destructive=False)¶ Remove a list of metabolites from the the object.
The change is reverted upon exit when using the model as a context.
-
add_reaction
(self, reaction)¶ Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions.
- Parameters
reaction (cobra.Reaction) – The reaction to add
(0.6) Use ~cobra.Model.add_reactions instead (Deprecated) –
-
add_boundary
(self, metabolite, type='exchange', reaction_id=None, lb=None, ub=None, sbo_term=None)¶ Add a boundary reaction for a given metabolite.
There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, unbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites, i.e., a reversible reaction that adds or removes an intracellular metabolite.
If you set the reaction type to something else, you must specify the desired identifier of the created reaction along with its upper and lower bound. The name will be given by the metabolite name and the given type.
- Parameters
metabolite (cobra.Metabolite) – Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks.
type (str, {"exchange", "demand", "sink"}) – Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., ‘my-boundary’.
reaction_id (str, optional) – The ID of the resulting reaction. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using model.boundary or specifically model.exchanges etc.
lb (float, optional) – The lower bound of the resulting reaction.
ub (float, optional) – The upper bound of the resulting reaction.
sbo_term (str, optional) – A correct SBO term is set for the available types. If a custom type is chosen, a suitable SBO term should also be set.
- Returns
The created boundary reaction.
- Return type
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> demand = model.add_boundary(model.metabolites.atp_c, type="demand") >>> demand.id 'DM_atp_c' >>> demand.name 'ATP demand' >>> demand.bounds (0, 1000.0) >>> demand.build_reaction_string() 'atp_c --> '
-
add_reactions
(self, reaction_list)¶ Add reactions to the model.
Reactions with identifiers identical to a reaction already in the model are ignored.
The change is reverted upon exit when using the model as a context.
- Parameters
reaction_list (list) – A list of cobra.Reaction objects
-
remove_reactions
(self, reactions, remove_orphans=False)¶ Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
-
add_groups
(self, group_list)¶ Add groups to the model.
Groups with identifiers identical to a group already in the model are ignored.
If any group contains members that are not in the model, these members are added to the model as well. Only metabolites, reactions, and genes can have groups.
- Parameters
group_list (list) – A list of cobra.Group objects to add to the model.
-
remove_groups
(self, group_list)¶ Remove groups from the model.
Members of each group are not removed from the model (i.e. metabolites, reactions, and genes in the group stay in the model after any groups containing them are removed).
- Parameters
group_list (list) – A list of cobra.Group objects to remove from the model.
-
get_associated_groups
(self, element)¶ Returns a list of groups that an element (reaction, metabolite, gene) is associated with.
- Parameters
element (cobra.Reaction, cobra.Metabolite, or cobra.Gene) –
- Returns
All groups that the provided object is a member of
- Return type
list of cobra.Group
-
add_cons_vars
(self, what, **kwargs)¶ Add constraints and variables to the model’s mathematical problem.
Useful for variables and constraints that can not be expressed with reactions and simple lower and upper bounds.
Additions are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
**kwargs (keyword arguments) – Passed to solver.add()
-
remove_cons_vars
(self, what)¶ Remove variables and constraints from the model’s mathematical problem.
Remove variables and constraints that were added directly to the model’s underlying mathematical problem. Removals are reversed upon exit if the model itself is used as context.
- Parameters
what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
-
property
problem
(self)¶ The interface to the model’s underlying mathematical problem.
Solutions to cobra models are obtained by formulating a mathematical problem and solving it. Cobrapy uses the optlang package to accomplish that and with this property you can get access to the problem interface directly.
- Returns
The problem interface that defines methods for interacting with the problem and associated solver directly.
- Return type
optlang.interface
-
property
variables
(self)¶ The mathematical variables in the cobra model.
In a cobra model, most variables are reactions. However, for specific use cases, it may also be useful to have other types of variables. This property defines all variables currently associated with the model’s problem.
- Returns
A container with all associated variables.
- Return type
optlang.container.Container
-
property
constraints
(self)¶ The constraints in the cobra model.
In a cobra model, most constraints are metabolites and their stoichiometries. However, for specific use cases, it may also be useful to have other types of constraints. This property defines all constraints currently associated with the model’s problem.
- Returns
A container with all associated constraints.
- Return type
optlang.container.Container
-
property
boundary
(self)¶ Boundary reactions in the model. Reactions that either have no substrate or product.
-
property
exchanges
(self)¶ Exchange reactions in model. Reactions that exchange mass with the exterior. Uses annotations and heuristics to exclude non-exchanges such as sink reactions.
-
property
demands
(self)¶ Demand reactions in model. Irreversible reactions that accumulate or consume a metabolite in the inside of the model.
-
property
sinks
(self)¶ Sink reactions in model. Reversible reactions that accumulate or consume a metabolite in the inside of the model.
-
_populate_solver
(self, reaction_list, metabolite_list=None)¶ Populate attached solver with constraints and variables that model the provided reactions.
-
slim_optimize
(self, error_value=float('nan'), message=None)¶ Optimize model without creating a solution object.
Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and in cases where only one or two values are of interest, it is recommended to instead use this function which does not create a solution object returning only the value of the objective. Note however that the optimize() function uses efficient means to fetch values so if you need fluxes/shadow prices for more than say 4 reactions/metabolites, then the total speed increase of slim_optimize versus optimize is expected to be small or even negative depending on how you fetch the values after optimization.
-
optimize
(self, objective_sense=None, raise_error=False)¶ Optimize the model using flux balance analysis.
- Parameters
objective_sense ({None, 'maximize' 'minimize'}, optional) – Whether fluxes should be maximized or minimized. In case of None, the previous direction is used.
raise_error (bool) –
- If true, raise an OptimizationError if solver status is not
optimal.
Notes
Only the most commonly used parameters are presented here. Additional parameters for cobra.solvers may be available and specified with the appropriate keyword argument.
-
repair
(self, rebuild_index=True, rebuild_relationships=True)¶ Update all indexes and pointers in a model
-
property
objective
(self)¶ Get or set the solver objective
Before introduction of the optlang based problems, this function returned the objective reactions as a list. With optlang, the objective is not limited a simple linear summation of individual reaction fluxes, making that return value ambiguous. Henceforth, use cobra.util.solver.linear_reaction_coefficients to get a dictionary of reactions with their linear coefficients (empty if there are none)
The set value can be dictionary (reactions as keys, linear coefficients as values), string (reaction identifier), int (reaction index), Reaction or problem.Objective or sympy expression directly interpreted as objectives.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
objective_direction
(self)¶ Get or set the objective direction.
When using a HistoryManager context, this attribute can be set temporarily, reversed when exiting the context.
-
summary
(self, solution=None, fva=None)¶ Create a summary of the exchange fluxes of the model.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.ModelSummary
See also
-
__enter__
(self)¶ Record all future changes to the model, undoing them when a call to __exit__ is received
-
__exit__
(self, type, value, traceback)¶ Pop the top context manager and trigger the undo functions
-
merge
(self, right, prefix_existing=None, inplace=True, objective='left')¶ Merge two models to create a model with the reactions from both models.
Custom constraints and variables from right models are also copied to left model, however note that, constraints and variables are assumed to be the same if they have the same name.
- rightcobra.Model
The model to add reactions from
- prefix_existingstring
Prefix the reaction identifier in the right that already exist in the left model with this string.
- inplacebool
Add reactions from right directly to left model object. Otherwise, create a new model leaving the left model untouched. When done within the model as context, changes to the models are reverted upon exit.
- objectivestring
One of ‘left’, ‘right’ or ‘sum’ for setting the objective of the resulting model to that of the corresponding model or the sum of both.
-
_repr_html_
(self)¶
-
class
cobra.
Object
(id=None, name='')¶ Bases:
object
Defines common behavior of object in cobra.core
-
property
id
(self)¶
-
_set_id_with_model
(self, value)¶
-
property
annotation
(self)¶
-
__getstate__
(self)¶ To prevent excessive replication during deepcopy.
-
__repr__
(self)¶ Return repr(self).
-
__str__
(self)¶ Return str(self).
-
property
-
class
cobra.
Reaction
(id=None, name='', subsystem='', lower_bound=0.0, upper_bound=None)¶ Bases:
cobra.core.object.Object
Reaction is a class for holding information regarding a biochemical reaction in a cobra.Model object.
Reactions are by default irreversible with bounds (0.0, cobra.Configuration().upper_bound) if no bounds are provided on creation. To create an irreversible reaction use lower_bound=None, resulting in reaction bounds of (cobra.Configuration().lower_bound, cobra.Configuration().upper_bound).
- Parameters
-
__radd__
¶
-
_set_id_with_model
(self, value)¶
-
property
reverse_id
(self)¶ Generate the id of reverse_variable from the reaction’s id.
-
property
flux_expression
(self)¶ Forward flux expression
- Returns
The expression representing the the forward flux (if associated with model), otherwise None. Representing the net flux if model.reversible_encoding == ‘unsplit’ or None if reaction is not associated with a model
- Return type
sympy expression
-
property
forward_variable
(self)¶ An optlang variable representing the forward flux
- Returns
An optlang variable for the forward flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
reverse_variable
(self)¶ An optlang variable representing the reverse flux
- Returns
An optlang variable for the reverse flux or None if reaction is not associated with a model.
- Return type
optlang.interface.Variable
-
property
objective_coefficient
(self)¶ Get the coefficient for this reaction in a linear objective (float)
Assuming that the objective of the associated model is summation of fluxes from a set of reactions, the coefficient for each reaction can be obtained individually using this property. A more general way is to use the model.objective property directly.
-
__copy__
(self)¶
-
__deepcopy__
(self, memo)¶
-
static
_check_bounds
(lb, ub)¶
-
update_variable_bounds
(self)¶
-
property
lower_bound
(self)¶ Get or set the lower bound
Setting the lower bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a lower bound higher than the current upper bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
upper_bound
(self)¶ Get or set the upper bound
Setting the upper bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a upper bound lower than the current lower bound will update the other bound.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
bounds
(self)¶ Get or set the bounds directly from a tuple
Convenience method for setting upper and lower bounds in one line using a tuple of lower and upper bound. Invalid bounds will raise an AssertionError.
When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.
-
property
flux
(self)¶ The flux value in the most recent solution.
Flux is the primal value of the corresponding variable in the model.
Warning
Accessing reaction fluxes through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reaction flux is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
AssertionError – If the flux value is not within the bounds.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.flux 7.477381962160283 >>> solution.fluxes.PFK 7.4773819621602833
-
property
reduced_cost
(self)¶ The reduced cost in the most recent solution.
Reduced cost is the dual value of the corresponding variable in the model.
Warning
Accessing reduced costs through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.
Reduced cost is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.
If you modify the underlying model after an optimization, you will retrieve the old optimization values.
- Raises
RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.
OptimizationError – If the solver status is anything other than ‘optimal’.
Examples
>>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.reduced_cost -8.673617379884035e-18 >>> solution.reduced_costs.PFK -8.6736173798840355e-18
-
property
metabolites
(self)¶
-
property
genes
(self)¶
-
property
gene_reaction_rule
(self)¶
-
property
gene_name_reaction_rule
(self)¶ Display gene_reaction_rule with names intead.
Do NOT use this string for computation. It is intended to give a representation of the rule using more familiar gene names instead of the often cryptic ids.
-
property
functional
(self)¶ All required enzymes for reaction are functional.
- Returns
True if the gene-protein-reaction (GPR) rule is fulfilled for this reaction, or if reaction is not associated to a model, otherwise False.
- Return type
-
property
x
(self)¶ The flux through the reaction in the most recent solution.
Flux values are computed from the primal values of the variables in the solution.
-
property
y
(self)¶ The reduced cost of the reaction in the most recent solution.
Reduced costs are computed from the dual values of the variables in the solution.
-
property
reversibility
(self)¶ Whether the reaction can proceed in both directions (reversible)
This is computed from the current upper and lower bounds.
-
property
boundary
(self)¶ Whether or not this reaction is an exchange reaction.
Returns True if the reaction has either no products or reactants.
-
property
model
(self)¶ returns the model the reaction is a part of
-
_update_awareness
(self)¶ Make sure all metabolites and genes that are associated with this reaction are aware of it.
-
remove_from_model
(self, remove_orphans=False)¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
delete
(self, remove_orphans=False)¶ Removes the reaction from a model.
This removes all associations between a reaction the associated model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Deprecated, use reaction.remove_from_model instead.
- Parameters
remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
-
__setstate__
(self, state)¶ Probably not necessary to set _model as the cobra.Model that contains self sets the _model attribute for all metabolites and genes in the reaction.
However, to increase performance speed we do want to let the metabolite and gene know that they are employed in this reaction
-
copy
(self)¶ Copy a reaction
The referenced metabolites and genes are also copied.
-
__add__
(self, other)¶ Add two reactions
The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction
-
__iadd__
(self, other)¶
-
__sub__
(self, other)¶
-
__isub__
(self, other)¶
-
__imul__
(self, coefficient)¶ Scale coefficients in a reaction by a given value
E.g. A -> B becomes 2A -> 2B.
If coefficient is less than zero, the reaction is reversed and the bounds are swapped.
-
__mul__
(self, coefficient)¶
-
property
reactants
(self)¶ Return a list of reactants for the reaction.
-
property
products
(self)¶ Return a list of products for the reaction
-
get_coefficient
(self, metabolite_id)¶ Return the stoichiometric coefficient of a metabolite.
- Parameters
metabolite_id (str or cobra.Metabolite) –
-
get_coefficients
(self, metabolite_ids)¶ Return the stoichiometric coefficients for a list of metabolites.
- Parameters
metabolite_ids (iterable) – Containing
str
or ``cobra.Metabolite``s.
-
add_metabolites
(self, metabolites_to_add, combine=True, reversibly=True)¶ Add metabolites and stoichiometric coefficients to the reaction. If the final coefficient for a metabolite is 0 then it is removed from the reaction.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites_to_add (dict) – Dictionary with metabolite objects or metabolite identifiers as keys and coefficients as values. If keys are strings (name of a metabolite) the reaction must already be part of a model and a metabolite with the given name must exist in the model.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
subtract_metabolites
(self, metabolites, combine=True, reversibly=True)¶ Subtract metabolites from a reaction.
That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction.
Notes
A final coefficient < 0 implies a reactant.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolites (dict) – Dictionary where the keys are of class Metabolite and the values are the coefficients. These metabolites will be added to the reaction.
combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.
reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).
-
property
reaction
(self)¶ Human readable reaction string
-
build_reaction_string
(self, use_metabolite_names=False)¶ Generate a human readable reaction string
-
check_mass_balance
(self)¶ Compute mass and charge balance for the reaction
returns a dict of {element: amount} for unbalanced elements. “charge” is treated as an element in this dict This should be empty for balanced reactions.
-
property
compartments
(self)¶ lists compartments the metabolites are in
-
get_compartments
(self)¶ lists compartments the metabolites are in
-
_associate_gene
(self, cobra_gene)¶ Associates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
_dissociate_gene
(self, cobra_gene)¶ Dissociates a cobra.Gene object with a cobra.Reaction.
- Parameters
cobra_gene (cobra.core.Gene.Gene) –
-
knock_out
(self)¶ Knockout reaction by setting its bounds to zero.
-
build_reaction_from_string
(self, reaction_str, verbose=True, fwd_arrow=None, rev_arrow=None, reversible_arrow=None, term_split='+')¶ Builds reaction from reaction equation reaction_str using parser
Takes a string and using the specifications supplied in the optional arguments infers a set of metabolites, metabolite compartments and stoichiometries for the reaction. It also infers the reversibility of the reaction from the reaction arrow.
Changes to the associated model are reverted upon exit when using the model as a context.
- Parameters
reaction_str (string) – a string containing a reaction formula (equation)
verbose (bool) – setting verbosity of function
fwd_arrow (re.compile) – for forward irreversible reaction arrows
rev_arrow (re.compile) – for backward irreversible reaction arrows
reversible_arrow (re.compile) – for reversible reaction arrows
term_split (string) – dividing individual metabolite entries
-
summary
(self, solution=None, fva=None)¶ Create a summary of the reaction flux.
- Parameters
solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If
None
, the summary method will generate a parsimonious flux distribution (default None).fva (pandas.DataFrame or float, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched (default None).
- Returns
- Return type
cobra.summary.ReactionSummary
See also
-
__str__
(self)¶ Return str(self).
-
_repr_html_
(self)¶
-
class
cobra.
Solution
(objective_value, status, fluxes, reduced_costs=None, shadow_prices=None, **kwargs)¶ Bases:
object
A unified interface to a cobra.Model optimization solution.
Notes
Solution is meant to be constructed by get_solution please look at that function to fully understand the Solution class.
-
fluxes
¶ Contains the reaction fluxes (primal values of variables).
- Type
pandas.Series
-
reduced_costs
¶ Contains reaction reduced costs (dual values of variables).
- Type
pandas.Series
-
shadow_prices
¶ Contains metabolite shadow prices (dual values of constraints).
- Type
pandas.Series
-
get_primal_by_id
¶
-
__repr__
(self)¶ String representation of the solution instance.
-
_repr_html_
(self)¶
-
__getitem__
(self, reaction_id)¶ Return the flux of a reaction.
- Parameters
reaction (str) – A model reaction ID.
-
to_frame
(self)¶ Return the fluxes and reduced costs as a data frame
-
-
class
cobra.
Species
(id=None, name=None)¶ Bases:
cobra.core.object.Object
Species is a class for holding information regarding a chemical Species
- Parameters
id (string) – An identifier for the chemical species
name (string) – A human readable name.
-
property
reactions
(self)¶
-
__getstate__
(self)¶ Remove the references to container reactions when serializing to avoid problems associated with recursion.
-
copy
(self)¶ When copying a reaction, it is necessary to deepcopy the components so the list references aren’t carried over.
Additionally, a copy of a reaction is no longer in a cobra.Model.
This should be fixed with self.__deepcopy__ if possible
-
property
model
(self)¶
-
cobra.
show_versions
() → None¶ Print dependency information.
test_room
¶
Test functionalities of ROOM.
Module Contents¶
Functions¶
|
Test optimization criterion and optimality for ROOM. |
test_geometric
¶
Test functionalities of Geometric FBA.
Module Contents¶
Functions¶
|
Generate geometric FBA model as described in 1 . |
|
Benchmark geometric_fba. |
|
Test geometric_fba. |
-
test_geometric.
geometric_fba_model
() → Model[source]¶ Generate geometric FBA model as described in 1 .
References
test_parsimonious
¶
Test functionalities of pFBA.
Module Contents¶
Functions¶
|
Benchmark pFBA functionality. |
|
Test pFBA functionality. |
test_helpers
¶
Test functionalities of flux analysis helper functions.
Module Contents¶
Functions¶
|
Test normalize cutoff. |
|
Test normalize cutoff with specified cutoff greater than default. |
|
Test normalize cutoff with specified cutoff less than default. |
test_reaction
¶
Test assessing functions in flux_analysis.reaction.
Module Contents¶
Functions¶
|
Test assess functions. |
test_gapfilling
¶
Test functionalities of gap filling.
Module Contents¶
Functions¶
|
Test Gapfilling. |
test_variability
¶
Test functionalities of Flux Variability Analysis.
Module Contents¶
Functions¶
|
Benchmark FVA. |
|
Test FVA using pFBA. |
|
Test loopless FVA using pFBA. |
|
Test FVA. |
|
Test parallel FVA. |
|
Benchmark loopless FVA. |
|
Test loopless FVA. |
|
Test DataFrame obtained from FVA. |
|
Test FVA infeasibility. |
|
Test minimization using FVA. |
|
Test find_blocked_reactions() [no specific solver]. |
|
Test find_essential_genes(). |
|
Test find_blocked_reactions(). |
|
Test find_blocked_reactions(). |
-
test_variability.
test_flux_variability_benchmark
(large_model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark FVA.
-
test_variability.
test_pfba_flux_variability
(model: Model, pfba_fva_results: pd.DataFrame, fva_results: pd.DataFrame, all_solvers: List[str]) → None[source]¶ Test FVA using pFBA.
-
test_variability.
test_flux_variability
(model: Model, fva_results: pd.DataFrame, all_solvers: List[str]) → None[source]¶ Test FVA.
-
test_variability.
test_parallel_flux_variability
(model: Model, fva_results: pd.DataFrame, all_solvers: List[str]) → None[source]¶ Test parallel FVA.
-
test_variability.
test_flux_variability_loopless_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark loopless FVA.
-
test_variability.
test_flux_variability_loopless
(model: Model, all_solvers: List[str]) → None[source]¶ Test loopless FVA.
-
test_variability.
test_fva_data_frame
(model: Model) → None[source]¶ Test DataFrame obtained from FVA.
-
test_variability.
test_find_blocked_reactions_solver_none
(model: Model) → None[source]¶ Test find_blocked_reactions() [no specific solver].
test_fastcc
¶
Test functionalities of FASTCC.
Module Contents¶
Functions¶
|
Generate a toy model as described in 1 figure 1. |
|
Generate a toy model with opposing reversible reactions. |
|
Benchmark fastcc. |
|
Test FASTCC. |
|
Test FASTCC. |
|
Test non-blocked reactions obtained by FASTCC against FVA. |
-
test_fastcc.
figure1_model
() → Model[source]¶ Generate a toy model as described in 1 figure 1.
References
-
test_fastcc.
opposing_model
() → Model[source]¶ Generate a toy model with opposing reversible reactions.
This toy model ensures that two opposing reversible reactions do not appear as blocked.
-
test_fastcc.
test_fastcc_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark fastcc.
test_moma
¶
Test functionalities of MOMA.
Module Contents¶
Functions¶
|
Test optimization criterion and optimality for MOMA. |
|
Test optimization criterion and optimality for linear MOMA. |
conftest
¶
Define module level fixtures.
Module Contents¶
Functions¶
|
Return ACHRSampler instance for tests. |
test_loopless
¶
Test functionalities of removing loops in model.
Module Contents¶
Functions¶
|
Construct test model. |
|
Return test model set with different solvers. |
|
Benchmark initial condition. |
|
Benchmark final condition. |
|
Test loopless_solution(). |
|
Test fluxes of loopless_solution(). |
|
Test add_loopless(). |
-
test_loopless.
ll_test_model
(request: pytest.FixtureRequest) → Model[source]¶ Return test model set with different solvers.
-
test_loopless.
test_loopless_benchmark_before
(benchmark: Callable) → None[source]¶ Benchmark initial condition.
-
test_loopless.
test_loopless_benchmark_after
(benchmark: Callable) → None[source]¶ Benchmark final condition.
-
test_loopless.
test_loopless_solution
(ll_test_model: Model) → None[source]¶ Test loopless_solution().
test_deletion
¶
Test functionalities of reaction and gene deletions.
Module Contents¶
Functions¶
|
Benchmark single gene deletion using FBA. |
|
Test single gene deletion using FBA. |
|
Benchmark single gene deletion using MOMA. |
|
Test single gene deletion using MOMA. |
|
Test single gene deletion using MOMA (reference solution). |
|
Benchmark single gene deletion using linear MOMA. |
|
Test single gene deletion using linear MOMA (reference solution). |
|
Benchmark single gene deletion using ROOM. |
|
Benchmark single gene deletion using linear ROOM. |
|
Benchmark single reaction deletion. |
|
Test single reaction deletion. |
|
Test single reaction deletion using ROOM. |
|
Test single reaction deletion using linear ROOM. |
|
Benchmark double gene deletion. |
|
Test double gene deletion. |
|
Test that the bug reported in #1102 is fixed. |
|
Benchmark double reaction deletion. |
|
Test double reaction deletion. |
|
Test the DataFrame accessor. |
-
test_deletion.
test_single_gene_deletion_fba_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark single gene deletion using FBA.
-
test_deletion.
test_single_gene_deletion_fba
(model: Model, all_solvers: List[str]) → None[source]¶ Test single gene deletion using FBA.
-
test_deletion.
test_single_gene_deletion_moma_benchmark
(model: Model, benchmark: Callable, qp_solvers: List[str]) → None[source]¶ Benchmark single gene deletion using MOMA.
-
test_deletion.
test_single_gene_deletion_moma
(model: Model, qp_solvers: List[str]) → None[source]¶ Test single gene deletion using MOMA.
-
test_deletion.
test_single_gene_deletion_moma_reference
(model: Model, qp_solvers: List[str]) → None[source]¶ Test single gene deletion using MOMA (reference solution).
-
test_deletion.
test_single_gene_deletion_linear_moma_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark single gene deletion using linear MOMA.
-
test_deletion.
test_single_gene_deletion_linear_moma
(model: Model, all_solvers: List[str]) → None[source]¶ Test single gene deletion using linear MOMA (reference solution).
-
test_deletion.
test_single_gene_deletion_room_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark single gene deletion using ROOM.
-
test_deletion.
test_single_gene_deletion_linear_room_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark single gene deletion using linear ROOM.
-
test_deletion.
test_single_reaction_deletion_benchmark
(model: Model, benchmark: Callable, all_solvers: List[str]) → None[source]¶ Benchmark single reaction deletion.
-
test_deletion.
test_single_reaction_deletion
(model: Model, all_solvers) → None[source]¶ Test single reaction deletion.
-
test_deletion.
test_single_reaction_deletion_room
(room_model: Model, room_solution: Solution, all_solvers: List[str]) → None[source]¶ Test single reaction deletion using ROOM.
-
test_deletion.
test_single_reaction_deletion_linear_room
(room_model: Model, room_solution: Solution, all_solvers: List[str]) → None[source]¶ Test single reaction deletion using linear ROOM.
-
test_deletion.
test_double_gene_deletion_benchmark
(large_model: Model, benchmark: Callable) → None[source]¶ Benchmark double gene deletion.
-
test_deletion.
test_double_gene_knockout_bug
(large_model: Model) → None[source]¶ Test that the bug reported in #1102 is fixed.
-
test_deletion.
test_double_reaction_deletion_benchmark
(large_model: Model, benchmark: Callable) → None[source]¶ Benchmark double reaction deletion.
test_phenotype_phase_plane
¶
Test functionalities of Phenotype Phase Plane Analysis.
Module Contents¶
Functions¶
|
Test flux of production envelope. |
|
Test production of multiple objectives. |
|
Test production of envelope (multiple variable). |
|
Test production of envelope. |
-
test_phenotype_phase_plane.
test_envelope_one
(model: Model) → None[source]¶ Test flux of production envelope.
-
test_phenotype_phase_plane.
test_envelope_multi_reaction_objective
(model: Model) → None[source]¶ Test production of multiple objectives.
update_pickles
¶
Regenerate model pickle files.
This should be performed after updating core classes in order to prevent suble bugs.
Module Contents¶
test_util
¶
Test functions of util.py .
Module Contents¶
Functions¶
|
Test functionality of format long string. |
|
Test proper functionality of autovivification. |
|
Test output of dependency information. |
test_array
¶
Test functions of array.py.
Module Contents¶
Functions¶
|
Test dense stoichiometric matrix creation. |
|
Test sparse stoichiometric matrix creation. |
test_context
¶
Test functions of context.py.
Module Contents¶
Functions¶
|
Test initialization and resetting of HistoryManager. |
|
Test if context retrieval is working. |
|
Test if resettable decorator is functional. |
test_process_pool
¶
Test the behaviour of the ProcessPool class.
Module Contents¶
Functions¶
|
Implement a ‘do nothing’ function that accepts initialization arguments. |
|
Return the square of an integer. |
|
Return the sum of all integer arguments. |
|
Test that a process pool can be initialized with each of its arguments. |
|
Test that the composed pool is closed as well. |
|
Test that the composed pool’s context is managed as well. |
|
Test that a function can be applied. |
|
Test that a function can be applied asynchronously. |
|
Test that a function can be mapped over an iterable of values. |
|
Test that a function can be mapped over an iterable of values asynchronously. |
|
Test that mapped function results can be iterated. |
|
Test that mapped function results can be iterated in any order. |
|
Test that a function can be starmapped over many iterables. |
|
Test that a function can be starmapped over many iterables asynchronously. |
-
test_process_pool.
dummy_initializer
(*args: Iterable) → Tuple[source]¶ Implement a ‘do nothing’ function that accepts initialization arguments.
-
test_process_pool.
summation
(*args: Iterable[int]) → int[source]¶ Return the sum of all integer arguments.
-
test_process_pool.
test_init
(attributes: dict) → None[source]¶ Test that a process pool can be initialized with each of its arguments.
-
test_process_pool.
test_close
(mocker: MockerFixture) → None[source]¶ Test that the composed pool is closed as well.
-
test_process_pool.
test_with_context
(mocker: MockerFixture) → None[source]¶ Test that the composed pool’s context is managed as well.
-
test_process_pool.
test_apply_async
() → None[source]¶ Test that a function can be applied asynchronously.
-
test_process_pool.
test_map
() → None[source]¶ Test that a function can be mapped over an iterable of values.
-
test_process_pool.
test_map_async
() → None[source]¶ Test that a function can be mapped over an iterable of values asynchronously.
-
test_process_pool.
test_imap_unordered
() → None[source]¶ Test that mapped function results can be iterated in any order.
test_solver
¶
Test functions of solver.py.
Module Contents¶
Functions¶
|
Expect that at least the GLPK solver is found. |
|
Test the string representation of solver interfaces. |
|
Test that the default LP solver name is GLPK. |
|
Test that solver switching is working. |
|
Test that linear coefficients are identifiable in objective. |
|
Test failure of non-linear coefficient identification in reaction. |
|
Test addition and removal of variables and constraints. |
|
Test addition and removal of variables and constraints within context. |
|
Test addition of an absolute expression. |
|
Test fixing present objective as a constraint. |
|
Test fixing present objective as a constraint but as a minimization. |
|
Test functionality to ensure LP feasibility. |
|
Test addition of lexicographic constraints. |
|
Test time limit while optimizing a model. |
|
Test the warning for specialized solvers. |
-
test_solver.
test_interface_str
() → None[source]¶ Test the string representation of solver interfaces.
-
test_solver.
test_choose_solver
(model: Model) → Optional[su.SolverNotFound][source]¶ Test that solver switching is working.
-
test_solver.
test_linear_reaction_coefficients
(model: Model) → None[source]¶ Test that linear coefficients are identifiable in objective.
-
test_solver.
test_fail_non_linear_reaction_coefficients
(model: Model) → None[source]¶ Test failure of non-linear coefficient identification in reaction.
-
test_solver.
test_add_remove
(model: Model) → None[source]¶ Test addition and removal of variables and constraints.
-
test_solver.
test_add_remove_in_context
(model: Model) → None[source]¶ Test addition and removal of variables and constraints within context.
-
test_solver.
test_absolute_expression
(model: Model) → None[source]¶ Test addition of an absolute expression.
-
test_solver.
test_fix_objective_as_constraint
(solver: str, model: Model) → None[source]¶ Test fixing present objective as a constraint.
-
test_solver.
test_fix_objective_as_constraint_minimize
(model: Model, solver: str) → None[source]¶ Test fixing present objective as a constraint but as a minimization.
-
test_solver.
test_add_lp_feasibility
(model: Model, solver: str) → None[source]¶ Test functionality to ensure LP feasibility.
-
test_solver.
test_add_lexicographic_constraints
(model: Model, solver: str) → None[source]¶ Test addition of lexicographic constraints.
test_notes
¶
Module Contents¶
Functions¶
|
Testing if model notes are written in SBML |
test_json
¶
Test functionalities of json.py
Module Contents¶
Functions¶
|
Validate file according to JSON-schema. |
|
Test the reading of JSON model. |
|
Test the writing of JSON model. |
|
Test reading and writing of model with inf bounds in json |
-
test_json.
test_validate_json
(data_directory, json_schema_v1)[source]¶ Validate file according to JSON-schema.
test_annotation_format
¶
Module Contents¶
Functions¶
|
Test loading a valid annotation from JSON. |
|
Test that loading an invalid annotation from JSON raises TypeError |
test_mat
¶
Test functionalities provided by mat.py
Module Contents¶
Functions¶
|
Fixture for RAVEN model. |
|
Test the reading of MAT model. |
|
Test the writing of MAT model. |
test_annotation
¶
Module Contents¶
Functions¶
|
Checks the annotations from the annotation.xml. |
|
Test reading and writing annotations. |
|
Test reading and writing annotations. |
-
test_annotation.
_check_sbml_annotations
(model)[source]¶ Checks the annotations from the annotation.xml.
test_sbml
¶
Testing SBML functionality based on libsbml.
Module Contents¶
Classes¶
Tests the read and write functions. |
Functions¶
|
Test validation function. |
|
|
|
Test reading and writing to file handle. |
|
Test reading from SBML string. |
|
Testing reading and writing of ModelHistory. |
|
Testing reading and writing of groups |
|
|
|
|
|
Test validation function. |
|
Test the validation warnings. |
|
Test infinity bound example. |
|
Test infinity bound example. |
|
Test that GPRs are written and read correctly |
|
Test that NOTES in the RECON 2.2 style are written and read correctly |
|
-
test_sbml.
test_filehandle
(data_directory, tmp_path)[source]¶ Test reading and writing to file handle.
-
test_sbml.
test_validate
(data_directory)[source] Test the validation code.
-
test_sbml.
test_gprs
(data_directory, tmp_path)[source]¶ Test that GPRs are written and read correctly
test_yaml
¶
Test functionalities provided by yaml.py
Module Contents¶
Functions¶
|
Test the reading of YAML model. |
|
test_io_order
¶
Module Contents¶
Functions¶
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_pickle
¶
Test data storage and recovery using pickle.
Module Contents¶
Functions¶
|
Test the reading of model from pickle. |
|
Test the writing of model to pickle. |
test_load
¶
Module Contents¶
Functions¶
|
Provide a gzip-compressed SBML document. |
|
Provide a mocked BiGG Models repository interface. |
|
Provide a mocked BioModels repository interface. |
|
Test that SBML would be retrieved from the BiGG Models repository. |
|
Test that SBML would be retrieved from the BioModels repository. |
Expect that a not found error is raised (e2e). |
|
|
Test that sample models can be loaded from remote repositories (e2e). |
|
Test that remote models are properly cached. |
-
test_load.
bigg_models
(mini_sbml, mocker)[source]¶ Provide a mocked BiGG Models repository interface.
-
test_load.
test_bigg_access
(bigg_models)[source]¶ Test that SBML would be retrieved from the BiGG Models repository.
-
test_load.
test_biomodels_access
(biomodels)[source]¶ Test that SBML would be retrieved from the BioModels repository.
test_metabolite_summary
¶
Unit test the MetaboliteSummary class.
Module Contents¶
Functions¶
|
Test that a summary can be created successfully. |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the production summary of q8 is accurate. |
|
Test that the consumption summary of q8 is accurate. |
|
Test that the production summary of fdp is within expected bounds. |
|
Test that the metabolite summary inside and outside of a context are equal. |
-
test_metabolite_summary.
test_metabolite_summary_interface
(model, opt_solver)[source]¶ Test that a summary can be created successfully.
-
test_metabolite_summary.
test_metabolite_summary_to_frame
(model, opt_solver)[source]¶ Test that the summary’s method
to_frame
can be called.
-
test_metabolite_summary.
test_metabolite_summary_to_string
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_string
can be called.
-
test_metabolite_summary.
test_metabolite_summary_to_html
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_html
can be called.
-
test_metabolite_summary.
test_q8_producing_summary
(model, opt_solver)[source]¶ Test that the production summary of q8 is accurate.
-
test_metabolite_summary.
test_q8_consuming_summary
(model, opt_solver)[source]¶ Test that the consumption summary of q8 is accurate.
test_model_summary
¶
Unit test the model summary.
Module Contents¶
Functions¶
|
Test that a summary can be created successfully. |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the summary correctly uses an existing solution. |
|
Test that the summary has expected fluxes. |
|
Test that the exchange summary is within expected bounds. |
|
Test that the model summary inside and outside of a context are equal. |
-
test_model_summary.
test_model_summary_interface
(model, opt_solver)[source]¶ Test that a summary can be created successfully.
-
test_model_summary.
test_model_summary_to_frame
(model, opt_solver)[source]¶ Test that the summary’s method
to_frame
can be called.
-
test_model_summary.
test_model_summary_to_string
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_string
can be called.
-
test_model_summary.
test_model_summary_to_html
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_html
can be called.
-
test_model_summary.
test_model_summary_to_frame_previous_solution
(model, opt_solver)[source]¶ Test that the summary correctly uses an existing solution.
-
test_model_summary.
test_model_summary_flux
(model, opt_solver)[source]¶ Test that the summary has expected fluxes.
test_reaction_summary
¶
Unit test the ReactionSummary class.
Module Contents¶
Functions¶
|
Test that a summary can be created successfully. |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the summary’s method |
|
Test that the reported flux in the summary is reasonable. |
|
Test that the reported flux ranges in the summary are reasonable. |
|
Test that the reaction summary inside and outside of a context are equal. |
-
test_reaction_summary.
test_reaction_summary_interface
(model, opt_solver)[source]¶ Test that a summary can be created successfully.
-
test_reaction_summary.
test_reaction_summary_to_frame
(model, opt_solver)[source]¶ Test that the summary’s method
to_frame
can be called.
-
test_reaction_summary.
test_reaction_summary_to_string
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_string
can be called.
-
test_reaction_summary.
test_reaction_summary_to_html
(model, opt_solver, kwargs)[source]¶ Test that the summary’s method
to_html
can be called.
-
test_reaction_summary.
test_reaction_summary_flux
(model, reaction_id: str, expected: float) → None[source]¶ Test that the reported flux in the summary is reasonable.
test_boundary_types
¶
Test functionalities of boundary type detection functions.
Module Contents¶
Functions¶
|
Test external compartment identification. |
|
Test multiple external compartment identification. |
|
Test absence of name or boundary reactions. |
|
Test boundary type identification for exchanges. |
|
Test boundary type identification for demands. |
|
Test boundary type identification for sinks. |
|
Test proper identification of no boundary reactions. |
|
Test correct identification of boundary types for reactions. |
|
Test bad exchange reaction identification. |
-
test_boundary_types.
test_find_external_compartment_single
(model: Model) → None[source]¶ Test external compartment identification.
-
test_boundary_types.
test_find_external_compartment_multi
(model: Model) → None[source]¶ Test multiple external compartment identification.
-
test_boundary_types.
test_no_names_or_boundary_reactions
(empty_model: Model) → None[source]¶ Test absence of name or boundary reactions.
-
test_boundary_types.
test_find_boundary_types_exchange
(model: Model) → None[source]¶ Test boundary type identification for exchanges.
-
test_boundary_types.
test_find_boundary_types_demand
(model: Model) → None[source]¶ Test boundary type identification for demands.
-
test_boundary_types.
test_find_boundary_types_sink
(model: Model) → None[source]¶ Test boundary type identification for sinks.
-
test_boundary_types.
test_no_boundary_reactions
(empty_model: Model) → None[source]¶ Test proper identification of no boundary reactions.
test_minimal_medium
¶
Test functionalities of minimal medium creation and analysis.
Module Contents¶
Functions¶
|
Test linear minimal medium. |
|
Benchmark linear minimal medium. |
|
Test mixed-integer minimal medium. |
|
Benchmark mixed-integer minimal medium. |
|
Test alternative mixed-integer minimal medium. |
|
Test exports of a minimal medium. |
|
Test open exchanges of a minimal medium. |
|
Test proper functioning of model medium manipulations. |
|
Test that the medium setter does not overwrite exports defined as reactants. |
|
Test that the medium setter does not overwrite exports defined as products. |
-
test_minimal_medium.
test_minimal_medium_linear
(model: Model) → None[source]¶ Test linear minimal medium.
-
test_minimal_medium.
test_minimal_medium_linear_benchmark
(model: Model, benchmark: Callable) → None[source]¶ Benchmark linear minimal medium.
-
test_minimal_medium.
test_minimal_medium_mip
(model: Model) → None[source]¶ Test mixed-integer minimal medium.
-
test_minimal_medium.
test_minimal_medium_mip_benchmark
(model: Model, benchmark: Callable) → None[source]¶ Benchmark mixed-integer minimal medium.
-
test_minimal_medium.
test_minimal_medium_alternative_mip
(model: Model) → None[source]¶ Test alternative mixed-integer minimal medium.
-
test_minimal_medium.
test_minimal_medium_exports
(model: Model) → None[source]¶ Test exports of a minimal medium.
-
test_minimal_medium.
test_minimal_medium_open_exchanges
(model: Model) → None[source]¶ Test open exchanges of a minimal medium.
-
test_minimal_medium.
test_model_medium
(model: Model) → None[source]¶ Test proper functioning of model medium manipulations.
test_group
¶
Test functions of model.py
Module Contents¶
Functions¶
|
|
test_configuration
¶
Test functions of configuration.py
Module Contents¶
Functions¶
Verify the default bounds. |
|
Test changing bounds. |
|
Test assignment of different solvers. |
|
|
Verify the default solver tolerance. |
Verify that different default tolerance is respected by Model. |
|
|
Test assignment of solver tolerance. |
test_solution
¶
Test functions of solution.py
Module Contents¶
Functions¶
|
test_dictlist
¶
Test functions of dictlist.py
Module Contents¶
Functions¶
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_core_reaction
¶
Test functions of cobra.core.reaction .
Module Contents¶
Functions¶
|
Test GPR evaluation. |
|
Test GPR manipulations. |
|
Test gene knockout effect on reaction. |
|
Test str output for a reaction. |
|
Test str output for a reaction associated with a model. |
|
Test metabolite addition to a reaction from a solved model. |
|
Benchmark metabolite addition to a reaction associated with a model. |
|
Test metabolite addition to a reaction from an unsolved model. |
|
Benchmark metabolite deletion from a reaction. |
|
Test metabolite deletion from a reaction associated with an unsolved model. |
|
Test mass balance of metabolites of a reaction. |
|
Test reaction building from string evaluation. |
|
Test reaction bounds setter. |
|
Test reaction copying. |
|
Test in-place addition of reaction. |
|
Test reaction addition to model. |
|
Test __radd__ for a reaction. |
|
Test scalar multiplication of factors with a reaction. |
|
Test reaction subtraction. |
|
Test reaction removal from a model, retains its bounds. |
|
Test reaction bounds setting for a scenario. |
|
Test reaction bounds setting for a scenario. |
|
Test reaction bounds setting for a scenario. |
|
Test reaction bounds setting for a scenario. |
|
Test reaction bounds setting to zero. |
|
Test reaction bounds change. |
|
Test reaction irreversibility. |
|
Test reaction reversibility. |
|
Test reaction irreversibility to irreversibility. |
|
Test reaction LHS irreversibility to reversibility. |
|
Test model without reactions. |
|
Test reaction knockouts. |
|
Test reaction without model association. |
|
Test absurd left to right reaction. |
|
Test left to right reaction with positive upper bound. |
|
Test reaction irreversibility with negative lower bound. |
|
Test irreversibility reversal from right to left to left to right. |
|
Test lower bound > upper bound makes upper bound to new lower bound. |
|
Test upper bound < lower bound makes lower bound to new upper bound. |
|
Test metabolite addition to reaction (with combine = True). |
|
Test metabolite addition to reaction (with combine = False). |
|
Test in-place scalar factor multiplication to reaction. |
|
Test reaction removal from model. |
|
Test reaction ID change reflection in solver. |
|
Test __repr_html__ functionality. |
|
Test reaction compartment change. |
-
test_core_reaction.
test_gene_knock_out
(model: Model) → None[source]¶ Test gene knockout effect on reaction.
-
test_core_reaction.
test_str_from_model
(model: Model) → None[source]¶ Test str output for a reaction associated with a model.
-
test_core_reaction.
test_add_metabolite_from_solved_model
(solved_model: Model) → None[source]¶ Test metabolite addition to a reaction from a solved model.
-
test_core_reaction.
test_add_metabolite_benchmark
(model: Model, benchmark, solver: Iterable) → None[source]¶ Benchmark metabolite addition to a reaction associated with a model.
-
test_core_reaction.
test_add_metabolite
(model: Model) → None[source]¶ Test metabolite addition to a reaction from an unsolved model.
-
test_core_reaction.
test_subtract_metabolite_benchmark
(model: Model, benchmark, solver: Iterable) → None[source]¶ Benchmark metabolite deletion from a reaction.
-
test_core_reaction.
test_subtract_metabolite
(model: Model, solver: Iterable) → None[source]¶ Test metabolite deletion from a reaction associated with an unsolved model.
-
test_core_reaction.
test_mass_balance
(model: Model) → None[source]¶ Test mass balance of metabolites of a reaction.
-
test_core_reaction.
test_build_from_string
(model: Model) → None[source]¶ Test reaction building from string evaluation.
-
test_core_reaction.
test_mul
(model: Model) → None[source]¶ Test scalar multiplication of factors with a reaction.
-
test_core_reaction.
test_removal_from_model_retains_bounds
(model: Model) → None[source]¶ Test reaction removal from a model, retains its bounds.
-
test_core_reaction.
test_set_bounds_scenario_1
(model: Model) → None[source]¶ Test reaction bounds setting for a scenario.
-
test_core_reaction.
test_set_bounds_scenario_2
(model: Model) → None[source]¶ Test reaction bounds setting for a scenario.
-
test_core_reaction.
test_set_bounds_scenario_3
(model: Model) → None[source]¶ Test reaction bounds setting for a scenario.
-
test_core_reaction.
test_set_bounds_scenario_4
(model: Model) → None[source]¶ Test reaction bounds setting for a scenario.
-
test_core_reaction.
test_set_upper_before_lower_bound_to_0
(model: Model) → None[source]¶ Test reaction bounds setting to zero.
-
test_core_reaction.
test_make_irreversible
(model: Model) → None[source]¶ Test reaction irreversibility.
-
test_core_reaction.
test_make_irreversible_irreversible_to_the_other_side
(model: Model) → None[source]¶ Test reaction irreversibility to irreversibility.
-
test_core_reaction.
test_make_lhs_irreversible_reversible
(model: Model) → None[source]¶ Test reaction LHS irreversibility to reversibility.
-
test_core_reaction.
test_model_less_reaction
(model: Model) → None[source]¶ Test model without reactions.
-
test_core_reaction.
test_reaction_without_model
() → None[source]¶ Test reaction without model association.
-
test_core_reaction.
test_weird_left_to_right_reaction_issue
(tiny_toy_model: Model) → None[source]¶ Test absurd left to right reaction.
-
test_core_reaction.
test_one_left_to_right_reaction_set_positive_ub
(tiny_toy_model: Model) → None[source]¶ Test left to right reaction with positive upper bound.
-
test_core_reaction.
test_irrev_reaction_set_negative_lb
(model: Model) → None[source]¶ Test reaction irreversibility with negative lower bound.
-
test_core_reaction.
test_twist_irrev_right_to_left_reaction_to_left_to_right
(model: Model) → None[source]¶ Test irreversibility reversal from right to left to left to right.
-
test_core_reaction.
test_set_lb_higher_than_ub_sets_ub_to_new_lb
(model: Model) → None[source]¶ Test lower bound > upper bound makes upper bound to new lower bound.
-
test_core_reaction.
test_set_ub_lower_than_lb_sets_lb_to_new_ub
(model: Model) → None[source]¶ Test upper bound < lower bound makes lower bound to new upper bound.
-
test_core_reaction.
test_add_metabolites_combine_true
(model: Model) → None[source]¶ Test metabolite addition to reaction (with combine = True).
-
test_core_reaction.
test_add_metabolites_combine_false
(model: Model) → None[source]¶ Test metabolite addition to reaction (with combine = False).
-
test_core_reaction.
test_reaction_imul
(model: Model) → None[source]¶ Test in-place scalar factor multiplication to reaction.
-
test_core_reaction.
test_remove_from_model
(model: Model) → None[source]¶ Test reaction removal from model.
test_model
¶
Test functions of model.py
Module Contents¶
Functions¶
-
test_model.
test_change_objective
(model)[source]
test_metabolite
¶
Test functions of metabolite.py
Module Contents¶
Functions¶
|
|
|
|
|
|
|
test_gene
¶
Test functions of gene.py
Module Contents¶
Functions¶
|
test_optgp
¶
Test functionalities of OptGPSampler.
Module Contents¶
Functions¶
|
Return OptGPSampler instance for tests. |
|
Benchmark inital OptGP sampling. |
|
Benchmark OptGP sampling. |
|
Test sampling. |
|
Test batch sampling. |
|
Test variable samples. |
|
Test reprojection of sampling. |
-
test_optgp.
test_optgp_init_benchmark
(model: Model, benchmark: Callable) → None[source]¶ Benchmark inital OptGP sampling.
-
test_optgp.
test_optgp_sample_benchmark
(optgp: Model, benchmark: Callable) → None[source]¶ Benchmark OptGP sampling.
test_achr
¶
Test functionalities of ACHRSampler.
Module Contents¶
Functions¶
|
Benchmark inital ACHR sampling. |
|
Benchmark ACHR sampling. |
|
Test sample correctness. |
|
Test sampling. |
|
Test batch sampling. |
|
Test variable samples. |
-
test_achr.
test_achr_init_benchmark
(model: Model, benchmark: Callable) → None[source]¶ Benchmark inital ACHR sampling.
-
test_achr.
test_achr_sample_benchmark
(achr: ACHRSampler, benchmark: Callable) → None[source]¶ Benchmark ACHR sampling.
test_sampling
¶
Test functionalities of flux sampling methods.
Module Contents¶
Functions¶
|
Test ACHR sampling (one sample). |
|
Test OptGP sampling (one sample). |
|
Test OptGP sampling (multi sample). |
|
Test method intake sanity. |
|
Test result of fixed seed for sampling. |
|
Test equality constraint. |
|
Test inequality constraint. |
|
Test standard deviation between inhomogeneous and homogeneous sampling. |
|
Test a complicated model. |
|
Test the reduction of the sampling space to one point. |
-
test_sampling.
test_inhomogeneous_sanity
(model: Model) → None[source]¶ Test standard deviation between inhomogeneous and homogeneous sampling.
- 1
Created with sphinx-autoapi