Skip to content

Joint, community, and SteadyCom flux balance

Two members of the E. coli core system that share a medium.

  • Class: CommunityFBASystem
  • Import: from skcomplex.systems.biology.ecology import CommunityFBASystem
  • Field: biology/ecology
  • Topics: community flux balance, SteadyCom, cross-feeding, linear program, metabolism, static
  • References:
    • Raman 2021
    • Khandelwal et al. 2013
    • Chan et al. 2017
    • Diener et al. 2020

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.biology.ecology import CommunityFBASystem

trajectory = CommunityFBASystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
knockouts ('ICDHyr', 'NH4t')
abundances (0.5, 0.5)
exchanges None
common_rate False
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time continuous, discrete, static
Space none
Laws equation
Randomness unknown
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class CommunityFBASystem(BaseSystem):
    """Two members of the E. coli core system that share a medium.

    It needs the extra `metabolism`.

    The programs of the members merge through a medium, and the joint program minimises the growth weighted by the
    abundances with its sign changed, recorded as `medium.objective_0` (Raman 2021, Section 11.1.3). By default one
    member lacks isocitrate dehydrogenase and takes up 2-oxoglutarate, and the other lacks ammonium transport and takes
    up glutamate, each from what the other secretes, so neither grows alone, and together both grow.
    `community_growth` gives SteadyCom and the cooperative trade-off of the same members. The pair is an illustration
    found on the E. coli core system: the consortium of Raman (Section 11.1.3.6) has four mutants that need amino
    acids, whose synthesis the core system does not hold.

    Args:
        knockouts:
            The reaction to close in each member, or the empty string for none.

        abundances:
            The abundance of each member.

        exchanges:
            The lower bound of the net exchange of the community, by reaction, or `None` for no net uptake of the
            cross-fed metabolites.

        common_rate:
            Whether the members grow at one specific rate, as in community FBA, rather than each at its own, as in joint
            FBA.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.ecology import CommunityFBASystem
        >>> trajectory = CommunityFBASystem().prepare().simulate(until=0.0)
        >>> round(-float(trajectory.get_values('medium.objective_0')[0]), 3)
        0.862
    """

    field = 'biology/ecology'
    topics = ('community flux balance', 'SteadyCom', 'cross-feeding', 'linear program', 'metabolism', 'static')
    references = ('Raman 2021', 'Khandelwal et al. 2013', 'Chan et al. 2017', 'Diener et al. 2020')
    until = 0.0

    def __init__(
        self,
        knockouts: Sequence[str] = ('ICDHyr', 'NH4t'),
        *,
        abundances: Sequence[float] = (0.5, 0.5),
        exchanges: Mapping[str, float] | None = None,
        common_rate: bool = False,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.knockouts = knockouts
        self.abundances = abundances
        self.exchanges = exchanges
        self.common_rate = common_rate

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of two members of the E. coli core system that share a medium.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        shared = dict(self.exchanges) if self.exchanges is not None else dict.fromkeys(CROSS_FED, 0.0)
        members, networks = [], []
        for position, knockout in enumerate(self.knockouts):
            network = load_network(
                'textbook',
                f'member_{position}',
                label=f'fba_{position}',
                needed_by='community_fba',
            ).set_params(objective={})
            values = network.get_values()
            for reaction in shared:
                if shared[reaction] >= 0:
                    values[f'lower_{network._get_identifier(reaction)}'] = OPEN_UPTAKE
            if knockout:
                identifier = network._get_identifier(knockout)
                values |= {f'lower_{identifier}': 0.0, f'upper_{identifier}': 0.0}
            members.append(MetabolicCellElement(network.cell, values=values))
            networks.append(network)
        joint = CommunityInteraction(
            'joint',
            members=tuple(member.label for member in members),
            medium='medium',
            abundances=tuple(self.abundances),
            exchanges=shared,
            growth=GROWTH,
            common_rate=self.common_rate,
        )
        self.system_ = System(
            self.label,
            elements=[*members, Element('medium', values=joint.get_values())],
            interactions=[*networks, joint],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • FluxBalanceInteraction, from Interaction
  • CommunityInteraction, from Interaction
class MetabolicCellElement(Element):
    """Cell whose values hold the fluxes, the bounds, and the gene switches of a metabolic network.

    It is drawn as the linear program of its network, and `FluxBalanceInteraction.get_values` gives its values.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, MetabolicCellElement
        >>> from skcomplex.systems.biology.common.metabolism import ReactionSpec
        >>> network = FluxBalanceInteraction('fba', reactions={'r': ReactionSpec({'A': -1.0})})
        >>> MetabolicCellElement('cell', values=network.get_values()).values['upper_r']
        1000.0
    """

    visual = VisualSpec('linear_program')

class Element(BaseElement):
    """An element that holds named values of one thing or of a group of members.

    It holds its values by name, such as the height and mass of a ball in
    `Element('ball', values={'x': 10.0, 'm': 1.0})`, and the laws of the interactions decide which values change. With
    `size` it holds a group of members with values of their own, such as 1000 molecules of a gas, and with `space` one
    member per site, such as the cells of a grid. A subclass may take its values as arguments of `__init__` instead,
    such as a population class with a growth rate. Members whose values change by agent rules, Python functions run for
    each member at each step, act as agents, and their values may be any Python object. It holds a prey population, a
    firm of an economy, and the charge of a capacitor.

    Read more in the user guide, under Elements.

    Args:
        label:
            The name of the element, unique among the components of its system, such as `'rabbits'`.

        values:
            Values by name, such as `{'x': 10.0, 'm': 1.0}`. A derivative or a past value that a law reads starts from
            the value named with primes or a past index, such as `{'x': 10.0, "x'": 3.0}` for a ball thrown upwards or
            `{'y': 1.0, 'y[-1]': 0.5}` for an economy. A group of members takes one value per member as an array.

        size:
            The number of members, each with its own values, such as `1000` molecules of a gas, or `None` for one.

        space:
            The space of the element, with one member per site, such as a lattice of cells, or `None` for none.

        on:
            The part of a network space that holds one member each: `'edges'` for every link, `'hyperedges'` for every
            hyperedge, the name of a layer for every link of that layer, such as `'immune'`, or `None` for every site.

    Attributes:
        default_visual_:
            How the element is drawn by default, the `visual` of its class.

    See Also:
        BaseElement: The base of every element.
        Interaction: States the laws that change the values of elements.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
        >>> ball.get_params()['x']
        10.0
    """

    law_classes: ClassVar[tuple[type, ...]] = ()

    def __init__(
        self,
        label: str,
        *,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
        on: str | None = None,
    ) -> None:
        super().__init__(label)
        self.values = values
        self.size = size
        self.space = space
        self.on: object = on

    def get_params(self, deep: bool = True) -> dict[str, Any]:
        """Return the parameters of the element, with each entry of `values` when deep.

        An entry of `values` whose name is a Python identifier is listed under its own name, so a system lists it as
        `<element>__<name>` and `set_params(ball__x=2.0)`, grid searches, and sweeps reach it. A primed or past value,
        such as `"x'"` or `'x[-1]'`, is no identifier and stays inside `values`. An entry that has the name of an
        argument is not listed twice.

        Args:
            deep:
                Whether to add the parameters of nested estimators and the entries of `values`.

        Returns:
            params:
                The parameters by name.

        Examples:
            >>> from skcomplex.core.components.elements import Element
            >>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
            >>> params['x'], "x'" in params
            (10.0, False)
        """
        params = super().get_params(deep=deep)
        if deep and isinstance(self.values, Mapping):
            entries = self._get_value_entries()
            params.update({name: value for name, value in entries.items() if name not in params})
        return params

    def set_params(self, **params: object) -> Self:
        """Set parameters of the element and entries of `values` by name.

        An entry of `values` takes its new value in a new mapping, so the mapping the user gave never changes, as
        `clone` of scikit-learn leaves the arguments of an estimator unchanged. A new `values` is set first, so the
        output of `get_params` is accepted as it is.

        Args:
            **params:
                The new values, by the name of a parameter or of an entry of `values`, such as `x=2.0`.

        Returns:
            self:
                The element.

        Examples:
            >>> from skcomplex.core.components.elements import Element
            >>> values = {'x': 10.0}
            >>> Element('ball', values=values).set_params(x=2.0).values, values
            ({'x': 2.0}, {'x': 10.0})
        """
        arguments = super().get_params(deep=True)
        if 'values' in params:
            super().set_params(values=params['values'])
        entries = self._get_value_entries()
        changed = {name: value for name, value in params.items() if name in entries and name not in arguments}
        rest = {name: value for name, value in params.items() if name not in changed and name != 'values'}
        super().set_params(**rest)
        if changed:
            self.values = {**(self.values or {}), **changed}
        return self

    def _get_value_entries(self) -> dict[str, object]:
        """Return the entries of `values` whose names are Python identifiers."""
        values = self.values if isinstance(self.values, Mapping) else {}
        return {name: value for name, value in values.items() if name.isidentifier()}

    def _prepare(self, context: BaseSpace | None = None) -> None:
        """Set `default_visual_`, checking the reserved names.

        Args:
            context:
                The space the element inherits from its system, which an element with `on` and no space of its own
                sits on.

        Raises:
            ValidationError:
                `size` is not a number of members, `space` is not a space, or `values` is not a mapping, as when a
                subclass stores a quantity of its own under a reserved name.
        """
        super()._prepare(context)
        size = self.size
        checks = {
            'size': size is None or (isinstance(size, numbers.Integral) and not isinstance(size, bool) and size >= 1),
            'space': self.space is None or isinstance(self.space, BaseSpace),
            'values': self.values is None or isinstance(self.values, Mapping),
        }
        for name, valid in checks.items():
            if not valid:
                error_msg = (
                    f'Element {self.label!r} has {name} = {getattr(self, name)!r}, but {name} is the '
                    f'{RESERVED_MEANINGS[name]}. The names {", ".join(RESERVED)} are reserved, so rename the value, '
                    f'such as half_side for the half side of a table.'
                )
                raise ValidationError(error_msg)
        self._check_on(self.space if self.space is not None else context)

    def _get_tags(self) -> Tags:
        """Return the tags of the element, with the tags of its space when it has one.

        A field on a phase space thus asks for a solver that supports phase spaces, as a group on it does.
        """
        tags = super()._get_tags()
        if not isinstance(self.space, BaseSpace):
            return tags
        return replace(tags, space=self.space.get_tags().space)

    def _check_on(self, space: BaseSpace | None) -> None:
        """Raise an error for an `on` that names no part of a network space.

        A value named `on` that the element declares as its own state or parameter names no place. The space is the
        element's own, or else that of its system.
        """
        if isinstance(type(self)._get_specs().get('on'), _StateSpec | _ParameterSpec):
            return
        on = getattr(self, 'on', None)
        if on is None or (isinstance(space, NetworkSpace) and (on in LINKS or on in space.prepare().graphs_)):
            return
        error_msg = (
            f'Element {self.label!r} has on = {on!r}, but on is the part of a network space that holds one member '
            "each, 'edges', 'hyperedges', or the name of a layer for its edges, such as "
            "Element('links', values={'sign': 1}, space=network, on='edges'). The names "
            f'{", ".join(RESERVED)} are reserved, so rename a value of the element named on, such as closed for a '
            'switch.'
        )
        raise ValidationError(error_msg)

    @staticmethod
    def _get_domain_of(annotation: object, value: object) -> object:
        """Return the domain of a value from its annotation or its Python type.

        A value without an annotation, such as one given through `values`, takes the domain of its type, so `3` is an
        integer and `0.5 + 1j` is complex. The annotation `object` says nothing of the kind, so a value annotated so,
        such as a point that may be one number or an array of complex numbers, also takes the domain of its type, and
        so does a value of one of several types, such as `float | Sequence[float]`. A subshift, such as
        `Annotated[int, SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))]`, is the domain of the cells of a
        lattice whose configurations hold no forbidden word.
        """
        if get_origin(annotation) is Annotated:
            for item in get_args(annotation)[1:]:
                if isinstance(item, set | frozenset):
                    return FiniteEnumeratedSet(sorted(item, key=str))
                allowed = hasattr(item, '__contains__') and not isinstance(item, str | MatrixGroupSpec)
                if allowed or isinstance(item, SubshiftSpec | PowerSeriesSpec):
                    return item
            annotation = get_args(annotation)[0]
        annotated = isinstance(annotation, type) and annotation not in {inspect.Parameter.empty, object}
        kind = annotation if annotated else type(value)
        if kind is bool:
            return BOOLEAN
        if kind is int:
            return ZZ
        if kind is complex or (isinstance(kind, type) and issubclass(kind, np.complexfloating)):
            return CC
        return RR

    def _get_domain_tags(self) -> frozenset[str]:
        """Return the domain tags of the states of the element.

        An element that declares no states has the domains of all its numeric values, since the laws of the system
        decide which of them are states, such as `boolean` for `opinion: Annotated[int, {0, 1}] = 0`.
        """
        if self._get_component_specs():
            return super()._get_domain_tags()
        params = self.get_params(deep=False)
        values = {name: params.get(name) for name in self._get_hints()}
        values |= {name: value for name, value in (self.values or {}).items() if name.isidentifier()}
        hints = self._get_hints()
        domains = {
            _StateSpec(domain=self._get_domain_of(hints.get(name, inspect.Parameter.empty), value))._get_domain_tag()
            for name, value in values.items()
            if isinstance(value, numbers.Number | list | np.ndarray)
        }
        return frozenset(domain for domain in domains if domain is not None)

    def _get_hints(self) -> dict[str, object]:
        """Return the type hint of every value argument by name, in their order.

        The hints are the annotations of the arguments of the class, such as `Annotated[float, Quantity('energy')]`,
        from which the kind, the allowed values, the quantity, and the period of each value are read. A generic
        subclass that takes its values through `values` gives their hints here instead, and the arguments it leaves
        out, such as the allowed values themselves, are no values.
        """
        parameters = inspect.signature(type(self)).parameters
        return {name: parameter.annotation for name, parameter in parameters.items() if name not in RESERVED}

    @classmethod
    def _get_view(cls) -> type | None:
        """Return the class of the views of the element's agents.

        The result is `None` for the engine's plain view. An agent element names a subclass of the engine's `AgentView`
        that annotates its states and parameters, such as `class WordView(AgentView): count: float`, so its rules read
        them with checked types.
        """
        return None

class FluxBalanceInteraction(Interaction):
    """Flux balance of a metabolic network, which sets its fluxes to the best ones its balances and bounds allow.

    A network is a set of reactions, each with the coefficients of its metabolites, its bounds, and the rule of the
    genes that make its enzymes. The interaction sets the flux `v_<reaction>` of its cell, one per reaction, to the
    optimum of a linear program: every metabolite balances, `sum_r S_mr v_r = 0`, every flux stays between the values
    `lower_<reaction>` and `upper_<reaction>` of the cell, and the weighted sum of the fluxes of `objective` is
    greatest (Raman 2021, Eq. 8.9). A reaction whose rule is false, read from the switches `g_<gene>` of the cell,
    carries no flux. The program is solved at every time of a run, so the network also drives a culture that changes
    in time, and `get_values` gives the values the cell starts with.

    Args:
        label:
            The label of the interaction.

        cell:
            The path of the cell whose values hold the fluxes, the bounds, and the switches.

        reactions:
            The reactions by name.

        objective:
            The coefficient of every reaction in the objective, or nothing for a network whose fluxes another objective
            chooses, such as the growth of a community.

        parsimonious:
            Whether to minimise the total absolute flux after the objective.

        infeasible:
            What a run does when the balances and bounds cannot all hold: `'raise'`, `'zero'` to set the fluxes to
            zero, or `'hold'` to keep their last values.

        name:
            The name of the network, or `None` for none.

        biomass:
            The path of the biomass that `threshold` reads, or `None` for none.

        threshold:
            The biomass above which the program is solved, or `None` for always. The fluxes are zero elsewhere, as at
            the empty boxes of a plate.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec
        >>> reactions = {'uptake': ReactionSpec({'A': 1.0}, upper=4.0), 'use': ReactionSpec({'A': -1.0})}
        >>> fba = FluxBalanceInteraction('fba', cell='cell', reactions=reactions, objective={'use': 1.0})
        >>> cell = Element('cell', values=fba.get_values())
        >>> trajectory = System(elements=[cell], interactions=[fba]).prepare().simulate(until=0.0)
        >>> float(trajectory.get_values('cell.v_use')[0])
        4.0
    """

    def __init__(
        self,
        label: str = 'fba',
        *,
        cell: Role = 'cell',
        reactions: Mapping[str, ReactionSpec] = NO_REACTIONS,
        objective: Mapping[str, float] = NO_OBJECTIVE,
        parsimonious: bool = False,
        infeasible: str = 'raise',
        name: str | None = None,
        biomass: Role | None = None,
        threshold: float | None = None,
    ) -> None:
        super().__init__(label)
        self.cell = cell
        self.reactions = reactions
        self.objective = objective
        self.parsimonious = parsimonious
        self.infeasible = infeasible
        self.name = name
        self.biomass = biomass
        self.threshold = threshold

    @staticmethod
    @functools.cache
    def _get_rule_genes(rule: str) -> tuple[str, ...]:
        """Return the gene names in a rule, read once per rule.

        Compiling reads the rules of a network often.
        """
        if not rule.strip():
            return ()
        return tuple(node.id for node in ast.walk(ast.parse(rule, mode='eval')) if isinstance(node, ast.Name))

    @staticmethod
    def _get_identifier(name: str) -> str:
        """Return a name as a part of an identifier."""
        return re.sub(r'\W', '_', name)

    @classmethod
    def get_flux_name(cls, reaction: str) -> str:
        """Return the name of the value of the cell that holds the flux of a reaction.

        Args:
            reaction:
                The name of the reaction.

        Returns:
            name:
                The name of the value, such as `v_PGI` for the reaction `PGI`.
        """
        return f'v_{cls._get_identifier(reaction)}'

    @classmethod
    def get_gene_name(cls, gene: str) -> str:
        """Return the name of the value of the cell that holds the switch of a gene.

        Args:
            gene:
                The name of the gene.

        Returns:
            name:
                The name of the value, such as `g_b4025` for the gene `b4025`.
        """
        return f'g_{cls._get_identifier(gene)}'

    def get_genes_of(self) -> tuple[str, ...]:
        """Return the names of the genes that the rules of the reactions read.

        Returns:
            genes:
                The names, in the order the rules name them.
        """
        names = [name for reaction in self.reactions.values() for name in self._get_rule_genes(reaction.rule)]
        return tuple(dict.fromkeys(names))

    def get_values(self) -> dict[str, float]:
        """Return the values the cell of the network starts with.

        They are, for every reaction in order, its flux at zero and its bounds, and then the switch of every gene, on
        at 1.

        Returns:
            values:
                The values by name, such as `{'v_r': 0.0, 'lower_r': 0.0, 'upper_r': 1000.0, 'g_g': 1.0}`.

        Examples:
            >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec
            >>> reactions = {'r': ReactionSpec({'A': -1.0}, upper=4.0, rule='g')}
            >>> FluxBalanceInteraction('fba', reactions=reactions).get_values()
            {'v_r': 0.0, 'lower_r': 0.0, 'upper_r': 4.0, 'g_g': 1.0}
        """
        values = {}
        for reaction, spec in self.reactions.items():
            identifier = self._get_identifier(reaction)
            values[f'v_{identifier}'] = 0.0
            values[f'lower_{identifier}'] = float(spec.lower)
            values[f'upper_{identifier}'] = float(spec.upper)
        return values | dict.fromkeys(map(self.get_gene_name, self.get_genes_of()), 1.0)

    def _get_gate(self, cell: SimpleNamespace, rule: str) -> Expression | int:
        """Return the condition of a rule on the switches of its genes.

        A reaction without genes has the condition 1.
        """
        if not rule.strip():
            return 1
        return both(self._get_condition(cell, ast.parse(rule, mode='eval').body))

    def _get_condition(self, cell: SimpleNamespace, node: ast.expr) -> Expression:
        """Return the condition of a node of a rule."""
        if isinstance(node, ast.BoolOp):
            combine = both if isinstance(node.op, ast.And) else either
            return combine(*(self._get_condition(cell, item) for item in node.values))
        if isinstance(node, ast.Name):
            return getattr(cell, self.get_gene_name(node.id)) > SWITCH_THRESHOLD
        error_msg = f'A gene rule of {self.label} holds {ast.dump(node)}. Use gene names, `and`, `or`, and parentheses.'
        raise ValidationError(error_msg)

    def _get_balances(self, cell: SimpleNamespace) -> list[ConstraintLaw]:
        """Return the balance of every metabolite."""
        terms: dict[str, list[Expression]] = {}
        for reaction, spec in self.reactions.items():
            flux = getattr(cell, self.get_flux_name(reaction))
            for metabolite, coefficient in spec.coefficients.items():
                terms.setdefault(metabolite, []).append(float(coefficient) * flux)
        return [ConstraintLaw(sum(items[1:], items[0]) == 0) for items in terms.values()]

    def _get_bounds(self, cell: SimpleNamespace) -> list[ConstraintLaw]:
        """Return the lower and upper bound of every reaction, gated by its rule."""
        bounds = []
        for reaction, spec in self.reactions.items():
            flux = getattr(cell, self.get_flux_name(reaction))
            gate = self._get_gate(cell, spec.rule)
            identifier = self._get_identifier(reaction)
            bounds.append(ConstraintLaw(flux >= getattr(cell, f'lower_{identifier}') * gate))
            bounds.append(ConstraintLaw(flux <= getattr(cell, f'upper_{identifier}') * gate))
        return bounds

    def _get_objective(self, cell: SimpleNamespace, biomass: SimpleNamespace | None) -> ObjectiveLaw:
        """Return the objective of the network over its fluxes.

        It is the greatest weighted sum of `objective`, then the smallest total absolute flux for a parsimonious
        network, or any point that the balances and bounds allow for a network without an objective. With a threshold,
        it is sought only where the biomass lies above it.
        """
        active = None if self.threshold is None or biomass is None else biomass.x > float(self.threshold)
        fluxes = [getattr(cell, self.get_flux_name(name)) for name in self.reactions]
        values = []
        if self.objective:
            terms = [float(weight) * getattr(cell, self.get_flux_name(name)) for name, weight in self.objective.items()]
            values.append(-sum(terms[1:], terms[0]))
            if self.parsimonious:
                absolutes = [abs(flux) for flux in fluxes]
                values.append(sum(absolutes[1:], absolutes[0]))
        return ObjectiveLaw(values, fluxes, active=active, infeasible=self.infeasible)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the objective of the network with its balances and bounds.

        Args:
            context:
                The namespace of the cell and the biomass.
        """
        super()._prepare(context)
        laws: list[BaseLaw] = [*self._get_balances(context.cell), *self._get_bounds(context.cell)]
        self.laws_ = [*laws, self._get_objective(context.cell, None if self.biomass is None else context.biomass)]

class CommunityInteraction(Interaction):
    """Joint flux balance of a community, whose medium balances the exchanges of its members.

    The members share one program, which holds the objective of their growth, weighted by their abundances, and the
    medium holds the net exchange `u_<reaction>` of the community for every shared reaction, which `get_values` gives.

    Args:
        label:
            The label of the interaction.

        members:
            The paths of the cells whose values hold the fluxes of the members.

        medium:
            The path of the shared medium.

        abundances:
            The abundance of every member, which weighs its exchanges and its growth.

        exchanges:
            The lower bound of the net exchange of the community, by reaction.

        growth:
            The name of the reaction of growth of every member.

        common_rate:
            Whether every member grows at one specific rate, the balanced growth of community FBA (Raman 2021, Section
            11.1.3.2), rather than each at its own, as in joint FBA.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import CommunityInteraction
        >>> joint = CommunityInteraction('joint', members=['a', 'b'], medium='medium', exchanges={'EX_a': -10.0})
        >>> joint.get_values()
        {'u_EX_a': 0.0}
    """

    def __init__(
        self,
        label: str,
        *,
        members: tuple[Role, ...],
        medium: Role,
        abundances: Sequence[float] = (),
        exchanges: Mapping[str, float] | None = None,
        growth: str = 'Biomass_Ecoli_core',
        common_rate: bool = False,
    ) -> None:
        super().__init__(label)
        self.members = members
        self.medium = medium
        self.abundances = abundances
        self.exchanges = exchanges
        self.growth = growth
        self.common_rate = common_rate

    @staticmethod
    def get_state_name(reaction: str) -> str:
        """Return the name of the value of the medium that holds the net exchange of a reaction.

        Args:
            reaction:
                The name of the reaction.

        Returns:
            name:
                The name of the value, such as `u_EX_glc__D_e`.
        """
        return f'u_{FluxBalanceInteraction._get_identifier(reaction)}'

    def get_values(self) -> dict[str, float]:
        """Return the values the medium starts with, the net exchange of every reaction at zero.

        Returns:
            values:
                The values by name.
        """
        return dict.fromkeys(map(self.get_state_name, self.exchanges or {}), 0.0)

    def _get_weighted(self, members: Sequence[SimpleNamespace], reaction: str) -> Expression:
        """Return the sum over the members of the flux of a reaction.

        The flux of every member is weighted by its abundance.
        """
        name = FluxBalanceInteraction.get_flux_name(reaction)
        terms = [float(share) * getattr(member, name) for share, member in zip(self.abundances, members, strict=True)]
        return sum(terms[1:], terms[0])

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the objective that joins the members through the medium, with its balances.

        Args:
            context:
                The namespace of the members and the medium.
        """
        super()._prepare(context)
        targets = []
        laws: list[BaseLaw] = []
        for reaction, floor in (self.exchanges or {}).items():
            state = getattr(context.medium, self.get_state_name(reaction))
            targets.append(state)
            laws += [
                ConstraintLaw(state == self._get_weighted(context.members, reaction)),
                ConstraintLaw(state >= float(floor)),
            ]
        name = FluxBalanceInteraction.get_flux_name(self.growth)
        growth = [getattr(member, name) for member in context.members]
        if self.common_rate:
            laws += [ConstraintLaw(item == growth[0]) for item in growth[1:]]
        objective = -self._get_weighted(context.members, self.growth)
        self.laws_ = [*laws, ObjectiveLaw([objective], [*targets, *growth])]