Regulatory flux balance analysis
A batch culture on glucose and acetate with Boolean catabolite repression.
- Class:
RegulatoryFBASystem - Import:
from skcomplex.systems.biology.systems_biology import RegulatoryFBASystem - Field:
biology/systems_biology - Topics:
regulatory flux balance,boolean network,linear program,metabolism,diauxie,co-simulation - References:
- Raman 2021
- Covert et al. 2001
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.systems_biology import RegulatoryFBASystem
trajectory = RegulatoryFBASystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
biomass |
0.01 |
glucose |
10.0 |
acetate |
10.0 |
threshold |
0.1 |
lag |
10 |
acetate_vmax |
10.0 |
km |
0.015 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | any |
| Space | none |
| Laws | equation, rate, update |
| Randomness | unknown |
| Domains | boolean, real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class RegulatoryFBASystem(BaseSystem):
"""A batch culture on glucose and acetate with Boolean catabolite repression.
It needs the extra.
Boolean rules alternate with the program (Raman 2021, Eq. 9.7). A node reads whether glucose lies above a threshold,
a chain of nodes delays it, and while the last node is on it holds the genes of acetate kinase off through update
laws. So the culture leaves acetate alone while glucose lasts, stops at depletion, and grows again on acetate after
the lag of the chain.
The alternation is that of Raman, but the rules are an illustration and not those of Covert et al. (2001): the genes
of acetate kinase, the threshold, and the chain of nodes come from no source, and the diauxie of Raman is on glucose
and lactose, which the E. coli core system cannot take up.
Args:
biomass:
The initial biomass in gDW per L.
glucose:
The initial glucose in mM.
acetate:
The initial acetate in mM.
threshold:
The glucose above which the sensor is on, in mM.
lag:
The number of nodes after the sensor, each a synchronisation interval of delay.
acetate_vmax:
The largest acetate uptake in mmol per gDW per h.
km:
The half-saturation concentration of both substrates in mM.
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.systems_biology import RegulatoryFBASystem
>>> [system.label for system in RegulatoryFBASystem(lag=1).prepare().system_.systems]
['control', 'culture']
"""
field = 'biology/systems_biology'
topics = ('regulatory flux balance', 'boolean network', 'linear program', 'metabolism', 'diauxie', 'co-simulation')
references = ('Raman 2021', 'Covert et al. 2001')
until = 8.0
dt = SYNCHRONISATION
def __init__(
self,
*,
biomass: float = 0.01,
glucose: float = 10.0,
acetate: float = 10.0,
threshold: float = 0.1,
lag: int = 10,
acetate_vmax: float = 10.0,
km: float = 0.015,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.biomass = biomass
self.glucose = glucose
self.acetate = acetate
self.threshold = threshold
self.lag = lag
self.acetate_vmax = acetate_vmax
self.km = km
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of a batch culture with Boolean catabolite repression.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
network = load_network('textbook', 'cell', needed_by='regulatory_fba').set_params(
parsimonious=True,
infeasible='zero',
)
identifier = network._get_identifier(ACETATE_EXCHANGE)
values = network.get_values() | {
f'lower_{identifier}': -float(self.acetate_vmax),
**{network.get_gene_name(gene): 0.0 for gene in ACETATE_GENES},
}
cell = MetabolicCellElement('cell', values=values)
nodes = [BooleanNodeElement(f'node_{position}', x=1) for position in range(self.lag + 1)]
chain = [
GlucoseSensorInteraction(
f'delay_{position}',
node=f'control/node_{position}',
source=f'control/node_{position - 1}',
)
for position in range(1, self.lag + 1)
]
self.system_ = System(
self.label,
systems=[
System('control', elements=[cell, *nodes], interactions=[network]),
System(
'culture',
elements=[
BiomassElement('biomass', x=self.biomass),
SubstrateElement('glucose', c=self.glucose),
SubstrateElement('acetate', c=self.acetate),
],
),
],
interactions=[
GlucoseSensorInteraction(
'sensor',
node='control/node_0',
source='culture/glucose',
threshold=self.threshold,
),
*chain,
SwitchInteraction(
'repression',
node=f'control/node_{self.lag}',
cell='control/cell',
genes=ACETATE_GENES,
),
ExchangeInteraction(
'glucose_uptake',
cell='control/cell',
biomass='culture/biomass',
substrate='culture/glucose',
reaction=GLUCOSE_EXCHANGE,
km=self.km,
interval=SYNCHRONISATION,
),
ExchangeInteraction(
'acetate_uptake',
cell='control/cell',
biomass='culture/biomass',
substrate='culture/acetate',
reaction=ACETATE_EXCHANGE,
vmax=self.acetate_vmax,
km=self.km,
interval=SYNCHRONISATION,
),
GrowthInteraction('growth', cell='control/cell', biomass='culture/biomass', reaction=GROWTH),
],
solver=CoSimulationSolver(sync_dt=SYNCHRONISATION, solvers={'culture': RK4Solver(dt=ODE_STEP)}),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
MetabolicCellElement, fromElementBooleanNodeElement, fromElementBiomassElement, fromElementSubstrateElement, fromElement
Interactions:
GlucoseSensorInteraction, fromInteractionSwitchInteraction, fromInteractionExchangeInteraction, fromInteractionGrowthInteraction, fromInteractionFluxBalanceInteraction, fromInteraction
class GlucoseSensorInteraction(Interaction):
"""Boolean node that reads whether a substrate lies above a threshold.
It reads the previous node instead when it belongs to a chain.
Args:
label:
The label of the interaction.
node:
The path of the Boolean node.
source:
The path of what the node reads: a substrate with a threshold, or a Boolean node without one.
threshold:
The concentration above which the node turns on, or `None` for a node that copies another.
Examples:
>>> from skcomplex.systems.biology.systems_biology import GlucoseSensorInteraction
>>> GlucoseSensorInteraction('sensor', node='a', source='glucose', threshold=0.1).threshold
0.1
"""
def __init__(
self,
label: str,
*,
node: Role = 'node',
source: Role = 'source',
threshold: float | None = None,
) -> None:
super().__init__(label)
self.node = node
self.source = source
self.threshold = threshold
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the update of the node.
Args:
context:
The namespace of the node and its source.
"""
super()._prepare(context)
if self.threshold is None:
self.laws_: list[BaseLaw] = [UpdateLaw(context.node.x, context.source.x)]
else:
self.laws_ = [UpdateLaw(context.node.x, where(context.source.c > float(self.threshold), 1, 0))]
class SwitchInteraction(Interaction):
"""Update of the switches of genes from a Boolean node that represses them.
Args:
label:
The label of the interaction.
node:
The path of the Boolean node, whose state `x` is 1 for on.
cell:
The path of the cell whose values hold the switches of the network.
genes:
The names of the genes the node represses.
Examples:
>>> from skcomplex.systems.biology.common.metabolism import SwitchInteraction
>>> SwitchInteraction('repression', node='node', cell='cell', genes=('b2296',)).genes
('b2296',)
"""
def __init__(
self,
label: str,
*,
node: Role = 'node',
cell: Role = 'cell',
genes: Sequence[str] = (),
) -> None:
super().__init__(label)
self.node = node
self.cell = cell
self.genes = genes
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the update of every switch.
Args:
context:
The namespace of the node and the cell.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [
UpdateLaw(getattr(context.cell, FluxBalanceInteraction.get_gene_name(gene)), 1 - context.node.x)
for gene in self.genes
]
class ExchangeInteraction(Interaction):
"""Exchange of a metabolite between a metabolic network and its medium.
The exchange is bounded by Michaelis-Menten uptake.
The law bounds the uptake, the negative flux of the exchange reaction, by `vmax c / (km + c)` and, with an interval,
by what the medium holds per biomass over the interval (Raman 2021, Section 9.6). The medium changes at the rate
`dc/dt = v x`, and a depleted medium loses nothing more.
Args:
label:
The label of the interaction.
cell:
The path of the cell whose values hold the fluxes of the network.
biomass:
The path of the biomass.
substrate:
The path of the metabolite.
reaction:
The name of the exchange reaction.
vmax:
The largest uptake.
km:
The half-saturation concentration.
interval:
The time over which the medium must last, or `None` for no such bound.
Examples:
>>> from skcomplex.systems.biology.common.metabolism import ExchangeInteraction
>>> ExchangeInteraction('uptake', reaction='EX_glc__D_e').vmax
10.0
"""
def __init__(
self,
label: str,
*,
cell: Role = 'cell',
biomass: Role = 'biomass',
substrate: Role = 'substrate',
reaction: str = 'EX_glc__D_e',
vmax: Annotated[float, POSITIVE] = 10.0,
km: Annotated[float, POSITIVE] = 0.015,
interval: float | None = None,
) -> None:
super().__init__(label)
self.cell = cell
self.biomass = biomass
self.substrate = substrate
self.reaction = reaction
self.vmax = vmax
self.km = km
self.interval = interval
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the bounds of the uptake and the rate of the medium.
Args:
context:
The namespace of the roles and parameters.
"""
super()._prepare(context)
flux = getattr(context.cell, FluxBalanceInteraction.get_flux_name(self.reaction))
amount, biomass = context.substrate.c, context.biomass.x
held = where(amount > 0, amount, 0)
laws: list[BaseLaw] = [ConstraintLaw(flux >= -context.vmax * held / (context.km + held), target=flux)]
if self.interval is not None:
laws.append(ConstraintLaw(flux >= -held / (biomass * float(self.interval)), target=flux))
laws.append(RateLaw(amount, flux * biomass * where(either(amount > 0, flux > 0), 1, 0)))
self.laws_ = laws
class GrowthInteraction(Interaction):
"""Growth of biomass at the rate a reaction of a metabolic network gives.
The biomass follows `dx/dt = v x`.
Args:
label:
The label of the interaction.
cell:
The path of the cell whose values hold the fluxes of the network.
biomass:
The path of the biomass.
reaction:
The name of the reaction of growth.
Examples:
>>> from skcomplex.systems.biology.common.metabolism import GrowthInteraction
>>> GrowthInteraction('growth', cell='cell', biomass='culture', reaction='grow').reaction
'grow'
"""
def __init__(
self,
label: str,
*,
cell: Role = 'cell',
biomass: Role = 'biomass',
reaction: str = 'Biomass_Ecoli_core',
) -> None:
super().__init__(label)
self.cell = cell
self.biomass = biomass
self.reaction = reaction
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the rate of the biomass.
Args:
context:
The namespace of the cell and the biomass.
"""
super()._prepare(context)
flux = getattr(context.cell, FluxBalanceInteraction.get_flux_name(self.reaction))
self.laws_: list[BaseLaw] = [RateLaw(context.biomass.x, flux * context.biomass.x)]
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 BooleanNodeElement(Element):
"""Node of a Boolean network, a gene or protein that is on or off.
Args:
label:
The label of the node.
x:
The initial value, 0 or 1.
Examples:
>>> from skcomplex.systems.biology.systems_biology import BooleanNodeElement
>>> BooleanNodeElement('Sic1', x=1).x
1
"""
def __init__(
self,
label: str,
*,
x: Annotated[float, FiniteEnumeratedSet([0, 1])] = 0,
) -> None:
super().__init__(label)
self.x = x
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 BiomassElement(Element):
"""Biomass of a culture, in gDW per L.
Args:
label:
The label of the element.
x:
The biomass in gDW per L.
values:
Further values by name.
size:
The number of members, or `None` for one.
space:
The space of the members, such as the plate of a culture with one biomass per cell, or `None`.
Examples:
>>> from skcomplex.systems.biology.common.metabolism import BiomassElement
>>> BiomassElement('culture', x=0.01).x
0.01
"""
def __init__(
self,
label: str,
*,
x: float | npt.ArrayLike = 0.01,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.x = x
class SubstrateElement(Element):
"""Concentration of a metabolite of a medium, in mM.
Args:
label:
The label of the element.
c:
The concentration in mM.
values:
Further values by name.
size:
The number of members, or `None` for one.
space:
The space of the members, such as the plate of a culture with one concentration per cell, or `None`.
Examples:
>>> from skcomplex.systems.biology.common.metabolism import SubstrateElement
>>> SubstrateElement('glucose', c=10.0).c
10.0
"""
def __init__(
self,
label: str,
*,
c: float | npt.ArrayLike = 10.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.c = c