Gather kcats (Python)#
geckopy objects in geckopy.gather_kcats.
Functions#
Function |
Summary |
|---|---|
Escalate |
|
Choose one kcat value per reaction and write it to |
|
Assign kcats from the kcat source files and apply them, in place. |
|
Add a "standard" pseudoenzyme to |
|
The BRENDA aggregation of the adapter: |
|
Group BRENDA table row indices by lowercased |
|
Raise |
|
Decide one kcat per reaction from the kcat source files. |
|
One combined kcat per reaction from the kcat lists of several sources. |
|
Bias and error variance per source and evidence bin. |
|
A metabolite name as the compact keys of |
|
The OKP method used when none is given: the first of |
|
DIAMOND hits ( |
|
Build-independent keys of the |
|
Summarise a |
|
What the database holds for one EC number. |
|
EC-tree estimates from a BRENDA measurement table ( |
|
Replace the rightmost numeric level of |
|
The evidence bin of a source's value from its detail column. |
|
Enumerate (reaction, gene, substrate, SMILES, sequence) rows for an ec model. |
|
Filter |
|
Return BRENDA row indices matching |
|
One kcat assignment worth a closer look. |
|
The findings as a TSV document, header included. |
|
Build the provenance string written to |
|
Whole numbers as integers, others in the shortest decimal form that |
|
Match each ec reaction to BRENDA kcat data with progressive |
|
Whether an |
|
Escalate wildcards in |
|
Read |
|
Path of a kcat source file that may be written. |
|
The kcat assignment settings of an adapter, with a preset expanded. |
|
Gather kcats from BRENDA by fuzzy matching and keep them as |
|
Gather kcats from DLKcat and keep them as |
|
Estimate kcats from the EC tree and keep them as |
|
Estimate kcats from measured homologs and keep them as |
|
Gather kcats from OpenKineticsPredictor and keep them as |
|
The parts of one |
|
Read |
|
Read a kcat source file and map its rows to the |
|
Try each of the six search levels in MATLAB's order. |
|
One match attempt at one of the six search levels. |
|
Merge any number of kcat lists, keeping the best source per reaction. |
|
InChIKey (first 25 characters) per model metabolite id, where known: |
|
Fold a source label to lowercase |
|
The source file name of an OKP method, e.g. |
|
The OKP method whose source file is |
|
The OKP methods of the |
|
Thin wrapper over the OKP REST endpoints. |
|
Raised when the OpenKineticsPredictor API returns an error. |
|
Split a provenance string of |
|
Read a kcat source file as it is, without a model. |
|
Remove the standard pseudoenzyme and any standard kcat |
|
Find the model organism's row in PhylDist. |
|
Assignments worth reviewing, most consequential first. |
|
Write a kcat list to the kcat source file |
|
Gather the kcat sources that the configuration needs. |
Reference#
apply_force_wildcards#
apply_force_wildcards(ec_token: str, force_level: int)
Escalate ec_token by force_level wildcards from the right.
A no-op when force_level == 0 (the common case).
apply_kcat_list#
apply_kcat_list(model: 'EcModel', kcat_list: pd.DataFrame, *, criteria: Literal['max', 'min', 'median', 'mean']='max', overwrite: _OverwriteMode=True)
Choose one kcat value per reaction and write it to model.ec.kcat.
Low-level: collect_kcats and assign_kcats run this function; call
it directly only to change kcats by hand.
Ported from GECKO MATLAB: src/gather_kcats/assignKcatValues.m.
For each reaction with one or more entries in kcat_list,
aggregate the candidate kcats per criteria ("max" is the
default and most common) and write the result into
model.ec.kcat at the matching model.ec.rxns position.
The contributing entry's provenance is recorded in
model.ec.source via format_kcat_source: a lowercase
string whose first token is the source and whose bracketed detail,
for a fuzzy BRENDA match, contains the wildcard level and origin
(e.g. "brenda (wc=0, origin=1)"). If the list has no
wildcard_level / origin columns the source is the bare
token.
Rows with kcat == 0 mark "no match" and are dropped before
aggregation.
For criteria="median" or "mean", the aggregated value does
not come from a single input row, so the recorded source is that
of the first row in the reaction's group. For "max" and
"min" the source is unambiguous (the row whose kcat won).
Parameters
modelEcModel with
model.ec.rxns,model.ec.kcat, andmodel.ec.sourcealready allocated. Mutated in place.kcat_listDataFrame with at least the columns
rxn_id,kcat(1/s,0treated as no-match), andsource(per-row). Multiple rows for the same reaction are aggregated percriteria.criteriaHow to aggregate multiple candidates per reaction:
"max"(default),"min","median", or"mean".overwriteTrue(default) overwrites unconditionally.Falseonly fills entries currently 0 or NaN."if_higher"only updates when the new kcat exceeds the existing one (with 0/NaN counted as "infinitely small" so they always update).
Returns
list of strReaction IDs whose kcat was updated.
Raises
ValueErrorIf
criteriaoroverwriteis invalid, or if anyrxn_idinkcat_listis absent frommodel.ec.rxns.KeyErrorIf
kcat_listis missing therxn_id,kcat, orsourcecolumn.
assign_kcats#
assign_kcats(model: 'EcModel', *, adapter: Optional['ModelAdapter']=None, uniprot_db: Optional['UniprotDB']=None, write_report: bool=True)
Assign kcats from the kcat source files and apply them, in place.
Decides one kcat per reaction as collect_kcats does, writes
model.ec.kcat and model.ec.source, and applies the kcat
constraints. Any kcats the model had are replaced: the source files are
the input, and nothing in the model is written back to them.
Returns
(decisions, report)As returned by
collect_kcats.
assign_standard_kcat#
assign_standard_kcat(model: 'EcModel', uniprot_db: 'UniprotDB', *, threshold: int=10, fill_zero_kcat: bool=True)
Add a "standard" pseudoenzyme to model and assign it to
reactions without enzyme constraints.
Low-level: collect_kcats and assign_kcats run this function; call
it directly only to change kcats by hand.
Ported from GECKO MATLAB: src/gather_kcats/getStandardKcat.m.
A standard MW (median of all proteins in uniprot_db) and a
standard kcat (median of all non-zero, non-NaN model.ec.kcat
values, or a per-subsystem median when the subsystem has at least
threshold reactions with a real kcat) are computed. Reactions
that lack a GPR rule, or have a GPR but no entry in
model.ec.rxns, are added to model.ec with this standard
pseudoenzyme. Only the first subsystem of a reaction counts, and
subsystem names that differ only in letter case are one subsystem.
A reaction with an empty subsystem has none.
The function is idempotent: previous "standard" entries
(rows whose model.ec.source has the origin standard and no
tuning status) are stripped
before re-applying.
Filtering: exchange (a reaction without a substrate or without a
product), transport (same metabolite name across compartments), pseudo
(name contains "pseudoreaction", in any letter case), SLIME (name
contains "SLIME rxn", in any letter case), spontaneous (via
adapter.get_spontaneous_reactions(model)), and reactions
listed in adapter.params.path/data/pseudoRxns.tsv are
excluded from receiving the standard pseudoenzyme.
With fill_zero_kcat=True (default), reactions whose existing
ec.kcat is 0 or NaN have their kcat replaced with
standard_kcat and source set to "standard". They keep
their original enzyme assignment.
The function mutates model in place and returns None; the
standard MW/kcat and the counts of reactions touched are emitted
via logger.info instead.
Parameters
modelEcModel with
model.ecalready allocated, the protein pool machinery already set up (prot_poolmetabolite present in the full-model branch), andmodel.adapterset. Mutated in place.uniprot_dbPre-loaded UniprotDB; used only for the median MW.
thresholdMinimum number of reactions with a real kcat in a subsystem before a subsystem-specific median kcat is used. Subsystems with fewer such reactions fall back to the global standard kcat.
fill_zero_kcatWhether to replace existing 0/NaN
ec.kcatentries with the standard kcat.
Raises
ValueErrorIf
model.adapteris None.
brenda_aggregation#
brenda_aggregation(adapter: 'ModelAdapter')
The BRENDA aggregation of the adapter: [kcat_sources.brenda] aggregation.
As the kcat assignment config resolves it: the preset's value (median for
brenda_ec_tree and the other median presets, max for gecko_classic)
unless the file sets it. max when neither the preset nor the file sets it
(the okp preset, or stages without a [kcat_sources.brenda] table).
build_ec_indices#
build_ec_indices(table: pd.DataFrame)
Group BRENDA table row indices by lowercased ec_code.
check_okp_methods#
check_okp_methods(methods: list[str])
Raise ValueError naming the entries of methods that are no known OKP method.
The names are in the order given, each once.
collect_kcats#
collect_kcats(model: 'EcModel', *, adapter: Optional['ModelAdapter']=None, uniprot_db: Optional['UniprotDB']=None, write_report: bool=True)
Decide one kcat per reaction from the kcat source files.
Combines the kcat source files in data/kcats as [kcat_assignment]
in model_adapter.toml sets, without changing the model given;
assign_kcats applies the decisions.
The order is a preset or [[kcat_assignment.stage]] tables. A stage
assigns a kcat to the reactions that are still open:
select: the first listed source with a value (seemerge_kcats). Sources are source file names and the BRENDA tiersdatabase_exact,database_topanddatabase_bottom, which readbrenda.tsv.combine: all listed sources with a value, each corrected for its bias and weighted by its reliability for that reaction (seegeckopy.gather_kcats.combine_kcats);ec.sourcereadscombined (sd=<log10 sd>, n=<sources>).
In both, okp stands for the OKP methods of [kcat_sources.okp] methods (default: KinForm-H).
The presets:
brenda_ec_tree(the default): custom kcats, the BRENDA median of measurements of the organism on the reaction's substrate (origin 1, without EC wildcards), the EC tree (kcats_from_ec_tree); then the OKP methods combined for the reactions left (without an EC number).ec_tree_homologs: custom kcats, the organism's own BRENDA value; then the EC tree and homologs (kcats_from_homologs) combined; then the OKP methods combined.ec_tree_okp: custom kcats, the organism's own BRENDA value; then the EC tree, homologs and the OKP methods combined; then the OKP methods combined.okp: custom kcats; then the OKP methods combined.gecko_median: custom kcats, the BRENDA median of matches without EC wildcards from the organism or other organisms, with or without the substrate (origin 1 to 4), DLKcat, then the other BRENDA matches (EC wildcards, and specific activities, origin 5 and 6).gecko_classic: as gecko_median with the BRENDA maximum and the specific-activity matches above DLKcat (origin up to 6), as the GECKO 3 tutorial.
Against measured kcats hidden from the search, the EC tree was closer
than the BRENDA median at origins 2 and 4 and with EC wildcards and as
close at origins 1 and 3; the EC tree combined with the OKP methods was
slightly closer than the EC tree, and the OKP methods combined as close.
That comparison combined the eight OKP methods with combination
parameters; the default okp group is now KinForm-H alone. In ecModels, values combined with predictions set high-turnover enzymes
such as ATP synthase too low, which is why the default uses predictions
only where there is no value from measurements. The BRENDA aggregation is
[kcat_sources.brenda] aggregation (see update_kcat_sources).
After the stages: with isozymes, kcats from isozymes; with
standard, the standard kcat for the rest. A source file a stage names
that does not exist is reported and left out. A stage that lists custom
raises a ValueError when there is no data/kcats/custom.tsv but a
GECKO 3 data/customKcats.tsv: geckopy.upgrade.convert_custom_kcats
converts it.
Parameters
modelThe ecModel.
adapterModel adapter (default:
model.adapter).uniprot_dbUniProt data for the standard kcat (default:
data/uniprot.tsv).write_reportWrite the decisions to
output/<model id>_kcatDecisions.tsv.
Returns
(decisions, report, ec_model)decisionshas one row permodel.ecreaction:ec_rxn,stage(the stage number,isozymes,standard, or empty without a kcat),source,kcat,candidates(values the deciding source had),spread_log10(their range, in log10 units) andsd_log10(the uncertainty of a combined kcat, a standard deviation in log10 units; NaN for the other stages).reporthas thepreset, themissingsource files and, per source file, its load report.ec_modelis a copy of the model with the decided kcats, beforeapply_kcat_constraints.
combine_kcats#
combine_kcats(lists: dict[str, pd.DataFrame], params: CombineParams)
One combined kcat per reaction from the kcat lists of several sources.
Parameters
listsPer source name (
ec_tree,homologs,okp_<method>) its kcat list asload_kcat_sourcereturns it (rxn_id,kcat,detail). Several rows of one source for a reaction (substrates, isozymes) give that source's median, with the evidence bin of its row of best evidence.paramsFrom
load_combine_params.
Returns
pandas.DataFramerxn_id,kcat,sd(log10),n(sources),spread_log10(range of the sources' values) andsources.
CombineParams#
Bias and error variance per source and evidence bin.
compact_name#
compact_name(name: str)
A metabolite name as the compact keys of substrates.tsv: without
markup, Greek letters spelled out, accents dropped, lower case, and only
letters, digits and + kept.
default_okp_method#
default_okp_method(adapter: 'ModelAdapter')
The OKP method used when none is given: the first of [kcat_sources.okp] methods.
diamond_hits#
diamond_hits(queries: dict[str, str], targets: Path, *, min_identity: float=0.4, coverage: float=0.8, threads: Optional[int]=None, diamond: Optional[str]=None)
DIAMOND hits (query, target, identity as a fraction) of
the query sequences against a FASTA file, best identity per pair.
ec_rxn_keys#
ec_rxn_keys(model: 'EcModel')
Build-independent keys of the model.ec reactions.
Returns
(base_rxns, enzyme_sets)Per
model.ec.rxnsentry: the conventional reaction (without a trailing_EXP_<n>in a full model, or a leading<nnn>_in a light model; a reverse direction keeps its_REV), and the UniProt accessions of its enzymes, sorted and joined by" + "(empty without enzymes).
ec_stats_from_brenda#
ec_stats_from_brenda(brenda)
Summarise a BrendaData per EC number.
EcStats#
What the database holds for one EC number.
ECTree#
EC-tree estimates from a BRENDA measurement table (ec, log10_kcat).
escalate_wildcard#
escalate_wildcard(ec_token: str)
Replace the rightmost numeric level of ec_token with -.
Returns the new token, or None if every level is already
- (fully wildcarded).
evidence_bin#
evidence_bin(source: str, detail: str)
The evidence bin of a source's value from its detail column.
extract_enzyme_substrate_pairs#
extract_enzyme_substrate_pairs(model: 'EcModel', ignore_lists: 'DLKcatIgnoreLists', *, ec_rxns: Optional[Iterable[str]]=None, only_with_smiles: bool=True)
Enumerate (reaction, gene, substrate, SMILES, sequence) rows for an ec model.
Shared core of the DLKcat input writer and the OpenKineticsPredictor
input builder. Performs the same filtering (ignored metabolites,
prot_ pseudometabolites, currency-metabolite pairs) and the same
only_with_smiles handling, but does no file I/O.
Parameters
modelEcModel with
ec.rxns,ec.genes,ec.sequenceandec.rxn_enz_matpopulated, and per-metabolite SMILES inannotation['smiles'].ignore_listsLoaded
DLKcatIgnoreLists.ec_rxnsOptional iterable of reaction IDs (must be in
model.ec.rxns).Nonemeans all; the rows follow the order ofmodel.ec.rxns.only_with_smilesDrop rows with no SMILES when True; otherwise write
"None".
Returns
pandas.DataFrameColumns
rxn_id, gene, substrate, smiles, sequence, met_id.
filter_by_organism#
filter_by_organism(table: pd.DataFrame, rows: np.ndarray, organism: Optional[str], phyl_dist: 'PhylDist', org_index: Optional[int])
Filter rows of table by organism.
If organism is given, an exact case-insensitive match is
required. Otherwise the rows are restricted to the
phylogenetically closest organism(s) per phyl_dist (using
org_index as the model-organism row). If org_index is
also None, no filtering is applied -- matches MATLAB when
the model organism has no KEGG entry.
filter_by_substrate#
filter_by_substrate(table: pd.DataFrame, rows: np.ndarray, substrates: list[str])
find_ec_rows#
find_ec_rows(ec_token: str, ec_indices: dict[str, np.ndarray])
Return BRENDA row indices matching ec_token.
Wildcard handling: the prefix up to the first - is matched
case-insensitively against the start of each EC key. A fully-
wildcarded -.-.-.- matches every row.
Finding#
One kcat assignment worth a closer look.
findings_tsv#
findings_tsv(rows: Sequence[Finding])
The findings as a TSV document, header included.
format_kcat_source#
format_kcat_source(origin: object, detail: Optional[Mapping[str, object]]=None, tuned: Iterable[str]=(), prior: Optional[float]=None)
Build the provenance string written to model.ec.source.
Mirrors GECKO MATLAB's formatKcatSource.
Parameters
originWhere the kcat came from (
"brenda","custom","okp_catapro", ...). Lower-cased, with every run of characters outside[0-9a-z]folded to one_("OKP-CataPro"gives"okp_catapro").detailkey=valuepairs written in the order of the mapping, keys normalised as the origin. A number is written with%.6g, text verbatim. A pair whose value is None, NaN or infinite is left out, so is a pair whose key does not start with a letter after the normalisation, and the brackets are left out when no pair is left.tunedTuning methods applied to the kcat, in order of application. The tuning status is written when this is not empty.
priorThe kcat before the first tuning, written as
(prior=<value>)after the methods; None or NaN means none.
Returns
strThe provenance string. An empty
origingives""when there is no detail and no tuning status, and the originunknownotherwise.
Examples
>>> format_kcat_source("brenda", {"wc": 0, "origin": 1})
'brenda (wc=0, origin=1)'
>>> format_kcat_source("OKP-CataPro", {"similarity": 42}, ["cmaes"], 5.48)
'okp_catapro (similarity=42) | tuned=cmaes (prior=5.48)'
format_number#
format_number(x: Any)
Whole numbers as integers, others in the shortest decimal form that
reads back as the same float; "Inf" for infinity, "" for NaN.
Matches GECKO's saveKcatSource.
fuzzy_kcat_matching#
fuzzy_kcat_matching(model: 'EcModel', brenda: 'BrendaData', phyl_dist: 'PhylDist', *, ec_rxns: Optional[Iterable[str]]=None, force_wildcard_level: int=0, aggregate: Optional[str]=None, adapter: Optional['ModelAdapter']=None)
Match each ec reaction to BRENDA kcat data with progressive
relaxation of EC, substrate, and organism specificity.
Low-level: kcats_from_brenda runs this function; call it directly
only to inspect or change the BRENDA matches by hand.
Ported from GECKO MATLAB: src/gather_kcats/fuzzyKcatMatching.m.
For each selected reaction, the EC string in
model.ec.eccodes[i] is split on ; into one or more EC
tokens. Each token goes through:
Wildcard cascade (per token): try the token as-is. If no match, replace its rightmost numeric level with
-and try again. Repeat until matched or all four levels are wildcards.Six-level matching (per attempt): try increasingly relaxed criteria:
org + correct substrate + KCAT (output origin 1)
any organism + correct substrate + KCAT (output origin 2)
org + any substrate + KCAT (output origin 3)
org + specific activity (output origin 5)
any organism + any substrate + KCAT (output origin 4)
any organism + SA (output origin 6)
When the EC has any wildcard, substrate-matching levels are skipped (the substrate field of an EC holds the catalytic specificity that wildcards already discard).
Across the multiple EC tokens of one reaction, the best match is chosen by minimum wildcard count, then the earliest-tried level in the order above (so org + SA, origin 5, beats any organism + any substrate + KCAT, origin 4), then maximum kcat.
The model's organism is read from
model.adapter.params.org_name. When BRENDA has no exact
organism match, phyl_dist is used to select the BRENDA row(s)
for the phylogenetically closest organism(s) (with genus fallback
for organisms missing from KEGG).
The six levels are tried in the fixed order listed above, not in order of output rank: org + SA (origin 5) is tried before any organism + any substrate + KCAT (origin 4), so when both would match, org + SA is kept even though origin 4 would otherwise be considered the better rank.
Match statistics (counts per origin and per wildcard level) are
logged via logger.info rather than returned.
Parameters
modelEcModel with
model.ec.rxnsandmodel.ec.eccodesalready populated. Reactions whoseec.eccodesentry is empty contribute a row to the output withkcat=0andorigin=NA.brendaBRENDA tables loaded by
load_brenda_data.phyl_distKEGG phylogenetic distance loaded by
load_phyl_dist.ec_rxnsOptional iterable of reaction IDs (must appear in
model.ec.rxns) restricting which entries are matched.Nonemeans match all.force_wildcard_levelForce at least this many wildcards on every EC token before the iterative escalation begins. Default 0 (no forcing).
aggregateHow to collapse the BRENDA rows matched at a search level to one kcat:
"max"(the highest reported turnover) or"median"(more robust to assay outliers / engineered mutants).None(default) reads[kcat_sources.brenda] aggregationof the adapter as the kcat assignment resolves it: median for the default presetbrenda_ec_tree, max forgecko_classic.The choice sets both aggregation layers consistently: it selects the matching snapshot view (
brenda.kcat_for(aggregate)/brenda.sa_for(aggregate)) and applies the same reduction across whichever rows survive the EC + organism + substrate gates. See https://gecko-docs.readthedocs.io/en/latest/guide/kcat-sources.html for the empirical rationale.adapterModel adapter for
org_nameand the aggregation default (default:model.adapter).
Returns
pandas.DataFrameColumns:
============ ============================================================ rxn_id (str) reaction ID, matching
model.ec.rxnssource (str)"brenda"for every row eccode (str) the;-joined EC string used (afterforce_wildcard_levelbut before iterative escalation) substrates (list[str]) per-row substrate names genes (list[str]) always empty for fuzzy matching; kept for schema compatibility with future DLKcat output kcat (float) selected kcat in 1/s, or 0.0 if no match wildcard_level (Int64) actual wildcard count at match time, or NA origin (Int64) output origin 1..6, or NA if no match ============ ============================================================
is_standard_source#
is_standard_source(source: object)
Whether an ec.source entry marks the standard kcat.
True when the origin is standard (compared exactly) and the string has
no tuning status, so a tuned standard kcat counts as set on purpose.
iterative_match_one_ec#
iterative_match_one_ec(ec_token: str, substrates: list[str], substrate_coeffs: list[float], brenda_kcat: pd.DataFrame, brenda_sa: pd.DataFrame, kcat_ec_indices: dict[str, np.ndarray], sa_ec_indices: dict[str, np.ndarray], organism_name: str, phyl_dist: 'PhylDist', org_index: Optional[int], aggregate: str='max')
Escalate wildcards in ec_token until a match is found or
every level is wildcarded.
Returns (kcat, output_origin, wildcard_level). On no match,
returns (0.0, 0, NO_MATCH_WC).
kcat_assignment_config#
kcat_assignment_config(adapter: 'ModelAdapter')
Read [kcat_assignment] and [kcat_sources] of the adapter.
Without a preset or stages the preset is brenda_ec_tree. A
[kcat_sources.<name>] table overrides only the keys it sets of the
preset's settings for that source.
kcat_source_file#
kcat_source_file(name: str, *, model: Optional['EcModel']=None, adapter: Optional['ModelAdapter']=None, folder: Optional[str | Path]=None)
Path of a kcat source file that may be written.
Checks the name, resolves the folder (data/kcats in the project
folder by default), and refuses a file curated by hand: named
custom.tsv, or whose header says kind: curated or
source: custom (in any case).
KcatAssignmentConfig#
The kcat assignment settings of an adapter, with a preset expanded.
kcats_from_brenda#
kcats_from_brenda(model: 'EcModel', *, aggregation: Optional[str]=None, force_wildcard_level: int=0, ec_rxns: Optional[Iterable[str]]=None, brenda: Optional['BrendaData']=None, phyl_dist: Optional['PhylDist']=None, save: bool=True, save_as: str='brenda', adapter: Optional['ModelAdapter']=None)
Gather kcats from BRENDA by fuzzy matching and keep them as brenda.tsv.
Runs locally on the BRENDA files of geckopy (see
geckopy.gather_kcats.fuzzy_kcat_matching).
Parameters
modelEcModel with EC numbers.
aggregationWhich BRENDA value per EC number, substrate and organism is used:
"max"or"median"(default:[kcat_sources.brenda] aggregationas the kcat assignment resolves it: median for the default presetbrenda_ec_tree, max forgecko_classic).force_wildcard_levelForce a minimum wildcard level in the EC numbers.
ec_rxnsmodel.ec.rxnsto gather kcats for (default: all). With the defaultsave_asthe file then only holds those reactions.brenda, phyl_distLoaded BRENDA data and KEGG phylogenetic distances (default: loaded from the adapter's folders;
PhylDist.matis downloaded there when missing).save, save_asWrite the source file, and its name without
.tsv.adapterModel adapter (default:
model.adapter).
Returns
pandas.DataFrameThe kcat list.
kcats_from_dlkcat#
kcats_from_dlkcat(model: 'EcModel', *, via: Optional[str]=None, run: bool=False, wait: bool=False, ec_rxns: Optional[Iterable[str]]=None, save: bool=True, save_as: str='dlkcat', adapter: Optional['ModelAdapter']=None)
Gather kcats from DLKcat and keep them as dlkcat.tsv.
via sets where the predictions come from:
"okp": the DLKcat method of OpenKineticsPredictor (seekcats_from_okp), which needs an API key. OKP is a web service with a job queue: the first call submits a job, a later call fetches the result, anddoneis False while the job runs."file": the output of an earlier run indata/DLKcat.tsv, for example of a GECKO 3 project."docker": a local run of DLKcat in its Docker image, which needs Docker. This is the older method;"okp"runs the same predictor without Docker. A run records how many reactions it covered indata/DLKcat_run.txt, so that the source file says so also when the output is read later.
Parameters
modelEcModel with metabolite SMILES and protein sequences.
via"okp","file"or"docker"(default:"file"whendata/DLKcat.tsvexists,"okp"otherwise).runThe same as
via="docker"(default False). Combined with anotherviait raises aValueError.waitWith
via="okp": wait until the job is done.ec_rxnsmodel.ec.rxnsto predict for (default: all); needsvia="okp"orvia="docker". With"okp"it is only used when a job is submitted.save, save_as, adapterAs in
kcats_from_brenda.
Returns
(kcat_list, done)The kcat list (
Nonewhile an OKP job is not done), and whether the kcats were available.
kcats_from_ec_tree#
kcats_from_ec_tree(model: 'EcModel', *, k: float=5.0, ec_rxns: Optional[Iterable[str]]=None, measurements: Optional[pd.DataFrame]=None, save: bool=True, save_as: str='ec_tree', adapter: Optional['ModelAdapter']=None)
Estimate kcats from the EC tree and keep them as ec_tree.tsv.
Each reaction gets the median kcat of all wild-type BRENDA measurements
of its EC number, from any organism and substrate, shrunk toward the
median of the EC's 3-digit and 2-digit classes with weight
n / (n + k) for n measurements (see
geckopy.gather_kcats.ec_tree.ECTree). A reaction with several
EC numbers uses the one with most measurements. Reactions without an EC
number, or whose EC classes have no measurements, get no value.
Parameters
modelEcModel with EC numbers (
model.ec.eccodes).kShrinkage constant: the number of measurements at which an EC's own median and its class count equally.
ec_rxnsmodel.ec.rxnsto estimate kcats for (default: all). An empty list selects no reaction. With the defaultsave_asthe file then only holds those reactions.measurementsBRENDA measurement table (default:
measurements.tsvof the adapter's BRENDA folder, seegeckopy.databases.load_brenda_measurements).save, save_asWrite the source file, and its name without
.tsv.adapterModel adapter (default:
model.adapter).
Returns
pandas.DataFrameThe kcat list;
detailhas the number of measurements of the EC (n) and the deepest EC level with measurements (depth).
kcats_from_homologs#
kcats_from_homologs(model: 'EcModel', *, k: int=10, min_identity: float=0.4, coverage: float=0.8, threads: Optional[int]=None, diamond: Optional[str]=None, save: bool=True, save_as: str='homologs', adapter: Optional['ModelAdapter']=None)
Estimate kcats from measured homologs and keep them as homologs.tsv.
See geckopy.gather_kcats.homologs. One row per reaction and
substrate; for an enzyme complex the median of its subunits' estimates.
Reactions without a homolog measured on one of their substrates get no
value.
Parameters
modelEcModel with enzyme sequences (
ec.sequence).kThe number of most identical homologs averaged.
min_identity, coverageDIAMOND thresholds: identity, and coverage of both sequences.
threads, diamondDIAMOND threads, and its executable (default: found by raven-toolbox, which downloads it when needed).
save, save_asWrite the source file, and its name without
.tsv.adapterModel adapter (default:
model.adapter).
Returns
pandas.DataFrameThe kcat list;
detailhas the identity of the nearest homolog (identity) and the number of homologs used (n).
kcats_from_okp#
kcats_from_okp(model: 'EcModel', *, method: Optional[str]=None, wait: bool=False, resubmit: bool=False, use_stored: bool=False, ec_rxns: Optional[Iterable[str]]=None, save: bool=True, save_as: Optional[str]=None, adapter: Optional['ModelAdapter']=None)
Gather kcats from OpenKineticsPredictor and keep them as okp_<method>.tsv.
OKP is a web service with a job queue, so this can be called repeatedly:
without a job for method it submits one; with a job it fetches the
result, and writes the file once the job is done. Each method keeps its
own job in data/OKP_job_<method>.txt and its own result in
data/OKP_output_<method>.csv, so jobs of several methods can run at
the same time. The job file records which job the stored result came
from; use_stored only uses a result of the current job. An API key
is needed.
Parameters
modelEcModel with metabolite SMILES and protein sequences.
methodOKP method, e.g.
"CataPro","CatRange","UniKP"(default: the first of[kcat_sources.okp] methods,"KinForm-H"unless set).waitWait until the job is done.
resubmitSubmit a new job even if one exists for this method; its earlier result is removed.
use_storedRead the stored result of this method's job without contacting OKP.
ec_rxnsmodel.ec.rxnsto predict for (default: all); only used when a job is submitted.save, save_as, adapterAs in
kcats_from_brenda;save_asdefaults tookp_<method>, in lower case, with other characters than letters and digits as_.
Returns
(kcat_list, done)The kcat list (
Nonewhile the job is not done), and whether the result was available.
KcatSource#
The parts of one ec.source string.
Attributes
originThe origin as written (case is not changed);
""for a missing string.detailThe
key=valuepairs of the detail: a float when the value parses as a number, a str otherwise.tunedThe tuning methods in order of application.
priorThe kcat before the first tuning, or None.
load_combine_params#
load_combine_params(path: str | Path)
Read kcatCombineParams.tsv.
load_kcat_source#
load_kcat_source(model: 'EcModel', name: str | Path, *, adapter: Optional['ModelAdapter']=None)
Read a kcat source file and map its rows to the model.ec reactions.
A row with
rxnandenzymesapplies to themodel.ecrows with that conventional reaction and that enzyme set.A row with only
enzymesapplies to every row with that enzyme set; a row with onlyrxnto every row of that reaction (curated rows;save_kcat_sourcealways writes both).A row whose kcat is missing, not a number, infinite, or not above 0 is reported as invalid and not applied.
A row that matches nothing is reported, never dropped silently. If a
model.ecrow has at least half of the row's enzymes, that partial match is reported as well, but not applied.
The enzymes of a row may be listed in any order.
Parameters
modelThe ecModel.
nameName of the source (
data/kcats/<name>.tsvin the project folder), or the path to a kcat source file.
Returns
(kcat_list, report)kcat_listhas one row per applied match, in the kcat-list schema (rxn_id,source,eccode,substrates,genes,kcat,wildcard_level,origin) pluslog10_sd,detail(the detail column) andline(the line of the file).reporthas theinvalid,unmatchedandpartialrows.
main_match#
main_match(ec_token: str, substrates: list[str], substrate_coeffs: list[float], brenda_kcat: pd.DataFrame, brenda_sa: pd.DataFrame, kcat_ec_indices: dict[str, np.ndarray], sa_ec_indices: dict[str, np.ndarray], organism_name: str, phyl_dist: 'PhylDist', org_index: Optional[int], aggregate: str='max')
Try each of the six search levels in MATLAB's order.
Returns (kcat, output_origin, num_matches) from the first
level that matches. output_origin == 0 means no match.
match_kcat#
match_kcat(ec_token: str, substrates: list[str], substrate_coeffs: list[float], table: pd.DataFrame, ec_indices: dict[str, np.ndarray], organism: Optional[str], *, substrate_match: bool, sa: bool, phyl_dist: 'PhylDist', org_index: Optional[int], aggregate: str='max')
One match attempt at one of the six search levels.
substrate_match restricts table to rows whose substrate is
in substrates before the organism filter runs; sa selects
the specific-activity table instead of the kcat table. aggregate
("max" or "median") controls how the surviving rows are
collapsed to one value.
Returns (kcat_in_1_per_s, num_matched_rows), where kcat is
the value selected by aggregate. num_matched == 0 means no
rows survived the filters.
merge_kcats#
merge_kcats(*kcat_lists: pd.DataFrame, source_priority: Sequence[str], top_origin_limit: int=4, bottom_origin_limit: int=6, wildcard_limit: int=3, database_sources: Iterable[str]=_DEFAULT_DATABASE_SOURCES)
Merge any number of kcat lists, keeping the best source per reaction.
Low-level: collect_kcats runs this function; call it directly only
to merge kcat lists by hand.
All input lists are concatenated and each row is assigned a tier (see the module docstring). For every reaction the highest-priority tier present is kept, and all rows of that tier for that reaction are kept; rows of lower-priority tiers for the same reaction are dropped.
Rows whose kcat is non-positive or missing have no usable
turnover number and are dropped first. This also removes the
kcat == 0 / origin == NA rows that fuzzy_kcat_matching
emits for unmatched reactions, so a leftover NA-metadata
experimental-database row is unambiguously an exact OKP value and
is routed to database_top.
Parameters
*kcat_listsOne or more DataFrames in the canonical 8-column kcat-list schema. A single list may mix several sources.
source_priorityOrdered sequence (best first) of tier tokens / source labels. Tokens are normalised the same way as row sources, except the reserved
"database_top"/"database_bottom"tiers. A source not listed here is dropped (with a warning).top_origin_limitOrigin upper bound for
database_topfuzzy rows.[1, 6]. Default4, not6: origins 5-6 are specific-activity × molecular-weight derived kcats, which BRENDA's own data quality does not always support treating as better than a prediction (a bad SA/MW join can otherwise silently override a good prediction with an outlier -- seeload_brenda_data'sfilter_outlier_kcats, which removes the worst of these before they reach this function, but does not catch every one).bottom_origin_limitOrigin upper bound for
database_bottomfuzzy rows.[1, 6].wildcard_limitMaximum wildcard count for the
database_bottomwildcard branch.[0, 3].database_sourcesSource labels treated as experimental databases (routed to the
database_*tiers). Defaults to("brenda", "sabio_rk").
Returns
pandas.DataFrameMerged kcat list in the canonical 8-column schema. Row order follows the input lists (each list's surviving rows, in turn), matching MATLAB
mergeKcats. The original (un-normalised)sourcestrings are preserved.
Raises
ValueErrorIf no list is given,
source_priorityis empty, a limit is out of range, or any input list is missing required columns.
metabolite_inchikeys#
metabolite_inchikeys(model: 'EcModel', substrates: pd.DataFrame)
InChIKey (first 25 characters) per model metabolite id, where known:
from its ChEBI annotations, then its MetaNetX annotations, then its name.
normalize_source#
normalize_source(label: object)
Fold a source label to lowercase snake_case.
"Sabio-RK" -> "sabio_rk", "DLKcat" -> "dlkcat",
"CataPro" -> "catapro". Runs of non-alphanumeric characters
collapse to a single underscore; leading/trailing underscores are
stripped.
okp_file#
okp_file(method: str)
The source file name of an OKP method, e.g. okp_kinform_h.
okp_ and the method in lower case, with each run of characters other
than letters and digits as _ and no _ at either end.
okp_method_of_file#
okp_method_of_file(name: str)
The OKP method whose source file is name, e.g. KinForm-H for okp_kinform_h.
okp_methods#
okp_methods(config: KcatAssignmentConfig)
The OKP methods of the okp source group ([kcat_sources.okp] methods).
OKPClient#
Thin wrapper over the OKP REST endpoints.
The session argument exists so tests can inject a mocked
requests.Session; in production a fresh session is created.
OKPError#
Raised when the OpenKineticsPredictor API returns an error.
parse_kcat_source#
parse_kcat_source(text: object)
Split a provenance string of model.ec.source into its parts.
Mirrors GECKO MATLAB's parseKcatSource. A string that does not
follow the format is read as an origin with no detail and no tuning
status, so a string written by an earlier version stays readable.
Parameters
textOne
ec.sourceentry. None, NaN and anything that is not a str give the origin"".
Returns
KcatSourceoriginas written,detail(numbers as float),tuned(methods in order) andprior(None when absent).
Examples
>>> info = parse_kcat_source("brenda (wc=0, origin=2) | tuned=cmaes (prior=6.55)")
>>> info.origin, info.detail, info.tuned, info.prior
('brenda', {'wc': 0.0, 'origin': 2.0}, ('cmaes',), 6.55)
read_kcat_source#
read_kcat_source(path: str | Path)
Read a kcat source file as it is, without a model.
The file is read as UTF-8 (a leading byte-order mark is ignored). The
# lines before the column header are the header; # lines and
blank lines further down are skipped, as are rows without a filled field
(a row of empty quoted fields included). Fields wrapped in double quotes,
as a spreadsheet may save them, are unwrapped; a field that opens a
double quote and does not close it raises ValueError. kcat and
log10_sd must be plain numbers (12, 0.5, 1e-05); other
text, such as 5,5 with a decimal comma, is read as NaN, which
load_kcat_source reports. A row with more filled fields than
there are columns is an error.
Returns
(records, meta)recordshas one row per data row:kcatandlog10_sdas floats (NaN when empty or not a number), every other column as text; columns other than the standard ones are kept, andlineis the line number of each row in the file.metaholds the#header lines as{key: value}.
remove_standard_kcat#
remove_standard_kcat(model: 'EcModel')
Remove the standard pseudoenzyme and any standard kcat
assignments from model.
Low-level: it undoes assign_standard_kcat, which collect_kcats
and assign_kcats run; call it directly only to change kcats by hand.
Ported from GECKO MATLAB: src/gather_kcats/removeStandardKcat.m.
Inverse of assign_standard_kcat. Cleans up:
Reactions in
ec.rxnswhose row inrxn_enz_matpoints to the "standard" pseudoenzyme are dropped from all per-reaction ec fields.The "standard" entry is dropped from all per-enzyme ec fields, and its column is removed from
rxn_enz_mat.Remaining ec.rxns rows whose
sourcehas the originstandardand no tuning status (these are rxns whose existing kcat was filled byfill_zero_kcat=True, but linked to a real enzyme) have theirkcatreset to 0 andsourcecleared.apply_kcat_constraintsis invoked on the affected rxns to update theSmatrix.prot_standardmetabolite,usage_prot_standardreaction, and the"standard"gene are removed from the cobra model (if present).
Idempotent: running on a model with no standard pseudoenzyme is a no-op.
Parameters
modelEcModel with a standard pseudoenzyme installed by
assign_standard_kcat. Mutated in place.
resolve_organism_index#
resolve_organism_index(org_name: str, phyl_dist: 'PhylDist')
Find the model organism's row in PhylDist.
Returns None if neither a direct match nor a genus fallback
is found (in which case organism filtering is skipped, matching
MATLAB).
review_assignment#
review_assignment(rxn_ids: Sequence[str], kcats: np.ndarray, sources: Sequence[str], ec_codes: Sequence[str], *, ec_stats: Optional[Mapping[str, EcStats]]=None, enzymes: Optional[Sequence[Iterable[str]]]=None, names: Optional[Sequence[str]]=None, leverage: Optional[np.ndarray]=None, slow: float=0.01, fast: float=10000.0, ec_max_gap: float=3.0, repeat_min: int=5, include: Sequence[str]=(), coverage: Optional[float]=None, top: Optional[int]=None)
Assignments worth reviewing, most consequential first.
Parameters
ec_statsPer-EC database summary. Checks needing it are skipped when it is absent, so the function still runs without a database.
enzymesProtein ids per kcat, used to count how many other reactions share an enzyme -- a change here may imply changes there.
leveragePer-kcat effect on the distance from a one-at-a-time screen. Without it the findings cannot be ranked and are returned in input order.
coverage, topTruncate the report.
coveragekeeps the rows carrying that share of the flagged leverage, so 0.9 drops the tail that together accounts for a tenth of what the findings are worth; it adapts to the model wheretopdoes not. Measured against all kcats instead, the threshold would be unreachable, since flagged rows are a minority of the model's leverage.includeNames from
OPTIONAL_CHECKSto report as well.sourcesThe source labels
customandstandardare recognised without regard to letter case.
Returns
list of :class:Finding, one per free parameter.
:
save_kcat_source#
save_kcat_source(model: 'EcModel', kcat_list: pd.DataFrame, name: str, *, adapter: Optional['ModelAdapter']=None, folder: Optional[str | Path]=None, generator: str='save_kcat_source', parameters: Optional[dict]=None, data: str='', kind: str='gathered')
Write a kcat list to the kcat source file <name>.tsv.
Left out are rows with kcat 0, NaN or below (no value found), and rows
of model.ec reactions without enzymes, which have no enzyme
constraint and could not be told apart from their isozymes.
Parameters
modelThe ecModel the kcat list refers to.
kcat_listA kcat list as returned by the
kcats_from_*functions,fuzzy_kcat_matching,kcats_from_dlkcatormerge_kcats: columnsrxn_idandkcat, optionallysubstrates,eccode,wildcard_level,origin,source,log10_sdanddetail(furtherkey=valuepairs for the detail column).nameName of the source; the file is
<name>.tsv.adapterModel adapter (default:
model.adapter); gives the project folder.folderFolder to write to (default:
data/kcatsin the project folder).generator, parameters, dataWhat produced the values, its settings (written as JSON with sorted keys) and the version of the data they come from.
kind"gathered"(default) or"curated".
A file named ``custom.tsv``, or whose header says ``kind: curated`` or
:
```source: custom``, is never written.` :
Returns
pathlib.PathThe file written.
Stage#
update_kcat_sources#
update_kcat_sources(model: 'EcModel', *, dry_run: bool=False, adapter: Optional['ModelAdapter']=None)
Gather the kcat sources that the configuration needs.
Lists the source files that [kcat_assignment] uses and gathers those
that are missing or outdated with kcats_from_brenda,
kcats_from_ec_tree, kcats_from_dlkcat and
kcats_from_okp. A file is outdated when its header records other
settings than [kcat_sources.<name>] asks for (presets set these for
brenda and ec_tree) or, for brenda and ec_tree, another BRENDA release
than the BRENDA files in use. DLKcat reads data/DLKcat.tsv if it
exists and otherwise predicts with the DLKcat method of
OpenKineticsPredictor (see kcats_from_dlkcat); OKP and DLKcat
submit or fetch a job and report it as pending while it runs; they need
an OKP API key (DLKcat only without data/DLKcat.tsv).
custom.tsv and files it cannot gather are left as they are. Calling
it again is safe.
Returns
pandas.DataFrameOne row per source:
source,status(current, gathered, pending, outdated, missing, failed or skipped) andnote.