17.1.1.8. cobra.util

17.1.1.8.1. Submodules

17.1.1.8.2. Package Contents

17.1.1.8.2.1. Classes

HistoryManager

Record a list of actions to be taken at a later time. Used to

AutoVivification

Implementation of perl’s autovivification feature. Checkout

17.1.1.8.2.2. Functions

create_stoichiometric_matrix(model, array_type=’dense’, dtype=None)

Return a stoichiometric array representation of the given model.

nullspace(A, atol=1e-13, rtol=0)

Compute an approximate basis for the nullspace of A.

constraint_matrices(model, array_type=’dense’, include_vars=False, zero_tol=1e-06)

Create a matrix representation of the problem.

get_context(obj)

Search for a context manager

resettable(f)

A decorator to simplify the context management of simple object

get_context(obj)

Search for a context manager

linear_reaction_coefficients(model, reactions=None)

Coefficient for the reactions in a linear objective.

_valid_atoms(model, expression)

Check whether a sympy expression references the correct variables.

set_objective(model, value, additive=False)

Set the model objective.

interface_to_str(interface)

Give a string representation for an optlang interface.

get_solver_name(mip=False, qp=False)

Select a solver for a given optimization problem.

choose_solver(model, solver=None, qp=False)

Choose a solver given a solver name and model.

add_cons_vars_to_problem(model, what, **kwargs)

Add variables and constraints to a Model’s solver object.

remove_cons_vars_from_problem(model, what)

Remove variables and constraints from a Model’s solver object.

add_absolute_expression(model, expression, name=’abs_var’, ub=None, difference=0, add=True)

Add the absolute value of an expression to the model.

fix_objective_as_constraint(model, fraction=1, bound=None, name=’fixed_objective_{}’)

Fix current objective as an additional constraint.

check_solver_status(status, raise_error=False)

Perform standard checks on a solver’s status.

assert_optimal(model, message=’optimization failed’)

Assert model solver status is optimal.

add_lp_feasibility(model)

Add a new objective and variables to ensure a feasible solution.

add_lexicographic_constraints(model, objectives, objective_direction=’max’)

Successively optimize separate targets in a specific order.

format_long_string(string, max_length=50)

show_versions()

Print dependency information.

cobra.util.create_stoichiometric_matrix(model, array_type='dense', dtype=None)[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 (string) – The type of array to construct. if ‘dense’, return a standard numpy.array, ‘dok’, or ‘lil’ will construct a sparse array using scipy of the corresponding type and ‘DataFrame’ will give a pandas DataFrame with metabolite indices and reaction columns

  • dtype (data-type) – The desired data-type for the array. If not given, defaults to float.

Returns

The stoichiometric matrix for the given model.

Return type

matrix of class dtype

cobra.util.nullspace(A, atol=1e-13, rtol=0)[source]

Compute an approximate basis for the nullspace of A. The algorithm used by this function is based on the singular value decomposition of A.

Parameters
  • A (numpy.ndarray) – A should be at most 2-D. A 1-D array with length k will be treated as a 2-D with shape (1, k)

  • atol (float) – The absolute tolerance for a zero singular value. Singular values smaller than atol are considered to be zero.

  • rtol (float) – The relative tolerance. Singular values less than rtol*smax are considered to be zero, where smax is the largest singular value.

  • both atol and rtol are positive, the combined tolerance is the (If) –

  • of the two; that is:: (maximum) –

  • = max(atol, rtol * smax) (tol) –

  • values smaller than tol are considered to be zero. (Singular) –

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

numpy.ndarray

Notes

Taken from the numpy cookbook.

cobra.util.constraint_matrices(model, array_type='dense', include_vars=False, zero_tol=1e-06)[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.

Notes

To accomodate non-zero equalities the problem will add the variable “const_one” which is a variable that equals one.

Parameters
  • model (cobra.Model) – The model from which to obtain the LP problem.

  • array_type (string) – The type of array to construct. if ‘dense’, return a standard numpy.array, ‘dok’, or ‘lil’ will construct a sparse array using scipy of the corresponding type and ‘DataFrame’ will give a pandas DataFrame with metabolite indices and reaction columns.

  • zero_tol (float) – The zero tolerance used to judge whether two bounds are the same.

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

collections.namedtuple

class cobra.util.HistoryManager[source]

Bases: object

Record a list of actions to be taken at a later time. Used to implement context managers that allow temporary changes to a Model.

__call__(self, operation)

Add the corresponding method to the history stack.

Parameters

operation (function) – A function to be called at a later time

reset(self)

Trigger executions for all items in the stack in reverse order

cobra.util.get_context(obj)[source]

Search for a context manager

cobra.util.resettable(f)[source]

A decorator to simplify the context management of simple object attributes. Gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the HistoryManager.

cobra.util.OPTLANG_TO_EXCEPTIONS_DICT
exception cobra.util.OptimizationError(message)

Bases: Exception

Common base class for all non-exit exceptions.

exception cobra.util.SolverNotFound

Bases: Exception

A simple Exception when a solver can not be found.

cobra.util.get_context(obj)[source]

Search for a context manager

cobra.util.solvers[source]
cobra.util.qp_solvers = ['cplex', 'gurobi'][source]
cobra.util.has_primals[source]
cobra.util.linear_reaction_coefficients(model, reactions=None)[source]

Coefficient for the reactions in a linear objective.

Parameters
  • model (cobra model) – the model object that defined the objective

  • reactions (list) – an optional list for the reactions to get the coefficients for. All reactions if left missing.

Returns

A dictionary where the key is the reaction object and the value is the corresponding coefficient. Empty dictionary if there are no linear terms in the objective.

Return type

dict

cobra.util._valid_atoms(model, expression)[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

boolean

cobra.util.set_objective(model, value, additive=False)[source]

Set the model objective.

Parameters
  • model (cobra model) – The model to set the objective for

  • value (model.problem.Objective,) –

    e.g. optlang.glpk_interface.Objective, sympy.Basic or dict

    If the model objective is linear, the value can be a new Objective object or a dictionary with linear coefficients where each key is a reaction and the element the new coefficient (float).

    If the objective is not linear and additive is true, only values of class Objective.

  • additive (boolmodel.reactions.Biomass_Ecoli_core.bounds = (0.1, 0.1)) – If true, add the terms to the current objective, otherwise start with an empty objective.

cobra.util.interface_to_str(interface)[source]

Give a string representation for an optlang interface.

Parameters

interface (string, ModuleType) – Full name of the interface in optlang or cobra representation. For instance ‘optlang.glpk_interface’ or ‘optlang-glpk’.

Returns

The name of the interface as a string

Return type

string

cobra.util.get_solver_name(mip=False, qp=False)[source]

Select a solver for a given optimization problem.

Parameters
  • mip (bool) – Does the solver require mixed integer linear programming capabilities?

  • qp (bool) – Does the solver require quadratic programming capabilities?

Returns

The name of feasible solver.

Return type

string

Raises

SolverNotFound – If no suitable solver could be found.

cobra.util.choose_solver(model, solver=None, qp=False)[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 (a cobra model) – The model for which to choose the solver.

  • solver (str, optional) – The name of the solver to be used.

  • qp (boolean, optional) – Whether the solver needs Quadratic Programming capabilities.

Returns

solver – Returns a valid solver for the problem.

Return type

an optlang solver interface

Raises

SolverNotFound – If no suitable solver could be found.

cobra.util.add_cons_vars_to_problem(model, what, **kwargs)[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. Will integrate with the Model’s context manager in order to revert changes upon leaving the context.

Parameters
  • model (a cobra model) – The model to which to add the variables and constraints.

  • what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class model.problem.Variable or model.problem.Constraint.

  • **kwargs (keyword arguments) – passed to solver.add()

cobra.util.remove_cons_vars_from_problem(model, what)[source]

Remove variables and constraints from a Model’s solver object.

Useful to temporarily remove variables and constraints from a Models’s solver object.

Parameters
  • model (a cobra model) – The model from which to remove the variables and constraints.

  • what (list or tuple of optlang variables or constraints.) – The variables or constraints to remove from the model. Must be of class model.problem.Variable or model.problem.Constraint.

cobra.util.add_absolute_expression(model, expression, name='abs_var', ub=None, difference=0, add=True)[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 (a cobra model) – The model to which to add the absolute expression.

  • expression (A sympy expression) – Must be a valid expression within the Model’s solver object. The absolute value is applied automatically on the expression.

  • name (string) – The name of the newly created variable.

  • ub (positive float) – The upper bound for the variable.

  • difference (positive float) – The difference between the expression and the variable.

  • add (bool) – Whether to add the variable to the model at once.

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

namedtuple

cobra.util.fix_objective_as_constraint(model, fraction=1, bound=None, name='fixed_objective_{}')[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) – The fraction of the optimum the objective is allowed to reach.

  • bound (float, None) – The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored.

  • name (str) – Name of the objective. May contain one {} placeholder which is filled with the name of the old objective.

Returns

Return type

The value of the optimized objective * fraction

cobra.util.check_solver_status(status, raise_error=False)[source]

Perform standard checks on a solver’s status.

cobra.util.assert_optimal(model, message='optimization failed')[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 to for the exception if solver status was not optimal.

cobra.util.add_lp_feasibility(model)[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.

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, objectives, objective_direction='max')[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) – A list of reactions (or objectives) in the model for which unique fluxes are to be determined.

  • objective_direction (str or list, optional) – The desired objective direction for each reaction (if a list) or the objective direction to use for all reactions (default maximize).

Returns

optimized_fluxes – A vector 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, max_length=50)[source]
class cobra.util.AutoVivification[source]

Bases: dict

Implementation of perl’s autovivification feature. Checkout http://stackoverflow.com/a/652284/280182

__getitem__(self, item)

x.__getitem__(y) <==> x[y]

cobra.util.show_versions()[source]

Print dependency information.