:py:mod:`cobra` =============== .. py:module:: cobra Subpackages ----------- .. toctree:: :titlesonly: :maxdepth: 3 core/index.rst data/index.rst flux_analysis/index.rst io/index.rst manipulation/index.rst medium/index.rst sampling/index.rst summary/index.rst util/index.rst Submodules ---------- .. toctree:: :titlesonly: :maxdepth: 1 exceptions/index.rst Package Contents ---------------- Classes ~~~~~~~ .. autoapisummary:: cobra.Configuration cobra.DictList cobra.Gene cobra.Metabolite cobra.Model cobra.Object cobra.Reaction cobra.Solution cobra.Species Functions ~~~~~~~~~ .. autoapisummary:: cobra.show_versions Attributes ~~~~~~~~~~ .. autoapisummary:: cobra.__author__ cobra.__version__ .. py:data:: __author__ :value: 'The cobrapy core development team.' .. py:data:: __version__ :value: '0.27.0' .. py:class:: Configuration(**kwargs) Define a global configuration object. The attributes of this singleton object are used as default values by cobra functions. .. attribute:: solver The default solver for new models. The solver choices are the ones provided by `optlang` and depend on solvers installed in your environment. :type: {"glpk", "cplex", "gurobi", "glpk_exact"} .. attribute:: tolerance The default tolerance for the solver being used (default 1E-07). :type: float, optional .. attribute:: lower_bound The standard lower bound for reversible reactions (default -1000). :type: float, optional .. attribute:: upper_bound The standard upper bound for all reactions (default 1000). :type: float, optional .. attribute:: bounds The default reaction bounds for newly created reactions. The bounds are in the form of lower_bound, upper_bound (default -1000.0, 1000.0). :type: tuple of floats .. attribute:: processes A default number of processes to use where multiprocessing is possible. The default number corresponds to the number of available cores (hyperthreads) minus one. :type: int > 0 .. attribute:: cache_directory A path where the model cache should reside if caching is desired. The default directory depends on the operating system. :type: pathlib.Path or str, optional .. attribute:: max_cache_size The allowed maximum size of the model cache in bytes (default 1 GB). :type: int, optional .. attribute:: cache_expiration The expiration time in seconds for the model cache if any (default None). :type: int, optional .. py:property:: solver :type: types.ModuleType Return the optlang solver interface. .. py:property:: bounds :type: Tuple[Optional[numbers.Number], Optional[numbers.Number]] Return the lower, upper reaction bound pair. :returns: The lower and upper bounds for new reactions. :rtype: tuple of number and number or None and None .. py:property:: cache_directory :type: pathlib.Path Return the model cache directory. .. py:method:: _set_default_solver() -> None Set the default solver from a preferred order. .. py:method:: _set_default_processes() -> None Set the default number of processes. .. py:method:: _set_default_cache_directory() -> None Set the platform-dependent default cache directory. .. py:method:: __repr__() -> str Return a string representation of the current configuration values. .. py:method:: _repr_html_() -> str Return a rich HTML representation of the current configuration values. .. rubric:: Notes This special method is used automatically in Jupyter notebooks to display a result from a cell. .. py:class:: DictList(*args) Bases: :py:obj:`list` Define a combined dict and list. This object behaves like a list, but has the O(1) speed benefits of a dict when looking up elements by their id. .. py:method:: has_id(id: Union[cobra.core.object.Object, str]) -> bool Check if id is in DictList. .. py:method:: _check(id: Union[cobra.core.object.Object, str]) -> None Make sure duplicate id's are not added. This function is called before adding in elements. .. py:method:: _generate_index() -> None Rebuild the _dict index. .. py:method:: get_by_id(id: Union[cobra.core.object.Object, str]) -> cobra.core.object.Object Return the element with a matching id. .. py:method:: list_attr(attribute: str) -> list Return a list of the given attribute for every object. .. py:method:: get_by_any(iterable: List[Union[str, cobra.core.object.Object, int]]) -> list Get a list of members using several different ways of indexing. :param iterable: list where each element is either int (referring to an index in in this DictList), string (a id of a member in this DictList) or member of this DictList for pass-through :type iterable: list (if not, turned into single element list) :returns: a list of members :rtype: list .. py:method:: query(search_function: Union[str, Pattern, Callable], attribute: Union[str, None] = None) -> DictList Query the list. :param search_function: Used to find the matching elements in the list. - a regular expression (possibly compiled), in which case the given attribute of the object should match the regular expression. - a function which takes one argument and returns True for desired values :type search_function: a string, regular expression or function :param attribute: the name attribute of the object to passed as argument to the `search_function`. If this is None, the object itself is used. :type attribute: string or None :returns: a new list of objects which match the query :rtype: DictList .. rubric:: Examples >>> from cobra.io import load_model >>> model = load_model('textbook') >>> model.reactions.query(lambda x: x.boundary) >>> import re >>> regex = re.compile('^g', flags=re.IGNORECASE) >>> model.metabolites.query(regex, attribute='name') .. py:method:: _replace_on_id(new_object: cobra.core.object.Object) -> None Replace an object by another with the same id. .. py:method:: append(entity: cobra.core.object.Object) -> None Append object to end. .. py:method:: union(iterable: Iterable[cobra.core.object.Object]) -> None Add elements with id's not already in the model. .. py:method:: extend(iterable: Iterable[cobra.core.object.Object]) -> None Extend list by appending elements from the iterable. Sometimes during initialization from an older pickle, _dict will not have initialized yet, because the initialization class was left unspecified. This is an issue because unpickling calls DictList.extend, which requires the presence of _dict. Therefore, the issue is caught and addressed here. :param iterable: :type iterable: Iterable .. py:method:: _extend_nocheck(iterable: Iterable[cobra.core.object.Object]) -> None Extend without checking for uniqueness. This function should only be used internally by DictList when it can guarantee elements are already unique (as in when coming from self or other DictList). It will be faster because it skips these checks. :param iterable: :type iterable: Iterable .. py:method:: __sub__(other: Iterable[cobra.core.object.Object]) -> DictList Remove a value or values, and returns the new DictList. x.__sub__(y) <==> x - y :param other: other must contain only unique id's present in the list :type other: iterable :returns: **total** -- new DictList with item(s) removed :rtype: DictList .. py:method:: __isub__(other: Iterable[cobra.core.object.Object]) -> DictList Remove a value or values in place. x.__sub__(y) <==> x -= y :param other: other must contain only unique id's present in the list :type other: iterable .. py:method:: __add__(other: Iterable[cobra.core.object.Object]) -> DictList Add item while returning a new DictList. x.__add__(y) <==> x + y :param other: other must contain only unique id's which do not intersect with self :type other: iterable .. py:method:: __iadd__(other: Iterable[cobra.core.object.Object]) -> DictList Add item while returning the same DictList. x.__iadd__(y) <==> x += y :param other: other must contain only unique id's whcih do not intersect with self :type other: iterable .. py:method:: __reduce__() -> Tuple[Type[DictList], Tuple, dict, Iterator] Return a reduced version of DictList. This reduced version details the class, an empty Tuple, a dictionary of the state and an iterator to go over the DictList. .. py:method:: __getstate__() -> dict Get internal state. This is only provided for backwards compatibility so older versions of cobrapy can load pickles generated with cobrapy. In reality, the "_dict" state is ignored when loading a pickle .. py:method:: __setstate__(state: dict) -> None Pretend to set internal state. Actually recalculates. Ignore the passed in state and recalculate it. This is only for compatibility with older pickles which did not correctly specify the initialization class .. py:method:: index(id: Union[str, cobra.core.object.Object], *args) -> int Determine the position in the list. :param id: :type id: A string or a :class:`~cobra.core.Object.Object` .. py:method:: __contains__(entity: Union[str, cobra.core.object.Object]) -> bool Ask if the DictList contain an entity. DictList.__contains__(entity) <==> entity in DictList :param entity: :type entity: str or :class:`~cobra.core.Object.Object` .. py:method:: __copy__() -> DictList Copy the DictList into a new one. .. py:method:: insert(index: int, entity: cobra.core.object.Object) -> None Insert entity before index. .. py:method:: pop(*args) -> cobra.core.object.Object Remove and return item at index (default last). .. py:method:: add(x: cobra.core.object.Object) -> None Opposite of `remove`. Mirrors set.add. .. py:method:: remove(x: Union[str, cobra.core.object.Object]) -> None .. warning :: Internal use only. Each item is unique in the list which allows this It is much faster to do a dict lookup than n string comparisons .. py:method:: reverse() -> None Reverse *IN PLACE*. .. py:method:: sort(cmp: Callable = None, key: Callable = None, reverse: bool = False) -> None Stable sort *IN PLACE*. cmp(x, y) -> -1, 0, 1 .. py:method:: __getitem__(i: Union[int, slice, Iterable, cobra.core.object.Object, DictList]) -> Union[DictList, cobra.core.object.Object] Get item from DictList. .. py:method:: __setitem__(i: Union[slice, int], y: Union[list, cobra.core.object.Object]) -> None Set an item via index or slice. :param i: i can be slice or int. If i is a slice, y needs to be a list :type i: slice, int :param y: Object to set as :type y: list, Object .. py:method:: __delitem__(index: int) -> None Remove item from DictList. .. py:method:: __getslice__(i: int, j: int) -> DictList Get a slice from it to j of DictList. .. py:method:: __setslice__(i: int, j: int, y: Union[list, cobra.core.object.Object]) -> None Set slice, where y is an iterable. .. py:method:: __delslice__(i: int, j: int) -> None Remove slice. .. py:method:: __getattr__(attr: Any) -> Any Get an attribute by id. .. py:method:: __dir__() -> list Directory of the DictList. Override this to allow tab complete of items by their id. :returns: **attributes** -- A list of attributes/entities. :rtype: list .. py:class:: Gene(id: str = None, name: str = '', functional: bool = True) Bases: :py:obj:`cobra.core.species.Species` A Gene in a cobra model. :param id: The identifier to associate the gene with :type id: string :param name: A longer human readable name for the gene :type name: string :param functional: Indicates whether the gene is functional. If it is not functional then it cannot be used in an enzyme complex nor can its products be used. :type functional: bool .. py:property:: functional :type: bool Flag indicating if the gene is functional. Changing the flag is reverted upon exit if executed within the model as context. .. py:method:: knock_out() -> None Knockout gene by marking it as non-functional. Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero. The change is reverted upon exit if executed within the model as context. .. py:method:: _repr_html_() .. py:class:: Metabolite(id: Optional[str] = None, formula: Optional[str] = None, name: Optional[str] = '', charge: Optional[float] = None, compartment: Optional[str] = None) Bases: :py:obj:`cobra.core.species.Species` Class for information about metabolite in cobra.Reaction. Metabolite is a class for holding information regarding a metabolite in a cobra.Reaction object. :param id: the identifier to associate with the metabolite :type id: str :param formula: Chemical formula (e.g. H2O) :type formula: str :param name: A human readable name. :type name: str :param charge: The charge number of the metabolite :type charge: float :param compartment: Compartment of the metabolite. :type compartment: str or None .. py:property:: constraint :type: optlang.interface.Container Get the constraints associated with this metabolite from the solver. :returns: the optlang constraint for this metabolite :rtype: optlang..Containter .. py:property:: elements :type: Optional[Dict[str, Union[int, float]]] Get dicitonary of elements and counts. Dictionary of elements as keys and their count in the metabolite as integer. When set, the `formula` property is updated accordingly. :returns: **composition** -- A dictionary of elements and counts, where count is int unless it is needed to be a float. Returns None in case of error. :rtype: None or Dict .. py:property:: formula_weight :type: Union[int, float] Calculate the formula weight. :returns: Weight of formula, based on the weight and count of elements. Can be int if the formula weight is a whole number, but unlikely. :rtype: float, int .. py:property:: y :type: float Return the shadow price for the metabolite in the most recent solution. Shadow prices are computed from the dual values of the bounds in the solution. .. deprecated :: Use metabolite.shadow_price instead. :returns: Float representing the shadow price. :rtype: float .. py:property:: shadow_price :type: float Return the shadow price for the metabolite in the most recent solution. Shadow price is the dual value of the corresponding constraint in the model. :returns: **shadow_price** :rtype: float .. warning:: * Accessing shadow prices through a `Solution` object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples. * Shadow price is retrieved from the currently defined `self._model.solver`. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for. * If you modify the underlying model after an optimization, you will retrieve the old optimization values. :raises RuntimeError: If the underlying model was never optimized beforehand or the metabolite is not part of a model. :raises OptimizationError: If the solver status is anything other than 'optimal'. .. rubric:: Examples >>> from cobra.io import load_model >>> model = load_model("textbook") >>> solution = model.optimize() >>> model.metabolites.glc__D_e.shadow_price -0.09166474637510488 >>> solution.shadow_prices.glc__D_e -0.091664746375104883 .. py:method:: _set_id_with_model(value: str) -> None Set id with value. :param value: :type value: str .. py:method:: remove_from_model(destructive: bool = False) -> None Remove the association from self.model. The change is reverted upon exit when using the model as a context. :param destructive: If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model. :type destructive: bool, default False .. py:method:: summary(solution: Optional[cobra.core.Solution] = None, fva: Optional[Union[float, pandas.DataFrame]] = None) -> cobra.summary.MetaboliteSummary Create a summary of the producing and consuming fluxes. :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: pandas.DataFrame or float, optional :rtype: cobra.summary.MetaboliteSummary .. seealso:: :obj:`Reaction.summary`, :obj:`Model.summary` .. py:method:: _repr_html_() -> str Return the metabolite as an HTML string. .. 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 .. py:class:: Object(id: Optional[str] = None, name: str = '') Defines common behavior of object in cobra.core. .. py:property:: id :type: str Get the Object id. :returns: **id** :rtype: str .. py:property:: annotation :type: dict Get annotation dictionary. :returns: **_annotation** -- Returns _annotation as a dictionary. :rtype: dict .. py:method:: _set_id_with_model(value) -> None Set id with model. This appears to be a stub so it can be modified in dependant classes. :param value: The string to set the id to. :type value: str .. py:method:: __getstate__() -> dict Get state of annotation. To prevent excessive replication during deepcopy, ignores _model in state. :returns: **state** -- Dictionary of state, excluding _model. :rtype: dict .. py:method:: __repr__() -> str Return string representation of Object, with class. :returns: Composed of class.name, id and hexadecimal of id. :rtype: str .. py:method:: __str__() -> str Return string representation of object. :returns: Object.id as string. :rtype: str .. py:class:: Reaction(id: Optional[str] = None, name: str = '', subsystem: str = '', lower_bound: float = 0.0, upper_bound: Optional[float] = None, **kwargs) Bases: :py:obj:`cobra.core.object.Object` Define the cobra.Reaction class. Reaction is a class for holding information regarding a biochemical reaction in a cobra.Model object. Reactions are by default irreversible with bounds `(0.0, cobra.Configuration().upper_bound)` if no bounds are provided on creation. To create an irreversible reaction use `lower_bound=None`, resulting in reaction bounds of `(cobra.Configuration().lower_bound, cobra.Configuration().upper_bound)`. :param id: The identifier to associate with this reaction (default None). :type id: str, optional :param name: A human readable name for the reaction (default ""). :type name: str, optional :param subsystem: Subsystem where the reaction is meant to occur (default ""). :type subsystem: str, optional :param lower_bound: The lower flux bound (default 0.0). :type lower_bound: float :param upper_bound: The upper flux bound (default None). :type upper_bound: float, optional :param \*\*kwargs: Further keyword arguments are passed on to the parent class. .. py:property:: reverse_id :type: str Generate the id of reverse_variable from the reaction's id. :returns: The original id, joined to the word reverse and a partial hash of the utf-8 encoded id. :rtype: str .. py:property:: flux_expression :type: Optional[optlang.interface.Variable] Get Forward flux expression. :returns: **flux_expression** -- The expression representing the the forward flux (if associated with model), otherwise None. Representing the net flux if model.reversible_encoding == 'unsplit' or None if reaction is not associated with a model :rtype: optlang.interface.Variable, optional .. py:property:: forward_variable :type: Optional[optlang.interface.Variable] Get an optlang variable representing the forward flux. :returns: An optlang variable for the forward flux or None if reaction is not associated with a model. :rtype: optlang.interface.Variable, optional .. py:property:: reverse_variable :type: Optional[optlang.interface.Variable] Get an optlang variable representing the reverse flux. :returns: An optlang variable for the reverse flux or None if reaction is not associated with a model. :rtype: optlang.interface.Variable, optional .. py:property:: objective_coefficient :type: float Get the coefficient for this reaction in a linear objective (float). Assuming that the objective of the associated model is summation of fluxes from a set of reactions, the coefficient for each reaction can be obtained individually using this property. A more general way is to use the `model.objective` property directly. :returns: Linear coefficient if this reaction has any, or 0.0 otherwise. :rtype: float :raises AttributeError: If the model of the reaction is missing (None). .. py:property:: lower_bound :type: float Get the lower bound. :returns: The lower bound of the reaction. :rtype: float .. py:property:: upper_bound :type: float Get the upper bound. :returns: The upper bound of the reaction. :rtype: float .. py:property:: bounds :type: Tuple[float, float] Get or the bounds. :returns: **tuple** -- A tuple of floats, representing the lower and upper bound. :rtype: lower_bound, upper_bound .. py:property:: flux :type: float Get the flux value in the most recent solution. Flux is the primal value of the corresponding variable in the model. :returns: **flux** -- Flux is the primal value of the corresponding variable in the model. :rtype: float .. warning:: * Accessing reaction fluxes through a `Solution` object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples. * Reaction flux is retrieved from the currently defined `self._model.solver`. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for. * If you modify the underlying model after an optimization, you will retrieve the old optimization values. :raises RuntimeError: If the underlying model was never optimized beforehand or the reaction is not part of a model. :raises OptimizationError: If the solver status is anything other than 'optimal'. :raises AssertionError: If the flux value is not within the bounds. .. rubric:: Examples >>> from cobra.io import load_model >>> model = load_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.flux 7.477381962160283 >>> solution.fluxes.PFK 7.4773819621602833 .. py:property:: reduced_cost :type: float Get the reduced cost in the most recent solution. Reduced cost is the dual value of the corresponding variable in the model. :returns: **reducd_cost** -- A float representing the reduced cost. :rtype: float .. warning:: * Accessing reduced costs through a `Solution` object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples. * Reduced cost is retrieved from the currently defined `self._model.solver`. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for. * If you modify the underlying model after an optimization, you will retrieve the old optimization values. :raises RuntimeError: If the underlying model was never optimized beforehand or the reaction is not part of a model. :raises OptimizationError: If the solver status is anything other than 'optimal'. .. rubric:: Examples >>> from cobra.io import load_model >>> model = load_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.reduced_cost -8.673617379884035e-18 >>> solution.reduced_costs.PFK -8.6736173798840355e-18 .. py:property:: metabolites :type: Dict[cobra.core.metabolite.Metabolite, float] Get a dictionary of metabolites and coefficients. :returns: **metaoblites** -- A copy of self._metabolites, which is a dictionary of cobra.Metabolite for keys and floats for coeffecieints. Positive coefficient means the reaction produces this metabolite, while negative coefficient means the reaction consumes this metabolite. :rtype: Dict[Metabolite, float] .. py:property:: genes :type: FrozenSet Return the genes of the reaction. :returns: **genes** :rtype: FrozenSet .. py:property:: gene_reaction_rule :type: str See gene reaction rule as str. Uses the to_string() method of the GPR class :rtype: str .. py:property:: gene_name_reaction_rule Display gene_reaction_rule with names intead. Do NOT use this string for computation. It is intended to give a representation of the rule using more familiar gene names instead of the often cryptic ids. .. py:property:: gpr :type: cobra.core.gene.GPR Return the GPR associated with the reaction. :returns: **gpr** -- The GPR class, see cobra.core.gene.GPR() for details. :rtype: GPR .. py:property:: functional :type: bool All required enzymes for reaction are functional. :returns: True if the gene-protein-reaction (GPR) rule is fulfilled for this reaction, or if reaction is not associated to a model, otherwise False. :rtype: bool .. py:property:: x :type: float Get the flux through the reaction in the most recent solution. Flux values are computed from the primal values of the variables in the solution. :returns: * **flux** (*float*) -- Float representing the flux value. * *.. deprecated ::* * *Use reaction.flux instead.* .. py:property:: y :type: float Get the reduced cost of the reaction in the most recent solution. Reduced costs are computed from the dual values of the variables in the solution. :returns: * **flux** (*float*) -- Float representing the reduced cost value. * *.. deprecated ::* * *Use reaction.reduced_cost instead.* .. py:property:: reversibility :type: bool Whether the reaction can proceed in both directions (reversible). This is computed from the current upper and lower bounds. :returns: True if the reaction is reversible (lower bound lower than 0 and upper bound is higher than 0). :rtype: bool .. py:property:: boundary :type: bool Whether or not this reaction is an exchange reaction. :returns: **bool** :rtype: `True` if the reaction has either no products or reactants. .. py:property:: model :type: Optional[cobra.Model] Return the model the reaction is a part of. :returns: **model** -- The model this reaction belongs to. None if there is no model associated with this reaction. :rtype: cobra.Model, optional .. py:property:: reactants :type: List[cobra.core.metabolite.Metabolite] Return a list of reactants for the reaction. :returns: A list of the metabolites consudmed (coefficient < 0) by the reaction. :rtype: list .. py:property:: products :type: List[cobra.core.metabolite.Metabolite] Return a list of products for the reaction. :returns: A list of the metabolites produced (coefficient > 0) by the reaction. :rtype: list .. py:property:: reaction :type: str Return Human readable reaction str. :returns: The reaction in a human readble str. :rtype: str .. py:property:: compartments :type: Set Return set of compartments the metabolites are in. :returns: A set of compartments the metabolites are in. :rtype: set .. py:attribute:: __radd__ .. py:method:: _set_id_with_model(value: str) -> None Set Reaction id in model, check that it doesn't already exist. The function will rebuild the model reaction index. :param value: A string that represents the id. :type value: str :raises ValueError: If the model already contains a reaction with the id value. .. py:method:: __copy__() -> Reaction Copy the Reaction. :returns: A new reaction that is a copy of the original reaction. :rtype: Reaction .. py:method:: __deepcopy__(memo: dict) -> Reaction Copy the reaction with memo. :param memo: Automatically passed parameter. :type memo: dict :returns: A new reaction that is a deep copy of the original reaction with memo. :rtype: Reaction .. py:method:: _check_bounds(lb: float, ub: float) -> None :staticmethod: Check if the lower and upper bounds are valid. :param lb: The lower bound. :type lb: float :param ub: The upper bound. :type ub: float :raises ValueError: If the lower bound is higher than upper bound. .. py:method:: update_variable_bounds() -> None Update and correct variable bounds. Sets the forward_variable and reverse_variable bounds based on lower and upper bounds. This function corrects for bounds defined as inf or -inf. This function will also adjust the associated optlang variables associated with the reaction. .. seealso:: :obj:`optlang.interface.set_bounds` .. py:method:: update_genes_from_gpr() -> None Update genes of reation based on GPR. If the reaction has a model, and new genes appear in the GPR, they will be created as Gene() entities and added to the model. If the reaction doesn't have a model, genes will be created without a model. Genes that no longer appear in the GPR will be removed from the reaction, but not the model. If you want to remove them expliclty, use model.remove_genes(). .. py:method:: _update_awareness() -> None Update awareness for genes and metaoblites of the reaction. Make sure all metabolites and genes that are associated with this reaction are aware of it. .. py:method:: remove_from_model(remove_orphans: bool = False) -> None Remove the reaction from a model. This removes all associations between a reaction the associated model, metabolites and genes. The change is reverted upon exit when using the model as a context. :param remove_orphans: Remove orphaned genes and metabolites from the model as well (default False). :type remove_orphans: bool .. py:method:: delete(remove_orphans: bool = False) -> None Remove the reaction from a model. This removes all associations between a reaction the associated model, metabolites and genes. The change is reverted upon exit when using the model as a context. .. deprecated :: use `reaction.remove_from_model` instead. :param remove_orphans: Remove orphaned genes and metabolites from the model as well (default False). :type remove_orphans: bool .. py:method:: __getstate__() -> Dict Get state for reaction. This serializes the reaction object. The GPR will be converted to a string to avoid unneccessary copies due to interdependencies of used objects. :returns: The state/attributes of the reaction in serilized form. :rtype: dict .. py:method:: __setstate__(state: Dict) -> None Set state for reaction. Probably not necessary to set _model as the cobra.Model that contains self sets the _model attribute for all metabolites and genes in the reaction. However, to increase performance speed we do want to let the metabolite and gene know that they are employed in this reaction :param state: A dictionary of state, where keys are attribute names (str). Similar to __dict__. :type state: dict .. py:method:: copy() -> Reaction Copy a reaction. The referenced metabolites and genes are also copied. :returns: A copy of the Reaction. :rtype: cobra.Reaction .. py:method:: __add__(other: Reaction) -> Reaction Add two reactions and return a new one. The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction. Does not modify in place. :param other: Another reaction to add to the current one. :type other: cobra.Reaction :rtype: Reaction - new reaction with the added properties. .. py:method:: __iadd__(other: Reaction) -> Reaction Add two reactions in place and return the modified first one. The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction. Modifies in place. :param other: Another reaction to add to the current one. :type other: cobra.Reaction :rtype: Reaction - original reaction (self) with the added properties. .. py:method:: __sub__(other: Reaction) -> Reaction Subtract two reactions and return a new one. The stoichiometry will be the subtracted stoichiometry of the two reactions, and the gene_reaction_rule will be the gene_reaction_rule of the first reaction. All other attributes (i.e. reaction bounds) will match those of the first reaction. Does not modify in place. The name will still be that of the first reaction. :param other: The reaction to subtract from self. :type other: Reaction :rtype: Reaction - new reaction with the added properties. .. py:method:: __isub__(other: Reaction) -> Reaction Subtract metabolites of one reaction from another in place. The stoichiometry will be the metabolites of self minus the metabolites of the other. All other attributes including gene_reaction_rule (i.e. reaction bounds) will match those of the first reaction. Modifies in place and changes the original reaction. :param other: The reaction to subtract from self. :type other: Reaction :rtype: Reaction - self with the subtracted metabolites. .. py:method:: __imul__(coefficient: float) -> Reaction Scale coefficients in a reaction by a given value in place. E.g. A -> B becomes 2A -> 2B. If coefficient is less than zero, the reaction is reversed and the bounds are swapped. :param coefficient: Value to scale coefficients of metabolites by. If less than zero, reverses the reaction. :type coefficient: float :returns: Returns the same reaction modified in place. :rtype: Reaction .. py:method:: __mul__(coefficient: float) -> Reaction Scale coefficients in a reaction by a given value and return new reaction. E.g. A -> B becomes 2A -> 2B. If coefficient is less than zero, the reaction is reversed and the bounds are swapped. :param coefficient: Value to scale coefficients of metabolites by. If less than zero, reverses the reaction. :type coefficient: float :returns: Returns a new reaction, identical to the original except coefficients. :rtype: Reaction .. py:method:: get_coefficient(metabolite_id: Union[str, cobra.core.metabolite.Metabolite]) -> float Return the stoichiometric coefficient of a metabolite. :param metabolite_id: :type metabolite_id: str or cobra.Metabolite .. py:method:: get_coefficients(metabolite_ids: Iterable[Union[str, cobra.core.metabolite.Metabolite]]) -> Iterator[float] Return the stoichiometric coefficients for a list of metabolites. :param metabolite_ids: Containing ``str`` or ``cobra.Metabolite``s. :type metabolite_ids: iterable :returns: **map** -- Returns the result of map function, which is a map object (an Iterable). :rtype: Iterable .. py:method:: add_metabolites(metabolites_to_add: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) -> None Add metabolites and stoichiometric coefficients to the reaction. If the final coefficient for a metabolite is 0 then it is removed from the reaction. The change is reverted upon exit when using the model as a context. :param metabolites_to_add: Dictionary with metabolite objects or metabolite identifiers as keys and coefficients as values. If keys are strings (name of a metabolite) the reaction must already be part of a model and a metabolite with the given name must exist in the model. :type metabolites_to_add: dict :param combine: Describes behavior if a metabolite already exists in the reaction (default True). True causes the coefficients to be added. False causes the coefficient to be replaced. :type combine: bool :param reversibly: Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use). Default is True. :type reversibly: bool :raises KeyError: If the metabolite string id is not in the model. :raises ValueError: If the metabolite key in the dictionary is a string, and there is no model for the reaction. .. py:method:: subtract_metabolites(metabolites: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) -> None Subtract metabolites from a reaction. That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction. .. rubric:: Notes * A final coefficient < 0 implies a reactant. * The change is reverted upon exit when using the model as a context. :param metabolites: Dictionary where the keys are of class Metabolite and the values are the coefficients. These metabolites will be added to the reaction. :type metabolites: dict :param combine: Describes behavior if a metabolite already exists in the reaction (default True). True causes the coefficients to be added. False causes the coefficient to be replaced. :type combine: bool :param reversibly: Whether to add the change to the context to make the change reversibly or not ,primarily intended for internal use (default True). :type reversibly: bool .. py:method:: build_reaction_string(use_metabolite_names: bool = False) -> str Generate a human readable reaction str. :param use_metabolite_names: Whether to use metabolite names (when True) or metabolite ids (when False, default). :type use_metabolite_names: bool :returns: A human readable str. :rtype: str .. py:method:: check_mass_balance() -> Dict[str, float] Compute mass and charge balance for the reaction. :returns: a dict of {element: amount} for unbalanced elements. "charge" is treated as an element in this dict This should be empty for balanced reactions. :rtype: dict :raises ValueError: No elements were found in metabolite. .. py:method:: get_compartments() -> list List compartments the metabolites are in. :returns: * *list* -- A list of compartments the metabolites are in. * *.. deprecated ::* * *Use reaction.compartments() instead.* .. py:method:: _associate_gene(cobra_gene: cobra.core.gene.Gene) -> None Associates a cobra.Gene object with a cobra.Reaction. :param cobra_gene: :type cobra_gene: cobra.core.Gene.Gene .. py:method:: _dissociate_gene(cobra_gene: cobra.core.gene.Gene) -> None Dissociates a cobra.Gene object with a cobra.Reaction. :param cobra_gene: :type cobra_gene: cobra.core.Gene.Gene .. py:method:: knock_out() -> None Knockout reaction by setting its bounds to zero. .. py:method:: build_reaction_from_string(reaction_str: str, verbose: bool = True, fwd_arrow: Optional[AnyStr] = None, rev_arrow: Optional[AnyStr] = None, reversible_arrow: Optional[AnyStr] = None, term_split: str = '+') -> None Build reaction from reaction equation reaction_str using parser. Takes a string and using the specifications supplied in the optional arguments infers a set of metabolites, metabolite compartments and stoichiometries for the reaction. It also infers the reversibility of the reaction from the reaction arrow. Changes to the associated model are reverted upon exit when using the model as a context. :param reaction_str: a string containing a reaction formula (equation) :type reaction_str: str :param verbose: setting verbosity of function (default True) :type verbose: bool :param fwd_arrow: Str or bytes that encode forward irreversible reaction arrows (default None). :type fwd_arrow: AnyStr, optional :param rev_arrow: Str or bytes that encode backward irreversible reaction arrows (default None). :type rev_arrow: AnyStr, optional :param reversible_arrow: Str or bytes that encode reversible reaction arrows (default None). :type reversible_arrow: AnyStr, optional :param term_split: dividing individual metabolite entries (default "+")". :type term_split: str :raises ValueError: No arrow found in reaction string. .. py:method:: summary(solution: Optional[cobra.Solution] = None, fva: Optional[Union[float, pandas.DataFrame]] = None) -> cobra.summary.ReactionSummary Create a summary of the reaction flux. :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: pandas.DataFrame or float, optional :rtype: cobra.summary.ReactionSummary .. seealso:: :obj:`Metabolite.summary`, :obj:`Model.summary` .. py:method:: __str__() -> str Return reaction id and reaction as str. :returns: A string comprised out of reaction id and reaction. :rtype: str .. py:method:: _repr_html_() -> str Generate html representation of reaction. :returns: HTML representation of the reaction. :rtype: str .. py:class:: Solution(objective_value: float, status: str, fluxes: pandas.Series, reduced_costs: Optional[pandas.Series] = None, shadow_prices: Optional[pandas.Series] = None, **kwargs) A unified interface to a `cobra.Model` optimization solution. :param objective_value: The (optimal) value for the objective function. :type objective_value: float :param status: The solver status related to the solution. :type status: str :param fluxes: Contains the reaction fluxes (primal values of variables). :type fluxes: pandas.Series :param reduced_costs: Contains reaction reduced costs (dual values of variables) (default None). :type reduced_costs: pandas.Series :param shadow_prices: Contains metabolite shadow prices (dual values of constraints) (default None). :type shadow_prices: pandas.Series .. attribute:: objective_value The (optimal) value for the objective function. :type: float .. attribute:: status The solver status related to the solution. :type: str .. attribute:: fluxes Contains the reaction fluxes (primal values of variables). :type: pandas.Series .. attribute:: reduced_costs Contains reaction reduced costs (dual values of variables). :type: pandas.Series .. attribute:: shadow_prices Contains metabolite shadow prices (dual values of constraints). :type: pandas.Series .. rubric:: Notes Solution is meant to be constructed by `get_solution` please look at that function to fully understand the `Solution` class. .. py:attribute:: get_primal_by_id .. py:method:: __repr__() -> str Return a string representation of the solution instance. .. py:method:: _repr_html_() -> str Return a rich HTML representation of the solution. .. py:method:: __getitem__(reaction_id: str) -> float Return the flux of a reaction. :param reaction_id: A model reaction ID. :type reaction_id: str :returns: The flux of the reaction with ID `reaction_id`. :rtype: float .. py:method:: to_frame() -> pandas.DataFrame Return the fluxes and reduced costs as a pandas DataFrame. :returns: The fluxes and reduced cost. :rtype: pandas.DataFrame .. py:class:: Species(id: Optional[str] = None, name: Optional[str] = None, **kwargs) Bases: :py:obj:`cobra.core.object.Object` Species is a base class in Cobrapy. Species is a class for holding information regarding a chemical Species :param id: An identifier for the chemical species :type id: string :param name: A human readable name. :type name: string .. py:property:: reactions :type: FrozenSet Return a frozenset of reactions. :returns: A frozenset that includes the reactions of the species. :rtype: FrozenSet .. py:property:: model :type: Optional[cobra.Model] Return the model. :returns: Returns the cobra model that the species is associated with. None if there is no model associated with this species. :rtype: model .. py:method:: __getstate__() -> dict Return the state of the species. Remove the references to container reactions when serializing to avoid problems associated with recursion. :returns: A dictionary describing the state, without the self._reaction to avoid recursion. :rtype: dict .. py:method:: copy() -> Species Copy a species. When copying a reaction, it is necessary to deepcopy the components so the list references aren't carried over. Additionally, a copy of a reaction is no longer in a cobra.Model. This should be fixed with self.__deepcopy__ if possible :returns: A copy of the species. :rtype: Species .. py:function:: show_versions() -> None Print dependency information.