14.1.3. cobra.flux_analysis package

14.1.3.1. Submodules

14.1.3.2. cobra.flux_analysis.deletion_worker module

class cobra.flux_analysis.deletion_worker.CobraDeletionMockPool(cobra_model, n_processes=1, solver=None, **kwargs)[source]

Bases: object

Mock pool solves LP’s in the same process

receive_all()[source]
receive_one()[source]
start()[source]
submit(indexes, label=None)[source]
terminate()[source]
class cobra.flux_analysis.deletion_worker.CobraDeletionPool(cobra_model, n_processes=None, solver=None, **kwargs)[source]

Bases: object

A pool of workers for solving deletions

submit jobs to the pool using submit and recieve results using receive_all

pids
receive_all()[source]
receive_one()[source]

This function blocks

start()[source]
submit(indexes, label=None)[source]
terminate()[source]
cobra.flux_analysis.deletion_worker.compute_fba_deletion(lp, solver_object, model, indexes, **kwargs)[source]
cobra.flux_analysis.deletion_worker.compute_fba_deletion_worker(cobra_model, solver, job_queue, output_queue, **kwargs)[source]

14.1.3.3. cobra.flux_analysis.double_deletion module

cobra.flux_analysis.double_deletion.double_deletion(cobra_model, element_list_1=None, element_list_2=None, element_type='gene', **kwargs)[source]

Wrapper for double_gene_deletion and double_reaction_deletion

Deprecated since version 0.4: Use double_reaction_deletion and double_gene_deletion

cobra.flux_analysis.double_deletion.double_gene_deletion(cobra_model, gene_list1=None, gene_list2=None, method='fba', return_frame=False, solver=None, zero_cutoff=1e-12, **kwargs)[source]

sequentially knocks out pairs of genes in a model

cobra_model : Model
cobra model in which to perform deletions
gene_list1 : [Gene:] (or their id’s)
Genes to be deleted. These will be the rows in the result. If not provided, all reactions will be used.
gene_list1 : [Gene:] (or their id’s)
Genes to be deleted. These will be the rows in the result. If not provided, reaction_list1 will be used.
method: “fba” or “moma”
Procedure used to predict the growth rate
solver: str for solver name
This must be a QP-capable solver for MOMA. If left unspecified, a suitable solver will be automatically chosen.
zero_cutoff: float
When checking to see if a value is 0, this threshold is used.
number_of_processes: int for number of processes to use.
If unspecified, the number of parallel processes to use will be automatically determined. Setting this to 1 explicitly disables used of the multiprocessing library.

Note

multiprocessing is not supported with method=moma

return_frame: bool
If true, formats the results as a pandas.Dataframe. Otherwise returns a dict of the form: {“x”: row_labels, “y”: column_labels”, “data”: 2D matrix}
cobra.flux_analysis.double_deletion.double_reaction_deletion(cobra_model, reaction_list1=None, reaction_list2=None, method='fba', return_frame=False, solver=None, zero_cutoff=1e-12, **kwargs)[source]

sequentially knocks out pairs of reactions in a model

cobra_model : Model
cobra model in which to perform deletions
reaction_list1 : [Reaction:] (or their id’s)
Reactions to be deleted. These will be the rows in the result. If not provided, all reactions will be used.
reaction_list2 : [Reaction:] (or their id’s)
Reactions to be deleted. These will be the rows in the result. If not provided, reaction_list1 will be used.
method: “fba” or “moma”
Procedure used to predict the growth rate
solver: str for solver name
This must be a QP-capable solver for MOMA. If left unspecified, a suitable solver will be automatically chosen.
zero_cutoff: float
When checking to see if a value is 0, this threshold is used.
return_frame: bool
If true, formats the results as a pandas.Dataframe. Otherwise returns a dict of the form: {“x”: row_labels, “y”: column_labels”, “data”: 2D matrix}
cobra.flux_analysis.double_deletion.format_results_frame(row_ids, column_ids, matrix, return_frame=False)[source]

format results as a pandas.DataFrame if desired/possible

Otherwise returns a dict of {“x”: row_ids, “y”: column_ids”, “data”: result_matrx}

cobra.flux_analysis.double_deletion.generate_matrix_indexes(ids1, ids2)[source]

map an identifier to an entry in the square result matrix

cobra.flux_analysis.double_deletion.yield_upper_tria_indexes(ids1, ids2, id_to_index)[source]

gives the necessary indexes in the upper triangle

ids1 and ids2 are lists of the identifiers i.e. gene id’s or reaction indexes to be knocked out. id_to_index maps each identifier to its index in the result matrix.

Note that this does not return indexes for the diagonal. Those have to be computed separately.

14.1.3.4. cobra.flux_analysis.gapfilling module

class cobra.flux_analysis.gapfilling.GapFiller(model, universal=None, lower_bound=0.05, penalties=None, exchange_reactions=False, demand_reactions=True, integer_threshold=1e-06)[source]

Bases: object

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 >= t lb_i <= v_i <= ub_i v_i = 0 if z_i = 0

where lb, ub are 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 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) – A universal model with reactions that can be used to complete the model.
  • lower_bound (float) – The minimally accepted flux for the objective in the filled model.
  • penalties (dict, None) – 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.
  • integer_threshold (float) – 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.
  • exchange_reactions (bool) – Consider adding exchange (uptake) reactions for all metabolites in the model.
  • demand_reactions (bool) – Consider adding demand reactions for all metabolites.

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] http://opencobra.github.io/cobrapy/tags/gapfilling/

[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

add_switches_and_objective()[source]

Update gapfilling model with switches and the indicator objective.

extend_model(exchange_reactions=False, demand_reactions=True)[source]

Extend gapfilling model.

Add reactions from universal model and optionally exchange and demand reactions for all metabolites in the model to perform gapfilling on.

Parameters:
  • exchange_reactions (bool) – Consider adding exchange (uptake) reactions for all metabolites in the model.
  • demand_reactions (bool) – Consider adding demand reactions for all metabolites.
fill(iterations=1)[source]

Perform the gapfilling by iteratively solving the model, updating the costs and recording the used reactions.

Parameters:iterations (int) – The number of rounds of gapfilling 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.
Returns:A list of lists where each element is a list reactions that were used to gapfill the model.
Return type:iterable
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).
update_costs()[source]

Update the 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.

validate(reactions)[source]
cobra.flux_analysis.gapfilling.SMILEY(model, metabolite_id, Universal, dm_rxns=False, ex_rxns=False, penalties=None, **solver_parameters)[source]

runs the SMILEY algorithm. Legacy function, to be removed in future version of cobrapy in favor of gapfill.

cobra.flux_analysis.gapfilling.gapfill(model, universal=None, lower_bound=0.05, penalties=None, demand_reactions=True, exchange_reactions=False, iterations=1)[source]

Perform gapfilling on a model.

See documentation for the class GapFiller.

Parameters:
  • model (cobra.Model) – The model to perform gap filling on.
  • universal (cobra.Model, None) – A universal model with reactions that can be used to complete the model. Only gapfill considering demand and exchange reactions if left missing.
  • lower_bound (float) – The minimally accepted flux for the objective in the filled model.
  • penalties (dict, None) – 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.
  • iterations (int) – The number of rounds of gapfilling 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.
  • exchange_reactions (bool) – Consider adding exchange (uptake) reactions for all metabolites in the model.
  • demand_reactions (bool) – Consider adding demand reactions for all metabolites.
Returns:

list of lists with on set of reactions that completes the model per requested iteration.

Return type:

iterable

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)
cobra.flux_analysis.gapfilling.growMatch(model, Universal, dm_rxns=False, ex_rxns=False, penalties=None, iterations=1, **solver_parameters)[source]

runs (partial implementation of) growMatch. Legacy function, to be removed in future version of cobrapy in favor of gapfill.

14.1.3.5. cobra.flux_analysis.loopless module

Provides functions to remove thermodynamically infeasible loops.

cobra.flux_analysis.loopless.add_loopless(model, zero_cutoff=1e-12)[source]

Modify a model so all feasible flux distributions are loopless.

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 you model. 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.

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.
Returns:

Return type:

Nothing

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.construct_loopless_model(cobra_model)[source]

Construct a loopless model.

This adds MILP constraints to prevent flux from proceeding in a loop, as done in http://dx.doi.org/10.1016/j.bpj.2010.12.3707 Please see the documentation for an explanation of the algorithm.

This must be solved with an MILP capable solver.

cobra.flux_analysis.loopless.loopless_fva_iter(model, reaction, solution=False, zero_cutoff=1e-06)[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
  1. 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 (boolean, optional) – Whether to return the entire solution or only the minimum/maximum for reaction.
  • zero_cutoff (positive float, optional) – Cutoff used for loop removal. Fluxes with an absolute value smaller than zero_cutoff are considered to be zero.
Returns:

Returns the minimized/maximized flux through reaction if all_fluxes == False (default). Otherwise returns a loopless flux solution containing the minimum/maximum flux for reaction.

Return type:

single float or dict

cobra.flux_analysis.loopless.loopless_solution(model, fluxes=None)[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) – A dictionary {rxn_id: flux} that assigns a flux to each reaction. If not None will use the provided flux values to obtain a close loopless solution. Note that this requires a linear objective function involving only the model reactions. This is the case if linear_reaction_coefficients(model) is a correct representation of the objective.
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:

cobra.Solution

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 the same exact objective value as the previous solution
  • 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.

14.1.3.6. cobra.flux_analysis.moma module

Contains functions to run minimization of metabolic adjustment (MOMA).

cobra.flux_analysis.moma.add_moma(model, solution=None, linear=False)[source]

Add constraints and objective representing for MOMA.

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) – A previous solution to use as a reference.
  • linear (bool) – Whether to use the linear MOMA formulation or not.
Returns:

Return type:

Nothing.

Notes

In the original MOMA 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 <= v^d_i <= 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 <= v^d_i <= ub_i

So basically we just re-center the flux space at the old solution and than 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, 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 which 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.

cobra.flux_analysis.moma.create_euclidian_distance_lp(moma_model, solver)[source]

Create the distance linear program (legacy method).

cobra.flux_analysis.moma.create_euclidian_distance_objective(n_moma_reactions)[source]

Return a matrix which will minimize the euclidian distance (legacy).

This matrix has the structure [ I -I] [-I I] where I is the identity matrix the same size as the number of reactions in the original model.

Parameters:n_moma_reactions (int) – This is the number of reactions in the MOMA model, which should be twice the number of reactions in the original model
Returns:A matrix describing the distance objective.
Return type:scipy.sparse.dok_matrix
cobra.flux_analysis.moma.create_euclidian_moma_model(cobra_model, wt_model=None, **solver_args)[source]

Create a new moma model (legacy function).

cobra.flux_analysis.moma.moma(wt_model, mutant_model, solver=None, **solver_args)[source]

Run MOMA on models (legacy method).

cobra.flux_analysis.moma.moma_knockout(moma_model, moma_objective, reaction_indexes, **moma_args)[source]

Compute result of reaction_knockouts using moma.

cobra.flux_analysis.moma.solve_moma_model(moma_model, objective_id, solver=None, **solver_args)[source]

Solve the MOMA LP (legacy method).

14.1.3.7. cobra.flux_analysis.parsimonious module

cobra.flux_analysis.parsimonious.add_pfba(model, objective=None, fraction_of_optimum=1.0)[source]

Add pFBA objective

Add objective to minimize the summed flux of all reactions to the current objective.

See also

pfba()

Parameters:
  • model (cobra.Model) – The model to add the objective to
  • objective – An objective to set in combination with the pFBA objective.
  • fraction_of_optimum (float) – Fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal_value * fraction_of_optimum.
cobra.flux_analysis.parsimonious.optimize_minimal_flux(*args, **kwargs)[source]
cobra.flux_analysis.parsimonious.pfba(model, already_irreversible=False, fraction_of_optimum=1.0, solver=None, desired_objective_value=None, objective=None, reactions=None, **optimize_kwargs)[source]

Perform basic pFBA (parsimonious Enzyme Usage Flux Balance Analysis) to minimize total flux.

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
  • already_irreversible (bool, optional) – By default, the model is converted to an irreversible one. However, if the model is already irreversible, this step can be skipped. Ignored for optlang solvers as not relevant.
  • fraction_of_optimum (float, optional) – Fraction of optimum which must be maintained. The original objective reaction is constrained to be greater than maximal_value * fraction_of_optimum.
  • solver (str, optional) – Name of the solver to be used. If None it will respect the solver set in the model (model.solver).
  • desired_objective_value (float, optional) – A desired objective value for the minimal solution that bypasses the initial optimization result. Ignored for optlang solvers, instead, define your objective separately and pass using the objective argument.
  • objective (dict or model.problem.Objective) – 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. Not used for non-optlang solvers.
  • reactions (iterable) – List of reactions or reaction identifiers. Implies return_frame to be true. Only return fluxes for the given reactions. Faster than fetching all fluxes if only a few are needed. Only supported for optlang solvers.
  • **optimize_kwargs (additional arguments for legacy solver, optional) –

    Additional arguments passed to the legacy solver. Ignored for optlang solver (those can be configured using

    model.solver.configuration).
Returns:

The solution object to the optimized model with pFBA constraints added.

Return type:

cobra.Solution

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

14.1.3.8. cobra.flux_analysis.phenotype_phase_plane module

cobra.flux_analysis.phenotype_phase_plane.add_envelope(model, reactions, grid, c_input, c_output, threshold)[source]
cobra.flux_analysis.phenotype_phase_plane.calculate_phenotype_phase_plane(model, reaction1_name, reaction2_name, reaction1_range_max=20, reaction2_range_max=20, reaction1_npoints=50, reaction2_npoints=50, solver=None, n_processes=1, tolerance=1e-06)[source]

calculates the growth rates while varying the uptake rates for two reactions.

Returns:a phenotypePhasePlaneData object containing the growth rates

for the uptake rates. To plot the result, call the plot function of the returned object.

Example:
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> ppp = calculate_phenotype_phase_plane(model, "EX_glc__D_e", "EX_o2_e")
>>> ppp.plot()
cobra.flux_analysis.phenotype_phase_plane.find_carbon_sources(model)[source]

Find all active carbon source reactions.

Parameters:model (Model) – A genome-scale metabolic model.
Returns:The medium reactions with carbon input flux.
Return type:list
class cobra.flux_analysis.phenotype_phase_plane.phenotypePhasePlaneData(reaction1_name, reaction2_name, reaction1_range_max, reaction2_range_max, reaction1_npoints, reaction2_npoints)[source]

Bases: object

class to hold results of a phenotype phase plane analysis

plot()[source]

plot the phenotype phase plane in 3D using any available backend

plot_matplotlib(theme='Paired', scale_grid=False)[source]

Use matplotlib to plot a phenotype phase plane in 3D.

theme: color theme to use (requires palettable)

returns: maptlotlib 3d subplot object

plot_mayavi()[source]

Use mayavi to plot a phenotype phase plane in 3D. The resulting figure will be quick to interact with in real time, but might be difficult to save as a vector figure. returns: mlab figure object

segment(threshold=0.01)[source]

attempt to segment the data and identify the various phases

cobra.flux_analysis.phenotype_phase_plane.production_envelope(model, reactions, objective=None, carbon_sources=None, points=20, threshold=1e-07, solver=None)[source]

Calculate the objective value conditioned on all combinations of fluxes for a set of chosen reactions

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 or string) – A list of reactions, reaction identifiers or a single reaction.
  • objective (string, dict, model.solver.interface.Objective, optional) – The objective (reaction) to use for the production envelope. Use the model’s current objective if left missing.
  • carbon_sources (list or string, optional) – One or more reactions or reaction identifiers 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.
  • points (int, optional) – The number of points to calculate production for.
  • threshold (float, optional) – A cut-off under which flux values will be considered to be zero.
  • solver (string, optional) – The solver to use - only here for consistency with older implementations (this argument will be removed in the future). The solver should be set using model.solver directly. Only optlang based solvers are supported.
Returns:

A data frame with one row per evaluated point and

  • reaction id : one column per input reaction indicating the flux at each given point,
  • carbon_source: identifiers of carbon exchange reactions

A column for the maximum and minimum each for the following types:

  • flux: the objective flux
  • carbon_yield: if carbon source is defined and the product is a single metabolite (mol carbon product per mol carbon feeding source)
  • mass_yield: if carbon source is defined and the product is a single metabolite (gram product per 1 g of feeding source)

Return type:

pandas.DataFrame

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"])
cobra.flux_analysis.phenotype_phase_plane.reaction_elements(reaction)[source]

Split metabolites into the atoms times their stoichiometric coefficients.

Parameters:reaction (Reaction) – The metabolic reaction whose components are desired.
Returns:Each of the reaction’s metabolites’ desired carbon elements (if any) times that metabolite’s stoichiometric coefficient.
Return type:list
cobra.flux_analysis.phenotype_phase_plane.reaction_weight(reaction)[source]

Return the metabolite weight times its stoichiometric coefficient.

cobra.flux_analysis.phenotype_phase_plane.total_components_flux(flux, components, consumption=True)[source]

Compute the total components consumption or production flux.

Parameters:
  • flux (float) – The reaction flux for the components.
  • components (list) – List of stoichiometrically weighted components.
  • consumption (bool, optional) – Whether to sum up consumption or production fluxes.
cobra.flux_analysis.phenotype_phase_plane.total_yield(input_fluxes, input_elements, output_flux, output_elements)[source]

Compute total output per input unit.

Units are typically mol carbon atoms or gram of source and product.

Parameters:
  • input_fluxes (list) – A list of input reaction fluxes in the same order as the input_components.
  • input_elements (list) – 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).

Return type:

float

14.1.3.9. cobra.flux_analysis.reaction module

functions for analyzing / creating objective functions

cobra.flux_analysis.reaction.assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None)[source]

Assesses production capacity.

Assesses 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 cutoff.

Parameters:
  • model (cobra.Model) – The cobra model to assess production capacity for
  • reaction (reaction identifier or cobra.Reaction) – The reaction to assess
  • flux_coefficient_cutoff (float) – The minimum flux that reaction must carry to be considered active.
  • solver (basestring) – Solver name. If None, the default solver will be used.
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:

bool or dict

cobra.flux_analysis.reaction.assess_component(model, reaction, side, flux_coefficient_cutoff=0.001, solver=None)[source]

Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff.

Parameters:
  • model (cobra.Model) – The cobra model to assess production capacity for
  • reaction (reaction identifier or cobra.Reaction) – The reaction to assess
  • side (basestring) – Side of the reaction, ‘products’ or ‘reactants’
  • flux_coefficient_cutoff (float) – The minimum flux that reaction must carry to be considered active.
  • solver (basestring) – Solver name. If None, the default solver will be used.
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:

bool or dict

cobra.flux_analysis.reaction.assess_precursors(model, reaction, flux_coefficient_cutoff=0.001, solver=None)[source]

Assesses the ability of the model to provide sufficient precursors for a reaction operating at, or beyond, the specified cutoff.

Deprecated: use assess_component instead

Parameters:
  • model (cobra.Model) – The cobra model to assess production capacity for
  • reaction (reaction identifier or cobra.Reaction) – The reaction to assess
  • flux_coefficient_cutoff (float) – The minimum flux that reaction must carry to be considered active.
  • solver (basestring) – Solver name. If None, the default solver will be used.
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:

bool or dict

cobra.flux_analysis.reaction.assess_products(model, reaction, flux_coefficient_cutoff=0.001, solver=None)[source]

Assesses whether the model has the capacity 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: use assess_component instead

Parameters:
  • model (cobra.Model) – The cobra model to assess production capacity for
  • reaction (reaction identifier or cobra.Reaction) – The reaction to assess
  • flux_coefficient_cutoff (float) – The minimum flux that reaction must carry to be considered active.
  • solver (basestring) – Solver name. If None, the default solver will be used.
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:

bool or dict

14.1.3.10. cobra.flux_analysis.sampling module

Module implementing flux sampling for cobra models.

New samplers should derive from the abstract HRSampler class where possible to provide a uniform interface.

class cobra.flux_analysis.sampling.ACHRSampler(model, thinning=100, seed=None)[source]

Bases: cobra.flux_analysis.sampling.HRSampler

Artificial Centering Hit-and-Run sampler.

A sampler with low memory footprint and good convergence.

Parameters:
  • model (a 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.
  • seed (positive integer, optional) – Sets the random number seed. Initialized to the current time stamp if None.
model

cobra.Model – The cobra model from which the samples get generated.

thinning

int – The currently used thinning factor.

n_samples

int – The total number of samples that have been generated by this sampler instance.

problem

collections.namedtuple – A python object whose attributes define the entire sampling problem in matrix form. See docstring of Problem.

warmup

a numpy matrix – A matrix of 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.

seed

positive integer, optional – Sets the random number seed. Initialized to the current time stamp if None.

fwd_idx

np.array – Has one entry for each reaction in the model containing the index of the respective forward variable.

rev_idx

np.array – Has one entry for each reaction in the model containing the index of the respective reverse variable.

prev

numpy array – The current/last flux sample generated.

center

numpy array – The center of the sampling space as estimated by the mean of all previously generated samples.

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 iterates. 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 reactions)^2 due to the required nullspace matrices and warmup points. So large models easily take up a few GB 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]https://github.com/opencobra/cobratoolbox
sample(n, fluxes=True)[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 (boolean) – 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.
Returns:

Returns a matrix with n rows, each containing a flux sample.

Return type:

numpy.matrix

Notes

Performance of this function linearly depends on the number of reactions in your model and the thinning factor.

class cobra.flux_analysis.sampling.HRSampler(model, thinning, seed=None)[source]

Bases: object

The abstract base class for hit-and-run samplers.

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.
model

cobra.Model – The cobra model from which the samples get generated.

thinning

int – The currently used thinning factor.

n_samples

int – The total number of samples that have been generated by this sampler instance.

problem

collections.namedtuple – A python object whose attributes define the entire sampling problem in matrix form. See docstring of Problem.

warmup

a numpy matrix – A matrix of 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.

seed

positive integer, optional – Sets the random number seed. Initialized to the current time stamp if None.

fwd_idx

np.array – Has one entry for each reaction in the model containing the index of the respective forward variable.

rev_idx

np.array – Has one entry for each reaction in the model containing the index of the respective reverse variable.

batch(batch_size, batch_num, fluxes=True)[source]

Create a batch generator.

This is useful to generate n batches of m samples each.

Parameters:
  • batch_size (int) – The number of samples contained in each batch (m).
  • batch_num (int) – The number of batches in the generator (n).
  • fluxes (boolean) – 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.
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.

generate_fva_warmup()[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).

sample(n, fluxes=True)[source]

Abstract sampling function.

Should be overwritten by child classes.

validate(samples)[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 (n_samples x n_reactions). Contains the samples to be validated. Samples must be from fluxes.
Returns:A one-dimensional numpy array of length 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
cobra.flux_analysis.sampling.LOGGER = <logging.Logger object>

The logger for the package.

class cobra.flux_analysis.sampling.OptGPSampler(model, processes, thinning=100, seed=None)[source]

Bases: cobra.flux_analysis.sampling.HRSampler

A parallel optimized 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) – The number of processes used during sampling.
  • thinning (int, optional) – The thinning factor of the generated sampling chain. A thinning of 10 means samples are returned every 10 steps.
  • seed (positive integer, optional) – Sets the random number seed. Initialized to the current time stamp if None.
model

cobra.Model – The cobra model from which the samples get generated.

thinning

int – The currently used thinning factor.

n_samples

int – The total number of samples that have been generated by this sampler instance.

problem

collections.namedtuple – A python object whose attributes define the entire sampling problem in matrix form. See docstring of Problem.

warmup

a numpy matrix – A matrix of 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.

seed

positive integer, optional – Sets the random number seed. Initialized to the current time stamp if None.

fwd_idx

np.array – Has one entry for each reaction in the model containing the index of the respective forward variable.

rev_idx

np.array – Has one entry for each reaction in the model containing the index of the respective reverse variable.

prev

numpy.array – The current/last flux sample generated.

center

numpy.array – The center of the sampling space as estimated by the mean of all previously generated samples.

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 towards the a little bit towards the center of the sampling space.

If the number of processes used is larger than one the 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 reactions)^2 due to the required nullspace matrices and warmup points. So large models easily take up a few GB 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(n, fluxes=True)[source]

Generate a set of samples.

This is the basic sampling function for all hit-and-run samplers.

n : int
The minimum number of samples that are generated at once (see Notes).
fluxes : boolean
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.
Returns:Returns a matrix with n rows, each containing a flux sample.
Return type:numpy.matrix

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 as the CPUs of your machine. This may shorten computation time. However, there is also overhead in setting up parallel computation so we recommend to calculate large numbers of samples at once (n > 1000).

class cobra.flux_analysis.sampling.Problem(equalities, b, inequalities, bounds, variable_fixed, variable_bounds, nullspace, homogeneous)

Bases: tuple

Defines the matrix representation of a sampling problem.

equalities

numpy.array – All equality constraints in the model.

b

numpy.array – The right side of the equality constraints.

inequalities

numpy.array – All inequality constraints in the model.

bounds

numpy.array – The lower and upper bounds for the inequality constraints.

variable_bounds

numpy.array – The lower and upper bounds for the variables.

homogeneous

boolean – Indicates whether the sampling problem is homogenous, e.g. whether there exist no non-zero fixed variables or constraints.

nullspace

numpy.matrix – A matrix containing the nullspace of the equality constraints. Each column is one basis vector.

b

Alias for field number 1

bounds

Alias for field number 3

equalities

Alias for field number 0

homogeneous

Alias for field number 7

inequalities

Alias for field number 2

nullspace

Alias for field number 6

variable_bounds

Alias for field number 5

variable_fixed

Alias for field number 4

cobra.flux_analysis.sampling.bounds_tol

The tolerance used for checking bounds feasibility.

cobra.flux_analysis.sampling.feasibility_tol

The tolerance used for checking equalities feasibility.

cobra.flux_analysis.sampling.mp_init(obj)[source]

Initialize the multiprocessing pool.

cobra.flux_analysis.sampling.nproj = 1000000

Reproject the solution into the feasibility space every nproj iterations.

cobra.flux_analysis.sampling.nproj_center = 10000

Reproject the center into the nullspace every nproj_center iterations. Only used for inhomogeneous problems.

cobra.flux_analysis.sampling.sample(model, n, method='optgp', thinning=100, processes=1, seed=None)[source]

Sample valid flux distributions from a cobra model.

The function samples valid flux distributions from a cobra model. Currently we support two methods:

  1. ‘optgp’ (default) which uses the OptGPSampler that supports parallel
    sampling [1]_. Requires large numbers of samples to be performant (n < 1000). For smaller samples ‘achr’ might be better suited.

or

  1. ‘achr’ which uses artificial centering hit-and-run. This is a single process method with good convergence [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 (str, optional) – The sampling algorithm to use.
  • 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 one will return all iterates.
  • processes (int, optional) – Only used for ‘optgp’. The number of processes used to generate samples.
  • seed (positive integer, optional) – The random number seed to be used. Initialized to current time stamp if 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.
[2]Direction Choice for Accelerated Convergence in Hit-and-Run Sampling David E. Kaufman Robert L. Smith Operations Research 199846:1 , 84-95
cobra.flux_analysis.sampling.shared_np_array(shape, data=None, integer=False)[source]

Create a new numpy array that resides in shared memory.

Parameters:
  • shape (tuple of ints) – The shape of the new array.
  • data (numpy.array) – Data to copy to the new array. Has to have the same shape.
  • integer (boolean) – Whether to use an integer array. Defaults to False which means float array.

14.1.3.11. cobra.flux_analysis.single_deletion module

Bundles functions for successively deleting a set of genes or reactions.

cobra.flux_analysis.single_deletion.single_gene_deletion(cobra_model, gene_list=None, solver=None, method='fba', **solver_args)[source]

Sequentially knocks out each gene from a given gene list.

Parameters:
  • cobra_model (a cobra model) – The model from which to delete the genes. The model will not be modified.
  • gene_list (iterable) – List of gene IDs or cobra.Gene. If None (default) will use all genes in the model.
  • method (str, optional) – The method used to obtain fluxes. Must be one of “fba”, “moma” or “linear moma”.
  • solver (str, optional) – Name of the solver to be used.
  • solver_args (optional) – Additional arguments for the solver. Ignored for optlang solver, please use model.solver.configuration instead.
Returns:

Data frame with two column and reaction id as index: - flux: the value of the objective after the knockout - status: the solution’s status, (for instance “optimal” for each

knockout)

Return type:

pandas.DataFrame

cobra.flux_analysis.single_deletion.single_gene_deletion_fba(cobra_model, gene_list, solver=None, **solver_args)[source]

Sequentially knocks out each gene in a model using FBA.

Not supposed to be called directly use single_reactions_deletion(..., method=”fba”) instead.

Parameters:
  • gene_list (iterable) – List of gene IDs or cobra.Reaction.
  • solver (str, optional) – The name of the solver to be used.
Returns:

A tuple ({reaction_id: growth_rate}, {reaction_id: status})

Return type:

tuple of dicts

cobra.flux_analysis.single_deletion.single_gene_deletion_moma(cobra_model, gene_list, linear=False, solver=None, **solver_args)[source]

Sequentially knocks out each gene in a model using MOMA.

Not supposed to be called directly use single_reactions_deletion(..., method=”moma”) instead.

Parameters:
  • gene_list (iterable) – List of gene IDs or cobra.Reaction.
  • linear (bool) – Whether to use linear MOMA.
  • solver (str, optional) – The name of the solver to be used.
Returns:

A tuple ({reaction_id: growth_rate}, {reaction_id: status})

Return type:

tuple of dicts

cobra.flux_analysis.single_deletion.single_reaction_deletion(cobra_model, reaction_list=None, solver=None, method='fba', **solver_args)[source]

Sequentially knocks out each reaction from a given reaction list.

Parameters:
  • cobra_model (cobra.Model) – The model from which to delete the reactions. The model will not be modified.
  • reaction_list (iterable) – List of reaction IDs or cobra.Reaction. If None (default) will use all reactions in the model.
  • method (str, optional) – The method used to obtain fluxes. Must be one of “fba”, “moma” or “linear moma”.
  • solver (str, optional) – Name of the solver to be used.
  • solver_args (optional) – Additional arguments for the solver. Ignored for optlang solver, please use model.solver.configuration instead.
Returns:

Data frame with two column and reaction id as index: - flux: the value of the objective after the knockout - status: the solution’s status, (for instance “optimal” for each

knockout)

Return type:

pandas.DataFrame

cobra.flux_analysis.single_deletion.single_reaction_deletion_fba(cobra_model, reaction_list, solver=None, **solver_args)[source]

Sequentially knocks out each reaction in a model using FBA.

Not supposed to be called directly use single_reactions_deletion(..., method=”fba”) instead.

Parameters:
  • cobra_model (cobra.Model) – The model from which to delete the reactions. The model will not be modified.
  • reaction_list (iterable) – List of reaction Ids or cobra.Reaction.
  • solver (str, optional) – The name of the solver to be used.
Returns:

A tuple ({reaction_id: growth_rate}, {reaction_id: status})

Return type:

tuple of dicts

cobra.flux_analysis.single_deletion.single_reaction_deletion_moma(cobra_model, reaction_list, linear=False, solver=None, **solver_args)[source]

Sequentially knocks out each reaction in a model using MOMA.

Not supposed to be called directly use single_reactions_deletion(..., method=”moma”) instead.

Parameters:
  • cobra_model (cobra.Model) – The model from which to delete the reactions. The model will not be modified.
  • reaction_list (iterable) – List of reaction IDs or cobra.Reaction.
  • linear (bool) – Whether to use linear MOMA.
  • solver (str, optional) – The name of the solver to be used.
Returns:

A tuple ({reaction_id: growth_rate}, {reaction_id: status})

Return type:

tuple of dicts

14.1.3.12. cobra.flux_analysis.summary module

cobra.flux_analysis.summary.metabolite_summary(met, solution=None, threshold=0.01, fva=False, floatfmt='.3g')[source]

Print a summary of the reactions which produce and consume this metabolite

solution : cobra.core.Solution
A previously solved model solution to use for generating the summary. If none provided (default), the summary method will resolve the model. Note that the solution object must match the model, i.e., changes to the model such as changed bounds, added or removed reactions are not taken into account by this method.
threshold : float
a value below which to ignore reaction fluxes
fva : float (0->1), or None
Whether or not to include flux variability analysis in the output. If given, fva should be a float between 0 and 1, representing the fraction of the optimum objective to be searched.
floatfmt : string
format method for floats, passed to tabulate. Default is ‘.3g’.
cobra.flux_analysis.summary.model_summary(model, solution=None, threshold=1e-08, fva=None, floatfmt='.3g')[source]

Print a summary of the input and output fluxes of the model.

solution : cobra.core.Solution
A previously solved model solution to use for generating the summary. If none provided (default), the summary method will resolve the model. Note that the solution object must match the model, i.e., changes to the model such as changed bounds, added or removed reactions are not taken into account by this method.
threshold : float
tolerance for determining if a flux is zero (not printed)
fva : int or None
Whether or not to calculate and report flux variability in the output summary
floatfmt : string
format method for floats, passed to tabulate. Default is ‘.3g’.

14.1.3.13. cobra.flux_analysis.variability module

cobra.flux_analysis.variability.calculate_lp_variability(lp, solver, cobra_model, reaction_list, **solver_args)[source]

calculate max and min of selected variables in an LP

cobra.flux_analysis.variability.find_blocked_reactions(model, reaction_list=None, solver=None, zero_cutoff=1e-09, open_exchanges=False, **solver_args)[source]

Finds reactions that cannot carry a flux with the current exchange reaction settings for a cobra model, using flux variability analysis.

Parameters:
  • model (cobra.Model) – The model to analyze
  • reaction_list (list) – List of reactions to consider, use all if left missing
  • solver (string) – The name of the solver to use
  • zero_cutoff (float) – Flux value which is considered to effectively be zero.
  • open_exchanges (bool) – If true, set bounds on exchange reactions to very high values to avoid that being the bottle-neck.
  • **solver_args – Additional arguments to the solver. Ignored for optlang based solvers.
Returns:

List with the blocked reactions

Return type:

list

cobra.flux_analysis.variability.find_essential_genes(model, threshold=0.01)[source]

Return a set of essential genes.

A gene is considered essential if restricting the flux of all reactions that depends on it to zero causes the objective (e.g. the growth rate) to also be zero.

Parameters:
  • model (cobra.Model) – The model to find the essential genes for.
  • threshold (float (default 0.01)) – Minimal objective flux to be considered viable.
Returns:

Set of essential genes

Return type:

set

cobra.flux_analysis.variability.find_essential_reactions(model, threshold=0.01)[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.

Parameters:
  • model (cobra.Model) – The model to find the essential reactions for.
  • threshold (float (default 0.01)) – Minimal objective flux to be considered viable.
Returns:

Set of essential reactions

Return type:

set

cobra.flux_analysis.variability.flux_variability_analysis(model, reaction_list=None, loopless=False, fraction_of_optimum=1.0, pfba_factor=None, solver=None, **solver_args)[source]

Runs flux variability analysis to find the min/max flux values for each each reaction in reaction_list.

Parameters:
  • model (a 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.
  • loopless (boolean, optional) – Whether to return only loopless solutions. Ignored for legacy solvers, also see Notes.
  • fraction_of_optimum (float, optional) – Must be <= 1.0. Requires that the objective value is at least fraction * max_objective_value. A value of 0.85 for instance means that the objective has to be at least at 85% percent of its maximum.
  • pfba_factor (float, optional) – Add additional constraint to the model that 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 then 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.
  • solver (str, optional) – Name of the solver to be used. If None it will respect the solver set in the model (model.solver).
  • **solver_args (additional arguments for legacy solver, optional) – Additional arguments passed to the legacy solver. Ignored for optlang solver (those can be configured using model.solver.configuration).
Returns:

DataFrame with reaction identifier as the index 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 suboptimal.

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.

14.1.3.14. Module contents