cobra.core.model
¶
Define the Model class.
Module Contents¶
Classes¶
Class representation for a cobra model. |
Attributes¶
- class cobra.core.model.Model(id_or_model: Union[str, Model, None] = None, name: Optional[str] = None)[source]¶
Bases:
cobra.core.object.Object
Class representation for a cobra model.
- Parameters
id_or_model (str or Model, optional) – String to use as model id, or actual model to base new model one. If string, it is used as id. If model, a new model object is instantiated with the same properties as the original model (default None).
name (str, optional) – Human readable string to be model description (default None).
- 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
- property solver: optlang.interface.Model[source]¶
Get 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
>>> from cobra.io import load_model >>> model = load_model("textbook") >>> new = model.problem.Constraint(model.objective.expression, lb=0.99) >>> model.solver.add(new)
- property tolerance: float[source]¶
Get the tolerance.
- Returns
The tolerance of the mdoel.
- Return type
- property compartments: Dict[source]¶
Return all metabolites’ compartments.
- Returns
A dictionary of metabolite compartments, where the keys are the short version (one letter version) of the compartmetns, and the values are the full names (if they exist).
- Return type
- property medium: Dict[str, float][source]¶
Get the constraints on the model exchanges.
model.medium returns a dictionary of the bounds for each of the boundary reactions, in the form of {rxn_id: bound}, where bound specifies the absolute value of the bound in direction of metabolite creation (i.e., lower_bound for met <–, upper_bound for met –>)
- property problem: optlang.interface[source]¶
Get 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: optlang.container.Container[source]¶
Get 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: optlang.container.Container[source]¶
Get 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: List[cobra.core.reaction.Reaction][source]¶
Boundary reactions in the model.
Reactions that either have no substrate or product.
- Returns
A list of reactions that either have no substrate or product and only one metabolite overall.
- Return type
- property exchanges: List[cobra.core.reaction.Reaction][source]¶
Exchange reactions in model.
Reactions that exchange mass with the exterior. Uses annotations and heuristics to exclude non-exchanges such as sink reactions.
- Returns
A list of reactions that satisfy the conditions for exchange reactions.
- Return type
See also
- property demands: List[cobra.core.reaction.Reaction][source]¶
Demand reactions in model.
Irreversible reactions that accumulate or consume a metabolite in the inside of the model.
- Returns
A list of reactions that are demand reactions (reactions that accumulate/consume a metabolite irreversibly).
- Return type
See also
- property sinks: List[cobra.core.reaction.Reaction][source]¶
Sink reactions in model.
Reversible reactions that accumulate or consume a metabolite in the inside of the model.
- Returns
A list of reactions that are demand reactions (reactions that accumulate/consume a metabolite reversibly).
- Return type
See also
- property objective: Union[optlang.Objective][source]¶
Get the solver objective.
With optlang, the objective is not limited to a simple linear summation of individual reaction fluxes, making the 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).
- property objective_direction: str[source]¶
Get the objective direction.
- Returns
Objective direction as string. Should be “max” or “min”.
- Return type
- __setstate__(state: Dict) None [source]¶
Make sure all cobra.Objects in the model point to the model.
- Parameters
state (dict) –
- __getstate__() Dict [source]¶
Get state for serialization.
Ensures that the context stack is cleared prior to serialization, since partial functions cannot be pickled reliably.
- Returns
odict – A dictionary of state, based on self.__dict__.
- Return type
Dict
- copy() Model [source]¶
Provide a partial ‘deepcopy’ of the Model.
All the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy.
- Returns
cobra.Model
- Return type
new model copy
- add_metabolites(metabolite_list: Union[List, cobra.core.metabolite.Metabolite]) None [source]¶
Add new metabolites to a model.
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 (list or Metabolite.) – A list of cobra.core.Metabolite objects. If it isn’t an iterable container, the metabolite will be placed into a list.
- remove_metabolites(metabolite_list: Union[List, cobra.core.metabolite.Metabolite], destructive: bool = False) None [source]¶
Remove a list of metabolites from the the object.
The change is reverted upon exit when using the model as a context.
- Parameters
metabolite_list (list or Metaoblite) – A list of cobra.core.Metabolite objects. If it isn’t an iterable container, the metabolite will be placed into a list.
destructive (bool, optional) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model (default False).
- add_boundary(metabolite: cobra.core.metabolite.Metabolite, type: str = 'exchange', reaction_id: Optional[str] = None, lb: Optional[float] = None, ub: Optional[float] = None, sbo_term: Optional[str] = None) cobra.core.reaction.Reaction [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.
The change is reverted upon exit when using the model as a context.
- 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 ({"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’ (default “exchange”).
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. (default None).
lb (float, optional) – The lower bound of the resulting reaction (default None).
ub (float, optional) – The upper bound of the resulting reaction (default None).
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 (default None).
- Returns
The created boundary reaction.
- Return type
Examples
>>> from cobra.io load_model >>> model = load_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(reaction_list: Iterable[cobra.core.reaction.Reaction]) None [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(reactions: Union[str, cobra.core.reaction.Reaction, List[Union[str, cobra.core.reaction.Reaction]]], remove_orphans: bool = False) None [source]¶
Remove reactions from the model.
The change is reverted upon exit when using the model as a context.
- Parameters
reactions (list or reaction or str) – A list with reactions (cobra.Reaction), or their id’s, to remove. Reaction will be placed in a list. Str will be placed in a list and used to find the reaction in the model.
remove_orphans (bool, optional) – Remove orphaned genes and metabolites from the model as well (default False).
- add_groups(group_list: Union[str, cobra.core.group.Group, List[cobra.core.group.Group]]) None [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.
- remove_groups(group_list: Union[str, cobra.core.group.Group, List[cobra.core.group.Group]]) None [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).
- get_associated_groups(element: Union[cobra.core.reaction.Reaction, cobra.core.gene.Gene, cobra.core.metabolite.Metabolite]) List[cobra.core.group.Group] [source]¶
Get list of groups for 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(what: Union[List[cobra.util.solver.CONS_VARS], Tuple[cobra.util.solver.CONS_VARS]], **kwargs) None [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.
- remove_cons_vars(what: Union[List[cobra.util.solver.CONS_VARS], Tuple[cobra.util.solver.CONS_VARS]]) None [source]¶
Remove variables and constraints from problem.
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.
- _populate_solver(reaction_list: List[cobra.core.reaction.Reaction], metabolite_list: Optional[List[cobra.core.metabolite.Metabolite]] = None) None [source]¶
Populate attached solver with constraints and variables.
Populate attached solver with constraints and variables that model the provided reactions.
- slim_optimize(error_value: Optional[float] = float('nan'), message: Optional[str] = None) float [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.
- Parameters
- Returns
The objective value. Returns the error value if optimization failed and error_value was not None.
- Return type
- Raises
OptimizationError – If error_value was set as None and the optimization fails.
- optimize(objective_sense: Optional[str] = None, raise_error: bool = False) cobra.Solution [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 (default None).
raise_error (bool) –
- If true, raise an OptimizationError if solver status is not
optimal (default False).
- Return type
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(rebuild_index: bool = True, rebuild_relationships: bool = True) None [source]¶
Update all indexes and pointers in a model.
- summary(solution: Optional[cobra.Solution] = None, fva: Union[pandas.DataFrame, float, None] = None) cobra.summary.ModelSummary [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 (pd.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).
- Return type
cobra.ModelSummary
See also
Reaction.summary
,Metabolite.summary
- __enter__() Model [source]¶
Record future changes to the model.
Record all future changes to the model, undoing them when a call to __exit__ is received. Creates a new context and adds it to the stack.
- Returns
Returns the model with context added.
- Return type
- __exit__(type, value, traceback) None [source]¶
Pop the top context manager and trigger the undo functions.
- merge(right: Model, prefix_existing: Optional[str] = None, inplace: bool = True, objective: str = 'left') Model [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.
- Parameters
right (cobra.Model) – The model to add reactions from
prefix_existing (string or optional) – Prefix the reaction identifier in the right that already exist in the left model with this string (default None).
inplace (bool) – 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 (default True).
objective ({"left", "right", "sum"}) – 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 (default “left”).
- Returns
The merged model.
- Return type