:py:mod:`cobra.core.model` ========================== .. py:module:: cobra.core.model .. autoapi-nested-parse:: Define the Model class. Module Contents --------------- Classes ~~~~~~~ .. autoapisummary:: cobra.core.model.Model Attributes ~~~~~~~~~~ .. autoapisummary:: cobra.core.model.logger cobra.core.model.configuration .. py:data:: logger .. py:data:: configuration .. py:class:: Model(id_or_model: Union[str, Model, None] = None, name: Optional[str] = None) Bases: :py:obj:`cobra.core.object.Object` Class representation for a cobra model. :param id_or_model: 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). :type id_or_model: str or Model, optional :param name: Human readable string to be model description (default None). :type name: str, optional .. attribute:: reactions A DictList where the key is the reaction identifier and the value a Reaction :type: DictList .. attribute:: metabolites A DictList where the key is the metabolite identifier and the value a Metabolite :type: DictList .. attribute:: genes A DictList where the key is the gene identifier and the value a Gene :type: DictList .. attribute:: groups A DictList where the key is the group identifier and the value a Group :type: DictList .. py:property:: solver :type: optlang.interface.Model 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. .. rubric:: 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) .. py:property:: tolerance :type: float Get the tolerance. :returns: The tolerance of the mdoel. :rtype: float .. py:property:: compartments :type: Dict 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). :rtype: dict .. py:property:: medium :type: Dict[str, float] 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 -->`) :returns: A dictionary with rxn.id (str) as key, bound (float) as value. :rtype: Dict[str, float] .. py:property:: problem :type: optlang.interface 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. :rtype: optlang.interface .. py:property:: variables :type: optlang.container.Container 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. :rtype: optlang.container.Container .. py:property:: constraints :type: optlang.container.Container 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. :rtype: optlang.container.Container .. py:property:: boundary :type: List[cobra.core.reaction.Reaction] 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. :rtype: list .. py:property:: exchanges :type: List[cobra.core.reaction.Reaction] 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. :rtype: list .. seealso:: :obj:`cobra.medium.find_boundary_types` .. py:property:: demands :type: List[cobra.core.reaction.Reaction] 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). :rtype: list .. seealso:: :obj:`cobra.medium.find_boundary_types` .. py:property:: sinks :type: List[cobra.core.reaction.Reaction] 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). :rtype: list .. seealso:: :obj:`cobra.medium.find_boundary_types` .. py:property:: objective :type: Union[optlang.Objective] 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). .. py:property:: objective_direction :type: str Get the objective direction. :returns: Objective direction as string. Should be "max" or "min". :rtype: str .. py:method:: __setstate__(state: Dict) -> None Make sure all cobra.Objects in the model point to the model. :param state: :type state: dict .. py:method:: __getstate__() -> Dict 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__. :rtype: Dict .. py:method:: copy() -> Model 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** :rtype: new model copy .. py:method:: add_metabolites(metabolite_list: Union[List, cobra.core.metabolite.Metabolite]) -> None 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. :param metabolite_list: A list of `cobra.core.Metabolite` objects. If it isn't an iterable container, the metabolite will be placed into a list. :type metabolite_list: list or Metabolite. .. py:method:: remove_metabolites(metabolite_list: Union[List, cobra.core.metabolite.Metabolite], destructive: bool = False) -> None Remove a list of metabolites from the the object. The change is reverted upon exit when using the model as a context. :param metabolite_list: A list of `cobra.core.Metabolite` objects. If it isn't an iterable container, the metabolite will be placed into a list. :type metabolite_list: list or Metaoblite :param destructive: If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model (default False). :type destructive: bool, optional .. py:method:: 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 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. :param metabolite: Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks. :type metabolite: cobra.Metabolite :param type: 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"). :type type: {"exchange", "demand", "sink"} :param reaction_id: 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). :type reaction_id: str, optional :param lb: The lower bound of the resulting reaction (default None). :type lb: float, optional :param ub: The upper bound of the resulting reaction (default None). :type ub: float, optional :param sbo_term: 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). :type sbo_term: str, optional :returns: The created boundary reaction. :rtype: cobra.Reaction .. rubric:: 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 --> ' .. py:method:: add_reactions(reaction_list: Iterable[cobra.core.reaction.Reaction]) -> None 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. :param reaction_list: A list of `cobra.Reaction` objects :type reaction_list: list .. py:method:: remove_reactions(reactions: Union[str, cobra.core.reaction.Reaction, List[Union[str, cobra.core.reaction.Reaction]]], remove_orphans: bool = False) -> None Remove reactions from the model. The change is reverted upon exit when using the model as a context. :param reactions: 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. :type reactions: list or reaction or str :param remove_orphans: Remove orphaned genes and metabolites from the model as well (default False). :type remove_orphans: bool, optional .. py:method:: add_groups(group_list: Union[str, cobra.core.group.Group, List[cobra.core.group.Group]]) -> None 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. :param group_list: A list of `cobra.Group` objects to add to the model. Can also be a single group or a string representing group id. If the input is not a list, a warning is raised. :type group_list: list or str or Group .. py:method:: remove_groups(group_list: Union[str, cobra.core.group.Group, List[cobra.core.group.Group]]) -> None 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). :param group_list: A list of `cobra.Group` objects to remove from the model. Can also be a single group or a string representing group id. If the input is not a list, a warning is raised. :type group_list: list or str or Group .. py:method:: get_associated_groups(element: Union[cobra.core.reaction.Reaction, cobra.core.gene.Gene, cobra.core.metabolite.Metabolite]) -> List[cobra.core.group.Group] Get list of groups for element. Returns a list of groups that an element (reaction, metabolite, gene) is associated with. :param element: :type element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene` :returns: All groups that the provided object is a member of :rtype: list of `cobra.Group` .. py:method:: add_cons_vars(what: Union[List[cobra.util.solver.CONS_VARS], Tuple[cobra.util.solver.CONS_VARS]], **kwargs) -> None 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. :param what: The variables or constraints to add to the model. Must be of class `optlang.interface.Variable` or `optlang.interface.Constraint`. :type what: list or tuple of optlang variables or constraints. :param \*\*kwargs: Passed to solver.add() :type \*\*kwargs: keyword arguments .. py:method:: remove_cons_vars(what: Union[List[cobra.util.solver.CONS_VARS], Tuple[cobra.util.solver.CONS_VARS]]) -> None 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. :param what: The variables or constraints to add to the model. Must be of class `optlang.interface.Variable` or `optlang.interface.Constraint`. :type what: list or tuple of optlang variables or constraints. .. py:method:: _populate_solver(reaction_list: List[cobra.core.reaction.Reaction], metabolite_list: Optional[List[cobra.core.metabolite.Metabolite]] = None) -> None Populate attached solver with constraints and variables. Populate attached solver with constraints and variables that model the provided reactions. :param reaction_list: A list of cobra.Reaction to add to the solver. This list will be constrained. :type reaction_list: list :param metabolite_list: A list of cobra.Metabolite to add to the solver. This list will be constrained (default None). :type metabolite_list: list, optional .. py:method:: slim_optimize(error_value: Optional[float] = float('nan'), message: Optional[str] = None) -> float 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. :param error_value: The value to return if optimization failed due to e.g. infeasibility. If None, raise `OptimizationError` if the optimization fails (default float("nan")). :type error_value: float, None :param message: Error message to use if the model optimization did not succeed (default None). :type message: str, optional :returns: The objective value. Returns the error value if optimization failed and error_value was not None. :rtype: float :raises OptimizationError: If error_value was set as None and the optimization fails. .. py:method:: optimize(objective_sense: Optional[str] = None, raise_error: bool = False) -> cobra.Solution Optimize the model using flux balance analysis. :param objective_sense: Whether fluxes should be maximized or minimized. In case of None, the previous direction is used (default None). :type objective_sense: {None, 'maximize' 'minimize'}, optional :param raise_error: If true, raise an OptimizationError if solver status is not optimal (default False). :type raise_error: bool :rtype: Solution .. rubric:: 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. .. py:method:: repair(rebuild_index: bool = True, rebuild_relationships: bool = True) -> None Update all indexes and pointers in a model. :param rebuild_index: rebuild the indices kept in reactions, metabolites and genes :type rebuild_index: bool :param rebuild_relationships: reset all associations between genes, metabolites, model and then re-add them. :type rebuild_relationships: bool .. py:method:: summary(solution: Optional[cobra.Solution] = None, fva: Union[pandas.DataFrame, float, None] = None) -> cobra.summary.ModelSummary Create a summary of the exchange fluxes of the model. :param solution: A previous model solution to use for generating the summary. If ``None``, the summary method will generate a parsimonious flux distribution (default None). :type solution: cobra.Solution, optional :param fva: 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). :type fva: pd.DataFrame or float, optional :rtype: cobra.ModelSummary .. seealso:: :obj:`Reaction.summary`, :obj:`Metabolite.summary` .. py:method:: __enter__() -> Model 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. :rtype: cobra.Model .. py:method:: __exit__(type, value, traceback) -> None Pop the top context manager and trigger the undo functions. .. py:method:: merge(right: Model, prefix_existing: Optional[str] = None, inplace: bool = True, objective: str = 'left') -> Model 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. :param right: The model to add reactions from :type right: cobra.Model :param prefix_existing: Prefix the reaction identifier in the right that already exist in the left model with this string (default None). :type prefix_existing: string or optional :param inplace: 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). :type inplace: bool :param objective: 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"). :type objective: {"left", "right", "sum"} :returns: The merged model. :rtype: cobra.Model .. py:method:: _repr_html_() -> str Get HTML represenation of the model. :returns: Model representation as HTML string. :rtype: str