micom.community =============== .. py:module:: micom.community .. autoapi-nested-parse:: A class representing a microbial or tissue community. Attributes ---------- .. autoapisummary:: micom.community.logger Classes ------- .. autoapisummary:: micom.community.Community Module Contents --------------- .. py:data:: logger .. py:class:: Community(taxonomy: pandas.DataFrame, model_db: Union[str, pathlib.Path] = None, host_db: Dict[str, pathlib.Path] = None, id: str = None, name: str = None, rel_threshold: float = 1e-06, solver: str = None, progress: bool = True, max_exchange: float = 100.0, mass: float = 1.0) Bases: :py:obj:`cobra.Model` A community of models. This class represents a community of individual models. It was designed for microbial communities but may also be used for multi-tissue or tissue-cell mixture models as long as all individuals exist within a single enclosing compartment. .. py:attribute:: solver :value: None 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:attribute:: _rtol :value: 1e-06 .. py:attribute:: _modification :value: None .. py:attribute:: host :value: [] .. py:attribute:: mass :value: 1.0 .. py:attribute:: max_exchange :value: 100.0 .. py:attribute:: __db_metrics :value: None .. py:attribute:: __taxonomy .. py:attribute:: taxa :value: [] .. py:attribute:: 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:method:: __add_model(model, taxon_id) Add a new model to the community. .. py:method:: __add_exchanges(reactions, coef, external_compartment='e', internal_exchange=1000, environment_id='m', environment_name='medium') Add exchange reactions for a new model. .. py:method:: __update_exchanges(compartment='m') Update exchanges. .. py:method:: __update_community_objective() Update the community objective. .. py:method:: optimize_single(id) Optimize growth rate for one individual. `optimize_single` will calculate the maximal growth rate for one individual member of the community. .. rubric:: Notes This might well mean that growth rates for all other individuals are low since the individual may use up all available resources. :param id: The ID of the individual to be optimized. :type id: str :param fluxes: Whether to return all fluxes. Defaults to just returning the maximal growth rate. :type fluxes: boolean, optional :returns: The maximal growth rate for the given taxa. :rtype: float .. py:method:: optimize_all(progress=False) Return solutions for individually optimizing each model. .. rubric:: Notes This might well mean that growth rates for all other individuals are low since the individual may use up all available resources. As a consequence the reported growth rates may usually never be obtained all at once. :param progress: Whether to show a progress bar. :type progress: boolean, optional :returns: The maximal growth rate for each taxa. :rtype: pandas.Series .. py:method:: optimize(fluxes=False, pfba=False, raise_error=False, atol=None, rtol=None) Optimize the model using flux balance analysis. This is the primary accessor for optimization in MICOM and should be used for all optimizations. Different from cobrapy this will *not* return the full solution by default but only growth rates which is much quicker. You can request a full solution by setting the `fluxes` and `pFBA` arguments. :param raise_error: Should an error be raised if the solution is not optimal. Defaults to False which will either return a solution with a non-optimal status or None if optimization fails. :type raise_error: boolean, optional :param fluxes: Whether to return the fluxes as well. :type fluxes: boolean, optional :param pfba: Whether to obtain fluxes by parsimonious FBA rather than "classical" FBA. This is highly recommended. :type pfba: boolean, optional :param atol: Absolute tolerance for the growth rates. If None will use the solver tolerance. :type atol: float :param rtol: Relative tolerqance for the growth rates. If None will use the solver tolerance. :type rtol: float :returns: The solution after optimization or None if there is no optimum. :rtype: micom.CommunitySolution .. py:method:: optimize_host(fluxes=False, pfba=False, raise_error=False, atol=None, rtol=None) Maximize the host maintenance or growth rate. :param raise_error: Should an error be raised if the solution is not optimal. Defaults to False which will either return a solution with a non-optimal status or None if optimization fails. :type raise_error: boolean, optional :param fluxes: Whether to return the fluxes as well. :type fluxes: boolean, optional :param pfba: Whether to obtain fluxes by parsimonious FBA rather than "classical" FBA. This is highly recommended. :type pfba: boolean, optional :param atol: Absolute tolerance for the growth rates. If None will use the solver tolerance. :type atol: float :param rtol: Relative tolerqance for the growth rates. If None will use the solver tolerance. :type rtol: float :returns: **dict of str** -- The solution after optimization for each host tissue or None if there is no optimum. :rtype: micom.CommunitySolution .. py:property:: microbial_abundances The normalized abundances. Setting this attribute will also trigger the appropriate updates in the exchange fluxes and the community objective. :type: pandas.Series .. py:method:: set_microbial_abundance(value, normalize=True) Change abundances for one or more microbial taxa. :param value: The new abundances. Indices must me taxon IDs. :type value: pandas.Series :param normalize: Whether to normalize the *microbial* abundances to a total of 1.0. Many things in micom asssume that this is always the case. Only change this if you know what you are doing :O Host abundances are adjusted relative to this. :type normalize: boolean, optional .. py:property:: host_abundances The host abundances normalized to 1gDW of microbial biomass. Setting this attribute will also trigger the appropriate updates in the exchange fluxes and the community objective. :type: pandas.Series .. py:method:: set_host_abundance(value, normalize=True) Change abundances for one or more host tissues. :param value: The new abundances. Indices must me host IDs. :type value: pandas.Series :param normalize: Whether to normalize the *microbial* abundances to a total of 1.0. Many things in micom asssume that this is always the case. Only change this if you know what you are doing :O Host abundances are adjusted relative to this. :type normalize: boolean, optional .. py:property:: taxonomy The taxonomy used within the model. This attribute only returns a copy. :type: pandas.DataFrame .. py:property:: modification Denotes modifications to the model currently applied. Will be None if the community is unmodified. :type: str .. py:property:: exchanges Return all exchange reactions in the model. Uses several heuristics based on the reaction name and compartments to exclude reactions that are *not* exchange reactions. :type: list .. py:property:: internal_exchanges Return all internal exchanges. Internal exchanges are exchanges between individual taxa and the medium. :type: list .. py:property:: internal_reactions Return all internal reactions. Internal reactions are reactions that only involve metabolites from the inside of the organism and are not demands or sinks. :type: list .. py:property:: host_exchanges Return all host-side exchange reactions in the model. :type: list .. py:property:: medium Return the medium. .. py:property:: build_metrics Returns general metrics for database matching. Only available when built using a model database. :type: pd.Series .. py:method:: optcom(strategy='lagrangian', min_growth=0.0, fluxes=False, pfba=True) Run OptCom for the community. OptCom methods are a group of optimization procedures to find community solutions that provide a tradeoff between the cooperative community growth and the egoistic growth of each individual [#c1]_. `micom` provides several strategies that can be used to find optimal solutions: - "moma": Minimization of metabolic adjustment. Simultaneously optimizes the community objective (maximize) and the cooperativity cost (minimize). This method finds an exact maximum but doubles the number of required variables, thus being slow. - "lmoma": The same as "moma" only with a linear representation of the cooperativity cost (absolute value). - "original": Solves the multi-objective problem described in [#c1]_. Here, the community growth rate is maximized simultanously with all individual growth rates. Note that there are usually many Pareto-optimal solutions to this problem and the method will only give one solution. This is also the slowest method. :param community: The community to optimize. :type community: micom.Community :param strategy: The strategy used to solve the OptCom formulation. Defaults to "lagrangian" which gives a decent tradeoff between speed and correctness. :type strategy: str :param min_growth: The minimal growth rate required for each individual. May be a single value or an array-like object with the same length as there are individuals. :type min_growth: float or array-like :param fluxes: Whether to return the fluxes as well. :type fluxes: boolean :param pfba: Whether to obtain fluxes by parsimonious FBA rather than "classical" FBA. :type pfba: boolean :returns: The solution of the optimization. If fluxes==False will only contain the objective value, community growth rate and individual growth rates. :rtype: micom.CommunitySolution .. rubric:: References .. [#c1] OptCom: a multi-level optimization framework for the metabolic modeling and analysis of microbial communities. Zomorrodi AR, Maranas CD. PLoS Comput Biol. 2012 Feb;8(2):e1002363. doi: 10.1371/journal.pcbi.1002363, PMID: 22319433 .. py:method:: cooperative_tradeoff(min_growth=0.0, fraction=1.0, fluxes=False, pfba=False, atol=None, rtol=None) Find the best tradeoff between community and individual growth. Finds the set of growth rates which maintian a particular community growth and spread up growth across all taxa as much as possible. This is done by minimizing the L2 norm of the growth rates with a minimal community growth. :param min_growth: The minimal growth rate required for each individual. May be a single value or an array-like object with the same length as there are individuals. :type min_growth: float or array-like, optional :param fraction: The minum percentage of the community growth rate that has to be maintained. For instance 0.9 means maintain 90% of the maximal community growth rate. Defaults to 100%. :type fraction: float or list of floats in [0, 1] :param fluxes: Whether to return the fluxes as well. :type fluxes: boolean, optional :param pfba: Whether to obtain fluxes by parsimonious FBA rather than "classical" FBA. This is highly recommended. :type pfba: boolean, optional :param atol: Absolute tolerance for the growth rates. If None will use the solver tolerance. :type atol: float :param rtol: Relative tolerqance for the growth rates. If None will use the solver tolerance. :type rtol: float :returns: The solution of the optimization. If fluxes==False will only contain the objective value, community growth rate and individual growth rates. If more than one fraction value is given will return a pandas Series of solutions with the fractions as indices. :rtype: micom.CommunitySolution or pd.Series of solutions .. py:method:: knockout_taxa(taxa=None, fraction=1.0, method='change', progress=True, diag=True) Sequentially knockout a list of taxa in the model. This uses cooperative tradeoff as optimization criterion in order to get unqiue solutions for individual growth rates. Requires a QP solver to work. :param taxa: Names of taxa to be knocked out. :type taxa: str or list of strs :param fraction: Percentage of the maximum community growth rate that has to be maintained. Defaults to 100%. :type fraction: float in [0, 1], optional :param method: One of "raw", "change" or "relative change" that dictates whether to return the new growth rate (raw), the change in growth rate new - old or the relative change ([new - old] / old). :type method: str, optional :param progress: Whether to show a progress bar. On by default. :type progress: bool, optional :param diag: Whether the diagonal should contain values as well. If False will be filled with NaNs. :type diag: bool, optional :returns: A data frame with one row for each knockout and growth rates in the columns. Here the row name indicates which taxon has been knocked out and the columns contain the growth changes for all taxa in that knockout. :rtype: pandas.DataFrame .. py:property:: scale Get a scale to improve numerical properties. .. py:method:: to_pickle(filename: Union[str, pathlib.Path]) -> None Save a community in serialized form. :param filename: Where to save the pickled community. :type filename: str :rtype: Nothing .. py:method:: add_host(table: pandas.DataFrame, host_db: Dict[str, pathlib.Path], shared_compartment: str = 'l', own_compartment: str = 'e') Add a host model to the community. :param model: The host model to add to the community. :type model: str or cobra.Model :param table: A DataFrame containing the columns "id" and "abundance" and additional columns such as taxonomic ranks and or "file" denoting the location of the model. :type table: pandas.DataFrame :param shared_compartment: The id for the compartment that is shared with the microbes. For instance, the luminal side for an intestinal cell. :type shared_compartment: str :param own_compartment: The id for the compartment that is not shared with the microbes. The "other side". For instance, the blood stream for intestinal cells. :type own_compartment: str :param abundance: The abundance of the host **relative to 1gDW** bacteria. :type abundance: float .. py:property:: host_medium Return the medium for the host side. .. py:method:: add_coupling_constraints(ids=None, strategy='resource coupling', include_exchanges=False, constraint=1000.0, lower=1e-06) Add enzyme resource constraints. This will add constraints to the model that couple the enzyme usage to the growth rate or keep it constant. This is useful to model the fact that enzyme usage is proportional to the growth rate in many cases. The following strategie are available: resource constraint: The total flux is constrained to be below a certain threshold. .. math:: \sum_{i} |v_i| \leq ext{constraint} This is also known as resource allocation constraint [#c1]_. resource coupling: The total flux is constrained proportionally to the growth rate. .. math:: \sum_{i} |v_i| \leq ext{constraint} * \mu enzyme coupling: Individual enzyme usage is constrained by the growth rate except for a small maintenance flux. .. math:: |v_i| \leq ext{constraint} * \mu + ext{lower} This is the most commonly used version in the literature [#c2]_ but requires adding an additional constraint for each reaction which can be slow for large communities. .. note:: Usually one does not include exchanges in the resource constraints since they are not limited by enzyme availability (often passive transport). However, this can be changed by setting `include_exchanges` to True. The default value is based on Figure 6 of [#c1]_ which shows that for microbial communities a resource allocation constraint of 50 for a fixed gowth rate of 0.05 yields the largest alpha diversity. This corresponds to a constraint of 1000 for a growth rate of 1.0. :param strategy: The type of coupling to add. One of "resource constraint", "resource coupling", or "enzyme coupling". Defaults to "resource coupling". :type strategy: str :param ids: The taxa or host tissues to add the constraints for. If None will add constraints for all taxa and host tissues. :type ids: list of str, optional :param include_exchanges: Whether to include exchange reactions in the resource constraints. :type include_exchanges: bool :param constraint: The constraint on the total enzyme usage in mmol/gDW or mmol/gDW/h. :type constraint: float :param lower: A small lower bound for the enzyme usage. Only used for coupled enzyme usages. Can be used to model a small maintenance flux for enzymes. Defaults to no maintenance flux. :type lower: float :rtype: Nothing. Will add constraints to the model inplace. .. rubric:: References .. [#c1] Kim M, Sung J, Chia N. Resource-allocation constraint governs structure and function of microbial communities in metabolic modeling. Metab Eng. 2022;70: 12–22. doi:10.1016/j.ymben.2021.12.011 .. [#c2] Burgard AP, Nikolaev EV, Schilling CH, Maranas CD. Flux coupling analysis of genome-scale metabolic network reconstructions. Genome Res. 2004;14: 301–312. doi:10.1101/gr.1926504