Utilities (Python)#
geckopy objects in geckopy.utilities.
Functions#
Function |
Summary |
|---|---|
Add reactions and their enzymes to an ecModel. |
|
IDs of what was actually added (after isozyme/reversibility |
|
Run Flux-Scanning with Enforced Objective Function on an ecModel. |
|
Flux variability analysis on an ecModel, mapped to conventional rxns. |
|
Compute per-enzyme absolute and capacity usage from |
|
Two human-readable tables summarising enzyme usage. |
|
Per-enzyme usage info from a flux distribution. |
|
Top-N enzymes by absolute shadow price. |
|
Trim |
|
Load the starting GEM file pointed to by |
|
Load an ecModel from a YAML file. |
|
Translate ec-rxn fluxes back to conventional-rxn fluxes. |
|
Output of mapping ec-rxn fluxes back to conventional rxns. |
|
An enzyme to add alongside the new reactions. |
|
Parsimonious FBA minimising the L1 norm of |
|
Summarise enzyme usage as two DataFrames. |
|
Save an ecModel to a YAML file. |
Reference#
add_new_rxns_to_ec#
add_new_rxns_to_ec(model: 'EcModel', new_rxns: list[cobra.Reaction], new_enzymes: list[NewEnzyme])
Add reactions and their enzymes to an ecModel.
For each new reaction, the function:
Splits a reversible reaction (
lower_bound < 0) into a forward copy plus a_REVcopy with negated stoichiometry.Splits an OR-of-ANDs GPR into one
_EXP_<n>copy per AND-clause using the same DNF logic asexpand_model.
The combination of both splits gives all four variants when
applicable (R_EXP_1, R_EXP_2, R_REV_EXP_1, R_REV_EXP_2).
Each new enzyme contributes:
a
prot_<enzyme>pseudometabolite in the enzyme compartment,a
usage_prot_<enzyme>reaction (prot_pool -> prot_<enzyme>, bounds(0, 1000), GPR set to the gene),an entry appended to
model.ec.enzymes/genes/mw/sequence/concs,a new column in
model.ec.rxn_enz_mat.
Each new reaction with a non-empty GPR also gets:
an entry appended to
model.ec.rxns(with kcat=0, source=""),a new row in
rxn_enz_matwith 1.0 in the columns of every gene in its (single, post-split) AND-clause.
Ported from GECKO MATLAB: src/geckomat/utilities/addNewRxnsToEC.m.
Parameters
modelFull EcModel (not gecko-light) with the protein pool / usage rxn machinery already installed. Mutated in place.
new_rxnsReactions to add, as pre-built
cobra.Reactionobjects. Each must have stoichiometry,gene_reaction_rule,lower_bound,upper_boundset; build one from a string equation with cobra'sReaction.build_reaction_from_stringif that's more convenient.new_enzymesEnzymes to add (one per UniProt ID). Enzymes already in
model.ec.enzymesare silently skipped with a warning.
Returns
AddNewRxnsResult
:
Raises
NotImplementedErrorIf
model.ec.gecko_lightis True.ValueErrorIf a gene referenced in a new rxn's GPR is missing from both
model.genesandnew_enzymes.
AddNewRxnsResult#
IDs of what was actually added (after isozyme/reversibility
expansion and the dedupe of already-present enzymes).
Attributes
rxns_addedIDs of every cobra reaction actually added to the model, after isozyme (
_EXP_<n>) and reversibility (_REV) expansion.enz_addedUniProt IDs of the enzymes actually added (enzymes already present in
model.ec.enzymesare excluded).
ec_fseof#
ec_fseof(model: 'EcModel', prod_target_rxn: str, cs_rxn: Optional[str]=None, *, n_steps: int=10, bio_rxn: Optional[str]=None, max_fraction: float=0.9, correlation_threshold: float=0.9, flux_eps: float=1e-06)
Run Flux-Scanning with Enforced Objective Function on an ecModel.
Enforces an increasing flux toward prod_target_rxn while
optimising biomass, runs pFBA at each step, regresses every
reaction's flux against the enforced product flux, and returns
reactions with strong slope-vs-correlation signal as engineering
targets.
Parameters
modelEcModel with the protein-pool / usage-rxn machinery.
prod_target_rxnReaction id for the production target (typically a product-exchange).
cs_rxnReaction id for the main carbon source. When passed, a warning is emitted if its lower bound is tighter than its uptake at biomass-max (a common mis-configuration).
Noneskips the check.n_stepsNumber of enforced-flux levels in the scan. Default 10.
bio_rxnBiomass reaction id. Defaults to
adapter.params.bio_rxnwhenmodel.adapteris set.max_fractionTop of the scan range as a fraction of the theoretical maximum product flux. Default 0.9. The floor of the scan range is the production target's flux at biomass-optimum, not a fraction of this ceiling.
correlation_thresholdA reaction is a target when
|corr(flux, enforced)| >=this value. Default 0.9.flux_epsMinimum
|slope|(flux change per enforced-flux step) for a reaction to count as responsive; below this it is treated as flat regardless of correlation, so it cannot become a target. Default 1e-6.
Returns
FSEOFResultraven-toolbox's FSEOF output dataclass, with
usage_prot_*rows filtered out of bothscanandtargets. Seeraven_toolbox.analysis.fseof.FSEOFResultfor the full field list (scan,enforced,targets, plus theamplification/knockout/gene_targetsproperties).
ec_fva#
ec_fva(ec_model: 'EcModel', model: 'cobra.Model', *, progress: bool=True, n_proc: Optional[int]=None)
Flux variability analysis on an ecModel, mapped to conventional rxns.
For each canonical reaction (after stripping _REV and
_EXP_<N> suffixes), maximises and minimises the combined
(forward minus reverse) flux of all its ec variants, and reports
the combined flux at each of those two optima as the reaction's
max and min — i.e. the exact per-reaction FVA bound (the
"diagonal"), not the outer envelope obtained by reducing each ec
variant across all reactions' solutions and summing.
Ported from GECKO MATLAB: src/geckomat/utilities/ecFVA.m.
Parameters
ec_modelEcModel with
_REVand_EXP_<N>suffixes fromexpand_modelandconvert_to_irreversible.modelThe non-ec model to which the fluxes are mapped. Must be the same model that was used to build
ec_model.progressShow a tqdm progress bar over the per-canonical-rxn LP solves. Defaults to True; set False to silence output.
n_procNumber of worker processes. Defaults to
cobra.Configuration().processes. Set to 1 to run the original serial path; values >= 2 parallelise viacobra.util.ProcessPool, the same pool cobrapy's ownflux_variability_analysis/single_reaction_deletionuse.
Returns
pandas.DataFrameIndex:
rxn_id(inmodel.reactionsorder). Columns:min_flux,max_flux.
enzyme_usage#
enzyme_usage(model: 'EcModel', fluxes: Union[pd.Series, Mapping[str, float]], *, include_zero: bool=True)
Compute per-enzyme absolute and capacity usage from fluxes.
For each enzyme in model.ec.enzymes:
abs_usage = |fluxes[usage_prot_<enzyme>]|(mg/gDCW).ub= the usage reaction's upper bound.cap_usage = abs_usage / ub(or 0 ifub == 0).
Ported from GECKO MATLAB: src/geckomat/utilities/enzymeUsage.m.
Parameters
modelFull (non-light) EcModel with
usage_prot_*reactions installed for every enzyme.fluxesFlux distribution. Typically
solution.fluxesfrommodel.optimize(); any dict-like keyed by rxn id works.include_zeroWhen False, enzymes with zero absolute usage are dropped from the result.
Raises
NotImplementedErrorIf
model.ec.gecko_lightis True.
EnzymeUsageReport#
Two human-readable tables summarising enzyme usage.
Attributes
high_cap_usageDataFrame of enzymes whose
cap_usageexceeds thehigh_cap_usagethreshold. For enzymes catalysing multiple flux-carrying reactions, a combined header row (with"==="placeholders) is followed by per-reaction breakdown rows.top_abs_usageDataFrame of the top-N enzymes by absolute usage. Same layout but with
perc_usage(= abs_usage / total_pool * 100) replacingcap_usage.total_usage_fluxThe protein pool exchange capacity (mg/gDCW) used as the denominator for
perc_usage.
EnzymeUsageResult#
Per-enzyme usage info from a flux distribution.
Attributes
prot_idUniProt IDs (matching
model.ec.enzymesorder, modulo zero-usage filtering).abs_usageAbsolute enzyme usage in mg/gDCW (= |flux through the
usage_prot_<X>reaction|).cap_usageCapacity usage =
abs_usage / ub.0for enzymes whose usage rxn upper bound is 0.ubUpper bound of each
usage_prot_<X>reaction.fluxesThe original input flux distribution (carried through for downstream use, e.g. by
report_enzyme_usage).
get_enzyme_bottlenecks#
get_enzyme_bottlenecks(model: 'EcModel', *, top: int=10)
Top-N enzymes by absolute shadow price.
Solves the model, ranks enzymes by |shadow_price|, returns a
DataFrame indexed by uniprot id with columns
[gene, shadow_price, flux, cap_usage, upper_bound].
Ported from the legacy geckopy package (Carrasco et al., 2023, https://doi.org/10.1128/spectrum.01705-23), geckopy/flux_analysis.py:275-281.
Parameters
modelEcModel to solve.
topNumber of top-ranked enzymes to return. Default 10.
Returns
pandas.DataFrameIndexed by uniprot id, columns
[gene, shadow_price, flux, cap_usage, upper_bound], sorted by descending|shadow_price|and truncated totoprows.
Raises
RuntimeErrorIf the solve status is not optimal.
get_subset_ec_model#
get_subset_ec_model(big_ec_model: 'EcModel', small_gem: 'cobra.Model')
Trim big_ec_model to the gene/reaction set of small_gem.
Both models must have been derived from the same starting GEM.
Reactions in small_gem are matched against canonicalised
(suffix-stripped) reaction ids in big_ec_model; if any
small_gem reaction is missing, the function raises.
Returns a fresh EcModel; the input big_ec_model is not
mutated.
Algorithm (mirrors MATLAB):
Copy
big_ec_model.Compute genes to remove (
big.genesminussmall_gem.genes, preserving thestandardpseudo-gene fromassign_standard_kcat).Remove reactions blocked by that gene removal (cobra's
GPR.eval(knockouts=...)).Remove the genes from
model.genes.Trim the corresponding columns of
model.ec.genes/enzymes/mw/sequence/concs/rxn_enz_mat.Remove reactions whose canonicalised id is not in
small_gem.reactions, exceptusage_prot_*andprot_pool_exchangewhich are always preserved.Trim the corresponding rows of
model.ec.rxns/kcat/source/notes/eccodes/rxn_enz_mat.
Ported from GECKO MATLAB: src/geckomat/utilities/getSubsetEcModel.m.
If any usage_prot_* reaction's upper bound differs from the
default (1000), a warning is logged: protein-concentration
constraints on big_ec_model may not carry over meaningfully
to the subset.
Parameters
big_ec_modelThe full ecModel covering many genes/reactions.
small_gemThe conventional (non-ec) context-specific model whose gene/reaction set is the target.
Returns
EcModelA new ecModel restricted to
small_gem's gene/reaction set, with the protein pool / usage rxn machinery preserved.
Raises
ValueErrorIf any reaction in
small_gemis missing frombig_ec_model(after suffix stripping).
load_conventional_gem#
load_conventional_gem(adapter: 'ModelAdapter')
Load the starting GEM file pointed to by adapter.
Parameters
adapterA
ModelAdapterwhoseparams.conv_gemfield gives the path to the GEM file. The path is used as-is; the adapter's loader has already resolved it relative to the adapter folder.
Returns
cobra.ModelThe loaded model. Use it as the input to
make_ec_model.
Raises
FileNotFoundErrorIf
params.conv_gemdoesn't point to an existing file.
load_ec_model#
load_ec_model(filename: Optional[Union[str, Path]]=None, adapter: Optional['ModelAdapter']=None)
Load an ecModel from a YAML file.
Parameters
filenamePath to the ecModel file. If
None, defaults toecModel.yml. Relative paths resolve against<adapter.params.path>/models/<filename>; absolute paths are used as-is andadaptermay beNone.adapterA
ModelAdapterused to resolve a relativefilenameand attached to the loaded model asmodel.adapter. Required whenfilenameis relative.
Returns
EcModelThe loaded ecModel with a populated
model.ec. Thegecko_lightflag, ec arrays, and coupling matrix are all read from the file.
Raises
ValueErrorIf the extension isn't YAML, the filename is relative without an adapter, or the YAML lacks the GECKO
ec-rxns/ec-enzymessections (in which case it isn't an ecModel).FileNotFoundErrorIf the resolved file doesn't exist.
map_rxns_to_conv#
map_rxns_to_conv(ec_model: 'EcModel', model: 'cobra.Model', flux_vect: Union[np.ndarray, pd.Series])
Translate ec-rxn fluxes back to conventional-rxn fluxes.
For each ec_model.reactions entry, the rxn id is canonicalised:
_REVsuffix or_REV_EXP_infix -> the flux is negated (reverse direction in geckopy convention) and the suffix stripped._EXP_<N>suffix -> stripped (isozyme split combined).
Fluxes belonging to the same canonical rxn id are summed, then
reordered to match model.reactions. A separate output
surfaces protein-usage fluxes (usage_prot_* and
prot_pool_exchange) under their stripped labels.
Ported from GECKO MATLAB: src/geckomat/utilities/mapRxnsToConv.m.
Parameters
ec_modelThe EcModel from which
flux_vectwas obtained.modelThe conventional (non-ec) model that
ec_modelwas built from.model.reactionsdefines the output ordering.flux_vectEither a 1-D
np.ndarrayaligned toec_model.reactionsorder, a 2-Dnp.ndarraywith the same row order, or apd.Seriesindexed by ec-rxn id (missing entries default to 0).
Returns
MapRxnsResult
:
Raises
ValueErrorIf
flux_vectis empty, has the wrong shape, or any conventional rxn ID is missing from the canonicalised set.
MapRxnsResult#
Output of mapping ec-rxn fluxes back to conventional rxns.
Attributes
mapped_flux1-D or 2-D array of fluxes in the conventional model's
model.reactionsorder. Same number of columns/scenarios as the input (1-D in / 1-D out; 2-D in / 2-D out).enz_usage_fluxFluxes of the protein-usage reactions (
usage_prot_*andprot_pool_exchange), inusage_enzorder.usage_enzLabels for
enz_usage_flux: protein IDs forusage_prot_*rows, or"pool"for the exchange row.
NewEnzyme#
An enzyme to add alongside the new reactions.
Attributes
enzymeUniProt ID. Used as the
<X>inprot_<X>andusage_prot_<X>.geneGene ID for
model.genesand the usage rxn's GPR.mwMolecular weight (g/mmol) for
model.ec.mw.
pfba_enzymes#
pfba_enzymes(model: 'EcModel', objective: Union[cobra.Reaction, str, None]=None, *, fraction_of_optimum: float=1.0)
Parsimonious FBA minimising the L1 norm of usage_prot_* fluxes.
Sets the objective (if given), fixes it at
fraction_of_optimum * optimal_value, then minimises
sum(usage_prot_*.forward_variable). Usage reactions are
forward-only in the GECKO 3 layout (lb=0); if a user has
flipped one to allow reverse flux, its reverse_variable is
included automatically.
Ported from the legacy geckopy package (Carrasco et al., 2023, https://doi.org/10.1128/spectrum.01705-23), geckopy/flux_analysis.py:342-386.
Parameters
modelFull EcModel (not gecko-light) with
usage_prot_*reactions installed.objectiveReaction (or reaction id) to optimise before minimising enzyme usage. If
None, the model's current objective is used as-is.fraction_of_optimumFraction of the objective's optimal value to fix as a constraint before minimising enzyme usage.
1.0(default) requires the biomass-optimal solution; a lower value trades some objective value for potentially lower enzyme usage.
Returns
cobra.SolutionStandard cobra solution over all reactions, at the flux distribution that minimises total (mass-weighted) enzyme usage subject to the objective constraint.
Raises
NotImplementedErrorIf
model.ec.gecko_lightis True.ValueErrorIf
model's objective is already the internalpfba_enzymesobjective, indicating a nested call.cobra.exceptions.OptimizationErrorIf minimising enzyme usage is infeasible at the requested
fraction_of_optimum.
report_enzyme_usage#
report_enzyme_usage(model: 'EcModel', usage_data: 'EnzymeUsageResult', *, high_cap_usage: float=0.9, top_abs_usage: int=10)
Summarise enzyme usage as two DataFrames.
High capacity: enzymes whose
cap_usageexceedshigh_cap_usage. The enzymes catalysing more than one flux-carrying reaction get a combined header row plus one detail row per reaction, where the detail rows split the absolute usage proportionally to-S[prot_<enzyme>, rxn] * flux[rxn]. Combined header rows use the literal"==="placeholder for non-applicable string fields andNaNforkcat.Top absolute: the top
top_abs_usageenzymes by absolute usage, same shape but withperc_usage(a percent ofprot_pool_exchangecapacity) replacingcap_usage.
Ported from GECKO MATLAB: src/geckomat/utilities/reportEnzymeUsage.m.
Parameters
modelFull EcModel with the protein pool / usage rxn machinery.
usage_dataResult from
enzyme_usageon the same model.high_cap_usageCapacity-usage threshold for the first report: enzymes whose
cap_usageexceeds this fraction are included. Default 0.9 (90% of capacity).top_abs_usageNumber of top enzymes for the second report.
0orinfreturns all enzymes. Default 10.
Returns
EnzymeUsageReport
:
save_ec_model#
save_ec_model(model: EcModel, filename: Optional[Union[str, Path]]=None, adapter: Optional['ModelAdapter']=None)
Save an ecModel to a YAML file.
Parameters
modelThe ecModel to save. Must have a populated
model.ec(bothec.rxnsandec.enzymesnon-empty). Empty ecModels are rejected because they're almost always a bug — you probably forgot to runmake_ec_modelfirst.filenameDestination path. If
None, defaults toecModel.yml. Relative paths resolve against<adapter.params.path>/models/<filename>; absolute paths are used as-is.adapterUsed to resolve a relative
filename. Defaults tomodel.adapter. Required whenfilenameis relative ANDmodel.adapterisNone.
Returns
PathThe absolute path of the file that was written.
Raises
ValueErrorIf
model.ecis empty, if the file extension isn't YAML, or if the filename is relative and no adapter is available.