Limit proteins (Python)#
geckopy objects in geckopy.limit_proteins.
Functions#
Function |
Summary |
|---|---|
Constrain the model's exchange fluxes from a |
|
Compute the f-factor for an ec model. |
|
Group the enzymes of multi-subunit reactions into complexes. |
|
The complexes of an ecModel and their shared subunits. |
|
Constrain |
|
Fill |
|
Information about which enzyme constraints were flexibilized. |
|
Iteratively relax enzyme concentration constraints until the |
|
Compute control coefficients for enzyme concentrations. |
|
Report isozyme groups with partial proteomics coverage. |
|
Level molar abundances to one abundance per complex. |
|
Give every complex in |
|
What |
|
Relax enzyme caps by the least total amount that reaches |
|
Greedy relaxation of proteomics constraints until growth >= minimal_growth. |
|
Limit unmeasured isozymes that have a measured sibling. |
Reference#
apply_flux_data_constraints#
apply_flux_data_constraints(model: 'EcModel', flux_data: 'FluxData', *, condition: int | str=0, max_min_growth: Literal['max', 'min']='max', loose_strict_flux: _LooseStrict='loose', bio_rxn: Optional[str]=None, c_source: Optional[str]=None)
Constrain the model's exchange fluxes from a FluxData measurement.
Sets the biomass reaction bounds to the measured growth rate and
each exchange reaction in flux_data.exch_rxn_ids to its
measured flux for the chosen condition. Also zeros out the
adapter's preferred carbon source so the data determines the choice.
Ported from GECKO MATLAB: src/limit_proteins/constrainFluxData.m.
A +/-1000 measured flux means unconstrained, regardless of
loose_strict_flux:
-1000 -> lb=-1000, ub=0 (free uptake), +1000 ->
lb=0, ub=1000 (free excretion).
Parameters
modelEcModel with the exchange reactions referenced by
flux_dataalready in place. Mutated in place.flux_dataPre-loaded FluxData (typically from a future
load_flux_datautility).conditionEither the 0-indexed condition number, or the condition name (matched against
flux_data.conds).max_min_growth"max"setsbio_rxnupper bound to the measured growth rate (and lower bound to 0);"min"sets the lower bound (suitable when minimisingprot_pool_exchange).loose_strict_flux"loose"keeps one bound at 0 and the other at the measured value (allows zero flux). A numeric percentagepbrackets the measured value with hard bounds:lb = val * (1 - p/200),ub = val * (1 + p/200), swapped as needed to keeplb <= ubwhenvalis negative.p=10allows 10% total variance (i.e. +/-5%).bio_rxnBiomass reaction ID. Defaults to the adapter's configured biomass reaction (
model.adapter.params.bio_rxn) whenNone.c_sourceReaction ID of the preferred carbon-source uptake reaction; its bounds are set to
(0, 0)before applying the flux data so that the data alone determines the carbon source used. Defaults tomodel.adapter.params.c_source(or no blocking if there is no adapter) whenNone; pass""to skip blocking any reaction. Silently ignored if the reaction id is not found in the model.
Raises
ValueErrorIf
model.adapteris None,max_min_growth/loose_strict_fluxis invalid,condition(as string) is not influx_data.conds, or anyflux_data.exch_rxn_idsis missing from the model.IndexErrorIf
condition(as int) is out of range.
calculate_f_factor#
calculate_f_factor(model: 'EcModel', prot_data: Optional['ProtData']=None, *, enzymes: Optional[list[str]]=None)
Compute the f-factor for an ec model.
The f-factor is the mass fraction of total cellular protein that is accounted for by enzymes in the model. It is computed as
f = sum(abundances of in-model enzymes) / sum(all abundances)
where abundances are read from a pre-loaded ProtData (typically
populated via load_pax_db).
For 2-D abundances (multiple proteomics samples), the
per-protein average is taken first via np.nanmean(axis=1).
Ported from GECKO MATLAB: src/limit_proteins/calculateFfactor.m.
Parameters
modelEcModel; defaults
enzymestomodel.ec.enzymes, and its adapter locatesdata/paxDB.tsvwithoutprot_data.prot_dataPre-loaded proteomics data (typically from
load_pax_db). If None,data/paxDB.tsvof the adapter's project is loaded withload_pax_dband the project'sdata/uniprot.tsv(downloaded with the adapter's[uniprot]settings when missing;FileNotFoundErrorwhen it is missing and[uniprot] idis empty). Without that file, a warning is logged and the default f of 0.5 is returned, as GECKO'scalculateFfactordoes.enzymesUniProt IDs counted as "in the model". Defaults to
model.ec.enzymes.
Returns
floatThe f-factor in [0, 1]. Returns 0.5 without proteomics data, NaN, as MATLAB does, if the total proteome abundance is zero (the factor is 0/0), and 0.0 if none of the proteomics UniProt IDs match a model enzyme.
complex_families#
complex_families(model: 'EcModel', min_overlap: float=0.5, min_shared: int=2)
Group the enzymes of multi-subunit reactions into complexes.
Parameters
modelAn EcModel with
ec.rxn_enz_mat(copies per subunit).min_overlapTwo enzyme sets are one complex when they share at least this fraction of the larger set's subunits...
min_shared...and at least this many subunits.
ComplexFamilies#
The complexes of an ecModel and their shared subunits.
Attributes
complexesOne dict per complex,
{enzyme: copies}over every subunit that appears in any of its enzyme sets.ownerFor every subunit that belongs to a complex, the index of that complex in
complexes.sharedSubunits of a complex that belong to none: carriers and subunits shared between complexes.
constrain_enz_concs#
constrain_enz_concs(model: 'EcModel', *, remove_constraints: bool=False, restrict_to: list[str] | None=None)
Constrain usage_prot_<enzyme> reactions by model.ec.concs.
For each enzyme in model.ec.enzymes whose entry in
model.ec.concs is non-NaN, the corresponding
usage_prot_<enzyme> reaction's upper bound is set to that
concentration. Enzymes with NaN concentrations have their usage
reaction reset to the default upper_bound = 1000, drawing
freely from prot_pool. Each processed usage reaction is first
reset to lower_bound = 0, upper_bound = 1000 and a
prot_pool coefficient of -1, so a prior lower bound above the
new upper bound does not conflict with it.
A NaN entry means that the enzyme was not measured, and its usage
draws from the protein pool. An entry of 0 means that the enzyme was
measured as absent: its usage upper bound is 0, which removes every
flux through the enzyme. flexibilize_enz_concs multiplies the
concentration and cannot raise a bound of 0;
relax_proteomics_greedy sets the bound back to its default.
Ported from GECKO MATLAB: src/limit_proteins/constrainEnzConcs.m.
Parameters
modelEcModel with
model.ec.concspopulated (typically byfill_enz_concs) and the protein pool / usage reaction machinery already in place. Mutated in place.remove_constraintsWhen True, all usage reactions are reset to their default
upper_bound = 1000(withlower_bound = 0and aprot_poolcoefficient of -1), regardless ofec.concs.ec.concsitself is left unchanged.restrict_toIf supplied, only the listed enzyme uniprot IDs are processed (others are left untouched). Useful for incremental updates from
Enzyme.concentrationsetters. Unknown IDs in the list are silently ignored. DefaultNone= process every enzyme inmodel.ec.enzymes.
Raises
ValueErrorIf
model.ec.concsholds a negative concentration for a processed enzyme (unlessremove_constraintsis set), if theprot_poolmetabolite is missing, or if anyusage_prot_<enzyme>reaction is missing for an enzyme inmodel.ec.enzymes(e.g. because the model is gecko-light, which has no usage reactions).
fill_enz_concs#
fill_enz_concs(model: 'EcModel', prot_data: 'ProtData', *, data_col: int=0)
Fill model.ec.concs from prot_data.abundances (mg/gDCW).
Resets model.ec.concs to all-NaN of length n_enzymes,
then writes each (uniprot_id, abundance) pair into the slot
matching model.ec.enzymes. UniProt IDs absent from
model.ec.enzymes are silently ignored. Enzymes absent from
prot_data keep their NaN.
A NaN entry in model.ec.concs means that the protein was not
measured, and the usage of the enzyme draws from the protein pool. An
entry of 0 means that the protein was measured as absent, and
constrain_enz_concs limits the usage of the enzyme to 0.
load_prot_data returns a measured 0 with the option
zeros_as_measured, and reads a 0 as NaN otherwise.
For 2-D prot_data.abundances (multiple conditions /
samples), data_col selects which column to use.
Ported from GECKO MATLAB: src/limit_proteins/fillEnzConcs.m.
Parameters
modelEcModel;
model.ec.concsis replaced in place.prot_dataPre-loaded proteomics data (e.g. from
load_pax_dbor a manual TSV reader). Abundances are expected in mg/gDCW.data_col0-indexed column of
prot_data.abundancesto read. Must be0for 1-D abundances.
Raises
ValueErrorIf a protein that is an enzyme of the model has a negative abundance.
IndexErrorIf
data_colis out of range for the supplied abundances.
FlexEnzResult#
Information about which enzyme constraints were flexibilized.
All arrays are sorted by ratio_incr descending. May contain a
final entry with uniprot_ids[-1] == "prot_pool" if the protein
pool exchange itself was relaxed.
Attributes
uniprot_idsUniProt IDs of the flexibilized enzymes (plus
"prot_pool"as a final entry when the protein pool itself was relaxed).old_concsUpper bound of each enzyme's usage reaction (or of
prot_pool_exchangefor the"prot_pool"entry) before relaxation.flex_concsUpper bound after relaxation.
ratio_incrflex_concs / old_concs;infwhereold_concsis 0.frequenceNumber of loop iterations in which each enzyme was selected as the most limiting one.
flexibilize_enz_concs#
flexibilize_enz_concs(model: 'EcModel', *, exp_growth: Optional[float]=None, fold_change: float=2.0, iter_per_enzyme: int=5, bio_rxn: Optional[str]=None, verbose: bool=True, per_complex: bool=False)
Iteratively relax enzyme concentration constraints until the
model reaches exp_growth.
Each iteration uses get_conc_control_coeffs to find the most
limiting enzyme, then multiplies its usage_prot_<enzyme>
upper bound by (1 + fold_change * iteration_count). If no
enzyme is limiting (all control coefficients zero), the function
tries relaxing prot_pool_exchange.
After the loop, a refinement pass solves min prot_pool_exchange
with bio_rxn constrained to a soft +/-0.25% band around
exp_growth (matching MATLAB's flexibilizeEnzConcs.m, which
uses RAVEN's setParam('var', bioRxn, expGrowth, 0.5) for the same
solve) to find the minimal usage that supports growth. Because
minimal protein-pool usage is non-decreasing in growth rate near the
optimum, the minimiser typically settles at the band's low edge --
growth ends up about 0.25% below exp_growth, not at it exactly.
For each flexibilized enzyme, if the actual usage at this minimum is
less than its original concentration, the original constraint is
restored (i.e. that enzyme is dropped from the result). This avoids
over-relaxing enzymes that the prior iterative pass increased more
than necessary.
The usage upper bound of an enzyme is raised as a factor of its
concentration, so an enzyme with a concentration of 0 in
model.ec.concs stays at 0 and is never flexibilized. If such
enzymes exist, a warning lists them: a growth rate that is not
reached can then be caused by these enzymes, and
flexibilize_enz_concs reports no limiting enzyme for them.
Ported from GECKO MATLAB: src/limit_proteins/flexibilizeEnzConcs.m.
Parameters
modelEcModel with
prot_pool_exchangeandusage_prot_*reactions installed andmodel.ec.concspopulated for at least some enzymes (typically byfill_enz_concsandconstrain_enz_concs). Mutated in place;ec.concsitself is left unchanged.exp_growthTarget growth rate. Defaults to
model.adapter.params.gr_exp; raisesValueErrorwhen neither is set.fold_changeControls how much the limiting enzyme's usage upper bound grows each time it is selected: on its
k-th selection, the bound is set tooriginal_conc * (1 + fold_change * k).iter_per_enzymeMaximum number of times the same enzyme may be selected before warning and breaking.
0means no limit.bio_rxnBiomass reaction id. Defaults to
params.bio_rxnfrom the adapter; pass it (withexp_growth) to run without an adapter.verboseWhether per-iteration progress is logged at INFO.
per_complexTreat every complex (see
complex_families) as one enzyme: rank enzymes and complexes by the growth gained per fold of raising all their caps together (a levelled complex binds on all subunits at once, so no single subunit shows a gain), raise every measured subunit of the selected complex by the same factor, count iterations per complex, and keep one factor per complex in the refinement pass, so that concentrations levelled bylevel_complex_concsstay levelled. Thefrequenceof a complex is recorded on its first subunit with a concentration above 0. Off by default.
Returns
FlexEnzResultEmpty when the LP of the input model is not optimal (for example infeasible), as MATLAB's
flexibilizeEnzConcsreturns it.
Raises
ValueErrorIf no enzyme has a measured concentration (nothing to flexibilize), or if
model.adapteris None andexp_growthis also None.
get_conc_control_coeffs#
get_conc_control_coeffs(model: 'EcModel', proteins: Optional[list[str]]=None, fold_change: float=2.0, limit: float=0.0, method: str='finite_difference')
Compute control coefficients for enzyme concentrations.
For each protein in proteins, the coefficient quantifies how
much the LP optimum (typically growth) increases per unit increase
in that enzyme's upper bound. Proteins whose usage flux is at most
limit times their upper bound are skipped (no sensitivity to
expect there).
The default method="finite_difference" raises the upper bound of one usage reaction
by fold_change, re-solves and divides the rise of the optimum by the rise of the
bound, one solve per analysed protein (several minutes on a genome-scale ecModel). A
rise of at most 1e-10 counts as no sensitivity. This is what GECKO's
getConcControlCoeffs does, and it is a re-solved change of the objective, which
stays meaningful when the LP is degenerate and its duals are not.
method="shadow_price" reads, from a single LP solve, the reduced cost of
each analysed usage reaction's forward variable. That is the local
marginal d(objective)/d(usage_ub) of the enzyme's own bound: it is
zero for an enzyme whose bound does not bind, also when the shared
protein pool does, because the pool's price is part of the
prot_<id> metabolite dual and cancels out of the reduced cost
(|dual(prot_<id>) - dual(prot_pool)|). A nonzero reduced cost is
kept only if raising that bound by 0.01 percent raises the optimum
by at least half of the rise the reduced cost predicts (one extra
solve per nonzero value), because the dual overestimates the effect
at a degenerate vertex. The test is relative to the predicted rise,
so a small coefficient on a small bound is kept as readily as a large
one; the rise must also exceed 1e-12 times max(1, |optimum|). A zero
reduced cost needs no check. With optlang's scipy backend (HiGHS) the reduced cost is
read from the bound marginal of the last linprog result, since optlang does not
expose variable duals there. When the active solver gives no usable variable duals
(a missing or NaN value, or a scipy result without bound marginals) the function falls
back to the finite-difference loop and logs once that it has done so. The two methods
agree where raising the bound does not cross a change of the active set and differ
where it does.
Ported from GECKO MATLAB: src/limit_proteins/getConcControlCoeffs.m.
Parameters
modelEcModel with a defined LP objective (typically a biomass reaction) and
usage_prot_<enzyme>reactions for every analysed protein.proteinsUniProt IDs to analyse. Defaults to
model.ec.enzymes.fold_changeFactor by which the finite-difference path raises a usage upper bound (default 2.0). Used by
method="shadow_price"only when it falls back.limitSkip proteins whose usage flux is at most
limittimes their upper bound. Default 0.0 includes any protein with non-zero flux.method"finite_difference"(default) or"shadow_price".
Returns
enz_maskBoolean array of length
len(proteins); True where the protein was analysed.control_coeffsFloat array of length
len(proteins); 0.0 where the protein was either skipped or showed no sensitivity.
Raises
ValueErrorIf
methodis unknown, or if the solve of the model as given is not optimal (for example infeasible), as GECKO'sgetConcControlCoeffsraisesgetConcControlCoeffs:infeasible.
get_isozyme_coverage#
get_isozyme_coverage(model: 'EcModel')
Report isozyme groups with partial proteomics coverage.
The reactions in model.ec.rxns that share an identifier once the
suffix _EXP_<n> is removed are the isozymes of one reaction of the
conventional GEM. An entry is measured when at least one of its enzymes
has a concentration above 0 in model.ec.concs, and unmeasured when
none of its enzymes has a concentration (all NaN). A group has partial
coverage when it has both a measured and an unmeasured entry. An
unmeasured entry next to a measured one can be a protein below the
detection limit as well as a protein that is absent, so the report makes
no statement on which. The kcat of an entry is not considered. A missing
or short model.ec.concs counts as NaN for the enzymes it does not
cover.
Ported from GECKO MATLAB: src/limit_proteins/getIsozymeCoverage.m.
Parameters
modelFull (not gecko-light) EcModel with concentrations in
model.ec.concs(seefill_enz_concs). Not modified.
Returns
coverage: pandas.DataFrameOne row per group with partial coverage, sorted by reaction, with the columns:
rxn: the reaction identifier without the_EXP_<n>suffix.n_entries: number of entries of the group inmodel.ec.rxns.n_measured: number of measured entries.n_unmeasured: number of unmeasured entries.measured_enzymes: list of the enzymes of the measured entries that have a concentration above 0.unmeasured_enzymes: list of the enzymes of the unmeasured entries.shared_enzymes: list of the unmeasured enzymes that also catalyse an entry outside the unmeasured entries of groups with partial coverage.zero_unmeasured_isozymesleaves them unchanged.
zeroable: list of strThe enzymes that
zero_unmeasured_isozymesacts on, in model order: the enzymes inunmeasured_enzymesthat are not inshared_enzymesof any group.
Raises
NotImplementedErrorIf the model is a gecko-light model.
ValueErrorIf
model.ec.rxn_enz_matis missing or empty.
GreedyRelaxResult#
level_complex_abundances#
level_complex_abundances(model: 'EcModel', uniprot_ids: Sequence[str], abundances: Sequence[float], *, statistic: str='median', fill_missing: bool=True, families: Optional[ComplexFamilies]=None)
Level molar abundances to one abundance per complex.
Parameters
modelThe EcModel whose complexes are used.
uniprot_ids, abundancesMeasured molar abundances (any molar unit; per subunit, not per complex).
statistic"median"or"mean"over the abundance divided by the copies of the non-shared subunits with an abundance above 0.fill_missingGive unmeasured, non-shared subunits the complex's abundance. A subunit with an abundance of 0 is measured as absent and stays 0.
familiesPrecomputed
complex_families(model).
Returns
ids, abundances, resultThe levelled data (unmeasured subunits appended when filled) and what changed.
level_complex_concs#
level_complex_concs(model: 'EcModel', *, statistic: str='median', fill_missing: bool=True, families: Optional[ComplexFamilies]=None)
Give every complex in model.ec.concs one abundance.
Run after fill_enz_concs and before constrain_enz_concs.
Concentrations (mg/gDCW) are converted to molar amounts with
ec.mw for the levelling and back afterwards. Mutates
model.ec.concs.
Parameters
modelEcModel with
ec.concsfilled.statistic"median"(default) or"mean".fill_missingGive unmeasured, non-shared subunits the complex's concentration. A subunit with a concentration of 0 is measured as absent and stays 0.
familiesThe complexes of the model, as returned by
complex_families(default: calculated from the model).
Returns
LevelComplexResultWhat changed.
ec.concshas one abundance per complex, except for subunits at 0, shared subunits and skipped complexes.
LevelComplexResult#
What level_complex_concs changed.
Attributes
adjustedMeasured subunits whose concentration was replaced by the complex's.
addedUnmeasured subunits given the complex's concentration.
sharedSubunits left as measured because they belong to more than one complex.
skippedComplexes (as sorted subunit tuples) without a non-shared subunit with a concentration above 0.
relax_enz_concs#
relax_enz_concs(model: 'EcModel', *, exp_growth: Optional[float]=None, bio_rxn: Optional[str]=None, per_complex: bool=False, weight: str='relative', pool_weight: float=1000.0, floor: float=1e-09)
Relax enzyme caps by the least total amount that reaches exp_growth.
Parameters
modelEcModel with
model.ec.concsfilled and the caps applied (fill_enz_concsandconstrain_enz_concs). The usage upper bounds (andprot_pool_exchange) are updated in place;ec.concsitself is left unchanged, as inflexibilize_enz_concs.exp_growthTarget growth rate. Defaults to
params.gr_exp; raisesValueErrorwhen neither is set.bio_rxnBiomass reaction id. Defaults to
params.bio_rxn.per_complexOne fold per complex (its measured, owned subunits; see
complex_families) instead of one per enzyme.weight"relative"minimises the summed fold increases, so an enzyme measured at almost nothing is not relaxed freely because its absolute cost is small;"absolute"minimises the mg/gDCW added.pool_weightPrice of one fold of the protein pool relative to one fold of an enzyme (or, with
weight="absolute", per mg).floorConcentration below which a measured value is treated as this floor when scaling its fold, so a zero measurement can still be relaxed (at a high relative price).
Returns
FlexEnzResultThe relaxed enzymes, as from
flexibilize_enz_concs(frequenceis 1 for every entry), with a"prot_pool"entry when the pool was raised.
Raises
ValueErrorIf no enzyme is measured, the weighting is unknown, or no relaxation reaches
exp_growth(the target is then not limited by protein).
relax_proteomics_greedy#
relax_proteomics_greedy(model: 'EcModel', *, minimal_growth: float, enzyme_set: Optional[set[str]]=None, max_iterations: int=100, default_upper_bound: float=1000.0)
Greedy relaxation of proteomics constraints until growth >= minimal_growth.
An enzyme with a concentration of 0 in model.ec.concs is a candidate
like any other and is relaxed in the same way.
Parameters
modelEcModel with proteomics-constrained enzymes (some
usage_prot_<id>reactions have finite upper bounds fromconstrain_enz_concs).minimal_growthTarget objective value.
enzyme_setSubset of uniprot IDs eligible for relaxation.
None= all currently proteomics-constrained enzymes.max_iterationsSafety cap on the number of relaxations; raises
RuntimeErrorwhen growth is still belowminimal_growthafter that many and candidates remain. When no candidate is left, a warning is logged and the result hasconverged=False.default_upper_boundValue to restore on a relaxed usage reaction. Matches the default set by
add_protein_usage_reactions.
Returns
GreedyRelaxResultrelaxedmaps uniprot to the original concentration (so the caller can restore if desired);tracerecords each step;final_growthis the objective value reached at the last iteration attempted;convergedis True ifffinal_growth >= minimal_growth.
Ported from the legacy geckopy package (Carrasco et al., 2023,
:
https://doi.org/10.1128/spectrum.01705-23),
:
geckopy/experimental/relaxation.py (relax_proteomics_greedy).
:
RelaxationStep#
zero_unmeasured_isozymes#
zero_unmeasured_isozymes(model: 'EcModel', *, method: str='zero', limit: Optional[float]=None)
Limit unmeasured isozymes that have a measured sibling.
For a reaction with a measured and an unmeasured isozyme (see
get_isozyme_coverage), the usage upper bound of the enzymes of the
unmeasured isozyme is lowered, instead of leaving them to draw from the
protein pool without a limit. The function lowers the usage upper bound
in the model and does not change model.ec.concs. An enzyme that also
catalyses a reaction without a measured sibling is left unchanged,
because limiting it would limit that reaction as well.
Not detecting a protein is not the same as the protein being absent: a
protein below the detection limit of the measurement is missing from the
data as well. Method "zero" treats the unmeasured isozyme as absent
and sets its usage upper bound to 0, which removes every flux through
the enzyme and can lower the growth rate or make the model infeasible.
Method "detection_limit" treats it as present at or below the
detection limit and sets the upper bound to the detection limit. An
upper bound that is already below the value to set is not raised. A
lower bound above the upper bound to set is lowered to it.
An enzyme lowered by the function has a NaN concentration and is a
candidate in relax_proteomics_greedy like any other enzyme with a
bound below the default.
Run after constrain_enz_concs, which resets the usage upper bounds of
all enzymes. The function is not called by other functions of geckopy.
Ported from GECKO MATLAB:
src/limit_proteins/zeroUnmeasuredIsozymes.m (method
'detectionLimit' there is "detection_limit" here).
Parameters
modelFull (not gecko-light) EcModel with concentrations in
model.ec.concs, constrained byconstrain_enz_concs. The usage upper bounds are lowered in place.method"zero"or"detection_limit".limitThe detection limit in mg/gDCW for
method="detection_limit". Defaults to the smallest concentration above 0 inmodel.ec.concs.
Returns
pandas.DataFrameOne row per enzyme that the function acted on, with the columns
uniprotandnew_upper_bound.
Raises
ValueErrorIf
methodis unknown, if the detection limit is negative, NaN or missing (no concentration above 0 and nolimit), or if a usage reaction of an enzyme to act on is missing.NotImplementedErrorIf the model is a gecko-light model.