Skip to content

Metabolism

Metabolism shared by the biology packages.

It covers metabolic networks, their standard formats, and their analyses.

BiomassElement(label, *, x=0.01, values=None, size=None, space=None)

Bases: Element

Biomass of a culture, in gDW per L.

Parameters:

Name Type Description Default
label str

The label of the element.

required
x float | ArrayLike

The biomass in gDW per L.

0.01
values Mapping[str, object] | None

Further values by name.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The space of the members, such as the plate of a culture with one biomass per cell, or None.

None

Examples:

>>> from skcomplex.systems.biology.common.metabolism import BiomassElement
>>> BiomassElement('culture', x=0.01).x
0.01
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
53
54
55
56
57
58
59
60
61
62
63
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

CobraMeasuresResult(network, system, ranges=None, fluxes=None, total=None, growth=None, pairs=None) dataclass

Result of a COBRApy method on a metabolic network.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance of the metabolic network.

required
system object

The cobra.Model of the network.

required
ranges DataFrame | None

The columns minimum and maximum of every reaction, for 'variability', or None.

None
fluxes Series | None

The flux of every reaction, for 'parsimonious', 'moma', and 'room', or None.

None
total float | None

The total absolute flux, for 'parsimonious', or None.

None
growth Series | float | None

The growth of every deletion, by the name of the gene or reaction or by a pair of names, for 'deletions', and the adjusted growth for 'moma' and 'room', or None.

None
pairs list[tuple[str, ...]] | None

The lethal pairs, for 'synthetic-lethals', or None.

None

CommunityGrowthResult(growth, abundances=None, members=None) dataclass

Growth of a community of metabolic networks that share a medium.

Parameters:

Name Type Description Default
growth float

The common growth rate, or the community growth rate of the trade-off.

required
abundances dict[str, float] | None

The abundance of every member, by its label, for 'steadycom', or None.

None
members dict[str, float] | None

The growth of every member, by its label, for 'tradeoff', or None.

None

CommunityInteraction(label, *, members, medium, abundances=(), exchanges=None, growth='Biomass_Ecoli_core', common_rate=False)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
members tuple[Role, ...]

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

required
medium Role

The path of the shared medium.

required
abundances Sequence[float]

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

()
exchanges Mapping[str, float] | None

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

None
growth str

The name of the reaction of growth of every member.

'Biomass_Ecoli_core'
common_rate bool

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.

False

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}
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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

get_state_name(reaction) staticmethod

Return the name of the value of the medium that holds the net exchange of a reaction.

Parameters:

Name Type Description Default
reaction str

The name of the reaction.

required

Returns:

Name Type Description
name str

The name of the value, such as u_EX_glc__D_e.

Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
287
288
289
290
291
292
293
294
295
296
297
298
299
@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)}'

get_values()

Return the values the medium starts with, the net exchange of every reaction at zero.

Returns:

Name Type Description
values dict[str, float]

The values by name.

Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
301
302
303
304
305
306
307
308
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)

ExchangeInteraction(label, *, cell='cell', biomass='biomass', substrate='substrate', reaction='EX_glc__D_e', vmax=10.0, km=0.015, interval=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cell Role

The path of the cell whose values hold the fluxes of the network.

'cell'
biomass Role

The path of the biomass.

'biomass'
substrate Role

The path of the metabolite.

'substrate'
reaction str

The name of the exchange reaction.

'EX_glc__D_e'
vmax Annotated[float, POSITIVE]

The largest uptake.

10.0
km Annotated[float, POSITIVE]

The half-saturation concentration.

0.015
interval float | None

The time over which the medium must last, or None for no such bound.

None

Examples:

>>> from skcomplex.systems.biology.common.metabolism import ExchangeInteraction
>>> ExchangeInteraction('uptake', reaction='EX_glc__D_e').vmax
10.0
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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

FluxBalanceInteraction(label='fba', *, cell='cell', reactions=NO_REACTIONS, objective=NO_OBJECTIVE, parsimonious=False, infeasible='raise', name=None, biomass=None, threshold=None)

Bases: 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.

Parameters:

Name Type Description Default
label str

The label of the interaction.

'fba'
cell Role

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

'cell'
reactions Mapping[str, ReactionSpec]

The reactions by name.

NO_REACTIONS
objective Mapping[str, float]

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.

NO_OBJECTIVE
parsimonious bool

Whether to minimise the total absolute flux after the objective.

False
infeasible str

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.

'raise'
name str | None

The name of the network, or None for none.

None
biomass Role | None

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

None
threshold float | None

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.

None

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
Source code in src/skcomplex/systems/biology/common/metabolism/_flux_balance.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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

get_flux_name(reaction) classmethod

Return the name of the value of the cell that holds the flux of a reaction.

Parameters:

Name Type Description Default
reaction str

The name of the reaction.

required

Returns:

Name Type Description
name str

The name of the value, such as v_PGI for the reaction PGI.

Source code in src/skcomplex/systems/biology/common/metabolism/_flux_balance.py
139
140
141
142
143
144
145
146
147
148
149
150
151
@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)}'

get_gene_name(gene) classmethod

Return the name of the value of the cell that holds the switch of a gene.

Parameters:

Name Type Description Default
gene str

The name of the gene.

required

Returns:

Name Type Description
name str

The name of the value, such as g_b4025 for the gene b4025.

Source code in src/skcomplex/systems/biology/common/metabolism/_flux_balance.py
153
154
155
156
157
158
159
160
161
162
163
164
165
@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)}'

get_genes_of()

Return the names of the genes that the rules of the reactions read.

Returns:

Name Type Description
genes tuple[str, ...]

The names, in the order the rules name them.

Source code in src/skcomplex/systems/biology/common/metabolism/_flux_balance.py
167
168
169
170
171
172
173
174
175
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))

get_values()

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:

Name Type Description
values dict[str, float]

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}
Source code in src/skcomplex/systems/biology/common/metabolism/_flux_balance.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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)

FluxVariabilityResult(network, system, optimum, ranges) dataclass

Range of every flux of a metabolic network at a fraction of its optimum.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance of the metabolic network.

required
system System

The system that holds the network.

required
optimum float

The optimum of the objective.

required
ranges DataFrame

The columns minimum and maximum of every reaction.

required

GrowthInteraction(label, *, cell='cell', biomass='biomass', reaction='Biomass_Ecoli_core')

Bases: Interaction

Growth of biomass at the rate a reaction of a metabolic network gives.

The biomass follows dx/dt = v x.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cell Role

The path of the cell whose values hold the fluxes of the network.

'cell'
biomass Role

The path of the biomass.

'biomass'
reaction str

The name of the reaction of growth.

'Biomass_Ecoli_core'

Examples:

>>> from skcomplex.systems.biology.common.metabolism import GrowthInteraction
>>> GrowthInteraction('growth', cell='cell', biomass='culture', reaction='grow').reaction
'grow'
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
128
129
130
131
132
133
134
135
136
137
138
139
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

MetabolicCellElement(label, *, values=None, size=None, space=None, on=None)

Bases: 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
Source code in src/skcomplex/core/components/elements/_element.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
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

ObjectiveFloorInteraction(label, *, cell='cell', weights=None, floor=0.0)

Bases: Interaction

Lower bound of the objective of a metabolic network as a whole.

The bound is c' v >= f (Raman 2021, Eq. 8.11d).

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
cell Role

The path of the cell whose values hold the fluxes of the network.

'cell'
weights Mapping[str, float] | None

The coefficient of every reaction in the objective.

None
floor float

The value the objective keeps.

0.0

Examples:

>>> from skcomplex.systems.biology.common.metabolism import ObjectiveFloorInteraction
>>> ObjectiveFloorInteraction('kept', weights={'grow': 1.0}, floor=0.5).floor
0.5
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
368
369
370
371
372
373
374
375
376
377
378
379
def __init__(
    self,
    label: str,
    *,
    cell: Role = 'cell',
    weights: Mapping[str, float] | None = None,
    floor: float = 0.0,
) -> None:
    super().__init__(label)
    self.cell = cell
    self.weights = weights
    self.floor = floor

ProductionScanResult(network, system, levels, objectives, fluxes, reactions) dataclass

Fluxes of a metabolic network at increasing levels of an enforced target flux.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance of the metabolic network.

required
system System

The system that holds the network.

required
levels Array

The enforced flux of every level.

required
objectives Array

The optimum of the objective at every level.

required
fluxes DataFrame

The fluxes by reaction, one row per reaction and one column per level.

required
reactions list[str]

The reactions whose absolute flux rises with every level.

required

ReactionSpec(coefficients, lower=0.0, upper=DEFAULT_BOUND, rule='') dataclass

Bases: BaseSpec

Reaction of a metabolic network.

It has its stoichiometry, its bounds, and the genes that gate them.

Parameters:

Name Type Description Default
coefficients Mapping[str, float]

The stoichiometric coefficient of every metabolite, negative for a reactant.

required
lower float

The lower bound of the flux.

0.0
upper float

The upper bound of the flux.

DEFAULT_BOUND
rule str

The gene rule, a Boolean expression of gene names with and, or, and parentheses, or the empty string for a reaction without genes.

''

Raises:

Type Description
ValidationError

The lower bound is above the upper bound, raised by prepare.

Examples:

>>> from skcomplex.systems.biology.common.metabolism import ReactionSpec
>>> ReactionSpec({'A': -1.0, 'B': 1.0}, rule='g1 or g2').upper
1000.0

StrainDesignResult(network, system, designs) dataclass

Strain designs of a metabolic network.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance of the metabolic network.

required
system object

The cobra.Model of the network.

required
designs list[set[str]]

Every design as a set of reaction names.

required

SubstrateElement(label, *, c=10.0, values=None, size=None, space=None)

Bases: Element

Concentration of a metabolite of a medium, in mM.

Parameters:

Name Type Description Default
label str

The label of the element.

required
c float | ArrayLike

The concentration in mM.

10.0
values Mapping[str, object] | None

Further values by name.

None
size int | None

The number of members, or None for one.

None
space BaseSpace | None

The space of the members, such as the plate of a culture with one concentration per cell, or None.

None

Examples:

>>> from skcomplex.systems.biology.common.metabolism import SubstrateElement
>>> SubstrateElement('glucose', c=10.0).c
10.0
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
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

SwitchInteraction(label, *, node='node', cell='cell', genes=())

Bases: Interaction

Update of the switches of genes from a Boolean node that represses them.

Parameters:

Name Type Description Default
label str

The label of the interaction.

required
node Role

The path of the Boolean node, whose state x is 1 for on.

'node'
cell Role

The path of the cell whose values hold the switches of the network.

'cell'
genes Sequence[str]

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',)
Source code in src/skcomplex/systems/biology/common/metabolism/_culture.py
417
418
419
420
421
422
423
424
425
426
427
428
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

ToyFluxBalanceInteraction(label='fba', *, cell='cell', reactions=TOY_REACTIONS, objective=TOY_OBJECTIVE, parsimonious=False, infeasible='raise', name='ToyNetwork')

Bases: FluxBalanceInteraction

Flux balance of the toy network of Table 8.2 of Raman (2021), which grows on A alone.

Parameters:

Name Type Description Default
label str

The label of the interaction.

'fba'
cell Role

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

'cell'
reactions Mapping[str, ReactionSpec]

The reactions by name.

TOY_REACTIONS
objective Mapping[str, float]

The coefficient of every reaction in the objective.

TOY_OBJECTIVE
parsimonious bool

Whether to minimise the total absolute flux after the objective.

False
infeasible str

What a run does when the balances and bounds cannot all hold.

'raise'
name str | None

The name of the network.

'ToyNetwork'

Examples:

>>> from skcomplex.systems.biology.common.metabolism import ToyFluxBalanceInteraction
>>> ToyFluxBalanceInteraction('fba').get_values()['upper_v1']
1000.0
Source code in src/skcomplex/systems/biology/common/metabolism/_toy_network.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    label: str = 'fba',
    *,
    cell: Role = 'cell',
    reactions: Mapping[str, ReactionSpec] = TOY_REACTIONS,
    objective: Mapping[str, float] = TOY_OBJECTIVE,
    parsimonious: bool = False,
    infeasible: str = 'raise',
    name: str | None = 'ToyNetwork',
) -> None:
    super().__init__(
        label,
        cell=cell,
        reactions=reactions,
        objective=objective,
        parsimonious=parsimonious,
        infeasible=infeasible,
        name=name,
    )

cobra_measures(source, *, kind='variability', fraction=1.0, target='gene', order=1, knockouts=(), linear=False, network=None)

Return the analysis of a metabolic network with COBRApy.

It needs the extra metabolism.

  • 'variability': the range of every flux at a fraction of the optimum.
  • 'parsimonious': the fluxes of the smallest total flux at the optimum.
  • 'deletions': the growth after single or double deletions of genes or reactions.
  • 'moma' and 'room': the fluxes of a knock-out adjusted against the wild-type solution.
  • 'synthetic-lethals': the pairs of genes or reactions lethal together, but not alone.

Parameters:

Name Type Description Default
source DataSource

The system that holds the metabolic network.

required
kind str

The analysis, one of the kinds above.

'variability'
fraction float

The fraction of the optimum for 'variability'.

1.0
target str

'gene' or 'reaction', what 'deletions' and 'synthetic-lethals' delete.

'gene'
order int

1 or 2, the size of the deletions.

1
knockouts Sequence[str]

The genes to knock out for 'moma' and 'room'.

()
linear bool

Whether to solve MoMA and ROOM in their linear forms, rather than the quadratic form of MoMA and the mixed-integer form of ROOM, with delta = 0.03 and epsilon = 0.001 (Raman 2021, Eqs. 9.1 and 9.5).

False
network str | None

The label of the network, or None for the first network of the system.

None

Returns:

Name Type Description
result CobraMeasuresResult

The network, its cobra.Model, and the values of the kind.

Raises:

Type Description
AnalysisError

The kind or the target is unknown, or the source is not a system with the network.

MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.common.metabolism import cobra_measures, load_network
>>> network = load_network('textbook', 'cell')
>>> system = System(elements=[Element('cell', values=network.get_values())], interactions=[network])
>>> round(float(cobra_measures(system, kind='parsimonious').total), 3)
518.422
Source code in src/skcomplex/systems/biology/common/metabolism/_analyses.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def cobra_measures(
    source: DataSource,
    *,
    kind: str = 'variability',
    fraction: float = 1.0,
    target: str = 'gene',
    order: int = 1,
    knockouts: Sequence[str] = (),
    linear: bool = False,
    network: str | None = None,
) -> CobraMeasuresResult:
    """Return the analysis of a metabolic network with COBRApy.

    It needs the extra `metabolism`.

    - `'variability'`: the range of every flux at a fraction of the optimum.
    - `'parsimonious'`: the fluxes of the smallest total flux at the optimum.
    - `'deletions'`: the growth after single or double deletions of genes or reactions.
    - `'moma'` and `'room'`: the fluxes of a knock-out adjusted against the wild-type solution.
    - `'synthetic-lethals'`: the pairs of genes or reactions lethal together, but not alone.

    Args:
        source:
            The system that holds the metabolic network.

        kind:
            The analysis, one of the kinds above.

        fraction:
            The fraction of the optimum for `'variability'`.

        target:
            `'gene'` or `'reaction'`, what `'deletions'` and `'synthetic-lethals'` delete.

        order:
            `1` or `2`, the size of the deletions.

        knockouts:
            The genes to knock out for `'moma'` and `'room'`.

        linear:
            Whether to solve MoMA and ROOM in their linear forms, rather than the quadratic form of MoMA and the
            mixed-integer form of ROOM, with `delta = 0.03` and `epsilon = 0.001` (Raman 2021, Eqs. 9.1 and 9.5).

        network:
            The label of the network, or `None` for the first network of the system.

    Returns:
        result:
            The network, its `cobra.Model`, and the values of the kind.

    Raises:
        AnalysisError:
            The kind or the target is unknown, or the source is not a system with the network.

        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import cobra_measures, load_network
        >>> network = load_network('textbook', 'cell')
        >>> system = System(elements=[Element('cell', values=network.get_values())], interactions=[network])
        >>> round(float(cobra_measures(system, kind='parsimonious').total), 3)
        518.422
    """
    _check_choice('cobra_measures', 'kind', kind, COBRA_KINDS)
    _check_choice('cobra_measures', 'target', target, ('gene', 'reaction'))
    load_extra(f'cobra_measures(kind={kind!r})')
    _, element, cell = _read_network(source, network, 'cobra_measures')
    model = to_cobra(element, cell, needed_by='cobra_measures')
    cobra = load_extra('cobra_measures')
    if kind == 'variability':
        table = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=fraction, processes=1)
        ranges = pd.DataFrame({'minimum': table['minimum'], 'maximum': table['maximum']})
        return CobraMeasuresResult(element, model, ranges=ranges)
    if kind == 'parsimonious':
        solution = cobra.flux_analysis.pfba(model)
        return CobraMeasuresResult(
            element,
            model,
            fluxes=solution.fluxes,
            total=float(solution.fluxes.abs().sum()),
        )
    if kind == 'deletions':
        return CobraMeasuresResult(element, model, growth=_deletions(model, target, int(order)))
    if kind in {'moma', 'room'}:
        fluxes, growth = _adjusted(model, kind, knockouts, linear=linear)
        return CobraMeasuresResult(element, model, fluxes=fluxes, growth=growth)
    alone = _deletions(model, target, 1)
    essential = set(alone.index[alone < LETHAL_GROWTH])
    together = _deletions(model, target, PAIR_SIZE)
    pairs = [
        pair
        for pair, growth in together.items()
        if isinstance(pair, tuple)
        and len(pair) == PAIR_SIZE
        and growth < LETHAL_GROWTH
        and not essential.intersection(pair)
    ]
    return CobraMeasuresResult(element, model, pairs=pairs)

community_growth(source, *, kind='steadycom', fraction=1.0, abundances=None, medium=None)

Return the growth of a community of metabolic networks that share a medium.

  • 'steadycom': the largest common growth rate of the members, after Chan et al. (2017), by a bisection on the rate with the solve of the core, without the extra. The fluxes of a member scale with its abundance, the abundances sum to at most 1, and a shared exchange of the medium stays above the bound that medium gives.
  • 'tradeoff': the cooperative trade-off of MICOM, which needs the extra metabolism.

Parameters:

Name Type Description Default
source DataSource

The system whose metabolic networks are the members.

required
kind str

The analysis, one of the kinds above.

'steadycom'
fraction float

The fraction of the community growth rate that the trade-off keeps.

1.0
abundances Sequence[float] | None

The abundance of every member for 'tradeoff', or None for equal ones.

None
medium Mapping[str, float] | None

The lower bound of every shared exchange of the whole community for 'steadycom', by reaction, or None for no shared bound.

None

Returns:

Name Type Description
result CommunityGrowthResult

The growth rate, and the abundances or the growth of every member.

Raises:

Type Description
AnalysisError

The kind is unknown, or the source is not a system with a metabolic network.

MissingExtraError

The kind 'tradeoff' needs the extra.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.common.metabolism import (
...     FluxBalanceInteraction,
...     ReactionSpec,
...     community_growth,
... )
>>> reactions = {
...     'EX_a': ReactionSpec({'a': 1.0}, upper=2.0),
...     'grow': ReactionSpec({'a': -1.0}),
... }
>>> networks = [
...     FluxBalanceInteraction(f'fba_{name}', cell=name, reactions=reactions, objective={'grow': 1.0})
...     for name in ('one', 'two')
... ]
>>> cells = [Element(network.cell, values=network.get_values()) for network in networks]
>>> result = community_growth(System(elements=cells, interactions=networks))
>>> round(result.growth, 6), round(sum(result.abundances.values()), 6)
(2.0, 1.0)
Source code in src/skcomplex/systems/biology/common/metabolism/_community.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def community_growth(
    source: DataSource,
    *,
    kind: str = 'steadycom',
    fraction: float = 1.0,
    abundances: Sequence[float] | None = None,
    medium: Mapping[str, float] | None = None,
) -> CommunityGrowthResult:
    """Return the growth of a community of metabolic networks that share a medium.

    - `'steadycom'`: the largest common growth rate of the members, after Chan et al. (2017), by a bisection on the rate
      with the solve of the core, without the extra. The fluxes of a member scale with its abundance, the abundances
      sum to at most 1, and a shared exchange of the medium stays above the bound that `medium` gives.
    - `'tradeoff'`: the cooperative trade-off of MICOM, which needs the extra `metabolism`.

    Args:
        source:
            The system whose metabolic networks are the members.

        kind:
            The analysis, one of the kinds above.

        fraction:
            The fraction of the community growth rate that the trade-off keeps.

        abundances:
            The abundance of every member for `'tradeoff'`, or `None` for equal ones.

        medium:
            The lower bound of every shared exchange of the whole community for `'steadycom'`, by reaction, or `None`
            for no shared bound.

    Returns:
        result:
            The growth rate, and the abundances or the growth of every member.

    Raises:
        AnalysisError:
            The kind is unknown, or the source is not a system with a metabolic network.

        MissingExtraError:
            The kind `'tradeoff'` needs the extra.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import (
        ...     FluxBalanceInteraction,
        ...     ReactionSpec,
        ...     community_growth,
        ... )
        >>> reactions = {
        ...     'EX_a': ReactionSpec({'a': 1.0}, upper=2.0),
        ...     'grow': ReactionSpec({'a': -1.0}),
        ... }
        >>> networks = [
        ...     FluxBalanceInteraction(f'fba_{name}', cell=name, reactions=reactions, objective={'grow': 1.0})
        ...     for name in ('one', 'two')
        ... ]
        >>> cells = [Element(network.cell, values=network.get_values()) for network in networks]
        >>> result = community_growth(System(elements=cells, interactions=networks))
        >>> round(result.growth, 6), round(sum(result.abundances.values()), 6)
        (2.0, 1.0)
    """
    _check_choice('community_growth', 'kind', kind, COMMUNITY_KINDS)
    if kind == 'tradeoff':
        load_extra(f'community_growth(kind={kind!r})')
    if isinstance(source, BaseSystem) and not isinstance(source, System):
        source = source.prepare().system_
    members = _get_members(source) if isinstance(source, System) else []
    if not members:
        error_msg = 'community_growth reads a system that holds the flux balance of a metabolic network.'
        raise AnalysisError(error_msg)
    if kind == 'steadycom':
        growth, found = _steadycom(members, medium)
        return CommunityGrowthResult(growth, abundances=found)
    growth, rates = _tradeoff(members, fraction, abundances)
    return CommunityGrowthResult(growth, members=rates)

flux_variability(source, *, fraction=1.0, network=None)

Return the range of every flux at an optimum.

The ranges come from the solve of the core, which runs without the extra.

Every flux is maximised and minimised with the objective kept at a fraction of its optimum, c' v >= f (Raman 2021, Eq. 8.11d). A network of a genome's size is faster with cobra_measures(system, kind='variability').

Parameters:

Name Type Description Default
source DataSource

The system that holds the metabolic network.

required
fraction float

The fraction of the optimum to keep.

1.0
network str | None

The label of the network, or None for the first network of the system.

None

Returns:

Name Type Description
result FluxVariabilityResult

The network, the optimum, and the range of every flux.

Raises:

Type Description
AnalysisError

The source is not a system with the network.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.common.metabolism import (
...     FluxBalanceInteraction,
...     ReactionSpec,
...     flux_variability,
... )
>>> reactions = {
...     'in': ReactionSpec({'A': 1.0}, upper=4.0),
...     'one': ReactionSpec({'A': -1.0}),
...     'two': ReactionSpec({'A': -1.0}),
... }
>>> network = FluxBalanceInteraction('fba', cell='net', reactions=reactions, objective={'in': 1.0})
>>> system = System(elements=[Element('net', values=network.get_values())], interactions=[network])
>>> flux_variability(system).ranges.loc['one'].tolist()
[0.0, 4.0]
Source code in src/skcomplex/systems/biology/common/metabolism/_analyses.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def flux_variability(source: DataSource, *, fraction: float = 1.0, network: str | None = None) -> FluxVariabilityResult:
    """Return the range of every flux at an optimum.

    The ranges come from the solve of the core, which runs without the extra.

    Every flux is maximised and minimised with the objective kept at a fraction of its optimum, `c' v >= f` (Raman 2021,
    Eq. 8.11d). A network of a genome's size is faster with `cobra_measures(system, kind='variability')`.

    Args:
        source:
            The system that holds the metabolic network.

        fraction:
            The fraction of the optimum to keep.

        network:
            The label of the network, or `None` for the first network of the system.

    Returns:
        result:
            The network, the optimum, and the range of every flux.

    Raises:
        AnalysisError:
            The source is not a system with the network.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import (
        ...     FluxBalanceInteraction,
        ...     ReactionSpec,
        ...     flux_variability,
        ... )
        >>> reactions = {
        ...     'in': ReactionSpec({'A': 1.0}, upper=4.0),
        ...     'one': ReactionSpec({'A': -1.0}),
        ...     'two': ReactionSpec({'A': -1.0}),
        ... }
        >>> network = FluxBalanceInteraction('fba', cell='net', reactions=reactions, objective={'in': 1.0})
        >>> system = System(elements=[Element('net', values=network.get_values())], interactions=[network])
        >>> flux_variability(system).ranges.loc['one'].tolist()
        [0.0, 4.0]
    """
    system, interaction, cell = _read_network(source, network, 'flux_variability')
    problem = _compiled_network(interaction, cell)
    optimum, _ = _solved(problem, interaction, cell)
    problem = _compiled_network(interaction, cell, floor=fraction * optimum)
    rows = {}
    for reaction in interaction.reactions:
        low = _solved(problem, interaction, cell, {reaction: 1.0}, sense=1.0)[0]
        high = _solved(problem, interaction, cell, {reaction: 1.0}, sense=-1.0)[0]
        rows[reaction] = (low, high)
    ranges = pd.DataFrame.from_dict(rows, orient='index', columns=['minimum', 'maximum'])
    return FluxVariabilityResult(interaction, system, optimum, ranges)

from_cobra(system, cell='network', *, label='fba', needed_by='from_cobra')

Return the flux balance of a COBRApy model.

The interaction keeps the reactions, bounds, rules, and objective of the model, and get_values gives the values of its cell.

Parameters:

Name Type Description Default
system object

The cobra.Model.

required
cell str

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

'network'
label str

The label of the interaction.

'fba'
needed_by str

The name of what needs the extra, for the error.

'from_cobra'

Returns:

Name Type Description
network FluxBalanceInteraction

The flux balance of the model.

Raises:

Type Description
MissingExtraError

The extra is not installed.

ValidationError

The system is not a cobra.Model.

Examples:

>>> import cobra
>>> from skcomplex.systems.biology.common.metabolism import from_cobra
>>> system = cobra.Model('one')
>>> reaction = cobra.Reaction('r', upper_bound=5.0)
>>> reaction.add_metabolites({cobra.Metabolite('a', compartment='c'): -1.0})
>>> system.add_reactions([reaction])
>>> from_cobra(system, 'cell').get_values()['upper_r']
5.0
Source code in src/skcomplex/systems/biology/common/metabolism/_cobra_io.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def from_cobra(
    system: object,
    cell: str = 'network',
    *,
    label: str = 'fba',
    needed_by: str = 'from_cobra',
) -> FluxBalanceInteraction:
    """Return the flux balance of a COBRApy model.

    The interaction keeps the reactions, bounds, rules, and objective of the model, and `get_values` gives the values
    of its cell.

    Args:
        system:
            The `cobra.Model`.

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

        label:
            The label of the interaction.

        needed_by:
            The name of what needs the extra, for the error.

    Returns:
        network:
            The flux balance of the model.

    Raises:
        MissingExtraError:
            The extra is not installed.

        ValidationError:
            The system is not a `cobra.Model`.

    Examples:
        >>> import cobra
        >>> from skcomplex.systems.biology.common.metabolism import from_cobra
        >>> system = cobra.Model('one')
        >>> reaction = cobra.Reaction('r', upper_bound=5.0)
        >>> reaction.add_metabolites({cobra.Metabolite('a', compartment='c'): -1.0})
        >>> system.add_reactions([reaction])
        >>> from_cobra(system, 'cell').get_values()['upper_r']
        5.0
    """
    cobra = load_extra(needed_by)
    if not isinstance(system, cobra.Model):
        error_msg = f'from_cobra converts a `cobra.Model`, not a {type(system).__name__}.'
        raise ValidationError(error_msg)
    reactions = {
        reaction.id: ReactionSpec(
            {metabolite.id: float(value) for metabolite, value in reaction.metabolites.items()},
            float(reaction.lower_bound),
            float(reaction.upper_bound),
            reaction.gene_reaction_rule,
        )
        for reaction in system.reactions
    }
    objective = {
        reaction.id: float(reaction.objective_coefficient)
        for reaction in system.reactions
        if reaction.objective_coefficient != 0
    }
    name = ''.join(part.capitalize() for part in str(system.id or 'network').split('_'))
    return FluxBalanceInteraction(
        label,
        cell=cell,
        reactions=reactions,
        objective=objective,
        name=FluxBalanceInteraction._get_identifier(name),
    )

load_extra(owner)

Return COBRApy, the first library of the extra metabolism.

Parameters:

Name Type Description Default
owner str

The name of the class, function, or system that needs the extra, for the error.

required

Returns:

Name Type Description
cobra ModuleType

The module.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.systems.biology.common.metabolism import load_extra
>>> load_extra('example').__name__
'cobra'
Source code in src/skcomplex/systems/biology/common/metabolism/_cobra_io.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def load_extra(owner: str) -> ModuleType:
    """Return COBRApy, the first library of the extra `metabolism`.

    Args:
        owner:
            The name of the class, function, or system that needs the extra, for the error.

    Returns:
        cobra:
            The module.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import load_extra
        >>> load_extra('example').__name__
        'cobra'
    """
    if sys.platform == 'linux':
        # Once GAP has run, loading libSBML the usual way binds it to a library of GAP, and its parser crashes.
        flags = sys.getdlopenflags()
        sys.setdlopenflags(flags | os.RTLD_DEEPBIND)
        try:
            import_extra('libsbml', owner, 'metabolism')
        finally:
            sys.setdlopenflags(flags)
    return import_extra('cobra', owner, 'metabolism')

load_network(source=BUNDLED_SYSTEM, cell='network', *, label='fba', needed_by='load_network')

Return the flux balance of a network in a file or of a BiGG identifier.

The file is an SBML or BiGG JSON file.

Parameters:

Name Type Description Default
source str | Path

The path of a .xml, .sbml, or .json file, a BiGG identifier, which COBRApy downloads, or 'textbook' for the E. coli core system it bundles.

BUNDLED_SYSTEM
cell str

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

'network'
label str

The label of the interaction.

'fba'
needed_by str

The name of what needs the extra, for the error.

'load_network'

Returns:

Name Type Description
network FluxBalanceInteraction

The flux balance of the network.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.systems.biology.common.metabolism import load_network
>>> len(load_network('textbook', 'cell').reactions)
95
Source code in src/skcomplex/systems/biology/common/metabolism/_cobra_io.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def load_network(
    source: str | Path = BUNDLED_SYSTEM,
    cell: str = 'network',
    *,
    label: str = 'fba',
    needed_by: str = 'load_network',
) -> FluxBalanceInteraction:
    """Return the flux balance of a network in a file or of a BiGG identifier.

    The file is an SBML or BiGG JSON file.

    Args:
        source:
            The path of a `.xml`, `.sbml`, or `.json` file, a BiGG identifier, which COBRApy downloads, or `'textbook'`
            for the E. coli core system it bundles.

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

        label:
            The label of the interaction.

        needed_by:
            The name of what needs the extra, for the error.

    Returns:
        network:
            The flux balance of the network.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import load_network
        >>> len(load_network('textbook', 'cell').reactions)
        95
    """
    cobra = load_extra(needed_by)
    path = Path(source)
    if path.suffix == '.json':
        return from_cobra(cobra.io.load_json_model(str(path)), cell, label=label)
    if path.suffix in {'.xml', '.sbml'}:
        return from_cobra(cobra.io.read_sbml_model(str(path)), cell, label=label)
    if str(source) == BUNDLED_SYSTEM:
        return from_cobra(cobra.io.load_model(BUNDLED_SYSTEM), cell, label=label)
    repository = cobra.io.web.load.BiGGModels()
    repository._url = repository.url.copy_with(scheme='https')
    return from_cobra(cobra.io.load_model(str(source), repositories=[repository]), cell, label=label)

production_scan(source, *, target='', steps=10, network=None)

Return the scan of fluxes with enforced objective flux (FSEOF).

The scan comes from the solve of the core, without the extra.

The target flux is enforced at increasing levels from its value at the optimum to its maximum, and every level maximises the objective, with the total absolute flux minimised after it. The scan reports the reactions whose absolute flux rises with every level.

Parameters:

Name Type Description Default
source DataSource

The system that holds the metabolic network.

required
target str

The reaction whose flux the scan enforces.

''
steps int

The number of levels.

10
network str | None

The label of the network, or None for the first network of the system.

None

Returns:

Name Type Description
result ProductionScanResult

The levels, the objective and the fluxes of every level, and the reactions whose flux rises.

Raises:

Type Description
AnalysisError

The source is not a system with the network, or the network holds no target reaction.

Examples:

>>> from skcomplex.core.components.elements import Element
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.common.metabolism import (
...     FluxBalanceInteraction,
...     ReactionSpec,
...     production_scan,
... )
>>> reactions = {
...     'in': ReactionSpec({'A': 1.0}, upper=4.0),
...     'grow': ReactionSpec({'A': -1.0}),
...     'make': ReactionSpec({'A': -1.0, 'P': 1.0}),
...     'out': ReactionSpec({'P': -1.0}),
... }
>>> network = FluxBalanceInteraction('fba', cell='net', reactions=reactions, objective={'grow': 1.0})
>>> system = System(elements=[Element('net', values=network.get_values())], interactions=[network])
>>> production_scan(system, target='out', steps=2).reactions
['make', 'out']
Source code in src/skcomplex/systems/biology/common/metabolism/_analyses.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def production_scan(
    source: DataSource,
    *,
    target: str = '',
    steps: int = 10,
    network: str | None = None,
) -> ProductionScanResult:
    """Return the scan of fluxes with enforced objective flux (FSEOF).

    The scan comes from the solve of the core, without the extra.

    The target flux is enforced at increasing levels from its value at the optimum to its maximum, and every level
    maximises the objective, with the total absolute flux minimised after it. The scan reports the reactions whose
    absolute flux rises with every level.

    Args:
        source:
            The system that holds the metabolic network.

        target:
            The reaction whose flux the scan enforces.

        steps:
            The number of levels.

        network:
            The label of the network, or `None` for the first network of the system.

    Returns:
        result:
            The levels, the objective and the fluxes of every level, and the reactions whose flux rises.

    Raises:
        AnalysisError:
            The source is not a system with the network, or the network holds no target reaction.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.biology.common.metabolism import (
        ...     FluxBalanceInteraction,
        ...     ReactionSpec,
        ...     production_scan,
        ... )
        >>> reactions = {
        ...     'in': ReactionSpec({'A': 1.0}, upper=4.0),
        ...     'grow': ReactionSpec({'A': -1.0}),
        ...     'make': ReactionSpec({'A': -1.0, 'P': 1.0}),
        ...     'out': ReactionSpec({'P': -1.0}),
        ... }
        >>> network = FluxBalanceInteraction('fba', cell='net', reactions=reactions, objective={'grow': 1.0})
        >>> system = System(elements=[Element('net', values=network.get_values())], interactions=[network])
        >>> production_scan(system, target='out', steps=2).reactions
        ['make', 'out']
    """
    system, interaction, cell = _read_network(source, network, 'production_scan')
    reactions = list(interaction.reactions)
    if target not in reactions:
        error_msg = f'The network holds no reaction {target!r}, the target of the scan.'
        raise AnalysisError(error_msg)
    problem = _compiled_network(interaction, cell, parsimonious=True)
    start = _solved(problem, interaction, cell)[1][reactions.index(target)]
    maximum = _solved(problem, interaction, cell, {target: 1.0})[0]
    levels = start + (maximum - start) * np.arange(int(steps) + 1) / int(steps)
    solved = [
        _solved(problem, interaction, cell, None, {target: (float(level), float(level))}) for level in levels[:-1]
    ]
    objectives = np.asarray([item[0] for item in solved], dtype=float)
    amounts = np.stack([item[1] for item in solved], axis=1)
    fluxes = pd.DataFrame(amounts, index=reactions)
    rising = np.all(np.diff(np.abs(amounts), axis=1) > LETHAL_GROWTH, axis=1)
    found = [name for name, rises in zip(reactions, rising, strict=True) if rises]
    return ProductionScanResult(interaction, system, levels, objectives, fluxes, found)

save_network(network, path, cell=None)

Write a flux balance to an SBML or BiGG JSON file.

The format follows the suffix of the path.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance.

required
path str | Path

The path of a .xml, .sbml, or .json file.

required
cell Element | None

The cell whose values hold the bounds and the switches, or None for the values the network starts with.

None

Raises:

Type Description
MissingExtraError

The extra is not installed.

ValidationError

The suffix names no format.

Examples:

>>> import tempfile
>>> from pathlib import Path
>>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec, save_network
>>> network = FluxBalanceInteraction('fba', reactions={'r': ReactionSpec({'a': -1.0})}, objective={'r': 1.0})
>>> with tempfile.TemporaryDirectory() as folder:
...     save_network(network, Path(folder) / 'network.json')
...     (Path(folder) / 'network.json').exists()
True
Source code in src/skcomplex/systems/biology/common/metabolism/_cobra_io.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def save_network(network: FluxBalanceInteraction, path: str | Path, cell: Element | None = None) -> None:
    """Write a flux balance to an SBML or BiGG JSON file.

    The format follows the suffix of the path.

    Args:
        network:
            The flux balance.

        path:
            The path of a `.xml`, `.sbml`, or `.json` file.

        cell:
            The cell whose values hold the bounds and the switches, or `None` for the values the network starts with.

    Raises:
        MissingExtraError:
            The extra is not installed.

        ValidationError:
            The suffix names no format.

    Examples:
        >>> import tempfile
        >>> from pathlib import Path
        >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec, save_network
        >>> network = FluxBalanceInteraction('fba', reactions={'r': ReactionSpec({'a': -1.0})}, objective={'r': 1.0})
        >>> with tempfile.TemporaryDirectory() as folder:
        ...     save_network(network, Path(folder) / 'network.json')
        ...     (Path(folder) / 'network.json').exists()
        True
    """
    cobra = load_extra('save_network')
    target = Path(path)
    if target.suffix == '.json':
        cobra.io.save_json_model(to_cobra(network, cell), str(target))
    elif target.suffix in {'.xml', '.sbml'}:
        cobra.io.write_sbml_model(to_cobra(network, cell), str(target))
    else:
        error_msg = f'The path {target} has the suffix {target.suffix!r}. Use `.xml`, `.sbml`, or `.json`.'
        raise ValidationError(error_msg)

strain_design(source, *, kind='optknock', product='', growth=None, constraints='', interventions=3, solutions=1, network=None)

Return the strain designs of a metabolic network with StrainDesign.

It needs the extra metabolism.

  • 'optknock', 'robustknock', and 'optcouple': the knock-outs that couple a product to growth.
  • 'mcs': the minimal cut sets that suppress the flux states of a constraint.

Parameters:

Name Type Description Default
source DataSource

The system that holds the metabolic network.

required
kind str

The design, one of the kinds above.

'optknock'
product str

The reaction of the product, the outer objective.

''
growth str | None

The reaction of growth, the inner objective, or None for the objective of the network.

None
constraints str

The constraints of the design in the syntax of StrainDesign, such as 'Biomass >= 0.1'.

''
interventions int

The largest number of interventions.

3
solutions int

The largest number of designs.

1
network str | None

The label of the network, or None for the first network of the system.

None

Returns:

Name Type Description
result StrainDesignResult

The network, its cobra.Model, and the designs.

Raises:

Type Description
AnalysisError

The kind is unknown, or the source is not a system with the network.

MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.core.errors import AnalysisError
>>> from skcomplex.systems.biology.common.metabolism import strain_design
>>> try:
...     strain_design(None, kind='minimal', product='EX_succ_e')
... except AnalysisError as error:
...     print(str(error).split('. ')[0])
strain_design has kind='minimal'
Source code in src/skcomplex/systems/biology/common/metabolism/_analyses.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def strain_design(
    source: DataSource,
    *,
    kind: str = 'optknock',
    product: str = '',
    growth: str | None = None,
    constraints: str = '',
    interventions: int = 3,
    solutions: int = 1,
    network: str | None = None,
) -> StrainDesignResult:
    """Return the strain designs of a metabolic network with StrainDesign.

    It needs the extra `metabolism`.

    - `'optknock'`, `'robustknock'`, and `'optcouple'`: the knock-outs that couple a product to growth.
    - `'mcs'`: the minimal cut sets that suppress the flux states of a constraint.

    Args:
        source:
            The system that holds the metabolic network.

        kind:
            The design, one of the kinds above.

        product:
            The reaction of the product, the outer objective.

        growth:
            The reaction of growth, the inner objective, or `None` for the objective of the network.

        constraints:
            The constraints of the design in the syntax of StrainDesign, such as `'Biomass >= 0.1'`.

        interventions:
            The largest number of interventions.

        solutions:
            The largest number of designs.

        network:
            The label of the network, or `None` for the first network of the system.

    Returns:
        result:
            The network, its `cobra.Model`, and the designs.

    Raises:
        AnalysisError:
            The kind is unknown, or the source is not a system with the network.

        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.core.errors import AnalysisError
        >>> from skcomplex.systems.biology.common.metabolism import strain_design
        >>> try:
        ...     strain_design(None, kind='minimal', product='EX_succ_e')
        ... except AnalysisError as error:
        ...     print(str(error).split('. ')[0])
        strain_design has kind='minimal'
    """
    _check_choice('strain_design', 'kind', kind, DESIGN_KINDS)
    load_extra(f'strain_design(kind={kind!r})')
    _, element, cell = _read_network(source, network, 'strain_design')
    model = to_cobra(element, cell, needed_by='strain_design')
    straindesign = import_extra('straindesign', 'strain_design', 'metabolism')
    inner = growth or next(iter(element.objective))
    module_kind = getattr(straindesign.names, DESIGN_NAMES[kind])
    options: dict[str, object] = {'constraints': constraints}
    if kind == 'optcouple':
        options |= {'inner_objective': inner, 'prod_id': product}
    elif kind != 'mcs':
        options |= {'inner_objective': inner, 'outer_objective': product}
    module = straindesign.SDModule(model, module_kind, **options)
    found = straindesign.compute_strain_designs(
        model,
        sd_modules=module,
        max_solutions=int(solutions),
        max_cost=int(interventions),
        solution_approach=straindesign.names.BEST,
        solver='scip',
    )
    return StrainDesignResult(element, model, [set(design) for design in found.reaction_sd])

to_cobra(network, cell=None, *, needed_by='to_cobra')

Return the COBRApy model of a flux balance.

The model keeps the reactions, rules, and objective of the network and the bounds of its cell.

A switch of the cell that is off knocks its gene out, and the system solves with the hybrid interface, which reaches HiGHS.

Parameters:

Name Type Description Default
network FluxBalanceInteraction

The flux balance.

required
cell Element | None

The cell whose values hold the bounds and the switches, or None for the values the network starts with.

None
needed_by str

The name of what needs the extra, for the error.

'to_cobra'

Returns:

Name Type Description
system object

The cobra.Model.

Raises:

Type Description
MissingExtraError

The extra is not installed.

Examples:

>>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec, to_cobra
>>> reactions = {'r': ReactionSpec({'a': -1.0}, upper=3.0, rule='g')}
>>> system = to_cobra(FluxBalanceInteraction('fba', reactions=reactions, objective={'r': 1.0}))
>>> system.reactions.r.upper_bound, system.reactions.r.gene_reaction_rule
(3.0, 'g')
Source code in src/skcomplex/systems/biology/common/metabolism/_cobra_io.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def to_cobra(network: FluxBalanceInteraction, cell: Element | None = None, *, needed_by: str = 'to_cobra') -> object:
    """Return the COBRApy model of a flux balance.

    The model keeps the reactions, rules, and objective of the network and the bounds of its cell.

    A switch of the cell that is off knocks its gene out, and the system solves with the `hybrid` interface, which
    reaches HiGHS.

    Args:
        network:
            The flux balance.

        cell:
            The cell whose values hold the bounds and the switches, or `None` for the values the network starts with.

        needed_by:
            The name of what needs the extra, for the error.

    Returns:
        system:
            The `cobra.Model`.

    Raises:
        MissingExtraError:
            The extra is not installed.

    Examples:
        >>> from skcomplex.systems.biology.common.metabolism import FluxBalanceInteraction, ReactionSpec, to_cobra
        >>> reactions = {'r': ReactionSpec({'a': -1.0}, upper=3.0, rule='g')}
        >>> system = to_cobra(FluxBalanceInteraction('fba', reactions=reactions, objective={'r': 1.0}))
        >>> system.reactions.r.upper_bound, system.reactions.r.gene_reaction_rule
        (3.0, 'g')
    """
    cobra = load_extra(needed_by)
    given = dict(cell.get_params()['values'] or {}) if cell is not None else {}
    values = network.get_values() | {name: float(np.asarray(value)) for name, value in given.items()}
    system = cobra.Model(network.cell if cell is None else cell.label)
    metabolites: dict[str, object] = {}
    for spec in network.reactions.values():
        for name in spec.coefficients:
            compartment = name.rpartition('_')[2] if '_' in name else DEFAULT_COMPARTMENT
            metabolites.setdefault(name, cobra.Metabolite(name, compartment=compartment))
    reactions = []
    for name, spec in network.reactions.items():
        identifier = network._get_identifier(name)
        reaction = cobra.Reaction(name)
        reaction.bounds = (values[f'lower_{identifier}'], values[f'upper_{identifier}'])
        reaction.add_metabolites({metabolites[item]: float(value) for item, value in spec.coefficients.items()})
        reaction.gene_reaction_rule = spec.rule
        reactions.append(reaction)
    system.add_reactions(reactions)
    system.solver = SOLVER
    system.objective = {system.reactions.get_by_id(name): float(value) for name, value in network.objective.items()}
    for gene in network.get_genes_of():
        if values[network.get_gene_name(gene)] < 1:
            system.genes.get_by_id(gene).knock_out()
    return system