Reconstruction (Python)#
raven-toolbox objects in raven_toolbox.reconstruction.
Functions#
Function |
Summary |
|---|---|
Build a draft model from a |
|
Assign genes to KOs from HMM hits, applying the cut-off and ratio filters. |
|
Load a precomputed homology hits table from a CSV path or a DataFrame (not Excel). |
|
Build the HMM library of a domain ( |
|
Build the minimal relational tables from parsed records. |
|
Write one |
|
Cluster, align and train a profile HMM for one KO's multi-FASTA. |
|
Assemble the gene-free KEGG reference model from parsed records. |
|
Fetch and arrange a complete KEGG dump into |
|
Extract and arrange the downloaded archives into the flat dump layout. |
|
Download the raw KEGG archives into |
|
Reaction ids whose |
|
Reconstruct a draft model for a KEGG species from its KO annotations. |
|
Load the published reference artefacts from |
|
Reconstruct a draft model for a proteome by HMM-searching the KO library. |
|
Load the reference model and tables from |
|
Build a draft model for |
|
Build a homology hits table from a SuppOrth |
|
Result of |
|
A metabolite parsed from the KEGG |
|
A KEGG Orthology entry: its name and the organism genes assigned to it. |
|
A reaction parsed from the KEGG |
|
Build a bidirectional hits table from a predefined ortholog list. |
|
Return |
|
Organism ids whose outermost category matches |
|
Parse |
|
Parse |
|
Parse a full KEGG dump into the reference model + tables and write them out. |
|
Parse |
|
Parse |
|
Return |
|
Return |
|
Compute the KEGG phylogenetic distance matrix from the |
|
KEGG phylogenetic distance structure of RAVEN |
|
Read a KEGG table from |
|
Bidirectional BLAST+ between an organism and template organisms. |
|
Bidirectional DIAMOND between an organism and template organisms. |
|
Search the profile |
|
Run SuppOrth on an organism and template proteomes and read its consensus. |
|
Stream the |
|
Check that a hits DataFrame has the required columns and return it unchanged. |
|
Write each table as a gzipped TSV ( |
Reference#
assemble_model_from_ko_genes#
assemble_model_from_ko_genes(reference_model: cobra.Model, ko_reaction: pd.DataFrame, ko_to_genes: dict[str, list[str]], *, rxn_flags: pd.DataFrame | None=None, keep_spontaneous: bool=True, keep_undefined_stoich: bool=True, keep_incomplete: bool=True, keep_general: bool=False, model_id: str | None=None, model_name: str | None=None, note: str | None=None, prune_orthology: bool=False)
Build a draft model from a {ko: [gene, ...]} assignment.
Returns (model, gpr_map) where gpr_map is the kept reactions' gene
lists, so callers can add gene annotations afterwards.
rxn_flags is a per-reaction quality-flag table (a reaction column
plus any of spontaneous, undefined_stoich, incomplete and general).
A reaction flagged undefined_stoich, incomplete or general is
dropped unless its matching keep_* argument is True; this takes
precedence over the reaction having genes. keep_spontaneous (default
True) additionally keeps otherwise gene-less reactions flagged
spontaneous.
prune_orthology restricts each gene-backed reaction's kegg.orthology
annotation to the KOs that contributed a gene, as in the HMM branch of RAVEN
getKEGGModelForOrganism. The organism-annotation path keeps the full
reference KO list, and the default is False.
assign_kos#
assign_kos(hits: pd.DataFrame, *, cutoff: float=1e-30, min_score_ratio_ko: float=0.3, min_score_ratio_g: float=0.9)
Assign genes to KOs from HMM hits, applying the cut-off and ratio filters.
Ports RAVEN's three steps on the KO by gene E-value matrix. An E-value of 0 is replaced by 1e-250. The steps are:
keep hits with
evalue <= cutoff;min_score_ratio_ko: within a KO, drop genes whoselog(evalue)/log(best_evalue_in_KO) < min_score_ratio_ko(removes weak members of a KO);min_score_ratio_g: within a gene, drop KOs whoselog(evalue)/log(best_evalue_for_gene) < min_score_ratio_g(removes the weaker KOs of a gene that has a better KO).
A smaller E-value is a better hit. All kept E-values are below 1, so their logs are negative, the best (smallest) hit has ratio 1, and weaker hits have a smaller positive ratio.
The defaults were calibrated by cross-validation against the KEGG gene and KO
annotation of four organisms that span the prokaryote and eukaryote libraries and
well- and less-studied species (S. cerevisiae, Cyanidioschyzon merolae,
E. coli, Mycoplasma genitalium). Annotated genes have a median E-value of
1e-100 to 1e-155, and spurious hits cluster at about 1e-8, a separation of ~20
orders of magnitude. RAVEN's cut-off of 1e-50 lies within the E-value range of
the annotated genes and drops real but divergent hits. For the divergent minimal genome
(M. genitalium, mge) the gene-to-KO recall is 0.95 at 1e-30 and 0.84 at 1e-50,
with no gain in rejecting noise (noise E-values are far weaker). The default cut-off
is therefore 1e-30, which recovers those hits and is ~22 orders of magnitude above
the noise level. min_score_ratio_g (default 0.9) sets the precision, because it
resolves genes with several KOs. Against RAVEN's settings (1e-50 and 0.8), the
recall for mge rises from 0.84 to 0.94. min_score_ratio_ko values of 0.0, 0.3
and 0.5 changed precision and recall by at most 0.02 across the four organisms; 0.3 is
kept as in RAVEN.
Parameters
hits: pandas.DataFrameHit table with the columns
ko,geneandevalue, as returned byparse_hmmsearch_tblout. For repeated(ko, gene)pairs the smallest E-value is used.cutoff: floatLargest E-value that is kept. Defaults to 1e-30. It must be below 1; a value of 1 or more raises a
ValueError.min_score_ratio_ko: floatSmallest ratio
log(evalue)/log(best_evalue_in_KO)that a gene must reach to stay in a KO. Defaults to 0.3. A value of 0 keeps all genes of a KO.min_score_ratio_g: floatSmallest ratio
log(evalue)/log(best_evalue_for_gene)that a KO must reach to stay assigned to a gene. Defaults to 0.9.
blast_from_table#
blast_from_table(source: str | Path | pd.DataFrame)
Load a precomputed homology hits table from a CSV path or a DataFrame (not Excel).
Must contain the HIT_COLUMNS columns.
Parameters
source: str or Path or pandas.DataFrameA DataFrame, or the path of a CSV file. The columns
from_geneandto_geneof a CSV are read as text, and numbers are parsed exactly. A table that lacks a column ofHIT_COLUMNSraisesValueError.
build_hmm_library#
build_hmm_library(organism_gene_ko: pd.DataFrame, genes_pep: str | Path, taxonomy: str | Path, out_dir: str | Path, *, domain: str, seq_identity: float=0.9, parttree_residues: int | None=None, threads: int | None=None, fast: bool=True, verbose: bool=False, progress: bool=False, force: bool=False, concatenate: bool=True, cdhit: str | Path | None=None, mafft: str | Path | None=None, hmmbuild: str | Path | None=None)
Build the HMM library of a domain ("prokaryotes" or "eukaryotes").
Restricts genes to the domain's organisms (from taxonomy), builds a
multi-FASTA and a profile HMM per KO under out_dir, and, if concatenate,
concatenates them into out_dir/library.hmm, which hmmsearch searches directly
without hmmpress. Returns {"hmms": [...], "library": path | None}.
The function is run by the maintainer once per KEGG release and needs CD-HIT, MAFFT
and hmmbuild. It skips KOs that already have an .hmm and reuses an existing
multi-FASTA (see build_ko_fastas), so a rerun after a failure continues from
the existing files. force rebuilds everything.
Parameters
organism_gene_ko: pandas.DataFrameGene-to-KO table with the columns
organism,geneandko. Seebuild_ko_fastas.genes_pep: str or PathMulti-FASTA file of the KEGG proteomes (
genes.pep).taxonomy: str or PathKEGG
taxonomyfile, from which the organism codes ofdomainare taken.out_dir: str or PathOutput directory. It receives the sub-directories
fastaandhmmsand, ifconcatenate,library.hmm.domain: strDomain whose organisms are used,
"prokaryotes"or"eukaryotes". AValueErroris raised if the taxonomy has no organism for it.seq_identity: floatCD-HIT identity threshold, in (0.4, 1.0]. Defaults to 0.9. A value of -1 skips CD-HIT. Passed to
build_ko_hmm.parttree_residues: int or NoneCutoff on the residue count above which MAFFT uses PartTree. When None (default), the DP-cost criterion of
build_ko_hmmis used.threads: int or NoneNumber of threads for CD-HIT, MAFFT and hmmbuild, passed to
build_ko_hmm. When None (default), every CPU the process may use.fast: boolIf True (default), MAFFT uses FFT-NS-2. If False, it uses
--auto. Passed tobuild_ko_hmm.verbose: boolIf True, log the per-KO steps at INFO and DEBUG. Defaults to False.
progress: boolIf True, show tqdm bars for the multi-FASTA and per-KO HMM passes, with an
N of Mcounter for the per-KO pass. It is independent ofverbose. With both on, per-KO log lines are routed throughtqdm.writeso that they do not overwrite the bar. Defaults to False.force: boolIf True, rebuild every multi-FASTA and every
.hmm. If False (default), existing files are reused.concatenate: boolIf True (default), write the per-KO HMMs, in sorted order, to
out_dir/library.hmm. If False, or if no HMM was built,libraryis None in the result.cdhit: str or Path or NonePath of the
cd-hitexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.mafft: str or Path or NonePath of the
mafftexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.hmmbuild: str or Path or NonePath of the
hmmbuildexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.
build_kegg_tables#
build_kegg_tables(reactions: list[KeggReaction], kos: list[KeggKO])
Build the minimal relational tables from parsed records.
Returns a dict of DataFrame objects keyed by table name: ko_reaction,
ko_names, organism_gene_ko, rxn_flags.
Parameters
reactions: list of KeggReactionRecords from
parse_kegg_reactions. They give the tablesko_reactionandrxn_flags.kos: list of KeggKORecords from
parse_kegg_kos. They give the tablesko_namesandorganism_gene_ko.
build_ko_fastas#
build_ko_fastas(organism_gene_ko: pd.DataFrame, genes_pep: str | Path, out_dir: str | Path, *, organisms: set[str] | None=None, progress: bool=False, force: bool=False)
Write one <KO>.fa per KO with its member genes' sequences.
The sequences are located through an index of byte offsets built in one pass over
genes_pep. KOs without a sequence in genes_pep are skipped and get no file.
Returns {ko: path} for the files written.
A <KO>.fa that already exists is kept and not rewritten. Once a full pass
completes, a .ko_fastas_complete marker is written, and a later call returns the
existing files without scanning genes_pep again. force ignores both and
rebuilds. The resume assumes the same inputs as the original run, as does the per-KO
HMM resume in build_hmm_library; force is needed after organism_gene_ko
or organisms change.
Parameters
organism_gene_ko: pandas.DataFrameGene-to-KO table with the columns
organism,geneandko. The sequence id of a row isorganism:gene, as in thegenes_pepheaders.genes_pep: str or PathMulti-FASTA file of the KEGG proteomes (
genes.pep). The id of a record is the first whitespace-delimited token of its>header.out_dir: str or PathDirectory for the
<KO>.fafiles. It is created, with parents, if missing.organisms: set of str or NoneOrganism codes to keep, for example the codes of one domain for the prokaryote and eukaryote libraries. When None (default), all rows of
organism_gene_koare used.progress: boolIf True, show a tqdm bar over the per-KO writing pass. Defaults to False.
force: boolIf True, rebuild every
<KO>.faand ignore the completion marker. If False (default), existing files and the marker are reused.
build_ko_hmm#
build_ko_hmm(ko_fasta: str | Path, out_hmm: str | Path, *, seq_identity: float=0.9, parttree_residues: int | None=None, threads: int | None=None, fast: bool=True, verbose: bool=False, cdhit: str | Path | None=None, mafft: str | Path | None=None, hmmbuild: str | Path | None=None)
Cluster, align and train a profile HMM for one KO's multi-FASTA.
A KO with one sequence skips CD-HIT and MAFFT, because a single sequence is its own
alignment; MAFFT is also skipped when one sequence remains after CD-HIT.
CD-HIT removes near-identical sequences at seq_identity, and no other sequences
are dropped. MAFFT switches to PartTree, which needs less memory, once an alignment is
predicted to need too much: by default from its DP cost (n_seqs × mean_len²)
against a RAM-derived budget (_auto_cost_budget). The cost of an alignment of
long proteins is higher than that of the same residue count in short proteins.
Returns out_hmm.
Parameters
ko_fasta: str or PathMulti-FASTA file of the sequences of one KO. A
ValueErroris raised if it contains no sequence.out_hmm: str or PathPath of the profile HMM to write. The parent directory is created if missing, and the file stem names the profile.
seq_identity: floatCD-HIT identity threshold, in (0.4, 1.0]. Defaults to 0.9. A value of -1 skips CD-HIT. A value outside the range raises a
ValueErrorwhen CD-HIT runs, that is for a KO with more than one sequence.parttree_residues: int or NoneCutoff on the residue count of the clustered sequences. An alignment with more residues uses MAFFT PartTree. When None (default), the DP-cost criterion above is used instead.
threads: int or NoneNumber of threads for CD-HIT, MAFFT and hmmbuild. When None (default), every CPU the process may use.
fast: boolIf True (default), MAFFT uses FFT-NS-2 (
--retree 2 --maxiterate 0), a fast progressive alignment. If False, it uses--auto. PartTree takes precedence over both.verbose: boolIf True, log via the
loggingmodule at INFO and DEBUG which tool is running for this KO, the sequence counts at each stage, the timings and the output of the tools. Defaults to False.cdhit: str or Path or NonePath of the
cd-hitexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary. It is resolved only when CD-HIT runs.mafft: str or Path or NonePath of the
mafftexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary. It is resolved only when MAFFT runs.hmmbuild: str or Path or NonePath of the
hmmbuildexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.
build_reference_model#
build_reference_model(reactions: list[KeggReaction], compounds: list[KeggCompound])
Assemble the gene-free KEGG reference model from parsed records.
Only metabolites used by a reaction are added. Reactions carry KEGG
annotations (reaction id, KO ids, EC codes, pathways) and no genes or GPRs.
Reactions with empty stoichiometry are skipped. Bounds are (-1000, 1000)
for reversible reactions and (0, 1000) otherwise.
Parameters
reactions: list of KeggReactionRecords from
parse_kegg_reactions. A record whose cached stoichiometry is empty is parsed again from its equation.compounds: list of KeggCompoundRecords from
parse_kegg_compounds. They give the name, formula and annotations of the metabolites. A metabolite without a record is named by its id.
download_kegg_dump#
download_kegg_dump(dest: str | Path, *, files: tuple[str, ...]=DEFAULT_FILES, base_url: str=BASE_URL, host: str=KEGG_HOST, auth: tuple[str, str] | None=None, netrc_path: str | Path | None=None, force: bool=False, verbose: bool=True, progress: bool=True)
Fetch and arrange a complete KEGG dump into dest.
Runs fetch_kegg_files and then extract_kegg_dump. Returns the mapping of
logical name to path of the arranged dump, the input of
raven_toolbox.reconstruction.kegg.parse_kegg_dump.
Parameters
dest: str or PathDirectory that receives the dump. It is created, with parents, if missing.
files: tuple of strKEGG FTP paths to download, relative to
base_url. Defaults toDEFAULT_FILES. Seefetch_kegg_files.base_url: strBase URL of the server. Defaults to
"https://ftp.kegg.net".host: strHost name looked up in the
.netrcfile. Defaults to"ftp.kegg.net". Unused whenauthis given.auth: tuple of (str, str) or None(user, password)for the server. When None (default), the credentials are read from the.netrcfile.netrc_path: str or Path or NonePath of the
.netrcfile. When None (default),~/.netrcis used. Ignored whenauthis given.force: boolIf True, archives that already exist in
destare downloaded again. If False (default), they are skipped.verbose: boolIf True (default), log the download, skip and extraction steps at INFO level.
progress: boolIf True (default), show download and extraction progress bars.
Returns
dict of str to PathLogical name to path of each arranged file that exists in
dest.
extract_kegg_dump#
extract_kegg_dump(dest: str | Path, *, progress: bool=False)
Extract and arrange the downloaded archives into the flat dump layout.
Mirrors the extract step of fetch_keggdb.sh: untars the *.tar.gz archives,
gunzips the *.pep.gz proteomes, moves the needed files out of their
sub-directories, and concatenates compound and glycan, and the two proteomes.
Tar extraction uses the data filter, which rejects paths outside dest. Returns
a mapping of logical name to path for the files produced. progress shows a
bar over the untar step and a byte bar per proteome gunzip.
The function makes no network access; download_kegg_dump runs
fetch_kegg_files before it.
Parameters
dest: str or PathDirectory that holds the downloaded archives. The extracted files are written into it, and the archives and sub-directories are deleted. A
FileNotFoundErroris raised if the reaction, compound or ko archive did not yield its file.progress: boolIf True, show a progress bar over the untar step and a byte bar for each proteome gunzip. Defaults to False.
fetch_kegg_files#
fetch_kegg_files(dest: str | Path, *, files: tuple[str, ...]=DEFAULT_FILES, base_url: str=BASE_URL, host: str=KEGG_HOST, auth: tuple[str, str] | None=None, netrc_path: str | Path | None=None, force: bool=False, verbose: bool=True, progress: bool=True)
Download the raw KEGG archives into dest, named by their basenames, and return the paths.
Existing files are skipped unless force=True. progress shows a per-file byte
download bar, sized from the response Content-Length; verbose enables the
fetching and skip INFO log lines.
Parameters
dest: str or PathDirectory that receives the archives. It is created, with parents, if missing.
files: tuple of strKEGG FTP paths to download, relative to
base_url. Each file is saved under its basename. Defaults toDEFAULT_FILES: the reaction, compound, glycan and ko archives, the eukaryote and prokaryote proteomes, and the taxonomy file.base_url: strBase URL of the server. Defaults to
"https://ftp.kegg.net". A trailing slash is removed.host: strHost name looked up in the
.netrcfile. Defaults to"ftp.kegg.net". It is unused whenauthis given.auth: tuple of (str, str) or None(user, password)for HTTP basic or digest authentication. When None (default), the credentials ofhostare read from the.netrcfile. AFileNotFoundErroris raised if that file does not exist, and aValueErrorif it cannot be parsed or has no complete entry forhost.netrc_path: str or Path or NonePath of the
.netrcfile. When None (default),~/.netrcis used. Ignored whenauthis given.force: boolIf True, files that already exist in
destare downloaded again. If False (default), they are skipped.verbose: boolIf True (default), log a
fetchingline for each download and askipline for each existing file at INFO level.progress: boolIf True (default), show a byte progress bar for each download. The total comes from the
Content-Lengthheader; without it the bar shows a byte count.
Returns
list of PathPaths of the files in
dest, in the order offiles, including skipped files.
flag_set#
flag_set(rxn_flags: pd.DataFrame | None, column: str)
Reaction ids whose column flag is truthy.
A flag is truthy when it is True or when its string form is "true" or "1" in any case.
get_kegg_model_for_organism#
get_kegg_model_for_organism(organism_id: str, reference_model: cobra.Model, ko_reaction: pd.DataFrame, organism_gene_ko: pd.DataFrame, *, rxn_flags: pd.DataFrame | None=None, taxonomy: str | Path | None=None, keep_spontaneous: bool=True, keep_undefined_stoich: bool=True, keep_incomplete: bool=True, keep_general: bool=False)
Reconstruct a draft model for a KEGG species from its KO annotations.
Parameters
organism_idThree- or four-letter KEGG organism code (for example
"eco"), or"eukaryotes"or"prokaryotes"for a whole-domain model (requirestaxonomy). Matched case-insensitively.reference_modelThe gene-free KEGG reference model (from
build_reference_model).ko_reaction, organism_gene_ko, rxn_flagsThe relational tables from
build_kegg_tables(or read back withread_kegg_table).taxonomyPath to the KEGG
taxonomyfile; required in domain mode.keep_spontaneous, keep_undefined_stoich, keep_incomplete, keep_generalQuality filters (RAVEN's
keep*). A reaction flagged inrxn_flagsis dropped unless its keep flag is set; this takes precedence over having genes. Spontaneous reactions without genes are also kept whenkeep_spontaneousis true.
Returns
cobra.ModelA copy of the reference restricted to the organism's reactions, with GPRs built and
kegg.genesannotations on the genes.
get_kegg_model_for_organism_from_artefacts#
get_kegg_model_for_organism_from_artefacts(organism_id: str, artefact_dir: str | Path | None=None, *, version: str | None=None, taxonomy: str | Path | None=None, **kwargs)
Load the published reference artefacts from artefact_dir and build the model.
Reads reference_model.yml.gz and the gzipped TSV tables ko_reaction,
organism_gene_ko and rxn_flags, then calls get_kegg_model_for_organism.
If artefact_dir is None, the published artefacts are fetched and cached via
raven_toolbox.data.ensure_kegg_data (version selects the release).
For a whole-domain model (organism_id "prokaryotes" or "eukaryotes")
the KEGG taxonomy artefact is taken from artefact_dir if present, otherwise
fetched via raven_toolbox.data.ensure_kegg_taxonomy, because it is a separate
artefact outside the core set. An explicit taxonomy path takes precedence.
Parameters
organism_id: strThree- or four-letter KEGG organism code (for example
"eco"), or"eukaryotes"or"prokaryotes"for a whole-domain model. Matched case-insensitively.artefact_dir: str or Path or NoneDirectory with the artefact files
reference_model.yml.gz,ko_reaction.tsv.gz,organism_gene_ko.tsv.gzandrxn_flags.tsv.gz, each with or without a<version>_prefix. When None (default), the published artefacts are fetched and cached.version: str or NoneKEGG release to fetch. Used only when
artefact_diris None, or when the taxonomy of a domain model is fetched. When None (default), the default release ofraven_toolbox.data.ensure_kegg_datais used.taxonomy: str or Path or NonePath of the KEGG
taxonomyfile for a domain model. When None (default), it is taken fromartefact_diror fetched. Unused for a single organism.**kwargs: dictKeyword arguments forwarded to
get_kegg_model_for_organism: the quality filterskeep_spontaneous,keep_undefined_stoich,keep_incompleteandkeep_general. The argumentsrxn_flagsandtaxonomyare set by this function.
get_kegg_model_from_sequences#
get_kegg_model_from_sequences(fasta: str | Path, reference_model: cobra.Model, ko_reaction: pd.DataFrame, library: str | Path, *, rxn_flags: pd.DataFrame | None=None, model_id: str | None=None, cutoff: float=1e-30, min_score_ratio_ko: float=0.3, min_score_ratio_g: float=0.9, keep_spontaneous: bool=True, keep_undefined_stoich: bool=True, keep_incomplete: bool=True, keep_general: bool=False, threads: int | None=None, hmmsearch: str | Path | None=None)
Reconstruct a draft model for a proteome by HMM-searching the KO library.
Searches the library against fasta, assigns KOs
(assign_kos), and assembles the model against reference_model and
ko_reaction. Genes are the identifiers of the query proteome. model_id
defaults to the stem of the fasta file name.
Parameters
fasta: str or PathProteome FASTA file of the query organism.
reference_model: cobra.ModelGene-free KEGG reference model (from
build_reference_model).ko_reaction: pandas.DataFrameTable with the columns
koandreactionthat maps KOs to reactions.library: str or PathConcatenated KO profile-HMM library, searched by
run_hmmsearch.rxn_flags: pandas.DataFrame or NonePer-reaction quality-flag table with a
reactioncolumn and any of the boolean columnsspontaneous,undefined_stoich,incompleteandgeneral. When None (default), no reaction is flagged.model_id: str or NoneId of the model. When None (default), the stem of the
fastafile name.cutoff: floatLargest E-value that is kept, passed to
assign_kos. Defaults to 1e-30.min_score_ratio_ko: floatMinimum score ratio of a gene within a KO, passed to
assign_kos. Defaults to 0.3.min_score_ratio_g: floatMinimum score ratio of a KO within a gene, passed to
assign_kos. Defaults to 0.9.keep_spontaneous: boolIf True (default), reactions flagged
spontaneousinrxn_flagsare kept without genes.keep_undefined_stoich: boolIf True (default), reactions flagged
undefined_stoichinrxn_flagsare kept. If False, they are dropped even if they have genes.keep_incomplete: boolIf True (default), reactions flagged
incompleteinrxn_flagsare kept. If False, they are dropped even if they have genes.keep_general: boolIf True, reactions flagged
generalinrxn_flagsare kept. If False (default), they are dropped even if they have genes.threads: int or NoneNumber of
hmmsearchthreads, passed torun_hmmsearch. When None (default), every CPU the process may use.hmmsearch: str or Path or NonePath of the
hmmsearchexecutable, passed torun_hmmsearch. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.
get_kegg_model_from_sequences_with_artefacts#
get_kegg_model_from_sequences_with_artefacts(fasta: str | Path, artefact_dir: str | Path | None=None, library: str | Path | None=None, *, domain: str='prokaryotes', version: str | None=None, **kwargs)
Load the reference model and tables from artefact_dir and run the HMM query.
If artefact_dir or library is None, it is fetched and cached via
raven_toolbox.data.ensure_kegg_data or
raven_toolbox.data.ensure_kegg_hmm_library. domain selects the
prokaryote or eukaryote library and version the release.
Parameters
fasta: str or PathProteome FASTA file of the query organism.
artefact_dir: str or Path or NoneDirectory with the artefact files
reference_model.yml.gz,ko_reaction.tsv.gzandrxn_flags.tsv.gz, each with or without a<version>_prefix. When None (default), the published artefacts are fetched and cached.library: str or Path or NoneConcatenated KO profile-HMM library. When None (default), the library of
domainis fetched and cached.domain: strLibrary to fetch when
libraryis None,"prokaryotes"(default) or"eukaryotes". Unused whenlibraryis given.version: str or NoneKEGG release to fetch. Used only for the files that are fetched. When None (default), the default release of the data registry is used.
**kwargs: dictKeyword arguments forwarded to
get_kegg_model_from_sequences:model_id,cutoff,min_score_ratio_ko,min_score_ratio_g,keep_spontaneous,keep_undefined_stoich,keep_incomplete,keep_general,threadsandhmmsearch. The argumentrxn_flagsis set by this function.
get_model_from_homology#
get_model_from_homology(models, hits: pd.DataFrame, model_for: str, *, preferred_order=None, strictness: int=1, map_direction: str='new_to_old', complex_policy: str='flag', only_genes_in_models: bool=False, max_evalue: float=1e-30, min_align_len: int=100, min_identity: float=40, review_identity: float | None=None, keep_gene_free: bool=False, preserve_notes: bool=False)
Build a draft model for model_for by transferring reactions from templates.
A hit passes when its e-value is below max_evalue and its alignment length and
identity are at least min_align_len and min_identity, as in RAVEN.
Defaults for the three filters come from a calibration against KEGG annotations and OMA assignments <https://github.com/CompMetEng/raven-docs/blob/main/docs/parameter-tuning/studies/homology-cutoff-calibration.md>_
on raven-docs, scored with precision weighted above recall (a wrongly transferred
reaction is harder to undo than a missing one).
Parameters
models: cobra.Model or Sequence[cobra.Model]Template models. Each template is identified by its
model.id, which must match thefrom_idorto_idvalues inhits. A single model is accepted as a list of one. Templates are merged in the order they are given, whatever the preferred order is.hits: pandas.DataFrameBidirectional hits table with the columns in
HIT_COLUMNS; a missing column raisesValueError. Organism ids inhitsare case-sensitive. An id that matchesmodel_foror a template id only when case is ignored raisesValueError; hits involving other organisms are ignored. RAVEN raises an error for hits from an organism that no template has asmodel.id, and matches the template ids case-insensitively.model_for: strId of the organism the draft model is built for, as it appears in
hits.preferred_order: Sequence[str] or NoneBreaks ties when more than one template maps the same new-organism gene: the gene is mapped to the earlier template in the list, and a gene of a later template that maps to any gene an earlier template already maps is removed from that template altogether, with its other mappings. A reaction of the later template that cannot work without the removed gene is not transferred. Templates are merged in the order they were given in
models, whatever the preferred order is, and a template thatpreferred_orderleaves out contributes nothing. The tie-break applies only when more than one model is given. DefaultNone, which uses the order ofmodels. RAVEN'spreferredOrderdecides which template receives a gene in the same way and merges the models in the order ofmodels.strictness: intHit-filtering policy. Default 1. Any other value than 1, 2 or 3 raises
ValueError.1: bidirectional. A template gene and a new-organism gene must have an accepted hit in both directions.
2: one-directional. A hit found in a single direction is accepted; the direction is selected by
map_direction.3: bidirectional and best hits only. Before matching, each gene keeps only its best hits (by bitscore) in each direction, all of them when several tie, then the bidirectional rule is applied.
map_direction: strDirection of the one-directional search when
strictnessis 2:"new_to_old"(hits found searching frommodel_for) or"old_to_new". Default"new_to_old". Any other value raisesValueError; the value has no effect with other strictness values.complex_policy: strWhat happens to an AND-linked subunit with no ortholog. Default
"flag"."flag"keeps the reaction with a placeholder gene (OLD_<model>_<gene>) for later curator review,"keep"removes that subunit,"drop"drops the whole reaction. An isozyme group counts as a subunit without an ortholog only when none of its members has one, and then one placeholder stands for it."drop"removes the reaction whenever a placeholder would remain, also when another isozyme branch is complete. Any other value raisesValueError.only_genes_in_models: boolRestricts the hits table to hits whose template gene appears in the given
modelsbefore mapping orthologs, so a gene the templates lack cannot be a best hit. It raisesValueErrorwhen no hit of a search direction betweenmodel_forand a template passes the cutoffs and this filter. As in RAVEN, it changes the mapping only withstrictness3: with 1 and 2 a template gene that no template contains is dropped in any case, and only theValueErrordiffers. DefaultFalse.max_evalue: floatA hit passes only when its e-value is below this value. Default 1e-30, the RAVEN value. It makes no difference between 1e-4 and 1e-50, because the other two filters exclude every hit that it would exclude.
min_align_len: intA hit passes only when its alignment length is at least this value. Default 100, as RAVEN's
minLen. Values at or below 150 measured the same; on each of the four organisms tested, the score against KEGG annotations (wrong matches counted double) was 0.010 to 0.020 lower at 200 than at 100.min_identity: floatA hit passes only when its identity is at least this value. Default 40. The value lies in the 35 to 45 range that the two reference sources favour; 35 scores higher for two organisms (
yli0.868 against 0.860,ani0.814 against 0.804). It is the filter that limits the result.review_identity: float or NoneLower identity threshold (for example 25) that collects the reactions the thresholds reject. Any reaction that transfers at this lower identity but not at
min_identityis reported inHomologyResult.candidateswith its strongest supporting hit and is not added to the model. A missing reaction can be gap-filled, whereas a wrongly transferred reaction is hard to find and remove, so the filters stay strict. It must be belowmin_identity, otherwiseValueErroris raised. Hits withhits.attrs["source"] == "SuppOrth"have a placeholder identity of 100, so a warning is issued and no reaction is a candidate. DefaultNone, which collects no candidates.keep_gene_free: boolAlso transfers the template reactions that have no GPR (spontaneous, transport, exchange, artificial). By default they are dropped, as in RAVEN, because no gene supports them in the new organism. True transfers them, which suits a curated reference template whose gene-free reactions belong in every derived model. Default
False.preserve_notes: boolKeeps each transferred reaction's own
notes(references, confidence score, free text) and only addshomology_source. By default they are replaced by a note that the reaction was included by this function. DefaultFalse.
Returns
HomologyResultThe draft model, the template-to-new gene map and, when
review_identityis given, the candidate reactions.
hits_from_supporth#
hits_from_supporth(source: str | Path | pd.DataFrame, organism_id: str, species_to_model: Mapping[str, str | None] | None=None, *, min_support: int=1, require_tools: Sequence[str]=(), min_identity: float | None=None, max_evalue: float | None=None, protein_to_gene: Mapping[str, str] | str | Path | None=None)
Build a homology hits table from a SuppOrth suppOrth.tsv.
Only the pairs between organism_id and another species are kept. Each pair is
written in both directions, so every strictness of
raven_toolbox.reconstruction.homology.get_model_from_homology accepts it,
and strictness 1 and 2 give the same result.
SuppOrth decides orthology by agreement between predictors, so the filters that
apply to it are in this function, and the hit metrics are placeholders that pass
the alignment filters of get_model_from_homology (evalue 0, identity
100, align_len 1000, ppos 100). bitscore is SuppOrth's own value (0
when it has none), which strictness=3 ranks by. Because the identity is a
placeholder, review_identity reports no candidates for these hits.
Parameters
sourcePath to
suppOrth.tsv, or the table as a DataFrame. A DataFrame read with pandas defaults has protein ids such asNAturned into NaN; read it withkeep_default_na=Falseor pass the path.organism_idSuppOrth species label of the organism to build a model for: the FASTA file name without extension, or the
--labelsvalue. It becomesfrom_idorto_idunlessspecies_to_modelmaps it to another id.species_to_modelSuppOrth species label to model id. A label mapped to
Noneis left out. When given, every label in the table must be present in the mapping. WhenNone, labels are used as model ids.min_supportMinimum number of predictors that found the pair (
Lv_support). SuppOrth has already filtered the table with its own--supportLvand--identity_filter; this filter is applied in addition.require_toolsPredictors that must all have found the pair, by column name (
"orthofinder","sonicparanoid","broccoli","oma").min_identity, max_evalueFilters on SuppOrth's alignment values: identity at least
min_identityand e-value at mostmax_evalue. A pair without an alignment hit fails both.protein_to_geneProtein id to model gene id, as a dict, a JSON file, or a two-column tab-separated file (lines starting with
#are skipped). Proteins missing from the map keep their id, and their number is reported in a warning. A gene pair takes the highest support over its protein pairs, the union of their predictors, the highest identity and bitscore, and the lowest e-value; these values can come from different protein pairs.
Returns
pandas.DataFrameHIT_COLUMNSfollowed bysupport,supported_by,identity_raw,evalue_rawandbitscore_raw(SuppOrth's values).attrs["source"]is"SuppOrth".
HomologyResult#
Result of get_model_from_homology.
Attributes
modelThe draft
cobra.Model.gene_map{model_id: {template_gene: [new_gene, ...]}}ortholog mapping used.candidatesReactions that transfer at the identity threshold
review_identitybut not atmin_identity, with the best hit supporting each, sorted by identity, strongest first.Noneunlessreview_identitywas given. These reactions are not inmodel.
KeggCompound#
A metabolite parsed from the KEGG compound flat file.
KeggKO#
A KEGG Orthology entry: its name and the organism genes assigned to it.
KeggReaction#
A reaction parsed from the KEGG reaction flat file.
make_ortholog_hits#
make_ortholog_hits(ortholog_pairs: Iterable[tuple[str, str]], source_model_id: str, target_id: str)
Build a bidirectional hits table from a predefined ortholog list.
Each (source_gene, target_gene) pair is emitted in both directions with
fixed metrics (evalue 0, identity 100, align_len 1000, bitscore 1000, ppos 100).
A known ortholog mapping can thus be passed to get_model_from_homology
without a BLAST run.
Parameters
ortholog_pairsIterable of
(source_gene, target_gene). The source gene belongs to the template model, the target gene to the organism being built.source_model_idID of the template model the source genes belong to.
target_idID of the organism to build a model for (
model_for).
organism_domains#
organism_domains(path: str | Path)
Return {organism_id: domain} (the outermost category).
Parameters
path: str or PathPath of the KEGG
taxonomyfile, plain or gzipped (suffix.gz).
organisms_in_domain#
organisms_in_domain(path: str | Path, domain: str)
Organism ids whose outermost category matches domain (case-insensitive).
Accepts a prefix, so "prok" matches "Prokaryotes".
Parameters
path: str or PathPath of the KEGG
taxonomyfile, plain or gzipped (suffix.gz).domain: strDomain name, or a prefix of it, for example
"prokaryotes"or"euk". A category also matches when it is a prefix ofdomain. RaisesValueErrorwhendomainis empty.
parse_hmmsearch_tblout#
parse_hmmsearch_tblout(text: str)
Parse hmmsearch --tblout text into a [ko, gene, evalue] table.
With the profile library as the query, column 1 (target name) is the proteome
gene, column 3 (query name) is the KO, and column 5 is the full-sequence E-value.
Comment lines (#), empty lines and lines with fewer than 5 fields are skipped.
Parameters
text: strContent of the
--tbloutfile ofhmmsearch.
parse_kegg_compounds#
parse_kegg_compounds(kegg_dir: str | Path)
Parse <kegg_dir>/compound and the optional compound.inchi into records.
Parameters
kegg_dir: str or PathDirectory of the arranged KEGG dump. It must contain the file
compoundand may containcompound.inchi. A compound with an InChI gets an empty formula.
parse_kegg_dump#
parse_kegg_dump(kegg_dir: str | Path, out_dir: str | Path, *, version: str | None=None, progress: bool=False)
Parse a full KEGG dump into the reference model + tables and write them out.
Writes reference_model.yml.gz (gzipped RAVEN or cobra YAML) plus the
gzipped TSV tables into out_dir and returns {name: path} for
everything written. The organism_gene_ko table is streamed to disk (see
stream_organism_gene_ko) and not built in memory, so the full KEGG database
can be processed; the other tables are built in memory.
When version is given (for example "kegg116"), the output filenames are
version-prefixed (<version>_<name>), as in the published release
assets; the keys of the returned dict are the logical table names.
Parameters
kegg_dir: str or PathDirectory of the arranged KEGG dump, as produced by
download_kegg_dump.out_dir: str or PathOutput directory. It is created, with parents, if missing.
version: str or NoneRelease tag, for example
"kegg116", put before each file name as<version>_. When None (default), the file names have no prefix.progress: boolIf True, report each stage and show a byte-progress bar over the
organism_gene_kostreaming pass, the longest stage. Defaults to False.
parse_kegg_kos#
parse_kegg_kos(kegg_dir: str | Path, *, keep: set[str] | None=None)
Parse <kegg_dir>/ko into KeggKO records (name and organism genes).
keep limits parsing to those KO ids (for example only KOs linked to reactions),
as RAVEN's koList argument does; the gene lists are large.
Parameters
kegg_dir: str or PathDirectory of the arranged KEGG dump. It must contain the file
ko.keep: set of str or NoneKO ids to parse. When None (default), all KOs are parsed.
parse_kegg_reactions#
parse_kegg_reactions(kegg_dir: str | Path)
Parse <kegg_dir>/reaction into KeggReaction records.
Reversibility is taken from the equation arrow and, when
reaction_mapformula.lst is present, set to irreversible for reactions that are
irreversible across all KEGG maps (see _irreversible_from_mapformula).
Parameters
kegg_dir: str or PathDirectory of the arranged KEGG dump. It must contain the file
reactionand may containreaction_mapformula.lst.
parse_taxonomy#
parse_taxonomy(path: str | Path)
Return {organism_id: [category, ...]} from outermost to innermost.
Parameters
path: str or PathPath of the KEGG
taxonomyfile, plain or gzipped (suffix.gz).
parse_taxonomy_records#
parse_taxonomy_records(path: str | Path)
Return [(organism_id, name, [category, ...]), ...] in file order.
name is the organism's scientific name with any trailing KEGG parenthetical
kept (for example "Homo sapiens (human)"), matching RAVEN getPhylDist; the category
list is the lineage from outermost (domain) to innermost. Order is preserved so it
aligns with the rows and columns of phyl_dist.
Parameters
path: str or PathPath of the KEGG
taxonomyfile, plain or gzipped (suffix.gz).
phyl_dist#
phyl_dist(path: str | Path, *, only_in_kingdom: bool=False)
Compute the KEGG phylogenetic distance matrix from the taxonomy file.
Port of RAVEN getPhylDist. For organisms i and j with category
lineages of lengths Li, Lj, the distance is (Li - Lj) + min(Li, Lj) - k where
k is the deepest level (within the shorter lineage, comparing position by position
from the root) at which the two categories coincide, or 1 if none coincide. This
reproduces the values of RAVEN, including their asymmetry and negative values, so the
output matches MATLAB keggPhylDist, which GECKO uses.
only_in_kingdom sets the distance to +inf between organisms in different
domains (RAVEN's onlyInKingdom variant); the matrix is then returned as float.
Time and memory use are O(N²), with N the number of KEGG organisms (~10⁴).
Parameters
path: str or PathPath of the KEGG
taxonomyfile, plain or gzipped (suffix.gz).only_in_kingdom: boolIf True, the distance between organisms of different domains is
infand the matrix has dtypefloat. If False (default), all distances are integers.
PhylDist#
KEGG phylogenetic distance structure of RAVEN getPhylDist and keggPhylDist.
ids and names are the KEGG organism ids and scientific names (names keep the
trailing parenthetical of RAVEN; consumers that need them without it, for example
geckopy, strip it). dist_matrix[i, j] is RAVEN's distance from ids[i] to
ids[j]. It reproduces RAVEN's metric, which is asymmetric and may be negative;
GECKO uses it only to select the closest (minimum-distance) organism, so the exact
values matter for parity with MATLAB, and the sign and asymmetry do not affect that
selection.
read_kegg_table#
read_kegg_table(path: str | Path)
Read a KEGG table from write_kegg_tables or stream_organism_gene_ko.
Compression is inferred from the file suffix. The published tables are gzipped TSV
(.tsv.gz), including those with a version prefix (kegg116_<name>.tsv.gz).
All columns are read as strings, and empty fields stay empty strings.
Parameters
path: str or PathPath of the tab-separated table.
run_blast#
run_blast(organism_id: str, fasta: str | Path, model_ids: Sequence[str], ref_fastas: Sequence[str | Path], *, evalue: float=0.0001, threads: int | None=None, blastp: str | Path | None=None, makeblastdb: str | Path | None=None)
Bidirectional BLAST+ between an organism and template organisms.
Returns the hits DataFrame, filtered at evalue. Requires BLAST+
(blastp, makeblastdb). threads defaults to every CPU the process
may use, as in RAVEN's getBlast.
The default evalue of 1e-4 equals the -evalue 10e-5 that MATLAB
RAVEN's getBlast hardcodes. Here evalue is an argument. The cutoff is
a pre-filter; the max_evalue, min_align_len and min_identity
arguments of
raven_toolbox.reconstruction.homology.homology.get_model_from_homology
apply stricter limits downstream.
Parameters
organism_id: strIdentifier of the organism. It is written to the
from_idcolumn of the hits from the organism to a template and to theto_idcolumn of the hits in the other direction.fasta: str or PathProtein FASTA file of the organism.
model_ids: Sequence[str]Identifiers of the template models, written to the
from_idandto_idcolumns. The sequence is parallel toref_fastasand must have the same length, otherwiseValueErroris raised.ref_fastas: Sequence[str or Path]Protein FASTA files of the templates.
ref_fastas[i]is the reference proteome for templatemodel_ids[i]. A single path is accepted as a list of one.evalue: floatE-value cutoff passed to
blastp. Default 1e-4.threads: int or NoneNumber of threads passed to
blastp. DefaultNone, which uses every CPU the process may use.blastp: str or Path or NonePath of the
blastpbinary. DefaultNone, which resolves the binary withraven_toolbox.binaries.resolve_binary.makeblastdb: str or Path or NonePath of the
makeblastdbbinary. DefaultNone, which resolves the binary withraven_toolbox.binaries.resolve_binary.
run_diamond#
run_diamond(organism_id: str, fasta: str | Path, model_ids: Sequence[str], ref_fastas: Sequence[str | Path], *, evalue: float=0.001, threads: int | None=None, sensitivity: str='--more-sensitive', diamond: str | Path | None=None)
Bidirectional DIAMOND between an organism and template organisms.
Returns the hits DataFrame. Requires DIAMOND. threads defaults to
every CPU the process may use, as in RAVEN's getDiamond.
The default evalue of 1e-3 equals DIAMOND's own default, which MATLAB
RAVEN's getDiamond uses because it passes no --evalue. run_blast
uses 1e-4, following getBlast. Neither cutoff has been calibrated
against data, unlike the KO-assignment cutoffs of
raven_toolbox.reconstruction.kegg.assign_kos, where measurement justified
diverging from RAVEN.
Parameters
organism_id: strIdentifier of the organism. It is written to the
from_idcolumn of the hits from the organism to a template and to theto_idcolumn of the hits in the other direction.fasta: str or PathProtein FASTA file of the organism.
model_ids: Sequence[str]Identifiers of the template models, written to the
from_idandto_idcolumns. The sequence is parallel toref_fastasand must have the same length, otherwiseValueErroris raised.ref_fastas: Sequence[str or Path]Protein FASTA files of the templates.
ref_fastas[i]is the reference proteome for templatemodel_ids[i]. A single path is accepted as a list of one.evalue: floatE-value cutoff passed to
diamond blastp. Default 1e-3.threads: int or NoneNumber of threads passed to
diamond blastp. DefaultNone, which uses every CPU the process may use.sensitivity: strDIAMOND command-line flag appended unchanged to the
diamond blastpcommand, for example"--more-sensitive"or"--sensitive".""appends no flag and selects DIAMOND's default fast mode. Default"--more-sensitive".diamond: str or Path or NonePath of the
diamondbinary. DefaultNone, which resolves the binary withraven_toolbox.binaries.resolve_binary.
run_hmmsearch#
run_hmmsearch(fasta: str | Path, library: str | Path, *, threads: int | None=None, hmmsearch: str | Path | None=None)
Search the profile library against proteome fasta; return tblout text.
One hmmsearch of the whole concatenated multi-profile library (query)
against fasta (target), which is the fast search direction. It runs with
--cpu and needs no hmmpress. -Z is set to the profile count (when it
is positive) so that the per-hit E-values match the convention assign_kos is
calibrated against (identical to a hmmscan against the same library). A
RuntimeError is raised if hmmsearch exits with a non-zero status.
Parameters
fasta: str or PathProteome FASTA file of the query organism (the search target).
library: str or PathConcatenated multi-profile HMMER file of the KO library (the search query). It does not need
hmmpress.threads: int or NoneNumber of
hmmsearchworker threads (--cpu). When None (default), every CPU the process may use, as in RAVEN'sgetKEGGModelForOrganism.hmmsearch: str or Path or NonePath of the
hmmsearchexecutable. When None (default), it is resolved byraven_toolbox.binaries.resolve_binary.
run_supporth#
run_supporth(organism_id: str, fasta: str | Path, model_ids: Sequence[str], ref_fastas: Sequence[str | Path], outdir: str | Path, *, tools: str | Sequence[str]='all', support_lv: int | None=None, identity_filter: float=80.0, alignment: str='diamond', threads: int | None=None, extra_args: Sequence[str]=(), supporth: str | os.PathLike | None=None, **reader_kwargs)
Run SuppOrth on an organism and template proteomes and read its consensus.
SuppOrth requires protein ids to be unique over all proteomes. When two FASTA
files share an id (for example two templates of the same species), every id is
given a <label>__ prefix in copies written to outdir/prefixed_inputs, and
the prefix is removed from the returned hits. outdir/suppOrth.tsv then
contains the prefixed ids. SuppOrth's console output is written to
outdir/run_supporth.log.
Requires the suppOrth command, found from supporth, then the
RAVEN_SUPPORTH environment variable, then PATH. SuppOrth's predictors do not
run on Windows. On Windows, SuppOrth can run under WSL or on a Linux host, and its
suppOrth.tsv can be read with hits_from_supporth.
Parameters
organism_id: strSuppOrth species label of the organism to build a model for. It is also the id of the organism in the returned hits. It must be non-empty, not
"."or"..", have no leading or trailing space, contain none of,,/and\, and differ from every id inmodel_ids; otherwiseValueErroris raised.fasta: str or PathProtein FASTA file of the organism. A
.gzfile is read as gzip when the ids are checked.model_ids: Sequence[str]Ids of the template models, with the same restrictions as
organism_id. The ids are passed to SuppOrth as--labels, so the table uses them as species labels. The sequence is parallel toref_fastasand must have the same length, otherwiseValueErroris raised. At least one template is needed.ref_fastas: Sequence[str or Path]Protein FASTA files of the templates.
ref_fastas[i]is the proteome of templatemodel_ids[i], with FASTA ids equal to that model's gene ids (or mapped to them withprotein_to_gene). A single path is accepted as a list of one.outdir: str or PathOutput directory of SuppOrth. It is created when it does not exist. It receives
suppOrth.tsvandrun_supporth.log.tools: str or Sequence[str]Predictors to run, passed to SuppOrth as
--tools: a comma-separated string or a sequence of names."all"selectsorthofinder,sonicparanoidandbroccoli. Default"all".support_lv: int or NoneSuppOrth's
--supportLv: a pair is kept if at leastsupport_lvpredictors found it, or if its identity is aboveidentity_filter. It must be between 1 and 4, otherwiseValueErroris raised. DefaultNone, which uses 3, or the number oftoolswhen fewer are selected. A warning is issued when it is larger than the number oftoolsandextra_argsdoes not contain"--oma".identity_filter: floatSuppOrth's
--identity_filterin percent: a pair is kept if its identity is above this value, or if at leastsupport_lvpredictors found it. Default 80.0.alignment: strAligner, passed to SuppOrth as
--alignment. Default"diamond".threads: int or NoneNumber of threads, passed to SuppOrth as
-t. DefaultNone, which uses every CPU the process may use, as in RAVEN'srunSuppOrth.extra_args: Sequence[str]Arguments appended to the
suppOrth runcommand, for example["--resume"]or["--oma", "path/to/Output"]. Default: none.supporth: str or os.PathLike or NonePath of the
suppOrthcommand. DefaultNone, which uses theRAVEN_SUPPORTHenvironment variable, thensuppOrthorsupporthon PATH. A missing command raisesFileNotFoundError.**reader_kwargs: dictKeyword arguments forwarded to
hits_from_supporth(species_to_model,min_support,require_tools,min_identity,max_evalueandprotein_to_gene).
stream_organism_gene_ko#
stream_organism_gene_ko(kegg_dir: str | Path, keep: set[str], ogk_path: str | Path, *, chunk_rows: int=1000000, progress: bool=False)
Stream the ko file to a sorted, gzipped organism_gene_ko.tsv.gz.
KEGG has ~9M gene and KO associations, which are too many to hold in memory as a
DataFrame. Rows are sorted by (organism, gene) before writing: gene IDs
from one organism share long common prefixes (locus tags, numeric runs), so
sorting makes them adjacent and improves compression; the order also matches
the by-organism query pattern in get_kegg_model_for_organism. The table is
compressed with gzip, which MATLAB's built-in gunzip reads without an external
tool; xz would give a smaller file.
The sort is an external merge sort: the row buffer is written as a sorted run, to a gzipped
temporary file, once it reaches chunk_rows rows, and the runs are merged with
heapq.merge, so peak memory does not grow with the size of KEGG. Only
the ko_names table (one row per KO) is held in full; it is returned with the
columns ko and name.
Parameters
kegg_dir: str or PathDirectory of the arranged KEGG dump. It must contain the file
ko.keep: set of strKO ids to write, for example only the KOs linked to reactions, as
keepofparse_kegg_kos.ogk_path: str or PathPath of the gzipped output table. Temporary sort files are written to its parent directory.
chunk_rows: intRow count at which the buffer is written as a sorted run. It is checked after all GENES lines of a KO entry are added, so a run can exceed it by the rows of one entry. Defaults to 1,000,000.
progress: boolIf True, show a tqdm byte-progress bar over the (large)
koread pass. Defaults to False.
validate_hits#
validate_hits(hits: pd.DataFrame)
Check that a hits DataFrame has the required columns and return it unchanged.
Parameters
hits: pandas.DataFrameHits table. It must contain every column in
HIT_COLUMNS, otherwiseValueErroris raised. Extra columns are allowed.
write_kegg_tables#
write_kegg_tables(tables: dict[str, pd.DataFrame], out_dir: str | Path, *, prefix: str='')
Write each table as a gzipped TSV (<prefix><name>.tsv.gz) into out_dir.
Gzipped TSV is the format shared with MATLAB RAVEN; MATLAB's built-in gunzip
reads it without an external tool. prefix version-tags the filenames (for
example kegg116_). Returns the written paths.
Parameters
tables: dict of str to pandas.DataFrameTables keyed by name, for example the result of
build_kegg_tables. Each is written to<prefix><name>.tsv.gzwithout the index.out_dir: str or PathOutput directory. It is created, with parents, if missing.
prefix: strString put before each file name. Defaults to
"".