diff --git a/DOCS.md b/DOCS.md index 2d302cba..48fd9073 100644 --- a/DOCS.md +++ b/DOCS.md @@ -51,65 +51,210 @@ Flags are kebab-case long options, defined in `crates/andes/src/bin/andes/cli.rs Native `.raw`/`.d` search MS2 only (MS3 reporter scans are filtered at load). -### Required + +### Input and output -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--spectrum` | path | *(required)* | Input spectrum file; reader chosen by extension (see above). | Java `-s ` | -| `--database` | path | *(required)* | Target FASTA, or UniProt XML when the name ends in `.xml` / `.xml.gz` ([§1a](#uniprot-xml-databases)). Gzip is read directly. Decoys are generated (see `--decoy-strategy`, `--decoy-prefix`), or taken from a target + decoy FASTA written by `andes database` ([§1d](#1d-decoy-databases-andes-database)). | Java `-d ` | -| `--output-pin` | path | *(required)* | Output Percolator `.pin`. | Java `-o ` (when `-outputFormat pin`) | +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--config` (command line only) | path | *(off)* | — | YAML file of options (config.example.yaml); a flag on the command line wins Sections and keys: DOCS.md §1b. | — | +| `--print-config` (advanced) (command line only) | path | *(off)* | — | Write the resolved settings as a config file that reproduces the run, then exit FILE, or `-` for stdout. Nothing is searched. Replay with --config FILE. | — | +| `--sdrf` | path | *(off)* | — | SDRF-Proteomics file: data files, protease, modifications, tolerance and labels Reads `comment[data file]` (looked up next to the SDRF), the cleavage agents, the modification parameters, the precursor mass tolerance and `comment[label]` (label free -> --lfq, TMT / iTRAQ -> --tmt with the smallest plex holding the labels, SILAC and dimethyl -> --label). A value on the command line or in --config wins. Rows must agree on these settings. The fragment tolerance is not applied (andes measures each run's), and the dissociation method is checked against the files. DOCS.md §1b, SDRF input. | — | +| `--spectrum` | path | *(required)* | — | Spectrum file: mzML, MGF, Thermo .raw or Bruker .d; repeat for several runs The reader follows the file extension. Several files are searched into one PIN. | `Java -s ` | +| `--database` | path | *(required)* | — | Protein database: FASTA, or UniProt XML (.xml); either may be gzipped Target sequences only: andes generates the decoys (--decoy-strategy), unless it is the target + decoy FASTA of `andes database`, whose decoys are searched as written. A UniProt XML database searches like the UniProt FASTA and also carries annotated modification sites (used by `restrict_to: annotated` modifications) and the entries of the Database variants options. | `Java -d ` | +| `--output-pin` | path | *(required unless --rescore)* | — | Percolator PIN output (required unless --rescore is given) | `Java -o (when -outputFormat pin)` | +| `--output-tsv` | path | *(off)* | — | Tab-separated PSM report | `Java -outputFormat 1 with output path` | +| `--output-parquet` | path | *(off)* | — | QPX .idparquet bundle directory (quantms-compatible) Writes psms.parquet, proteins.parquet, protein_groups.parquet (empty) and search_params.parquet, and with --tmt, --lfq or --label quantms.feature.parquet. | — | -### Search parameters +### Search -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--precursor-tol` | string | `20ppm` | Symmetric precursor tolerance, e.g. `20ppm` or `0.02da`. | Java `-t 20ppm` | -| `--enzyme` | enum | `trypsin` | `trypsin`, `chymotrypsin`, `lysc`, `aspn`, `gluc`, `lysn`, `argc`, `alphalp`, `nocleavage`, `nonspecific` (alias `elastase`). A comma list (`gluc,trypsin`) uses every enzyme listed. | Java `-e` | -| `--charge` | `MIN..MAX` | `2..5` | Charges tried when the spectrum has none. | *(no direct Java flag; set via param file in Java)* | -| `--enzyme-specificity` | enum | `fully` | Tolerable termini: `fully` (Java `-ntt 2`), `semi` (`-ntt 1`), `non-specific` (`-ntt 0`). | Java `-ntt` | -| `--max-missed-cleavages` | u32 | `2` | Missed cleavages per peptide. Not applied to a non-specific digest (`--enzyme nonspecific`, `--enzyme-specificity non-specific`), where every position is a cleavage site. | Java `-maxMissedCleavages 2` | -| `--min-length` | u32 | `6` | Minimum peptide length. | Java `-minLength 6` | -| `--max-length` | u32 | `50` | Maximum peptide length. | Java `-maxLength 40` | -| `--top-n` | u32 | `10` | PSMs kept per spectrum (before positional isomers are collapsed in the output, see §3a). | Java `-n 10` | -| `--isotope-error` | `MIN..MAX` | `-1..2` | Isotope-error offsets tried; `0..2` under `--glyco` and `--xl`. | Java `-ti -1,2` | -| `--min-peaks` | u32 | `10` | Spectra with fewer MS2 peaks are skipped. | Java `-minNumPeaks 10` | - -### Modifications - -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--fixed-mods` | list | `Carbamidomethyl (C)` | Fixed modifications, `Name (sites)` items with UNIMOD names (§2). Replaces the default; with the default, a detected TMT/iTRAQ tag is added on K and the peptide N-term. | Java `-mod ` | -| `--variable-mods` | list | `Oxidation (M), Acetyl (Protein N-term)` | Variable modifications, as `--fixed-mods` (§2); `""` = none. Replaces the default. Neutral losses, cleavage blocking, diagnostic ions, annotated-only sites and custom masses are config-only (§2). | Java `-mod ` | +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--precursor-tol` | ppm or Da | `20ppm` | `> 0, VALUE+unit, e.g. 20ppm or 0.02da` | Precursor mass tolerance in ppm or Da, e.g. 20ppm or 0.02da | `Java -t 20ppm` | +| `--enzyme` | — | `trypsin` | `trypsin \| chymotrypsin \| lysc \| aspn \| gluc \| lysn \| argc \| alphalp \| nocleavage \| nonspecific` | Protease; a comma list (gluc,trypsin) cleaves at the sites of each one The order of a list does not matter. The primary protease, which selects the model and the cleavage feature, is trypsin whenever the list has it; otherwise the one whose rule sets the C-terminal residue of most peptides (a C-terminal protease with more cleavage residues). A non-specific protease in a list makes the whole digest non-specific. Also accepted: tryp, chymo, lys-c, asp-n, glu-c, lys-n, arg-c, alp, alpha-lp, none (nocleavage), all and elastase (nonspecific), in any case. | `Java -e` | +| `--fixed-mods` | — | *(Carbamidomethyl (C))* | `list of Name (sites)` | Fixed modifications, a list of Name (sites) [default: Carbamidomethyl (C)] Comma-separated, e.g. "Carbamidomethyl (C), TMT6plex (K), TMT6plex (N-term)". The name is a UNIMOD name or accession (Phospho, UNIMOD:21; GlyGly, Deamidation, TMT10plex and TMT16plex are also accepted), which gives the mass. The sites are residues (STY), N-term, C-term, Protein N-term, Protein C-term, or a terminus followed by residues (N-term Q). The list replaces the default; with the default, a run found to carry a TMT or iTRAQ tag also gets the tag on K and the peptide N-term. Neutral losses, loss class, cleavage blocking, diagnostic ions, annotated-only sites and custom masses are set per modification in the config file (search.fixed_mods). Format and examples: DOCS.md §2. | `Java -mod ` | +| `--variable-mods` | — | *(Oxidation (M), Acetyl (Protein N-term))* | `list of Name (sites)` | Variable modifications, a list of Name (sites) [default: Oxidation (M), Acetyl (Protein N-term)] Written as --fixed-mods, e.g. "Oxidation (M), Phospho (STY), Gln->pyro-Glu (N-term Q)"; "" searches none. The list replaces the default, and --max-mods bounds the variable modifications per peptide. The per-modification settings are config-file keys (search.variable_mods). For `andes inference` and `andes quant finalize`, give the search's lists or its --config: PSMs that place a `restrict_to: annotated` modification on a knockoff site count for no protein group, as in the search. | `Java -mod ` | +| `--decoy-prefix` (advanced) | — | `XXX_` | — | Accession prefix that marks a decoy, given to the generated decoys | — | +| `--decoy-suffix` (advanced) | — | *(off)* | — | Accession suffix that also marks a decoy (e.g. rev for _rev decoys) A protein is a decoy when its accession starts with the --decoy-prefix or ends with this suffix. For a database that holds its decoys, with --decoy-strategy none, so that andes adds none of its own. | — | +| `--decoy-strategy` | — | `shuffle` | `shuffle \| reverse \| sequon \| mutate \| none` | How decoys are generated Decoys are peptide-level: each segment between two cleavage sites is permuted with its cleavage residues, its cleavage-side terminal residue and an initiator Met in place, so every enzymatic peptide has a decoy of the same composition and C-terminal residue (a non-specific search permutes whole sequences). Every decoy peptide the search enumerates (missed-cleavage joins, semi-specific and non-specific sub-spans included) is checked against the target peptides with I and L folded; one that equals a target is redrawn, and the few that still do are scored as targets. With none and a target-only database the search has no decoys and warns. | — | +| `--threads` | count | *(the number of logical CPUs)* | — | Worker threads [default: the number of logical CPUs] | `Java -thread N` | +| `--charge` (advanced) | charge | `2..5` | `MIN..MAX, 1..50, MIN <= MAX` | Precursor charges tried when the spectrum records none, as MIN..MAX (or MIN-MAX) | `no direct Java flag; set via param file in Java` | +| `--isotope-error` (advanced) | — | *(-1..2, 0..2 with --glyco or --xl)* | `MIN..MAX, MIN <= MAX` | Isotope-error offsets tried, as MIN..MAX (or MIN-MAX) [default: -1..2, 0..2 with --glyco or --xl] | `Java -ti -1,2` | +| `--open-search` (advanced) | — | *(off)* | — | Open (mass-offset) search: any peptide within --open-search-delta of the precursor | — | +| `--open-search-delta` (advanced) | Da | `-100..300` | `MIN..MAX in Da, contains 0, width <= 2000` | Mass-offset window for --open-search, as MIN..MAX in Da [default: -100..300] | — | +| `--open-search-top-k` (advanced) | count | `100` | — | Candidates scored per spectrum under --open-search [default: 100] | — | +| `--optimize` (advanced) | — | *(off)* | — | Parameter search: grid precursor tolerance, top-N and charge on a sample, then run | — | +| `--max-missed-cleavages` (advanced) | count | `2` | — | Missed cleavages per peptide (not applied to a non-specific digest) --glyco raises the value to 3 unless it is given on the command line or in --config. | `Java -maxMissedCleavages 2` | +| `--enzyme-specificity` (advanced) | — | `fully` | `non-specific \| semi \| fully` | Peptide ends that must be cleavage sites | `Java -ntt` | +| `--min-length` (advanced) | count | `6` | — | Shortest peptide, in residues | `Java -minLength 6` | +| `--max-length` (advanced) | count | `50` | — | Longest peptide, in residues | `Java -maxLength 40` | +| `--max-mods` (advanced) | count | `3` | — | Variable modifications per peptide | — | +| `--min-peaks` (advanced) | count | `10` | — | Fewest peaks of a scored MS2 spectrum; spectra with fewer are skipped | `Java -minNumPeaks 10` | +| `--top-n` (advanced) | count | `10` | — | PSMs kept per spectrum | `Java -n 10` | + +### Database variants + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--uniprot-variants` (advanced) | — | *(off)* | — | UniProt XML: also search each natural sequence variant as its own entry Only the peptides carrying the variant are added, under an accession naming the change (sp\|P04637_VAR_005851_D7H\|P53_HUMAN), and decoys mirror them. Grows the search space. | — | +| `--uniprot-isoforms` (advanced) | — | *(off)* | — | UniProt XML: also search each described isoform as its own entry An isoform (sp\|P04637-2\|P53_HUMAN) is rebuilt from the canonical sequence and its splice variants; it carries its own annotated sites, the canonical ones on the residues it shares and, with --uniprot-variants, its own natural variants. Grows the search space. | — | +| `--uniprot-chains` (advanced) | — | *(off)* | — | UniProt XML: also search each mature chain or peptide whose ends differ from the precursor's A chain is what remains after a signal peptide, propeptide or transit peptide is removed. Only the peptides at the new termini are added; they are protein-terminal there, so protein-terminal modifications apply. Grows the search space. | — | +| `--uniprot-evidence` (advanced) | — | `experimental` | `experimental \| curated \| any` | UniProt XML: least evidence of a variant, annotated site or chain that is used | — | +| `--annotations` (advanced) | path | *(off)* | — | Annotation file (.annotations.parquet) of variants, sites and chains; repeatable Claims about the database's reference proteins from any source, one row per claim: sequence edits become variant entries, chains become chain entries and sites are added to the reference, as from a UniProt XML database. Several files are merged by content. Columns: DOCS.md. | — | +| `--knockoffs` (advanced) | count | `4` | — | Knockoff entries per single-residue variant, which estimate the variant FDR (0: none) For --uniprot-variants and --annotations variants. A knockoff is the same substitution at another position holding the same residue, in a matched sequence context and at least 10 residues from every known variant: almost certainly absent from the sample, it fits a mass coincidence or an isotope error as well as the real variant. The knockoffs accepted per substitution class estimate how many accepted variant PSMs are false, and with --rescore variant PSMs get a q-value from that estimate too. A variant PSM is accepted only when its variant has a knockoff; knockoff PSMs are never reported. With 0, variant PSMs get the class FDR only. | — | -### Scoring +### FDR -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--fragmentation` | enum | `auto` | `auto`, `CID`, `ETD`, `HCD`, `UVPD`. `auto` reads the file (§4); on MGF it falls back to CID and warns. | Java `-m` | -| `--protocol` | enum | `auto` | `auto`, `phospho`, `iTRAQ`, `iTRAQ-phospho`, `TMT`, `standard`. An explicit value selects the protocol model. `auto` keeps the model; if it finds TMT/iTRAQ reporter ions it turns on the isobaric peak filter and (with no `--fixed-mods`) adds the tag as a fixed mod. | Java `-protocol` | -| `--score` | enum | `auto` | What ranks candidates and fills `RawScore`: `rank` (low-res), `strong` (high-res), or `auto` (by the model's instrument class). | — | -| `--gbdt-max-trees` | u32 | `100` | Trees per GBDT ensemble, `0` = all. 100 is 33–41% faster and identification-neutral (2026-09). `--glyco` uses all trees unless set. | — | -| `--peak-filter` | `WINDOW_DA:PEAKS` | protocol default | Keep the `PEAKS` most intense peaks per `WINDOW_DA`. Unset = `100:20` for isobaric data, else off; window `0` forces off. With `--dia` on `.d` input, the filter applies to the fragment-index vote only, and scoring uses every peak. | — | -| `--ethcd-activation` | enum | `ethcd` | EThcD/ETciD label: `ethcd` (EThcD model, b/y + c/z ions) or `etd` (ETD label; the `--glyco` c/z path). | — | -| `--model-store` | path | *(bundled)* | Model store instead of `resources/models/` (directory or one `models.parquet`). | — | -| `--model` | string | *(auto-select)* | Load this model id, skipping selection. | — | +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--psm-fdr` | fraction | *(0.01)* | `0..1` | PSM-level FDR: the q-value threshold of the reported PSMs [default: 0.01] It sets the filtered .q.tsv output (target PSMs at q <= this), the PSMs that quantification measures, the match-between-runs donors and the confident anchors of --refine. andes computes q-values only with --rescore; without it, setting it warns and writes no filtered output. | — | +| `--protein-fdr` | fraction | *(off)* | `0..1` | Protein-group q-value threshold of the filtered output [default: none] With --rescore, protein groups and their q-values (.protein_groups.tsv, picked target-decoy competition per protein family) are written either way; with this threshold the filtered TSV keeps only PSMs whose peptide counts for a group at or below it, and the proteoform table only the families of such groups. With --mbr and --output-parquet, the QPX pg and feature views keep the groups at or below it, 0.01 when it is not given. | — | +| `--quant-fdr` | fraction | *(0.01)* | `0..1` | Quantification FDR: q-value threshold of values measured without an identification [default: 0.01] It covers the match-between-runs transfers of --lfq, --tmt, --label and --glyco --lfq, the --label channels matched without an identification and, with --lfq, the feature q-value of `accepted` in lfq.parquet. A quantification-quality q-value, not an identification FDR. When neither this nor the value's advanced flag is given, the --label channels and transfers, the lfq.parquet `accepted` flag and the --glyco --lfq --mbr transfers use 0.05: their q-values come from one target/decoy competition per run with few decoys. | — | +| `--rescore` | — | *(off)* | — | Rescore the PIN with Percolator and write q-values, PEPs and the PSMs at --psm-fdr Percolator's PEP and q-value are joined into the outputs (QPX posterior_error_probability and a q-value score) and the filtered .q.tsv is written. Every Percolator pass (the main run, the per-run q-values, the PEP repair and the scores of every PIN row) runs in process with the native engine, which implements the Percolator algorithm (Käll et al., Nat. Methods 2007), tracks upstream Percolator master (commit a9783ee8) and writes Percolator's output files; no Percolator binary or Docker is needed. --percolator-bin or --percolator-docker runs an external Percolator instead. --xl does not use the native engine: its Percolator passes always run an external Percolator, --percolator-bin, else `percolator` on PATH, else the Docker image. | — | -**Model selection** tries an exact (activation, instrument class, enzyme, protocol) match, then -drops the protocol, then takes the closest instrument class. The instrument class comes from -the file; use `--model-store` plus `--model` for an unbundled model. +### Modes + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--chimeric` | — | *(off)* | — | Also search co-isolated peptides: a second PSM per scan from its MS1 isolation window Pass 1 is the normal search and keeps the same --top-n candidates per scan; pass 2 takes the best one as the primary peptide, detects co-isolated precursors in the scan's MS1 isolation window and searches the residual spectrum for a second peptide, written as an extra PSM. Needs MS1 scans (mzML, .raw); no effect on MGF input. | — | +| `--dia` | — | *(off)* | — | Data-independent acquisition: search every MS2 scan across its isolation window Each scan is searched against every peptide whose precursor m/z lies in its isolation window and has an MS1 peak (spectrum-centric DIA, as MSFragger-DIA); the PIN gets fragment and MS1 co-elution columns from the neighbouring cycles of the same window. With --rescore, Percolator runs with --trainFDR 0.05 and again after a per-run RT refinement. On Orbitrap Astral the fragment tolerance is 7 ppm unless --fragment-tol-* is set. Needs mzML or .raw with isolation windows and MS1 scans; replaces --chimeric and --precursor-cal; not with --open-search, --refine, --glyco or --xl. | — | +| `--dia-mobility-slices` (advanced) | count | `1` | — | diaPASEF (.d) only: split each isolation window's mobility range into N slices Each slice spans two N+1ths of the window's TIMS scan range, and neighbouring slices overlap by half. Each slice is searched as its own spectrum and traced on its own across cycles. A slice spectrum mixes fewer co-isolated peptides than the whole window. 1 keeps one spectrum per window. Ignored for mzML, .raw and ddaPASEF. | — | +| `--dia-ms1-tol-ppm` (advanced) | ppm | `5` | — | --dia MS1 gate: ppm tolerance for a candidate's monoisotopic peak in the survey scans A DIA candidate is scored only when its monoisotopic m/z has an MS1 peak within this tolerance in the survey scan nearest the MS2 scan or one either side. timsTOF MS1 is less accurate than Orbitrap MS1, so diaPASEF runs need a wider gate (8 on the ProteoBench low-input runs, after andes recentres their MS1 m/z). | — | +| `--refine` | — | *(off)* | — | Second pass for further modifications (oxidation, deamidation, ...) over the confident proteins The modifications are a built-in tier, or the tier of --refine-config. | — | +| `--localize` (advanced) | — | *(off)* | `ipf` | Site localization of variable modifications (`ipf`); needs --rescore `ipf`: inference of peptidoforms (the OpenSWATH/PyProphet hierarchical Bayesian model) over every placement of each identified PSM's variable mods, after rescoring. Writes .ipf.tsv, and the site probabilities into the QPX psms.parquet with --output-parquet. Experimental. | — | +| `--glyco` | — | *(off)* | — | Intact glycopeptide search into a .glyco.pin (needs a glycan database, e.g. --glyco-species) Glycans come from the glycan database (--glyco-species, --glyco-glycan-gdb or --glyco-glycan-wurcs); the backbone is solved as precursor minus glycan and filtered by the N-X-S/T sequon (any S/T with --glyco-core o). With --lfq the glycopeptides are quantified from MS1 as intact glycopeptides (peptide, glycan composition and charge) into .glyco.lfq.tsv (per feature), .glyco.quant.tsv (per glycopeptide), .glyco.site.tsv (glycoform shares per site), .glyco.protein.tsv and the cross-run .glyco.matrix.tsv and .glyco.protein_matrix.tsv; --lfq-tol, --lfq-rt-window, --lfq-min-cosine and --quant-transfer-fdr apply, and --mbr is the glycopeptide match between runs. The isobaric options do not apply. | — | +| `--xl` (advanced) | — | *(off)* | — | Crosslink search into .xl.tsv, linker as Name (sites), e.g. "DSSO"; several as "DSSO; DSBU" (experimental) The linker is written like a modification: a reagent name (DSSO, DSBU or BuUrBu, DSBSO, CDI; non-cleavable DSS or BS3, BS2G or DSG, EGS, DST, DSP or DTSSP, PhoX or DSPP, DMP, DTBP, DFDNB, BMOE, SMCC, SDA, EDC or DMTMM), its XLMOD accession (XLMOD:02126), or the UNIMOD name or accession of its intact cross-link (Xlink:DSS[138], UNIMOD:1898), then optionally its sites in parentheses: "DSSO (K, S, T, Y, Protein N-term)". Without sites the reagent's usual ones apply (Lys and the protein N-terminus for NHS esters); N-term adds every peptide N-terminus (synthetic peptide libraries), and a heterobifunctional reagent separates its two ends with /. The reagents and their masses (UNIMOD records, or cited compositions for reagents UNIMOD lacks) are the entries of resources/crosslinkers.yaml; a reagent the table lacks is an entry of the same schema in the config file (search.xl). An --sdrf comment[cross-linker] column sets the linker when neither the command line nor the config does. Monolinks are variable modifications, by UNIMOD record or as reagent:quencher (--variable-mods "Xlink:DSSO[176] (K), DSBSO:water (K)"). For an MS-cleavable linker each MS2 is searched for the reporter doublets; the doublet peptide masses and the precursor give the candidate peptide pairs. For a non-cleavable linker the fragment-ion index retrieves one peptide by its fragments that do not carry the link, and its partner is looked up by the remaining precursor mass. Each peptide is scored with the standard scorer carrying the cleaved stub or its partner on the link residue. Writes the best crosslink-spectrum match per spectrum into a pair-aware PIN (.xl.pin; both link classes are scored by the pair score, and --rescore does not change them) and the q-values, from the target-target, target-decoy and decoy-decoy counts split by intra-protein, homotypic (one peptide sequence on both sides) and inter-protein links and pooled over the runs, of the matches (.xl.tsv), residue pairs (.xl.residue_pairs.tsv) and protein pairs (.xl.ppi.tsv), with the doublet summary of every spectrum (.xl.doublets.tsv). | — | +| `--xl-linear-only` (advanced) | — | *(off)* | — | With --xl: search only linear and monolinked peptides and write their protein groups The search runs with the variable modifications --xl implies (the default ones plus the linker's water-quenched monolink) and no cross-link search; with --rescore it writes .protein_groups.tsv. `andes cohort run` uses it once per project to choose the proteins its cross-link searches look in. | — | +| `--glyco-species` | — | *(off)* | `human \| mouse \| mouse-large \| high-mannose` | Bundled N-glycan database of --glyco The databases and their attribution: crates/glyco/glycan-db/. | — | +| `--chimeric-max-coisolated` (advanced) | count | `4` | — | Most co-isolated peptides searched per scan with --chimeric | — | +| `--chimeric-max-kl` (advanced) | number | `0.3` | `>= 0` | Largest averagine-envelope KL divergence of an accepted co-isolated precursor (--chimeric) Lower is stricter: fewer spurious second peptides. | — | +| `--refine-config` (advanced) | path | *(the built-in tier)* | — | YAML file of the --refine modification tier [default: the built-in tier] | — | -### Calibration +### Quantification -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--precursor-cal` | enum | `off` | `off`, `auto`, `on`. A pre-pass learns a ppm shift from confident PSMs and tightens the precursor tolerance; `auto` skips it on small samples. Off by default: on the benchmark sets the pre-pass took 9–17% of the run and never fired, and where it fired (UPS1, larger sample) the tightened window lost 7.6% of PSMs. Skipped (with a warning) on `.raw` and `.d`. | Java `-precursorCal auto\|on\|off` | +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--tmt` | — | *(off)* | `tmt6 \| tmt10 \| tmt11 \| tmt16 \| tmt18 \| tmt32 \| tmt35 \| itraq4 \| itraq8` | Isobaric reporter-ion quantification with this labelling kit Writes .tmt.parquet and, with --output-parquet, the QPX quantms.feature.parquet. With --rescore only the PSMs at q <= --psm-fdr are quantified. Also accepted: the plex spellings (tmt10plex) and tmtpro, tmtpro16, tmtpro18, tmtpro32, tmtpro35, in any case. | — | +| `--lfq` | — | *(off)* | — | Label-free MS1 quantification of the identified precursors Isotope chromatograms are extracted around each identified peptidoform's retention time and integrated. Writes .lfq.parquet and, with --output-parquet, the QPX quantms.feature.parquet. mzML, Thermo .raw and Bruker .d input (a .d's MS1 frames are summed over ion mobility). With --glyco it quantifies intact glycopeptides instead (see --glyco). | — | +| `--label` | — | *(off)* | `preset or one bracket per channel` | MS1 labelled-pair quantification (SILAC, dimethyl): a preset or one bracket per channel Presets: silac2, silac3, dimethyl2, dimethyl3. Channels are brackets in increasing mass order, as OpenMS FeatureFinderMultiplex writes them ([][Lys8,Arg10], [Dimethyl0][Dimethyl4][Dimethyl8]); a label is one of Lys4 Lys6 Lys8 Arg6 Arg10 Leu3 Dimethyl0 Dimethyl4 Dimethyl6 Dimethyl8, or +[:[chem]CND] with the label's 13C, 15N and 2H atoms (chem: a chemical label that adds atoms; without atoms: a chemical shift of natural atoms). The labels are searched as variable modifications that every labelable site of a peptide carries alike, and each identified peptide is measured in every channel by one joint fit of their MS1 isotope traces; channels without an identification are matched at their exact position (match between channels), and with --mbr peptides are transferred between runs. Writes .label.parquet. mzML or .raw with high-resolution MS1; not with --lfq or --tmt. | — | +| `--mbr` | — | *(off)* | — | Match between runs across two or more inputs (needs --rescore, and --lfq, --tmt or --label) Label-free: after the per-run quantification, builds the precursor library, aligns retention times across runs, measures every library precursor in every run and writes .mbr.parquet and .mbr_validation.parquet (with --output-parquet, quantms.feature.parquet holds these rows instead of the per-run features, without the transfers above the threshold). Uses --quant-dir for the per-run tables, or a temporary directory. With --rescore (Percolator) it gives the same result as `andes quant library`, `extract` and `finalize` on the same files and Percolator results. With --tmt: the reporter ions of unidentified MS2 scans at an identified peptide's m/z and aligned retention time are transferred into the runs that lack it, each with an evidence type and a quantification-quality q-value (`quant_q`) in tmt.parquet and the QPX feature view; high-resolution MS2 reporters only (not SPS-MS3 or ion-trap MS2); identified rows are unchanged. With --glyco --lfq: every accepted glycopeptide is measured in each run that did not identify it, around its predicted apex on a retention-time map fitted to the first input on the glycopeptides both runs identified, and the transfers are scored in their own target/decoy competition. Transferred rows say so in the Evidence column of .glyco.lfq.tsv. Details: DOCS.md §9. | — | +| `--quant-dir` | path | *(off)* | — | Directory of the per-run tables of multi-run quantification For each input: .ms1.parquet (its MS1 scans, every FAIMS voltage), .ms2.parquet (its MS2 scans, reduced) and .quant.parquet (every rank-1 PSM, targets and decoys, unfiltered; with --chimeric also the best PSM of each co-isolated precursor). Input as for --lfq (mzML, .raw or .d); not with MGF or --glyco. | — | -### Parameter search (`--optimize`) +### Rescoring -| Flag | Type | Default | Description | -|---|---|---|---| -| `--optimize` | flag | *(off)* | Parameter search on a sample of the run: first the precursor tolerance (5/10/20/50 ppm, at the resolved top-N and charge range), then top-N (1/2/3/5 and the resolved value) x charge range (the resolved range and `2..=3`). Each combination's PIN is rescored with the native Percolator engine (in `--temp-dir`, removed afterwards); the combination with the most target PSMs at `q ≤ 0.01` is used for the whole run. On a tie the resolved value wins. The tolerance stage is skipped with `--open-search` (the tolerance is the offset window) and for a Da tolerance; the top-N/charge stage still runs on the sample. Refused with `--glyco`. | -| `--optimize-sample` | integer | `5000` | Spectra the grid scores, taken every k-th across the file (mzML and Thermo .raw); other formats fall back to the first 1,000 spectra. | +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--pep` (advanced) | fraction | *(off)* | `0..1` | PEP threshold applied with --psm-fdr: a PSM must pass both [default: none] | — | +| `--percolator-bin` (advanced) | path | *(off)* | — | Run --rescore with this external Percolator binary instead of the native engine With --xl the default is `percolator` on PATH, else the Docker image. | — | +| `--percolator-docker` (advanced) | — | *(off)* | — | Run --rescore with Percolator from its Docker image instead of the native engine Needs the docker command. | — | +| `--percolator-image` (advanced) | — | `quay.io/biocontainers/percolator:3.7.1--h3b5f4bd_2` | — | Docker image of Percolator, with --percolator-docker or --xl | — | +| `--percolator-args` (advanced) | — | *(no extra arguments)* | — | Extra arguments for an external Percolator, e.g. "--testFDR 0.05" Only with --percolator-bin, --percolator-docker or --xl; the native engine takes none. | — | +| `--keep-pin` (advanced) | — | `true` | `true \| false` | Keep the PIN after rescoring Without --output-pin, true writes the PIN (and Percolator's result files) as .pin, being --output-tsv, else --output-parquet, else ./andes; false uses a temporary PIN deleted at exit. An explicit --output-pin is always kept. | — | + +### Prediction + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--predict` (advanced) | — | `rt` | `rt \| ms2 \| peptdeep-ms2 \| peptdeep-rt \| deeplc-rt \| none` | Predicted features added to the PIN, comma-separated Predicted retention times are calibrated to the observed ones per input file. peptdeep-ms2, peptdeep-rt and deeplc-rt load exported ONNX models from --predictor-models and fail at start-up when a model file is missing. | — | +| `--predictor-models` (advanced) | path | *(off)* | — | Directory of the exported AlphaPeptDeep and DeepLC models peptdeep_mods.json, peptdeep_{ms2,rt}_dynamic.{json,onnx} and deeplc_rt.{json,onnx}, as the onnx-infer export scripts write them. | — | +| `--predictor-backend` (advanced) | — | `tract` | `tract \| ort` | ONNX engine of the AlphaPeptDeep and DeepLC models | — | +| `--predictor-nce` (advanced) | number | *(28 on Q Exactive, else 30)* | — | Collision energy given to the MS2 model [default: 28 on Q Exactive, else 30] | — | +| `--predictor-instrument` (advanced) | — | *(from the instrument)* | — | Instrument given to the MS2 model, e.g. QE, Lumos, timsTOF [default: from the instrument] One of the model's instrument names. Unset: QE for a Q Exactive, timsTOF for a timsTOF, SciexTOF for another TOF, otherwise Lumos. | — | +| `--predictor-batch` (advanced) | count | `256` | — | Peptides per predictor batch | — | + +### Isobaric (TMT, iTRAQ) + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--tmt-level` (advanced) | count | *(3 for SPS-MS3 data, else 2)* | `2 or 3` | MS level of the reporter ions: 2 (the identified MS2) or 3 (its SPS-MS3 scan) [default: 3 for SPS-MS3 data, else 2] 3 is the default when the MS2 is low-resolution, cannot separate the plex's channels and the MS3 scans carry reporters. MS3 needs mzML or .raw (a .d has no MS3 scans). | — | +| `--tmt-tol` (advanced) | ppm or Da | *(20ppm (10ppm for tmt32/tmt35), 0.3da on ion-trap MS2)* | `> 0, VALUE+unit, e.g. 20ppm or 0.003da` | Reporter-ion m/z tolerance, e.g. 20ppm or 0.003da [default: 20ppm (10ppm for tmt32/tmt35), 0.3da on ion-trap MS2] 20 ppm (10 ppm for tmt32 and tmt35) applies to high-resolution MS2 and to --tmt-level 3, whose reporters are read in the Orbitrap. A window reaching half the spacing of the kit's closest channels is refused. | — | +| `--tmt-correction` (advanced) | path | *(off)* | — | Isotope impurity matrix of the kit lot, in quantms text form [default: no correction] One line per channel with the -2/-1/+1/+2 percentages (eight columns for TMTpro 16/18). Corrected intensities are solved by non-negative least squares; the raw values are kept alongside. Not for tmt32 and tmt35. | — | +| `--tmt-min-purity` (advanced) | fraction | `0.7` | `0..1` | Quantification gate: least precursor isolation purity (0: off) The purity is the share of the MS1 isolation window that belongs to the precursor. PSMs that fail the gate are kept in tmt.parquet and the QPX parquet with quant_weight 0 (quant_gate_passed false in tmt.parquet). | — | +| `--tmt-min-sn` (advanced) | number | `0` | `>= 0` | Quantification gate: least summed reporter signal-to-noise (0: off) Applies where the reporter scan records noise (Thermo .raw, or mzML converted with noise arrays); other PSMs are not held to it. | — | +| `--tmt-unmix` (advanced) | — | `auto` | `auto \| off \| on` | Remove the co-isolation interference of high-resolution MS2 reporters Writes the reporter intensities with the interference removed as an extra unmix_ channel block and an interference column in tmt.parquet (the other columns are unchanged). A per-run regression explains each scan's summed reporter signal by the precursor's, the co-isolated ions' and the sub-threshold ion current in the isolation window of the bordering MS1 scans; the interference is removed with the run's mean reporter profile. The auto strength is the one under which a protein's interference-heavy PSMs best agree with its clean PSMs (in the tmt.parquet metadata). auto and on apply to --tmt-level 2 only; on needs --tmt. | — | +| `--mbr-wrong-log2` (advanced) | number | `0.5` | `> 0` | With --tmt --mbr: RMS log2 deviation from its reference scan above which a transferred profile counts as wrong The definition of an error used to learn the transfer risk, not an acceptance threshold. | — | + +### Label-free + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--lfq-tol` (advanced) | ppm or Da | *(10ppm)* | `> 0, VALUE+unit, e.g. 20ppm or 0.02da` | MS1 m/z tolerance of the isotope chromatograms, e.g. 10ppm [default: 10ppm] | — | +| `--lfq-rt-window` (advanced) | s | *(60; 120 with --glyco)* | `> 0` | Retention-time half-window around the identifying PSM, in seconds [default: 60; 120 with --glyco] | — | +| `--lfq-gaussian-width` (advanced) | s | *(Savitzky-Golay smoothing)* | `> 0` | Experimental: Gaussian peak width for peak detection, in seconds (eight sigma) [default: Savitzky-Golay smoothing] Areas still use the raw signal. Without it, peaks are detected on five-scan Savitzky-Golay smoothed traces. Check the feature q-value coverage on the acquisition before relying on it. | — | +| `--lfq-min-cosine` (advanced) | fraction | `0.7` | `0..1` | Least isotope-envelope cosine of a feature marked accepted in lfq.parquet lfq.parquet keeps every feature with its cosine. | — | + +### Labelled pairs + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--label-reference` (advanced) | count | `1` | `>= 1` | Reference channel of the --label ratios, 1-based | — | +| `--label-arg-pro` (advanced) | — | *(off)* | — | SILAC: fit the heavy proline made from heavy arginine and add it back to its channel Arg6 gives 13C5 Pro and Arg10 13C5 15N1 Pro, fitted as a satellite of each proline-containing peptide's arginine-labelled channels. label.parquet reports the converted fraction. | — | +| `--label-2h-enrichment-silac` (advanced) | fraction | `0.96` | `0..1` | 2H enrichment of metabolic deuterium labels (Lys4, Leu3) | — | +| `--label-2h-enrichment-chemical` (advanced) | fraction | `0.99` | `0..1` | 2H enrichment of chemical deuterium labels (dimethyl) | — | +| `--label-heavy-enrichment` (advanced) | fraction | `0.99` | `0..1` | 13C and 15N enrichment of heavy labels, per atom | — | + +### Glycopeptides + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--glyco-glycan-gdb` (advanced) | path | *(off)* | — | External .gdb glycan database of --glyco (instead of --glyco-species) Each canonical string keeps its tree structure (core- or antenna-fucose), and the file's NeuGc content is used as it is. Not with --glyco-glycan-wurcs or --glyco-species. | — | +| `--glyco-glycan-wurcs` (advanced) | path | *(off)* | — | WURCS 2.0 glycan database CSV of --glyco (instead of --glyco-species) Columns GlycanID, Mass, GlycanComposition and StructureInformation. Each StructureInformation is reduced to the five-symbol tree of a .gdb line (anomericity, ring and substituents dropped); mass and composition are computed from the tree. Not with --glyco-glycan-gdb or --glyco-species. | — | +| `--glyco-core` (advanced) | — | `n` | `n \| o` | Glycan core of --glyco An o run attaches glycans at any Ser or Thr (no sequon) and needs an O-glycan .gdb. | — | +| `--precursor-mono` (advanced) | — | `auto` | `off \| auto` | Correct each precursor to the monoisotopic peak of its MS1 envelope (--glyco) auto fits the MS1 envelope at the reported charge against a glycopeptide isotope model under the hypotheses "the recorded precursor is the M+k peak", k = 0..6, and moves the precursor down when a k > 0 clearly wins. A fitted spectrum is searched with isotope errors 0..1 instead of the glyco default 0..2; spectra without a linked MS1 or charge keep the default, and an explicit --isotope-error is used as given. Needs MS1 (mzML, .raw or .d); without it the search is as with off. | — | +| `--glyco-tol-ppm` (advanced) | ppm | `20` | `> 0` | Fragment tolerance in ppm of the glyco matching: oxonium ions, core Y ions, backbone, c/z Unset on low-resolution (ion-trap) MS2, it is 500 ppm (about 0.5 Da at m/z 1000). It is separate from --fragment-tol-ppm; the glycan-by-subtraction precursor matching uses --precursor-tol. | — | +| `--glyco-min-core-y` (advanced) | count | `0` | — | Fewest trimannosyl-core Y ions of a reported --glyco PSM (0: off) Reads spectral evidence only, so targets and decoys are held to it alike. 2 suits collision-dominated (HCD) data; electron-transfer data lose identifications with it (DOCS.md §9). With --glyco-core o the core ladder is Y0 and Y1 only, so a value above 2 rejects every O-glycopeptide. | — | +| `--glyco-hcd-pair` (advanced) | — | `true` | `true \| false` | On ETD scans, take the candidate backbones from the paired HCD scan of the same precursor c/z ions are still scored on the ETD scan. Scans without an HCD partner, and multi-file runs, are searched unpaired. | — | +| `--glyco-max-peaks` (advanced) | count | `0` | — | Most intense peaks considered when generating --glyco candidates (0: all) Scoring always reads the whole spectrum. 300 to 500 keeps profile or very dense scans from taking seconds each. Changing it changes results. | — | +| `--glyco-cz-max-charge` (advanced) | charge | *(from whether the spectrum is deconvoluted)* | — | Largest c/z fragment charge of --glyco ETD scoring [default: from whether the spectrum is deconvoluted] Set it only for data known to carry unresolved high-charge c/z ions. | — | +| `--glyco-y-max-charge` (advanced) | charge | `3` | — | Largest glycan Y fragment charge of --glyco | — | +| `--glyco-retrieval-tol-ppm` (advanced) | ppm | *(--glyco-tol-ppm on high-res MS2, 0.5 Da on low-res)* | `> 0` | Candidate retrieval tolerance in ppm of --glyco [default: --glyco-tol-ppm on high-res MS2, 0.5 Da on low-res] Retrieval only; the scoring tolerance is unchanged. | — | +| `--glyco-peptide-first` (advanced) | — | *(off)* | — | Peptide-first b/y fragment-index retrieval instead of the glycan-mass branch (slower) | — | +| `--glyco-index-sequon-only` (advanced) | — | *(off)* | — | Index only N-X-S/T peptides for --glyco, a much smaller index Glyco scoring reads only sequon-bearing candidates, so the results are those of the full index except for per-spectrum candidate-distribution features (RawScore, CandidateRankEntropy) on a few PSMs. | — | + +### Calibration and runtime + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--precursor-cal` (advanced) | — | `off` | `off \| auto \| on` | Precursor mass calibration pre-pass auto and on learn a systematic ppm shift from confident PSMs in a pre-pass and tighten the precursor tolerance of the main search. Not available for Thermo .raw input (warns). | `Java -precursorCal auto\|on\|off` | +| `--score` (advanced) | — | `auto` | `auto \| rank \| strong` | What ranks the candidates and fills the PIN RawScore | — | +| `--fragmentation` (advanced) | — | `auto` | `auto \| CID \| ETD \| HCD \| UVPD` | Fragmentation of MGF spectra (mzML, .raw and .d record it) | `Java -m` | +| `--protocol` (advanced) | — | `auto` | `auto \| phospho \| iTRAQ \| iTRAQ-phospho \| TMT \| standard` | Labelling or enrichment protocol, which selects the protocol model auto keeps the selected model; when it finds TMT or iTRAQ reporter ions it turns on the isobaric peak filter and, without --fixed-mods, adds the tag as a fixed modification. | `Java -protocol` | +| `--fragment-tol-ppm` (advanced) | ppm | *(measured per run)* | `> 0` | Fragment tolerance in ppm of the PIN features, replacing the per-run measurement On MGF it also selects the high-resolution model class. Not with --fragment-tol-da. | — | +| `--fragment-tol-da` (advanced) | Da | *(measured per run)* | `> 0` | Fragment tolerance in Da of the PIN features, replacing the per-run measurement On MGF it also selects the low-resolution model class. Not with --fragment-tol-ppm. | — | +| `--peak-filter` (advanced) | — | *(100:20 for isobaric data, else off)* | `WINDOW_DA:PEAKS` | Peak filter WINDOW_DA:PEAKS, e.g. 100:20 [default: 100:20 for isobaric data, else off] Keeps the PEAKS most intense peaks in every WINDOW_DA window; a window of 0 turns the filter off. | — | +| `--ethcd-activation` (advanced) | — | `ethcd` | `ethcd \| etd` | How EThcD and ETciD spectra are labelled | — | +| `--ms-level` (advanced) | count | `2` | — | MS level searched in mzML (MGF, .raw, .d and --chimeric search MS2) | — | +| `--fragment-index` (advanced) | — | `auto` | `auto \| on \| off` | Candidate retrieval At a low-resolution fragment tolerance only the 150 most intense peaks vote in the fragment-ion index. The search log reports the retrieval used. | — | +| `--fragment-index-slice-da` (advanced) | Da | *(from the memory budget)* | — | Precursor-mass width of one fragment-index slice, in Da [default: from the memory budget] | — | +| `--index-cache-dir` (advanced) | path | *(the directory of the outputs)* | — | Directory of the candidate-index cache [default: the directory of the outputs] The cache (andes-candidx-.bin) is created if missing. A shared directory builds the index once for several tasks, a node-local one gives a cache per node. A directory that cannot be written is an error. | — | +| `--temp-dir` (advanced) | path | *(the directory of the outputs)* | — | Directory of the run's temporary files [default: the directory of the outputs] Created if missing and emptied at exit. It holds the MS1 scans kept between searching and quantification, the directory of --mbr without --quant-dir, and the PIN of --rescore with --keep-pin false. A directory that cannot be written is an error. | — | +| `--model-store` (advanced) | path | *(the bundled store)* | — | Parquet model store (a file or a partitioned directory) instead of the bundled one | — | +| `--model` (advanced) | — | *(selected from the data)* | — | Model id to load from the model store, skipping the automatic selection | — | +| `--gbdt-max-trees` (advanced) | count | *(100; all with --glyco)* | — | Trees evaluated per GBDT ensemble, 0 for all [default: 100; all with --glyco] Applies to the fragment-intensity and rich-ion ensembles. Fewer trees change the predicted intensities, so the PIN feature values and, with --score strong, which candidate ranks first. | — | + +### Advanced FDR + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--proteoform-fdr` (advanced) | fraction | *(the larger of --psm-fdr and 0.05)* | `0..1` | q-value threshold of proteoform claims [default: the larger of --psm-fdr and 0.05] With rescoring, the filtered TSV, the proteoform table and quantification accept proteoform claims at this level instead of --psm-fdr. A proteoform claim is a PSM whose every protein is a UniProt variant entry; its q-value includes the class FDR and, with knockoffs, the knockoff estimate. Isoform and chain PSMs keep --psm-fdr. | — | +| `--mbr-donor-fdr` (advanced) | fraction | *(inherits --psm-fdr)* | `0..1` | Precursor q-value threshold of a match-between-runs library donor [default: inherits --psm-fdr] The best-PSM target/decoy q-value of the precursor. | — | +| `--quant-transfer-fdr` (advanced) | fraction | *(inherits --quant-fdr)* | `0..1` | q-value threshold of a reported transfer [default: inherits --quant-fdr] Transfers at or below it are reported as transfer_ms1 in .mbr.parquet; with --tmt, transferred reporter rows at or below it pass the quantification gate; with --label --mbr it is the label transfer threshold (the identity-decoy false-donor rate added); with --glyco --lfq --mbr the glycopeptide transfer threshold. When --quant-fdr is not given either, --label and --glyco use 0.05. | — | +| `--quant-channel-fdr` (advanced) | fraction | *(inherits --quant-fdr)* | `0..1` | --label: q-value threshold of a channel matched without an identification [default: inherits --quant-fdr] From the target/decoy competition, within its run, of the channel's fit against the same fit at non-label mass shifts. When --quant-fdr is not given either, 0.05. | — | + +### Options + +| Flag | Unit | Default | Range | Description | Legacy form | +|---|---|---|---|---|---| +| `--quiet` (command line only) | — | *(off)* | — | Print only warnings and errors to stderr | — | +| `--verbose` (command line only) | — | *(off)* | — | Also print debug lines to stderr | — | + + +### Notes on the flags + +**Model selection** tries an exact (activation, instrument class, enzyme, protocol) match, then +drops the protocol, then takes the closest instrument class. The instrument class comes from +the file; use `--model-store` plus `--model` for an unbundled model. + +#### Parameter search (`--optimize`) This is the parameter-optimization step of MSFragger's open-search pipeline (Yu et al., *Nat. Commun.* 2020), scoped to the parameters andes does not derive from the data. The **fragment** @@ -144,25 +289,6 @@ hold their c/z and a/x ions. The engine prints its choice; `--fragment-index off` scores every candidate in each precursor window instead ([benchmarks](docs/benchmarks/README.md)). -### Runtime - -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--threads` | usize | logical CPU count | Worker threads. | Java `-thread N` | -| `--quiet` | bool | `false` | Print only warnings and errors to stderr. Every subcommand takes it. Does not change any result. | — | -| `--verbose` | bool | `false` | Also print debug lines to stderr. Every subcommand takes it; `--quiet` wins over it. Does not change any result. | — | -| `--ms-level` | u8 | `2` | MS level to search in mzML. `.raw`/`.d`, MGF and `--chimeric` always search MS2. | — | -| `--temp-dir` | dir | output directory | Directory of the run's private temporary files (MS1 scans between searching and quantification, the `--mbr` directory without `--quant-dir`, the PIN of `--keep-pin false`); created if missing, emptied at exit; config key `io.temp_dir`. An unwritable directory is an error. | — | -| `--index-cache-dir` | dir | output directory | Directory of the candidate-index cache (`andes-candidx-.bin`), created if missing; config key `search.index_cache_dir`. A shared directory builds the index once for several tasks, a node-local one gives a cache per node. A directory that cannot be written is an error. | — | -| `--max-spectra` | usize | `0` | Bench mode: first N MS2 spectra only (`0` = all); skips TSV output. | — | - -### Output - -| Flag | Type | Default | Description | Legacy form | -|---|---|---|---|---| -| `--output-tsv` | path | *(off)* | Tab-separated PSM report (§3b). | Java `-outputFormat 1` with output path | -| `--output-parquet` | dir | *(off)* | QPX `.idparquet/` bundle (§3e). | — | - No environment variable changes a search result; the binary reads no `ANDES_*` variable. Search settings come from command-line flags or the `--config` YAML file; `--quiet` and `--verbose` are command-line only. The environment is used only to locate external tools: @@ -1271,13 +1397,14 @@ built-in default`**; unknown keys are a hard error. The UniProt XML options are (`uniprot_variants: true`, `uniprot_isoforms: true`, `uniprot_chains: true`, `uniprot_evidence: curated`). Values use the CLI strings (`precursor_tol: 20ppm`, `charge: "2..5"`, `isotope_error: "-1..2"`, `enzyme: gluc,trypsin`). -Every search flag has a key; a key is the flag name without its section prefix -(`--glyco-species` is `glyco.species`, `--glyco-glycan-gdb` is `glyco.glycan_gdb`, -`--fragment-index` is `search.fragment_index`, `--gbdt-max-trees` is +Every search flag listed in the reference (§1) has a key, except the ones marked "(command +line only)" there: `--config`, `--print-config`, `--quiet` and `--verbose`. The internal +diagnostics flags, which neither help lists, have no key either. A key is the flag name +without its section prefix (`--glyco-species` is `glyco.species`, `--glyco-glycan-gdb` is +`glyco.glycan_gdb`, `--fragment-index` is `search.fragment_index`, `--gbdt-max-trees` is `scoring.gbdt_max_trees`, `--lfq-gaussian-width` is `quant.lfq_gaussian_width`, `--quant-dir` is `quant.dir`). Each key's comment in the template names its flag and marks the advanced -ones. Five flags are CLI-only: `--config`, and the diagnostics `--cal-min-spec-keys`, -`--precursor-mono-dump`, `--glyco-scans` and `--glyco-mbr-match-train`. Setting +ones. Setting `search.max_missed_cleavages` or `search.isotope_error` counts as an explicit value, which `--glyco` then keeps instead of its own (3 missed cleavages, isotope errors 0..2). `glyco.enabled: true` needs `glyco.glycan_gdb` or `glyco.species` (or the CLI flag), checked after the merge; setting either glycan source on the command line replaces @@ -1296,6 +1423,18 @@ glyco: enabled: true ``` +`andes --print-config run.yaml` writes the settings the run resolves to (the command +line, `--config` and `--sdrf` merged) and exits without searching; `-` writes to stdout. +Settings that came from a config file, the SDRF or the command line are written as keys with a +comment naming the source; defaults stay commented out, so replaying the file with +`andes --config run.yaml` reproduces the run and keeps every default's own adjustments. Paths +are written as they were given, so a relative path is relative to the working directory of the +run: replay the file from the same directory. A command-line-only diagnostics flag that was set +has no key; the file ends with a comment naming it (`# set on the command line, no config key +(pass again to reproduce): --xl-oracle 5`), a warning names it too, and it must be given again +with `--config` to reproduce the run. A value with no config form (a path that is not UTF-8 +text) stops `--print-config` with an error. + ### SDRF input (`--sdrf`) `andes --sdrf design.sdrf.tsv --database human.fasta --output-pin out.pin` reads the search @@ -3392,12 +3531,12 @@ here only where the value is a fixed choice rather than a documented option. | PSMs kept per spectrum | 10 | `andes/src/bin/andes/cli.rs` | rows per spectrum in the PIN | `--top-n` | Inherited default; no recorded evidence | | Minimum peaks | 10 | `andes/src/bin/andes/cli.rs` | spectra skipped | `--min-peaks` | Inherited default | | Precursor tolerance | 20 ppm | `andes/src/bin/andes/cli.rs` | candidate window | `--precursor-tol`, `--precursor-cal` | No recorded evidence for 20 | -| Precursor calibration | off | `andes/src/bin/andes/cli.rs` | ppm shift pre-pass | `--precursor-cal` | Pre-pass cost 9-17% of the run on the benchmark sets (see [§1](#calibration)) | +| Precursor calibration | off | `andes/src/bin/andes/cli.rs` | ppm shift pre-pass | `--precursor-cal` | Pre-pass cost 9-17% of the run on the benchmark sets (see [§1](#calibration-and-runtime)) | | Pre-pass sample and floors | stride 10, at most 500 spectra, 10,000 spectrum keys, 150 confident PSMs, residual cap 200 | `search/src/precursor_cal.rs:76-89` | when the pre-pass runs and how many residuals feed the median | no | 150 chosen so ion-trap sets (about 193 confident PSMs in the sample) still calibrate (code comment); the others: no recorded evidence | | Tightened precursor window | floor 2 ppm, margin 0.5 ppm, 3 sigma, MAD scale 1.4826 | `precursor_cal.rs:92-95` | post-calibration tolerance | no | No recorded evidence (1.4826 is the Gaussian MAD factor) | | Calibration q cutoff | 0.01 | `search/src/mass_calibrator.rs:360` | PSMs trusted for the precursor residual | no | Standard 1% target-decoy cutoff | | Residual rejection | 50 ppm | `mass_calibrator.rs:30` | residuals dropped as isotope contamination | no | No recorded evidence | -| Fragment-index candidates | top 100 by votes, at least 3 matched b/y | `search_params.rs:24,28` | peptidoforms scored per spectrum | `--fragment-index` (advanced) only chooses the mode | 50-1000 within seed noise on phospho (code comment); +22.2% PSMs over window enumeration on Astral at 1.00% true FDP ([§1](#calibration)) | +| Fragment-index candidates | top 100 by votes, at least 3 matched b/y | `search_params.rs:24,28` | peptidoforms scored per spectrum | `--fragment-index` (advanced) only chooses the mode | 50-1000 within seed noise on phospho (code comment); +22.2% PSMs over window enumeration on Astral at 1.00% true FDP ([§1](#calibration-and-runtime)) | | Low-res voting peaks | 150 most intense | `search_params.rs:34` | peaks that vote at a low-resolution fragment tolerance | no | TMT low-res: all peaks 4,368 PSMs at 1%; 50/100/150 peaks 12,285/12,276/12,347 (code comment) | | Index slice width | 80 Da | `search/src/match_engine.rs:1464` | precursor-mass span of an out-of-core chunk | no | Changes which candidates share a vote table; no recorded evidence beyond the pinned value | | Strong-score retention | 25 | `search_params.rs:20` | candidates the strong re-rank can promote (strong mode only) | no | Code comment: larger pool recovers top-1 flips; no recorded measurement | diff --git a/config.example.yaml b/config.example.yaml index 36a8aa76..af298a7c 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -2,33 +2,33 @@ # # Every key is optional; a key left out keeps its default. A flag on the command line wins over # this file (command line > config > default). Unknown keys are an error. -# Values are written as on the command line ("20ppm", "2..5", auto). The values below are the -# defaults, except the example paths; a commented key without a default shows an example value. +# Values are written as on the command line ("20ppm", "2..5", auto). Every key below is commented +# out and shows its default, or an example value marked "(example)" when it has none; uncomment a +# key to set it. Only the example input and output paths are uncommented. # Each comment names the key's flag; "advanced" flags are listed by `andes --help` only, # "internal" ones by neither help. DOCS.md §1b describes the file. # ── Input and output ──────────────────────────────────────────────────────── io: - # sdrf: design.sdrf.tsv # --sdrf: SDRF-Proteomics settings, below the CLI and this file (example) - spectrum: [sample.mzML] # --spectrum: mzML, MGF, .raw or .d files (example) - database: human.fasta # --database: FASTA or UniProt XML, may be gzipped (example) - output_pin: out.pin # --output-pin: Percolator PIN, required without rescoring (example) - # output_tsv: out.tsv # --output-tsv: tab-separated PSM report (example) - # output_parquet: out.idparquet # --output-parquet: QPX bundle directory (example) - # temp_dir: tmp # --temp-dir (advanced): temporary files; unset: the output directory - # uniprot_variants: false # --uniprot-variants (advanced): search UniProt natural variants - # uniprot_isoforms: false # --uniprot-isoforms (advanced): search UniProt isoforms - # uniprot_chains: false # --uniprot-chains (advanced): search UniProt mature chains - # uniprot_evidence: experimental # --uniprot-evidence (advanced): experimental | curated | any - # annotations: [db.annotations.parquet] # --annotations (advanced): annotation files (example) - # knockoffs: 4 # --knockoffs (advanced): knockoff entries per variant, 0 = none + # uniprot_variants: false # --uniprot-variants (advanced): UniProt XML: also search each natural sequence variant as its own entry + # uniprot_isoforms: false # --uniprot-isoforms (advanced): UniProt XML: also search each described isoform as its own entry + # uniprot_chains: false # --uniprot-chains (advanced): UniProt XML: also search each mature chain or peptide whose ends differ from the precursor's + # uniprot_evidence: experimental # --uniprot-evidence (advanced): UniProt XML: least evidence of a variant, annotated site or chain that is used; experimental | curated | any + # annotations: [db.annotations.parquet] # --annotations (advanced): Annotation file (.annotations.parquet) of variants, sites and chains; repeatable (example) + # knockoffs: 4 # --knockoffs (advanced): Knockoff entries per single-residue variant, which estimate the variant FDR (0: none) + # sdrf: design.sdrf.tsv # --sdrf: SDRF-Proteomics file: data files, protease, modifications, tolerance and labels (example) + spectrum: [sample.mzML] # --spectrum: Spectrum file: mzML, MGF, Thermo .raw or Bruker .d; repeat for several runs (example) + database: human.fasta # --database: Protein database: FASTA, or UniProt XML (.xml); either may be gzipped (example) + output_pin: out.pin # --output-pin: Percolator PIN output (required unless --rescore is given) (example) + # output_tsv: out.tsv # --output-tsv: Tab-separated PSM report (example) + # output_parquet: out.idparquet # --output-parquet: QPX .idparquet bundle directory (quantms-compatible) (example) + # temp_dir: tmp # --temp-dir (advanced): Directory of the run's temporary files [default: the directory of the outputs] (example) # ── Search ────────────────────────────────────────────────────────────────── search: - precursor_tol: 20ppm # --precursor-tol: in ppm or Da (0.02da) - enzyme: trypsin # --enzyme: trypsin | chymotrypsin | lysc | aspn | gluc | lysn | argc | alphalp | nocleavage | nonspecific, or a list (gluc,trypsin) - # fixed_mods: ["Carbamidomethyl (C)"] # --fixed-mods: Name (sites) items, DOCS.md §2; unset: this list - # variable_mods: ["Oxidation (M)", "Acetyl (Protein N-term)"] # --variable-mods: as fixed_mods, [] = none; unset: this list + # enzyme: trypsin # --enzyme: Protease; a comma list (gluc,trypsin) cleaves at the sites of each one; trypsin | chymotrypsin | lysc | aspn | gluc | lysn | argc | alphalp | nocleavage | nonspecific + # fixed_mods: ["Carbamidomethyl (C)"] # --fixed-mods: Fixed modifications, a list of Name (sites) [default: Carbamidomethyl (C)] + # variable_mods: ["Oxidation (M)"] # --variable-mods: Variable modifications, a list of Name (sites) [default: Oxidation (M), Acetyl (Protein N-term)] (example) # A list item is the command-line string or a map that adds the config-only settings (example): # variable_mods: # - Oxidation (M) @@ -36,7 +36,25 @@ search: # - {name: GlyGly, sites: K, cleavage: blocked, diagnostic_ions: [215.1502, 198.1237]} # - {name: Phospho, sites: Y, restrict_to: annotated} # only at sites a UniProt XML database annotates # - {name: MyTag, mass: 123.4567, sites: N-term} # a custom mass, no UNIMOD lookup - # xl: DSSO (K, Protein N-term) # --xl (experimental crosslink search): reagent name, XLMOD accession or UNIMOD Xlink record, then sites + # precursor_tol: 20ppm # --precursor-tol: Precursor mass tolerance in ppm or Da, e.g. 20ppm or 0.02da + # charge: 2..5 # --charge (advanced): Precursor charges tried when the spectrum records none, as MIN..MAX (or MIN-MAX) + # isotope_error: 0..1 # --isotope-error (advanced): Isotope-error offsets tried, as MIN..MAX (or MIN-MAX) [default: -1..2, 0..2 with --glyco or --xl] (example) + # open_search: false # --open-search (advanced): Open (mass-offset) search: any peptide within --open-search-delta of the precursor + # open_search_delta: "-100..300" # --open-search-delta (advanced): Mass-offset window for --open-search, as MIN..MAX in Da [default: -100..300] + # open_search_top_k: 100 # --open-search-top-k (advanced): Candidates scored per spectrum under --open-search [default: 100] + # optimize: false # --optimize (advanced): Parameter search: grid precursor tolerance, top-N and charge on a sample, then run + # max_missed_cleavages: 2 # --max-missed-cleavages (advanced): Missed cleavages per peptide (not applied to a non-specific digest) + # enzyme_specificity: fully # --enzyme-specificity (advanced): Peptide ends that must be cleavage sites; non-specific | semi | fully + # min_length: 6 # --min-length (advanced): Shortest peptide, in residues + # max_length: 50 # --max-length (advanced): Longest peptide, in residues + # max_mods: 3 # --max-mods (advanced): Variable modifications per peptide + # min_peaks: 10 # --min-peaks (advanced): Fewest peaks of a scored MS2 spectrum; spectra with fewer are skipped + # top_n: 10 # --top-n (advanced): PSMs kept per spectrum + # dia: false # --dia: Data-independent acquisition: search every MS2 scan across its isolation window + # dia_mobility_slices: 1 # --dia-mobility-slices (advanced): diaPASEF (.d) only: split each isolation window's mobility range into N slices + # dia_ms1_tol_ppm: 5 # --dia-ms1-tol-ppm (advanced): --dia MS1 gate: ppm tolerance for a candidate's monoisotopic peak in the survey scans + # localize: ipf # --localize (advanced): Site localization of variable modifications (`ipf`); needs --rescore; ipf (example) + # xl: "DSSO (K, Protein N-term)" # --xl (advanced): Crosslink search into .xl.tsv, linker as Name (sites), e.g. "DSSO"; several as "DSSO; DSBU" (experimental) (example) # A reagent the table (resources/crosslinkers.yaml) lacks is an entry of that file's schema (example): # xl: # name: MyLinker @@ -45,119 +63,107 @@ search: # stubs: [{name: alkene, mass: 54.010565}, {name: thiol, mass: 85.982635}] # MS-cleavage stubs # doublets: [[alkene, thiol]] # reporter doublets, [light, heavy] stub names # monolinks: [{name: water, mass: 176.01433}] - charge: "2..5" # --charge (advanced): charges tried when the spectrum has none - enzyme_specificity: fully # --enzyme-specificity (advanced): fully | semi | non-specific - min_length: 6 # --min-length (advanced): shortest peptide - max_length: 50 # --max-length (advanced): longest peptide - # max_missed_cleavages: 2 # --max-missed-cleavages (advanced); setting it keeps --glyco from raising it to 3 - # isotope_error: "-1..2" # --isotope-error (advanced); unset: -1..2, or 0..2 with glyco; setting it keeps it under glyco - # max_mods: 3 # --max-mods (advanced): variable modifications per peptide - # min_peaks: 10 # --min-peaks (advanced): fewest peaks of a scored spectrum - # top_n: 10 # --top-n (advanced): PSMs kept per spectrum - # fragment_index: auto # --fragment-index (advanced): auto | on | off - # fragment_index_slice_da: 80 # --fragment-index-slice-da (advanced): index slice width in Da; unset: from memory (example) - # index_cache_dir: cache # --index-cache-dir (advanced): candidate-index cache; unset: the output directory + # xl_linear_only: false # --xl-linear-only (advanced): With --xl: search only linear and monolinked peptides and write their protein groups + # fragment_index: auto # --fragment-index (advanced): Candidate retrieval; auto | on | off + # fragment_index_slice_da: 80 # --fragment-index-slice-da (advanced): Precursor-mass width of one fragment-index slice, in Da [default: from the memory budget] (example) + # index_cache_dir: cache # --index-cache-dir (advanced): Directory of the candidate-index cache [default: the directory of the outputs] (example) # ── Calibration, model and runtime ────────────────────────────────────────── scoring: - score: auto # --score (advanced): auto | rank | strong - precursor_cal: "off" # --precursor-cal (advanced): off | auto | on - # threads: 16 # --threads: worker threads; unset: the number of logical CPUs (example) - # fragmentation: auto # --fragmentation (advanced): MGF only; auto | CID | ETD | HCD | UVPD - # protocol: auto # --protocol (advanced): auto | phospho | iTRAQ | iTRAQ-phospho | TMT | standard - # fragment_tol_ppm: 20 # --fragment-tol-ppm (advanced): PIN feature tolerance; not with fragment_tol_da (example) - # fragment_tol_da: 0.5 # --fragment-tol-da (advanced): PIN feature tolerance; not with fragment_tol_ppm (example) - # peak_filter: "100:20" # --peak-filter (advanced): WINDOW_DA:PEAKS; unset: 100:20 for isobaric data, else off - # ethcd_activation: ethcd # --ethcd-activation (advanced): ethcd | etd - # ms_level: 2 # --ms-level (advanced): MS level searched in mzML - # model_store: models.parquet # --model-store (advanced): model store instead of the bundled one (example) - # model: hcd_qexactive_tryp # --model (advanced): model id, skips the selection (example) - # gbdt_max_trees: 100 # --gbdt-max-trees (advanced): trees per ensemble, 0 = all; unset: 100, all with glyco - # precursor_mono: auto # --precursor-mono (advanced): auto | off; glyco only - # max_spectra: 0 # --max-spectra (internal): first N spectra only, 0 = all + # threads: 8 # --threads: Worker threads [default: the number of logical CPUs] (example) + # precursor_cal: "off" # --precursor-cal (advanced): Precursor mass calibration pre-pass; off | auto | on + # score: auto # --score (advanced): What ranks the candidates and fills the PIN RawScore; auto | rank | strong + # fragmentation: auto # --fragmentation (advanced): Fragmentation of MGF spectra (mzML, .raw and .d record it); auto | CID | ETD | HCD | UVPD + # protocol: auto # --protocol (advanced): Labelling or enrichment protocol, which selects the protocol model; auto | phospho | iTRAQ | iTRAQ-phospho | TMT | standard + # fragment_tol_ppm: 20 # --fragment-tol-ppm (advanced): Fragment tolerance in ppm of the PIN features, replacing the per-run measurement (example) + # fragment_tol_da: 0.5 # --fragment-tol-da (advanced): Fragment tolerance in Da of the PIN features, replacing the per-run measurement (example) + # peak_filter: "100:20" # --peak-filter (advanced): Peak filter WINDOW_DA:PEAKS, e.g. 100:20 [default: 100:20 for isobaric data, else off] (example) + # ethcd_activation: ethcd # --ethcd-activation (advanced): How EThcD and ETciD spectra are labelled; ethcd | etd + # ms_level: 2 # --ms-level (advanced): MS level searched in mzML (MGF, .raw, .d and --chimeric search MS2) + # model_store: models.parquet # --model-store (advanced): Parquet model store (a file or a partitioned directory) instead of the bundled one (example) + # model: hcd_qexactive_tryp # --model (advanced): Model id to load from the model store, skipping the automatic selection (example) + # gbdt_max_trees: 100 # --gbdt-max-trees (advanced): Trees evaluated per GBDT ensemble, 0 for all [default: 100; all with --glyco] (example) + # precursor_mono: auto # --precursor-mono (advanced): Correct each precursor to the monoisotopic peak of its MS1 envelope (--glyco); off | auto # ── Decoys ────────────────────────────────────────────────────────────────── decoys: - strategy: shuffle # --decoy-strategy: shuffle | reverse | sequon | none - prefix: XXX_ # --decoy-prefix (advanced): accession prefix of decoys - # suffix: rev # --decoy-suffix (advanced): accession suffix of a database's own decoys (example) - # seed: ... # --decoy-seed (internal): seed of the decoy shuffles + # prefix: XXX_ # --decoy-prefix (advanced): Accession prefix that marks a decoy, given to the generated decoys + # suffix: rev # --decoy-suffix (advanced): Accession suffix that also marks a decoy (e.g. rev for _rev decoys) (example) + # strategy: shuffle # --decoy-strategy: How decoys are generated; shuffle | reverse | sequon | mutate | none # ── Modes ─────────────────────────────────────────────────────────────────── chimeric: - enabled: false # --chimeric: also search co-isolated peptides - # max_coisolated: 4 # --chimeric-max-coisolated (advanced): co-isolated peptides per scan - # max_kl: 0.3 # --chimeric-max-kl (advanced): envelope KL bound of a co-isolated precursor + # enabled: false # --chimeric: Also search co-isolated peptides: a second PSM per scan from its MS1 isolation window + # max_coisolated: 4 # --chimeric-max-coisolated (advanced): Most co-isolated peptides searched per scan with --chimeric + # max_kl: 0.3 # --chimeric-max-kl (advanced): Largest averagine-envelope KL divergence of an accepted co-isolated precursor (--chimeric) refine: - enabled: false # --refine: second pass for further modifications - # config: refine_tiers.yaml # --refine-config (advanced): YAML modification tier of --refine; unset: built-in tier (example) + # enabled: false # --refine: Second pass for further modifications (oxidation, deamidation, ...) over the confident proteins + # config: refine_tiers.yaml # --refine-config (advanced): YAML file of the --refine modification tier [default: the built-in tier] (example) # ── Rescoring and FDR ─────────────────────────────────────────────────────── rescoring: - enabled: false # --rescore: rescore the PIN with the native Percolator engine - # psm_fdr: 0.01 # --psm-fdr: PSM q-value threshold - # protein_fdr: 0.01 # --protein-fdr: protein-group q-value threshold; unset: none (example) - # proteoform_fdr: 0.05 # --proteoform-fdr (advanced): unset: the larger of psm_fdr and 0.05 - # memory_gb: 16 # --rescore-memory-gb (advanced): fixed native engine storage budget (default: what the PIN needs, at most 16 GB and the free memory), not a memory cap: features, texts and training rows spill to --temp-dir within it; per-PSM metadata (~160 B a PSM) stays in memory - # pep: 0.05 # --pep (advanced): PEP threshold with psm_fdr; unset: none (example) - # percolator_bin: percolator # --percolator-bin (advanced): external Percolator instead of the native engine; with --xl unset: percolator on PATH, else Docker (example) - # percolator_docker: false # --percolator-docker (advanced): external Percolator from its Docker image instead of the native engine - # percolator_image: ... # --percolator-image (advanced): Docker image; unset: the pinned image - # percolator_args: "" # --percolator-args (advanced): extra arguments of an external Percolator - # keep_pin: true # --keep-pin (advanced): keep the PIN after rescoring - # predict: [rt] # --predict (advanced): rt | ms2 | peptdeep-ms2 | peptdeep-rt | deeplc-rt | none - # predictor_models: models/ # --predictor-models (advanced): AlphaPeptDeep / DeepLC ONNX models (example) - # predictor_backend: tract # --predictor-backend (advanced): tract | ort - # predictor_nce: 28 # --predictor-nce (advanced): unset: 28 on Q Exactive, else 30 (example) - # predictor_instrument: QE # --predictor-instrument (advanced): unset: from the instrument (example) - # predictor_batch: 256 # --predictor-batch (advanced): peptides per batch + # psm_fdr: 0.01 # --psm-fdr: PSM-level FDR: the q-value threshold of the reported PSMs [default: 0.01] + # protein_fdr: 0.01 # --protein-fdr: Protein-group q-value threshold of the filtered output [default: none] (example) + # enabled: false # --rescore: Rescore the PIN with Percolator and write q-values, PEPs and the PSMs at --psm-fdr + # pep: 0.05 # --pep (advanced): PEP threshold applied with --psm-fdr: a PSM must pass both [default: none] (example) + # percolator_bin: percolator # --percolator-bin (advanced): Run --rescore with this external Percolator binary instead of the native engine (example) + # percolator_docker: false # --percolator-docker (advanced): Run --rescore with Percolator from its Docker image instead of the native engine + # percolator_image: "quay.io/biocontainers/percolator:3.7.1--h3b5f4bd_2" # --percolator-image (advanced): Docker image of Percolator, with --percolator-docker or --xl + # percolator_args: "--testFDR 0.05" # --percolator-args (advanced): Extra arguments for an external Percolator, e.g. "--testFDR 0.05" (example) + # keep_pin: true # --keep-pin (advanced): Keep the PIN after rescoring; true | false + # predict: [rt] # --predict (advanced): Predicted features added to the PIN, comma-separated; rt | ms2 | peptdeep-ms2 | peptdeep-rt | deeplc-rt | none + # predictor_models: models/ # --predictor-models (advanced): Directory of the exported AlphaPeptDeep and DeepLC models (example) + # predictor_backend: tract # --predictor-backend (advanced): ONNX engine of the AlphaPeptDeep and DeepLC models; tract | ort + # predictor_nce: 28 # --predictor-nce (advanced): Collision energy given to the MS2 model [default: 28 on Q Exactive, else 30] (example) + # predictor_instrument: QE # --predictor-instrument (advanced): Instrument given to the MS2 model, e.g. QE, Lumos, timsTOF [default: from the instrument] (example) + # predictor_batch: 256 # --predictor-batch (advanced): Peptides per predictor batch + # proteoform_fdr: 0.05 # --proteoform-fdr (advanced): q-value threshold of proteoform claims [default: the larger of --psm-fdr and 0.05] (example) # ── Glycopeptides ─────────────────────────────────────────────────────────── glyco: - enabled: false # --glyco: intact glycopeptide search; needs species, glycan_gdb or glycan_wurcs - # species: human # --glyco-species: human | mouse | mouse-large | high-mannose (example) - # glycan_gdb: glycans.gdb # --glyco-glycan-gdb (advanced): external .gdb database (example) - # glycan_wurcs: glycans.csv # --glyco-glycan-wurcs (advanced): WURCS 2.0 CSV database (example) - # core: n # --glyco-core (advanced): n | o - # tol_ppm: 20 # --glyco-tol-ppm (advanced): glyco fragment tolerance; 500 on ion-trap MS2 when unset - # min_core_y: 0 # --glyco-min-core-y (advanced): core Y ions of a reported PSM, 0 = off - # hcd_pair: true # --glyco-hcd-pair (advanced): backbones from the paired HCD scan on ETD - # max_peaks: 0 # --glyco-max-peaks (advanced): peaks for candidate generation, 0 = all - # cz_max_charge: 1 # --glyco-cz-max-charge (advanced): unset: from deconvolution (example) - # y_max_charge: 3 # --glyco-y-max-charge (advanced): largest glycan Y fragment charge - # retrieval_tol_ppm: 20 # --glyco-retrieval-tol-ppm (advanced): unset: tol_ppm on high-res (example) - # peptide_first: false # --glyco-peptide-first (advanced): peptide-first retrieval - # index_sequon_only: false # --glyco-index-sequon-only (advanced): index only N-X-S/T peptides - # debug: false # --debug-glyco (internal): every candidate row; not for FDR + # enabled: false # --glyco: Intact glycopeptide search into a .glyco.pin (needs a glycan database, e.g. --glyco-species) + # species: human # --glyco-species: Bundled N-glycan database of --glyco; human | mouse | mouse-large | high-mannose (example) + # glycan_gdb: glycans.gdb # --glyco-glycan-gdb (advanced): External .gdb glycan database of --glyco (instead of --glyco-species) (example) + # glycan_wurcs: glycans.csv # --glyco-glycan-wurcs (advanced): WURCS 2.0 glycan database CSV of --glyco (instead of --glyco-species) (example) + # core: "n" # --glyco-core (advanced): Glycan core of --glyco; n | o + # tol_ppm: 20 # --glyco-tol-ppm (advanced): Fragment tolerance in ppm of the glyco matching: oxonium ions, core Y ions, backbone, c/z + # min_core_y: 0 # --glyco-min-core-y (advanced): Fewest trimannosyl-core Y ions of a reported --glyco PSM (0: off) + # hcd_pair: true # --glyco-hcd-pair (advanced): On ETD scans, take the candidate backbones from the paired HCD scan of the same precursor; true | false + # max_peaks: 0 # --glyco-max-peaks (advanced): Most intense peaks considered when generating --glyco candidates (0: all) + # cz_max_charge: 1 # --glyco-cz-max-charge (advanced): Largest c/z fragment charge of --glyco ETD scoring [default: from whether the spectrum is deconvoluted] (example) + # y_max_charge: 3 # --glyco-y-max-charge (advanced): Largest glycan Y fragment charge of --glyco + # retrieval_tol_ppm: 20 # --glyco-retrieval-tol-ppm (advanced): Candidate retrieval tolerance in ppm of --glyco [default: --glyco-tol-ppm on high-res MS2, 0.5 Da on low-res] (example) + # peptide_first: false # --glyco-peptide-first (advanced): Peptide-first b/y fragment-index retrieval instead of the glycan-mass branch (slower) + # index_sequon_only: false # --glyco-index-sequon-only (advanced): Index only N-X-S/T peptides for --glyco, a much smaller index # ── Quantification ────────────────────────────────────────────────────────── quant: - # tmt: tmt10 # --tmt: tmt6 | tmt10 | tmt11 | tmt16 | tmt18 | tmt32 | tmt35 | itraq4 | itraq8 (example) - # lfq: false # --lfq: label-free MS1 quantification - # label: silac2 # --label: silac2 | silac3 | dimethyl2 | dimethyl3 or channels like [][Lys8,Arg10] (example) - # mbr: false # --mbr: match between runs (needs rescoring and lfq, tmt or label) - # dir: quant_out # --quant-dir: per-run tables of multi-run quantification (example) - # quant_fdr: 0.01 # --quant-fdr: transfer and channel q-value threshold; unset: 0.01, 0.05 for label, lfq accepted and glyco - # mbr_donor_fdr: 0.01 # --mbr-donor-fdr (advanced): unset: inherits psm_fdr - # quant_transfer_fdr: 0.01 # --quant-transfer-fdr (advanced): unset: inherits quant_fdr - # quant_channel_fdr: 0.05 # --quant-channel-fdr (advanced): unset: inherits quant_fdr - # tmt_level: 2 # --tmt-level (advanced): 2 | 3; unset: 3 for SPS-MS3 data, else 2 - # tmt_tol: 20ppm # --tmt-tol (advanced): unset: 20ppm (10ppm tmt32/tmt35), 0.3da on ion-trap MS2 - # tmt_correction: lot.txt # --tmt-correction (advanced): kit impurity matrix; unset: none (example) - # tmt_min_purity: 0.7 # --tmt-min-purity (advanced): gate on precursor purity, 0 = off - # tmt_min_sn: 0 # --tmt-min-sn (advanced): gate on reporter signal-to-noise, 0 = off - # tmt_unmix: auto # --tmt-unmix (advanced): auto | off | on - # mbr_wrong_log2: 0.5 # --mbr-wrong-log2 (advanced): tmt mbr: profile deviation that counts as wrong - # lfq_tol: 10ppm # --lfq-tol (advanced): MS1 tolerance of the isotope chromatograms - # lfq_rt_window: 60 # --lfq-rt-window (advanced): seconds around the PSM; unset: 60, 120 with glyco - # lfq_gaussian_width: 12 # --lfq-gaussian-width (advanced): experimental; unset: Savitzky-Golay (example) - # lfq_min_cosine: 0.7 # --lfq-min-cosine (advanced): envelope cosine of an accepted feature - # label_reference: 1 # --label-reference (advanced): reference channel, 1-based - # label_arg_pro: false # --label-arg-pro (advanced): SILAC arginine-to-proline conversion - # label_2h_enrichment_silac: 0.96 # --label-2h-enrichment-silac (advanced) - # label_2h_enrichment_chemical: 0.99 # --label-2h-enrichment-chemical (advanced) - # label_heavy_enrichment: 0.99 # --label-heavy-enrichment (advanced) + # quant_fdr: 0.01 # --quant-fdr: Quantification FDR: q-value threshold of values measured without an identification [default: 0.01] + # tmt: tmt10 # --tmt: Isobaric reporter-ion quantification with this labelling kit; tmt6 | tmt10 | tmt11 | tmt16 | tmt18 | tmt32 | tmt35 | itraq4 | itraq8 (example) + # lfq: false # --lfq: Label-free MS1 quantification of the identified precursors + # label: silac2 # --label: MS1 labelled-pair quantification (SILAC, dimethyl): a preset or one bracket per channel (example) + # mbr: false # --mbr: Match between runs across two or more inputs (needs --rescore, and --lfq, --tmt or --label) + # dir: quant_out # --quant-dir: Directory of the per-run tables of multi-run quantification (example) + # tmt_level: 3 # --tmt-level (advanced): MS level of the reporter ions: 2 (the identified MS2) or 3 (its SPS-MS3 scan) [default: 3 for SPS-MS3 data, else 2] (example) + # tmt_tol: 20ppm # --tmt-tol (advanced): Reporter-ion m/z tolerance, e.g. 20ppm or 0.003da [default: 20ppm (10ppm for tmt32/tmt35), 0.3da on ion-trap MS2] (example) + # tmt_correction: lot.txt # --tmt-correction (advanced): Isotope impurity matrix of the kit lot, in quantms text form [default: no correction] (example) + # tmt_min_purity: 0.7 # --tmt-min-purity (advanced): Quantification gate: least precursor isolation purity (0: off) + # tmt_min_sn: 0 # --tmt-min-sn (advanced): Quantification gate: least summed reporter signal-to-noise (0: off) + # tmt_unmix: auto # --tmt-unmix (advanced): Remove the co-isolation interference of high-resolution MS2 reporters; auto | off | on + # mbr_wrong_log2: 0.5 # --mbr-wrong-log2 (advanced): With --tmt --mbr: RMS log2 deviation from its reference scan above which a transferred profile counts as wrong + # lfq_tol: 10ppm # --lfq-tol (advanced): MS1 m/z tolerance of the isotope chromatograms, e.g. 10ppm [default: 10ppm] + # lfq_rt_window: 60 # --lfq-rt-window (advanced): Retention-time half-window around the identifying PSM, in seconds [default: 60; 120 with --glyco] (example) + # lfq_gaussian_width: 12 # --lfq-gaussian-width (advanced): Experimental: Gaussian peak width for peak detection, in seconds (eight sigma) [default: Savitzky-Golay smoothing] (example) + # lfq_min_cosine: 0.7 # --lfq-min-cosine (advanced): Least isotope-envelope cosine of a feature marked accepted in lfq.parquet + # label_reference: 1 # --label-reference (advanced): Reference channel of the --label ratios, 1-based + # label_arg_pro: false # --label-arg-pro (advanced): SILAC: fit the heavy proline made from heavy arginine and add it back to its channel + # label_2h_enrichment_silac: 0.96 # --label-2h-enrichment-silac (advanced): 2H enrichment of metabolic deuterium labels (Lys4, Leu3) + # label_2h_enrichment_chemical: 0.99 # --label-2h-enrichment-chemical (advanced): 2H enrichment of chemical deuterium labels (dimethyl) + # label_heavy_enrichment: 0.99 # --label-heavy-enrichment (advanced): 13C and 15N enrichment of heavy labels, per atom + # mbr_donor_fdr: 0.01 # --mbr-donor-fdr (advanced): Precursor q-value threshold of a match-between-runs library donor [default: inherits --psm-fdr] (example) + # quant_transfer_fdr: 0.01 # --quant-transfer-fdr (advanced): q-value threshold of a reported transfer [default: inherits --quant-fdr] (example) + # quant_channel_fdr: 0.05 # --quant-channel-fdr (advanced): --label: q-value threshold of a channel matched without an identification [default: inherits --quant-fdr] (example) # Read by `andes cohort plan` and `andes cohort run`; a search ignores this section. The sections above are the # settings every run of the cohort shares; each run's own settings come from its SDRF row. diff --git a/crates/andes/src/bin/andes.rs b/crates/andes/src/bin/andes.rs index a52ebedf..98f427e7 100644 --- a/crates/andes/src/bin/andes.rs +++ b/crates/andes/src/bin/andes.rs @@ -6,12 +6,16 @@ use clap::{Parser, Subcommand}; mod acquisition; #[path = "andes/cli.rs"] mod cli; +#[path = "andes/cli_parse.rs"] +mod cli_parse; #[path = "../cohort.rs"] mod cohort; #[path = "andes/cohort_cmd.rs"] mod cohort_cmd; #[path = "../config.rs"] mod config; +#[path = "../config_mods.rs"] +mod config_mods; #[path = "andes/database_cmd.rs"] mod database_cmd; #[path = "andes/dia.rs"] @@ -58,6 +62,12 @@ mod quant_run; mod sdrf; #[path = "andes/optimize.rs"] mod optimize; +#[path = "../param_sources.rs"] +mod param_sources; +#[path = "../params.rs"] +mod params; +#[path = "../params_render.rs"] +mod params_render; #[path = "andes/search.rs"] mod search; #[path = "andes/spectra.rs"] @@ -256,12 +266,11 @@ fn main() -> ExitCode { Some(Command::Cohort(cmd)) => cohort_cmd::run(cmd), None => { let mut cfg_missed_cleavages = false; - let mut cfg_keys = sdrf::ConfigKeys::default(); + let mut sources = param_sources::from_command_line(&matches); if let Some(cfg_path) = top.search.config.clone() { if let Err(e) = config::RunConfig::load(&cfg_path).and_then(|c| { cfg_missed_cleavages = c.search.max_missed_cleavages.is_some(); - cfg_keys = sdrf::ConfigKeys::of(&c); - config::apply(c, &mut top.search, &matches) + config::apply(c, &mut top.search, &matches, &mut sources) }) { log::error!("{e}"); return ExitCode::from(2); @@ -269,7 +278,7 @@ fn main() -> ExitCode { } if let Some(sdrf_path) = top.search.sdrf.clone() { match sdrf::read(&sdrf_path) - .and_then(|s| sdrf::apply(&s, &mut top.search, &matches, cfg_keys)) + .and_then(|s| sdrf::apply(&s, &mut top.search, &matches, &mut sources)) { Ok(lines) => lines.iter().for_each(|l| match l.strip_prefix("WARN: ") { Some(w) => log::warn!(target: "sdrf", "{w}"), @@ -285,6 +294,9 @@ fn main() -> ExitCode { log::error!("{e}"); return ExitCode::from(2); } + if let Some(dest) = top.search.print_config.as_deref() { + return print_config(dest, &sources); + } let _ = EXPLICIT_MISSED_CLEAVAGES.set(missed_cleavages_explicit( matches.value_source("max_missed_cleavages"), cfg_missed_cleavages, @@ -326,6 +338,37 @@ fn main() -> ExitCode { } } +fn print_config(dest: &std::path::Path, sources: ¶m_sources::ParamSources) -> ExitCode { + let text = match params_render::effective_config(sources) { + Ok(text) => text, + Err(e) => { + log::error!("{e}"); + return ExitCode::from(2); + } + }; + let cli_only = params_render::command_line_only(sources); + if !cli_only.is_empty() { + log::warn!( + "--print-config: {} has no config key; the printed config lists it as a comment, \ + pass it again on the command line to reproduce the run", + cli_only.join(" ") + ); + } + let written = if dest == std::path::Path::new("-") { + use std::io::Write; + std::io::stdout().write_all(text.as_bytes()) + } else { + std::fs::write(dest, &text) + }; + match written { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + log::error!("cannot write the config to {}: {e}", dest.display()); + ExitCode::from(1) + } + } +} + fn run_rescore(args: cli::RescoreArgs) -> Result<(), Box> { cli::ensure_scratch_dir(&args.temp_dir)?; let limit = memlimit::rescore_memory(args.rescore_memory_gb, args.temp_dir); @@ -387,3 +430,15 @@ mod missed_cleavages_explicit_tests { assert!(!missed_cleavages_explicit(None, false)); } } + +#[cfg(test)] +#[path = "../tests/params_table.rs"] +mod params_table; + +#[cfg(test)] +#[path = "../tests/params_sources.rs"] +mod params_sources; + +#[cfg(test)] +#[path = "../tests/params_render.rs"] +mod params_render_tests; diff --git a/crates/andes/src/bin/andes/cli.rs b/crates/andes/src/bin/andes/cli.rs index 8f47c1d8..583e8eb9 100644 --- a/crates/andes/src/bin/andes/cli.rs +++ b/crates/andes/src/bin/andes/cli.rs @@ -6,6 +6,11 @@ use model::Tolerance; use model_train::geometry::GeometryConfig; use search::decoy::DecoyStrategy; use search::PrecursorCalMode; +pub(crate) use crate::cli_parse::{ + parse_charge_range, parse_isotope_error_range, parse_non_negative, parse_non_negative_f32, + parse_open_search_delta, parse_positive_tol, parse_precursor_tol, parse_unit_fraction, + parse_xl, +}; pub(crate) const H_IO: &str = "Input and output"; pub(crate) const H_SEARCH: &str = "Search"; @@ -301,22 +306,6 @@ impl XlSet { } } -pub(crate) fn parse_xl_one(s: &str) -> Result { - xl::spec::XlDecl::parse(s) - .and_then(|d| d.resolve(model::unimod::bundled())) - .map_err(|e| e.to_string()) -} - -pub(crate) fn parse_xl(s: &str) -> Result { - let linkers = s - .split(';') - .map(str::trim) - .filter(|x| !x.is_empty()) - .map(parse_xl_one) - .collect::, _>>()?; - XlSet::new("--xl", linkers) -} - /// The protein database options shared by the search, `andes inference` and /// `andes quant finalize`: how the database is digested and expanded, and how /// a decoy is recognised. Inference and finalize take the search's values. @@ -441,6 +430,12 @@ pub(crate) struct SearchArgs { #[arg(long, value_name = "FILE", help_heading = H_IO)] pub(crate) config: Option, + /// Write the resolved settings as a config file that reproduces the run, then exit + /// + /// FILE, or `-` for stdout. Nothing is searched. Replay with --config FILE. + #[arg(long, value_name = "FILE", help_heading = H_IO, hide_short_help = true)] + pub(crate) print_config: Option, + /// SDRF-Proteomics file: data files, protease, modifications, tolerance and labels /// /// Reads `comment[data file]` (looked up next to the SDRF), the cleavage agents, the @@ -2103,163 +2098,6 @@ pub(crate) fn parse_plex(s: &str) -> Result { quant::Plex::parse(s) } -pub(crate) fn dash_sep_index(s: &str) -> Option { - let b = s.as_bytes(); - (1..b.len()).find(|&i| b[i] == b'-' && b[i - 1].is_ascii_digit()) -} - -pub(crate) fn parse_int_range(s: &str, label: &str) -> Result<(T, T), String> -where - T: std::str::FromStr + PartialOrd + std::fmt::Display + Copy, -{ - let trimmed = s.trim(); - let (lo_s, hi_s) = if let Some((a, b)) = trimmed.split_once("..") { - (a.trim(), b.trim()) - } else if let Some(idx) = dash_sep_index(trimmed) { - (trimmed[..idx].trim(), trimmed[idx + 1..].trim()) - } else { - return Err(format!( - "invalid {label} `{s}`: expected MIN..MAX (or MIN-MAX)" - )); - }; - let lo: T = lo_s - .parse() - .map_err(|_| format!("invalid {label} `{s}`: bad MIN `{lo_s}`"))?; - let hi: T = hi_s - .parse() - .map_err(|_| format!("invalid {label} `{s}`: bad MAX `{hi_s}`"))?; - if lo > hi { - return Err(format!("invalid {label} `{s}`: MIN {lo} > MAX {hi}")); - } - Ok((lo, hi)) -} - -pub(crate) const MAX_SUPPORTED_CHARGE: u8 = 50; - -pub(crate) fn parse_charge_range(s: &str) -> Result<(u8, u8), String> { - let (lo, hi) = parse_int_range::(s, "charge")?; - if lo < 1 { - return Err(format!( - "invalid charge `{s}`: minimum charge must be >= 1 (got {lo})" - )); - } - if hi > MAX_SUPPORTED_CHARGE { - return Err(format!( - "invalid charge `{s}`: maximum charge {hi} exceeds supported bound {MAX_SUPPORTED_CHARGE}" - )); - } - Ok((lo, hi)) -} - -pub(crate) fn parse_isotope_error_range(s: &str) -> Result<(i8, i8), String> { - parse_int_range::(s, "isotope-error") -} - -pub(crate) fn parse_precursor_tol(s: &str) -> Result { - let t = s.trim(); - let lower = t.to_ascii_lowercase(); - let (num_str, is_ppm) = if let Some(n) = lower.strip_suffix("ppm") { - (n, true) - } else if let Some(n) = lower.strip_suffix("da") { - (n, false) - } else { - return Err(format!( - "invalid --precursor-tol `{s}`: expected VALUE+unit, e.g. 20ppm or 0.02da" - )); - }; - let v: f64 = num_str - .trim() - .parse() - .map_err(|_| format!("invalid --precursor-tol `{s}`: bad number `{num_str}`"))?; - if !v.is_finite() || v <= 0.0 { - return Err(format!( - "invalid --precursor-tol `{s}`: value must be finite and > 0 (got {v})" - )); - } - Ok(if is_ppm { - Tolerance::Ppm(v) - } else { - Tolerance::Da(v) - }) -} - -pub(crate) fn parse_open_search_delta(s: &str) -> Result<(f64, f64), String> { - let t = s.trim(); - let (min_s, max_s) = t.split_once("..").ok_or_else(|| { - format!("invalid --open-search-delta `{s}`: expected MIN..MAX in Da, e.g. -100..300") - })?; - let parse = |v: &str| -> Result { - v.trim() - .parse::() - .map_err(|_| format!("invalid --open-search-delta `{s}`: bad number `{}`", v.trim())) - }; - let (lo, hi) = (parse(min_s)?, parse(max_s)?); - if !lo.is_finite() || !hi.is_finite() || lo >= hi { - return Err(format!( - "invalid --open-search-delta `{s}`: need finite MIN < MAX (got {lo}..{hi})" - )); - } - if lo > 0.0 || hi < 0.0 { - return Err(format!( - "invalid --open-search-delta `{s}`: the window must contain 0 (got {lo}..{hi})" - )); - } - if hi - lo > 2000.0 { - return Err(format!( - "invalid --open-search-delta `{s}`: width {} Da exceeds the 2000 Da limit", - hi - lo - )); - } - Ok((lo, hi)) -} - -pub(crate) fn parse_unit_fraction(s: &str) -> Result { - let v: f64 = s - .trim() - .parse() - .map_err(|_| format!("invalid value `{s}`: expected a number in [0, 1]"))?; - if !v.is_finite() || !(0.0..=1.0).contains(&v) { - return Err(format!( - "invalid value `{s}`: must be finite and within [0, 1] (got {v})" - )); - } - Ok(v) -} - -pub(crate) fn parse_non_negative(s: &str) -> Result { - let v: f64 = s - .trim() - .parse() - .map_err(|_| format!("invalid value `{s}`: expected a number >= 0"))?; - if !v.is_finite() || v < 0.0 { - return Err(format!( - "invalid value `{s}`: must be finite and >= 0 (got {v})" - )); - } - Ok(v) -} - -pub(crate) fn parse_non_negative_f32(s: &str) -> Result { - let v = parse_non_negative(s)?; - if v > f32::MAX as f64 { - return Err(format!("invalid value `{s}`: out of range")); - } - Ok(v as f32) -} - -pub(crate) fn parse_positive_tol(s: &str) -> Result { - let v: f64 = s - .trim() - .parse() - .map_err(|_| format!("invalid tolerance `{s}`: expected a positive number"))?; - if !v.is_finite() || v <= 0.0 { - return Err(format!( - "invalid tolerance `{s}`: must be finite and > 0 (got {v})" - )); - } - Ok(v) -} - pub(crate) fn dir_or_output_dir(flag: Option<&Path>, output: &Path) -> PathBuf { match flag { Some(dir) => dir.to_path_buf(), diff --git a/crates/andes/src/bin/andes/cli_parse.rs b/crates/andes/src/bin/andes/cli_parse.rs new file mode 100644 index 00000000..2aca8190 --- /dev/null +++ b/crates/andes/src/bin/andes/cli_parse.rs @@ -0,0 +1,181 @@ +//! Value parsers for the search command-line arguments: numeric ranges, tolerances with units, +//! charge and isotope-error ranges, fractions and crosslinker lists. `cli.rs` declares the +//! arguments, keeps the enumerated-value parser `parse_enum`, and re-exports these parsers by +//! name; config files and `--print-config` reuse them so every path reads the same text. +use model::Tolerance; + +pub(crate) fn dash_sep_index(s: &str) -> Option { + let b = s.as_bytes(); + (1..b.len()).find(|&i| b[i] == b'-' && b[i - 1].is_ascii_digit()) +} + +pub(crate) fn parse_int_range(s: &str, label: &str) -> Result<(T, T), String> +where + T: std::str::FromStr + PartialOrd + std::fmt::Display + Copy, +{ + let trimmed = s.trim(); + let (lo_s, hi_s) = if let Some((a, b)) = trimmed.split_once("..") { + (a.trim(), b.trim()) + } else if let Some(idx) = dash_sep_index(trimmed) { + (trimmed[..idx].trim(), trimmed[idx + 1..].trim()) + } else { + return Err(format!( + "invalid {label} `{s}`: expected MIN..MAX (or MIN-MAX)" + )); + }; + let lo: T = lo_s + .parse() + .map_err(|_| format!("invalid {label} `{s}`: bad MIN `{lo_s}`"))?; + let hi: T = hi_s + .parse() + .map_err(|_| format!("invalid {label} `{s}`: bad MAX `{hi_s}`"))?; + if lo > hi { + return Err(format!("invalid {label} `{s}`: MIN {lo} > MAX {hi}")); + } + Ok((lo, hi)) +} + +pub(crate) const MAX_SUPPORTED_CHARGE: u8 = 50; + +pub(crate) fn parse_charge_range(s: &str) -> Result<(u8, u8), String> { + let (lo, hi) = parse_int_range::(s, "charge")?; + if lo < 1 { + return Err(format!( + "invalid charge `{s}`: minimum charge must be >= 1 (got {lo})" + )); + } + if hi > MAX_SUPPORTED_CHARGE { + return Err(format!( + "invalid charge `{s}`: maximum charge {hi} exceeds supported bound {MAX_SUPPORTED_CHARGE}" + )); + } + Ok((lo, hi)) +} + +pub(crate) fn parse_isotope_error_range(s: &str) -> Result<(i8, i8), String> { + parse_int_range::(s, "isotope-error") +} + +pub(crate) fn parse_precursor_tol(s: &str) -> Result { + let t = s.trim(); + let lower = t.to_ascii_lowercase(); + let (num_str, is_ppm) = if let Some(n) = lower.strip_suffix("ppm") { + (n, true) + } else if let Some(n) = lower.strip_suffix("da") { + (n, false) + } else { + return Err(format!( + "invalid --precursor-tol `{s}`: expected VALUE+unit, e.g. 20ppm or 0.02da" + )); + }; + let v: f64 = num_str + .trim() + .parse() + .map_err(|_| format!("invalid --precursor-tol `{s}`: bad number `{num_str}`"))?; + if !v.is_finite() || v <= 0.0 { + return Err(format!( + "invalid --precursor-tol `{s}`: value must be finite and > 0 (got {v})" + )); + } + Ok(if is_ppm { + Tolerance::Ppm(v) + } else { + Tolerance::Da(v) + }) +} + +pub(crate) fn parse_open_search_delta(s: &str) -> Result<(f64, f64), String> { + let t = s.trim(); + let (min_s, max_s) = t.split_once("..").ok_or_else(|| { + format!("invalid --open-search-delta `{s}`: expected MIN..MAX in Da, e.g. -100..300") + })?; + let parse = |v: &str| -> Result { + v.trim() + .parse::() + .map_err(|_| format!("invalid --open-search-delta `{s}`: bad number `{}`", v.trim())) + }; + let (lo, hi) = (parse(min_s)?, parse(max_s)?); + if !lo.is_finite() || !hi.is_finite() || lo >= hi { + return Err(format!( + "invalid --open-search-delta `{s}`: need finite MIN < MAX (got {lo}..{hi})" + )); + } + if lo > 0.0 || hi < 0.0 { + return Err(format!( + "invalid --open-search-delta `{s}`: the window must contain 0 (got {lo}..{hi})" + )); + } + if hi - lo > 2000.0 { + return Err(format!( + "invalid --open-search-delta `{s}`: width {} Da exceeds the 2000 Da limit", + hi - lo + )); + } + Ok((lo, hi)) +} + +pub(crate) fn parse_unit_fraction(s: &str) -> Result { + let v: f64 = s + .trim() + .parse() + .map_err(|_| format!("invalid value `{s}`: expected a number in [0, 1]"))?; + if !v.is_finite() || !(0.0..=1.0).contains(&v) { + return Err(format!( + "invalid value `{s}`: must be finite and within [0, 1] (got {v})" + )); + } + Ok(v) +} + +pub(crate) fn parse_non_negative(s: &str) -> Result { + let v: f64 = s + .trim() + .parse() + .map_err(|_| format!("invalid value `{s}`: expected a number >= 0"))?; + if !v.is_finite() || v < 0.0 { + return Err(format!( + "invalid value `{s}`: must be finite and >= 0 (got {v})" + )); + } + Ok(v) +} + +pub(crate) fn parse_non_negative_f32(s: &str) -> Result { + let v = parse_non_negative(s)?; + if v > f32::MAX as f64 { + return Err(format!("invalid value `{s}`: out of range")); + } + Ok(v as f32) +} + +pub(crate) fn parse_positive_tol(s: &str) -> Result { + let v: f64 = s + .trim() + .parse() + .map_err(|_| format!("invalid tolerance `{s}`: expected a positive number"))?; + if !v.is_finite() || v <= 0.0 { + return Err(format!( + "invalid tolerance `{s}`: must be finite and > 0 (got {v})" + )); + } + Ok(v) +} + +/// The crosslinker items of an `--xl` value: split at `;`, trimmed, empty items dropped. +pub(crate) fn split_xl(s: &str) -> Vec<&str> { + s.split(';').map(str::trim).filter(|x| !x.is_empty()).collect() +} + +pub(crate) fn parse_xl_one(s: &str) -> Result { + xl::spec::XlDecl::parse(s) + .and_then(|d| d.resolve(model::unimod::bundled())) + .map_err(|e| e.to_string()) +} + +pub(crate) fn parse_xl(s: &str) -> Result { + let linkers = split_xl(s) + .into_iter() + .map(parse_xl_one) + .collect::, _>>()?; + crate::cli::XlSet::new("--xl", linkers) +} diff --git a/crates/andes/src/bin/andes/xl_run.rs b/crates/andes/src/bin/andes/xl_run.rs index ea94426e..e8fa3f10 100644 --- a/crates/andes/src/bin/andes/xl_run.rs +++ b/crates/andes/src/bin/andes/xl_run.rs @@ -804,7 +804,7 @@ mod tests { use super::*; fn linker(spec: &str) -> Crosslinker { - crate::cli::parse_xl_one(spec).unwrap() + crate::cli_parse::parse_xl_one(spec).unwrap() } #[test] diff --git a/crates/andes/src/config.rs b/crates/andes/src/config.rs index 5ad71ace..83321fcd 100644 --- a/crates/andes/src/config.rs +++ b/crates/andes/src/config.rs @@ -2,6 +2,7 @@ use std::path::PathBuf; use serde::Deserialize; +use crate::param_sources::ParamSources; use crate::SearchArgs; #[derive(Debug, Default, Deserialize)] @@ -19,6 +20,9 @@ pub struct RunConfig { pub quant: QuantCfg, /// Read by `andes cohort plan`; a search ignores it. pub cohort: Option, + /// The file as parsed, so a recorded setting keeps the value as written. + #[serde(skip)] + pub written: serde_yaml::Value, } #[derive(Debug, Default, Deserialize)] @@ -56,6 +60,7 @@ pub struct SearchCfg { pub fixed_mods: Option>, pub variable_mods: Option>, pub xl: Option, + pub xl_linear_only: Option, pub localize: Option, pub fragment_index: Option, pub fragment_index_slice_da: Option, @@ -192,7 +197,10 @@ pub struct GlycoCfg { impl RunConfig { pub fn from_yaml_str(s: &str) -> Result { - serde_yaml::from_str(s).map_err(|e| format!("--config parse error: {e}")) + let mut cfg: Self = + serde_yaml::from_str(s).map_err(|e| format!("--config parse error: {e}"))?; + cfg.written = serde_yaml::from_str(s).unwrap_or_default(); + Ok(cfg) } pub fn load(path: &std::path::Path) -> Result { @@ -213,11 +221,13 @@ pub fn apply_db( cfg: &RunConfig, db: &mut crate::cli::DatabaseArgs, m: &clap::ArgMatches, + src: &mut ParamSources, ) -> Result<(), String> { macro_rules! set { ($id:literal, $field:ident, $val:expr) => { if let Some(v) = &$val { if !cli_set(m, $id) { + src.record_config($id, &cfg.written); db.$field = v.clone(); } } @@ -227,6 +237,7 @@ pub fn apply_db( ($id:literal, $field:ident, $val:expr) => { if let Some(v) = &$val { if !cli_set(m, $id) { + src.record_config($id, &cfg.written); db.$field = Some(v.clone()); } } @@ -237,6 +248,7 @@ pub fn apply_db( if let Some(s) = &$val { if !cli_set(m, $id) { db.$field = ($parse)(s)?; + src.record_config($id, &cfg.written); } } }; @@ -261,11 +273,13 @@ pub fn apply_db( if let Some(items) = &cfg.search.fixed_mods { if !cli_set(m, "fixed_mods") { db.fixed_mods = Some(mod_list("search.fixed_mods", items, true)?); + src.record_config("fixed_mods", &cfg.written); } } if let Some(items) = &cfg.search.variable_mods { if !cli_set(m, "variable_mods") { db.variable_mods = Some(mod_list("search.variable_mods", items, false)?); + src.record_config("variable_mods", &cfg.written); } } set!("decoy_prefix", decoy_prefix, cfg.decoys.prefix); @@ -278,142 +292,25 @@ pub fn apply_protein_config( m: &clap::ArgMatches, ) -> Result<(), String> { if let Some(path) = p.config.clone() { - apply_db(&RunConfig::load(&path)?, &mut p.db, m)?; + let cfg = RunConfig::load(&path)?; + apply_db(&cfg, &mut p.db, m, &mut ParamSources::default())?; } Ok(()) } -pub fn mod_list( - key: &str, - items: &[serde_yaml::Value], - fixed: bool, -) -> Result { - use model::mod_spec::ModDecl; - let mut mods = Vec::new(); - for (i, item) in items.iter().enumerate() { - let at = |e: String| format!("{key}[{i}]: {e}"); - let decl = match item { - serde_yaml::Value::String(s) => ModDecl::parse(s).map_err(|e| at(e.to_string()))?, - serde_yaml::Value::Mapping(map) => mod_decl(map).map_err(at)?, - _ => { - return Err(at( - "expected `Name (sites)` or a map with `name` or `mass` and `sites`".into(), - )) - } - }; - mods.extend( - decl.resolve(fixed, model::unimod::bundled()) - .map_err(|e| at(e.to_string()))?, - ); - } - Ok(crate::cli::ModList(mods)) -} - -fn mod_decl(map: &serde_yaml::Mapping) -> Result { - use serde_yaml::Value; - let text = |key: &str, v: &Value| -> Result { - match v { - Value::String(s) => Ok(s.clone()), - _ => Err(format!("`{key}` must be a string")), - } - }; - let numbers = |key: &str, v: &Value| -> Result, String> { - let one = |v: &Value| v.as_f64().ok_or_else(|| format!("`{key}` takes numbers")); - match v { - Value::Sequence(seq) => seq.iter().map(one).collect(), - v => Ok(vec![one(v)?]), - } - }; - let mut d = model::mod_spec::ModDecl::default(); - let mut sites = None; - for (k, v) in map { - let key = k.as_str().ok_or("modification keys are strings")?; - match key { - "name" => d.name = Some(text(key, v)?), - "mass" => { - d.mass = Some( - v.as_f64() - .ok_or("`mass` is a number (the mass shift in Da)")?, - ) - } - "sites" => sites = Some(text(key, v)?), - "neutral_loss" => d.neutral_loss = numbers(key, v)?, - "loss_class" => d.loss_class = Some(text(key, v)?), - "restrict_to" => d.restrict_to = Some(text(key, v)?), - "cleavage" => d.cleavage = Some(text(key, v)?), - "diagnostic_ions" => d.diagnostic_ions = numbers(key, v)?, - other => { - return Err(format!( - "unknown key `{other}` (expected name, mass, sites, neutral_loss, \ - loss_class, restrict_to, cleavage, diagnostic_ions)" - )) - } - } - } - match (sites, d.name.clone(), d.mass) { - (Some(s), _, _) => d.sites = s, - (None, Some(name), None) => { - let parsed = model::mod_spec::ModDecl::parse(&name).map_err(|e| e.to_string())?; - d.name = parsed.name; - d.sites = parsed.sites; - } - (None, _, _) => return Err("`sites` is missing".into()), - } - Ok(d) -} +use crate::config_mods::{mod_list, xl_set}; -pub fn xl_linker(key: &str, v: &serde_yaml::Value) -> Result { - use serde_yaml::Value; - use xl::spec::XlDecl; - let at = |e: String| format!("{key}: {e}"); - let db = model::unimod::bundled(); - match v { - Value::String(s) => XlDecl::parse(s) - .and_then(|d| d.resolve(db)) - .map_err(|e| at(e.to_string())), - Value::Mapping(map) if map.contains_key("intact") => { - let r: model::xl_reagents::Reagent = - serde_yaml::from_value(v.clone()).map_err(|e| at(e.to_string()))?; - xl::spec::custom(&r, db).map_err(|e| at(e.to_string())) - } - Value::Mapping(map) => { - let mut name = None; - let mut sites = None; - for (k, val) in map { - let text = || { - val.as_str().map(str::to_string).ok_or_else(|| { - at(format!("`{}` must be a string", k.as_str().unwrap_or("?"))) - }) - }; - match k.as_str() { - Some("name") => name = Some(text()?), - Some("sites") => sites = Some(text()?), - other => { - return Err(at(format!( - "unknown key `{}` (a named reagent takes name and sites; a custom \ - reagent also takes intact, stubs, doublets, monolinks, aliases, \ - xlmod, source)", - other.unwrap_or("?") - ))) - } - } - } - let name = name.ok_or_else(|| at("`name` is missing".into()))?; - let mut d = XlDecl::parse(&name).map_err(|e| at(e.to_string()))?; - if sites.is_some() { - d.sites = sites; - } - d.resolve(db).map_err(|e| at(e.to_string())) - } - _ => Err(at("expected `Name (sites)` or a map with `name`".into())), - } -} - -pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Result<(), String> { +pub fn apply( + cfg: RunConfig, + args: &mut SearchArgs, + m: &clap::ArgMatches, + src: &mut ParamSources, +) -> Result<(), String> { macro_rules! set { ($id:literal, $($field:ident).+, $val:expr) => { if let Some(v) = $val { if !cli_set(m, $id) { + src.record_config($id, &cfg.written); args.$($field).+ = v; } } @@ -423,6 +320,7 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res ($id:literal, $($field:ident).+, $val:expr) => { if let Some(v) = $val { if !cli_set(m, $id) { + src.record_config($id, &cfg.written); args.$($field).+ = Some(v); } } @@ -433,12 +331,13 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res if let Some(s) = $val { if !cli_set(m, $id) { args.$($field).+ = ($parse)(&s)?; + src.record_config($id, &cfg.written); } } }; } - apply_db(&cfg, &mut args.db, m)?; + apply_db(&cfg, &mut args.db, m, src)?; set_opt!("sdrf", sdrf, cfg.io.sdrf); set!("spectrum", spectrum, cfg.io.spectrum); @@ -462,6 +361,7 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res ); if let Some(s) = cfg.search.isotope_error { if !cli_set(m, "isotope_error") { + src.record_config("isotope_error", &cfg.written); args.isotope_error = Some(crate::parse_isotope_error_range(&s)?); } } @@ -493,6 +393,7 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res return Err(format!("search.localize: '{v}' is not one of: ipf")); } args.localize = Some(v); + src.record_config("localize", &cfg.written); } set_parsed!( "fragment_index", @@ -641,6 +542,7 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res .iter() .map(|s| crate::cli::parse_enum("predict entry", s, true)) .collect::>()?; + src.record_config("predict", &cfg.written); } } set_opt!( @@ -668,12 +570,14 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res if let Some(v) = cfg.quant.tmt { if !cli_set(m, "tmt") { + src.record_config("tmt", &cfg.written); args.tmt = Some(crate::cli::parse_plex(&v)?); } } set_opt!("tmt_level", tmt_level, cfg.quant.tmt_level); if let Some(v) = cfg.quant.tmt_tol { if !cli_set(m, "tmt_tol") { + src.record_config("tmt_tol", &cfg.written); args.tmt_tol = Some(parse_tol("tmt_tol", &v)?); } } @@ -689,6 +593,7 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res set!("lfq", lfq, cfg.quant.lfq); if let Some(v) = cfg.quant.lfq_tol { if !cli_set(m, "lfq_tol") { + src.record_config("lfq_tol", &cfg.written); args.lfq_tol = Some(parse_tol("lfq_tol", &v)?); } } @@ -740,16 +645,11 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res set!("glyco", glyco, cfg.glyco.enabled); if let Some(v) = &cfg.search.xl { if !cli_set(m, "xl") { - let linkers = match v { - serde_yaml::Value::Sequence(items) => items - .iter() - .map(|i| xl_linker("search.xl", i)) - .collect::, _>>()?, - _ => vec![xl_linker("search.xl", v)?], - }; - args.xl = Some(crate::cli::XlSet::new("search.xl", linkers)?); + src.record_config("xl", &cfg.written); + args.xl = Some(xl_set(v)?); } } + set!("xl_linear_only", xl_linear_only, cfg.search.xl_linear_only); set_parsed!("glyco_core", glyco_core, cfg.glyco.core, parse_glyco_core); set!("glyco_tol_ppm", glyco_tol_ppm, cfg.glyco.tol_ppm); set!("glyco_max_peaks", glyco_max_peaks, cfg.glyco.max_peaks); @@ -770,12 +670,15 @@ pub fn apply(cfg: RunConfig, args: &mut SearchArgs, m: &clap::ArgMatches) -> Res ); } if let Some(p) = cfg.glyco.glycan_gdb { + src.record_config("glyco_glycan_gdb", &cfg.written); args.glyco_glycan_gdb = Some(p); } if let Some(p) = cfg.glyco.glycan_wurcs { + src.record_config("glyco_glycan_wurcs", &cfg.written); args.glyco_glycan_wurcs = Some(p); } if let Some(s) = cfg.glyco.species { + src.record_config("glyco_species", &cfg.written); args.glyco_species = Some( parse_value_enum::(&s) .map_err(|e| format!("config: `glyco.species`: {e}"))?, @@ -933,6 +836,10 @@ fn check_positive(field: &str, v: f64) -> Result<(), String> { mod tests { use super::*; + fn apply(cfg: RunConfig, a: &mut SearchArgs, m: &clap::ArgMatches) -> Result<(), String> { + super::apply(cfg, a, m, &mut ParamSources::default()) + } + #[test] fn unknown_key_is_rejected() { let y = "search:\n precursor_tol: 20ppm\n bogus_key: 1\n"; @@ -1275,20 +1182,9 @@ glyco: Ok(a) } - const CLI_ONLY: &[&str] = &[ - "config", - "cal_min_spec_keys", - "precursor_mono_dump", - "glyco_scans", - "glyco_mbr_match_train", - "ipf_debug", - "xl_oracle", - "xl_linear_only", - "xl_rescore_intra", - "xl_rescore_inter", - "quiet", - "verbose", - ]; + fn cli_only(id: &str) -> bool { + crate::params::spec(id).is_some_and(|p| p.section == crate::params::Section::CliOnly) + } #[test] fn every_search_flag_has_a_config_key() { @@ -1306,7 +1202,7 @@ glyco: .get_arguments() .map(|a| a.get_id().to_string()) .filter(|id| !matches!(id.as_str(), "help" | "version")) - .filter(|id| !CLI_ONLY.contains(&id.as_str()) && !mapped(id)) + .filter(|id| !cli_only(id) && !mapped(id)) .collect(); assert!(missing.is_empty(), "flags with no config key: {missing:?}"); } diff --git a/crates/andes/src/config_mods.rs b/crates/andes/src/config_mods.rs new file mode 100644 index 00000000..ab28fcf8 --- /dev/null +++ b/crates/andes/src/config_mods.rs @@ -0,0 +1,143 @@ +//! Reads the modification and crosslinker declarations of a `--config` file. +//! +//! A modification or crosslinker is written as one `Name (sites)` string or as a map with +//! the fields of the declaration; both forms resolve to the same values as the command-line +//! flags. + +pub fn mod_list( + key: &str, + items: &[serde_yaml::Value], + fixed: bool, +) -> Result { + use model::mod_spec::ModDecl; + let mut mods = Vec::new(); + for (i, item) in items.iter().enumerate() { + let at = |e: String| format!("{key}[{i}]: {e}"); + let decl = match item { + serde_yaml::Value::String(s) => ModDecl::parse(s).map_err(|e| at(e.to_string()))?, + serde_yaml::Value::Mapping(map) => mod_decl(map).map_err(at)?, + _ => { + return Err(at( + "expected `Name (sites)` or a map with `name` or `mass` and `sites`".into(), + )) + } + }; + mods.extend( + decl.resolve(fixed, model::unimod::bundled()) + .map_err(|e| at(e.to_string()))?, + ); + } + Ok(crate::cli::ModList(mods)) +} + +fn mod_decl(map: &serde_yaml::Mapping) -> Result { + use serde_yaml::Value; + let text = |key: &str, v: &Value| -> Result { + match v { + Value::String(s) => Ok(s.clone()), + _ => Err(format!("`{key}` must be a string")), + } + }; + let numbers = |key: &str, v: &Value| -> Result, String> { + let one = |v: &Value| v.as_f64().ok_or_else(|| format!("`{key}` takes numbers")); + match v { + Value::Sequence(seq) => seq.iter().map(one).collect(), + v => Ok(vec![one(v)?]), + } + }; + let mut d = model::mod_spec::ModDecl::default(); + let mut sites = None; + for (k, v) in map { + let key = k.as_str().ok_or("modification keys are strings")?; + match key { + "name" => d.name = Some(text(key, v)?), + "mass" => { + d.mass = Some( + v.as_f64() + .ok_or("`mass` is a number (the mass shift in Da)")?, + ) + } + "sites" => sites = Some(text(key, v)?), + "neutral_loss" => d.neutral_loss = numbers(key, v)?, + "loss_class" => d.loss_class = Some(text(key, v)?), + "restrict_to" => d.restrict_to = Some(text(key, v)?), + "cleavage" => d.cleavage = Some(text(key, v)?), + "diagnostic_ions" => d.diagnostic_ions = numbers(key, v)?, + other => { + return Err(format!( + "unknown key `{other}` (expected name, mass, sites, neutral_loss, \ + loss_class, restrict_to, cleavage, diagnostic_ions)" + )) + } + } + } + match (sites, d.name.clone(), d.mass) { + (Some(s), _, _) => d.sites = s, + (None, Some(name), None) => { + let parsed = model::mod_spec::ModDecl::parse(&name).map_err(|e| e.to_string())?; + d.name = parsed.name; + d.sites = parsed.sites; + } + (None, _, _) => return Err("`sites` is missing".into()), + } + Ok(d) +} + +pub fn xl_linker(key: &str, v: &serde_yaml::Value) -> Result { + use serde_yaml::Value; + use xl::spec::XlDecl; + let at = |e: String| format!("{key}: {e}"); + let db = model::unimod::bundled(); + match v { + Value::String(s) => XlDecl::parse(s) + .and_then(|d| d.resolve(db)) + .map_err(|e| at(e.to_string())), + Value::Mapping(map) if map.contains_key("intact") => { + let r: model::xl_reagents::Reagent = + serde_yaml::from_value(v.clone()).map_err(|e| at(e.to_string()))?; + xl::spec::custom(&r, db).map_err(|e| at(e.to_string())) + } + Value::Mapping(map) => { + let mut name = None; + let mut sites = None; + for (k, val) in map { + let text = || { + val.as_str().map(str::to_string).ok_or_else(|| { + at(format!("`{}` must be a string", k.as_str().unwrap_or("?"))) + }) + }; + match k.as_str() { + Some("name") => name = Some(text()?), + Some("sites") => sites = Some(text()?), + other => { + return Err(at(format!( + "unknown key `{}` (a named reagent takes name and sites; a custom \ + reagent also takes intact, stubs, doublets, monolinks, aliases, \ + xlmod, source)", + other.unwrap_or("?") + ))) + } + } + } + let name = name.ok_or_else(|| at("`name` is missing".into()))?; + let mut d = XlDecl::parse(&name).map_err(|e| at(e.to_string()))?; + if sites.is_some() { + d.sites = sites; + } + d.resolve(db).map_err(|e| at(e.to_string())) + } + _ => Err(at("expected `Name (sites)` or a map with `name`".into())), + } +} + +/// The crosslinkers of the `search.xl` value: one declaration, or a list of them. +pub fn xl_set(v: &serde_yaml::Value) -> Result { + let linkers = match v { + serde_yaml::Value::Sequence(items) => items + .iter() + .map(|i| xl_linker("search.xl", i)) + .collect::, _>>()?, + _ => vec![xl_linker("search.xl", v)?], + }; + crate::cli::XlSet::new("search.xl", linkers) +} diff --git a/crates/andes/src/param_sources.rs b/crates/andes/src/param_sources.rs new file mode 100644 index 00000000..2920855e --- /dev/null +++ b/crates/andes/src/param_sources.rs @@ -0,0 +1,200 @@ +//! Records where each search setting came from: its default, the `--config` file, the SDRF or +//! the command line. +//! +//! The merge in `main` starts from [`from_command_line`] and lets `config::apply` and +//! `sdrf::apply` add what they set. A setting nobody recorded is a [`Source::Default`]. Each +//! record carries the value as a config value, in the shape the `RunConfig` key expects: the +//! command-line text typed by the argument, the YAML value of the config key, or the SDRF cell +//! turned into that shape. Later consumers (the run report, `--print-config`) read the +//! result through [`ParamSources::source`] and [`ParamSources::value`]. A value that has no +//! config form (text that is not UTF-8, a value YAML cannot hold) is noted in +//! [`ParamSources::unwritable`], so that `--print-config` refuses to write a config that would +//! not reproduce the run. + +use std::collections::BTreeMap; + +use clap::parser::ValueSource; +use clap::{ArgAction, CommandFactory}; +use serde_yaml::Value; + +use crate::params::{spec, Unit, PARAMS}; + +/// Where a setting's value came from. The command line beats the config file, which beats the +/// SDRF, which beats the default. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + Default, + Config, + Sdrf, + CommandLine, +} + +/// The source and written value of every search setting that was not left at its default, +/// keyed by clap id, and the settings whose value has no config form. +#[derive(Debug, Default, Clone)] +pub struct ParamSources { + set: BTreeMap<&'static str, (Source, Option)>, + unwritable: Vec, +} + +impl ParamSources { + /// Notes that `id` was set from `source` to `value`. An id outside the parameter table is + /// a programming error and is ignored in release builds. + pub fn record(&mut self, id: &str, source: Source, value: Value) { + match spec(id) { + Some(p) => { + self.set.insert(p.id, (source, Some(value))); + } + None => debug_assert!(false, "`{id}` is not a search parameter"), + } + } + + /// Like [`record`](Self::record), for a value that is not yet a YAML value (a list of + /// strings, a path, a flag). A value YAML cannot hold records the source alone and is + /// noted as unwritable. + pub fn record_as(&mut self, id: &str, source: Source, v: &T) { + match serde_yaml::to_value(v) { + Ok(value) => self.record(id, source, value), + Err(e) => { + self.record_without_value(id, source); + self.unwritable.push(format!("`{id}`: {e}")); + } + } + } + + /// Notes that `id` was set from `source` and that no config form of its value is known. + /// An id outside the parameter table is a programming error and is ignored in release + /// builds. + pub fn record_without_value(&mut self, id: &str, source: Source) { + match spec(id) { + Some(p) => { + self.set.insert(p.id, (source, None)); + } + None => debug_assert!(false, "`{id}` is not a search parameter"), + } + } + + /// The settings whose value was given but has no config form, each with the reason. + pub fn unwritable(&self) -> &[String] { + &self.unwritable + } + + /// Notes that `id` was set by the config file whose parsed text is `written`, with the value + /// of its section and key in that file. + pub fn record_config(&mut self, id: &str, written: &Value) { + let value = spec(id) + .and_then(|p| written.get(p.section.yaml_name()?)?.get(p.key)) + .cloned() + .unwrap_or_default(); + self.record(id, Source::Config, value); + } + + /// The source of `id`; [`Source::Default`] when nothing was recorded. + pub fn source(&self, id: &str) -> Source { + self.set.get(id).map_or(Source::Default, |(s, _)| *s) + } + + /// The value recorded for `id` as a config value; `None` when the source set the setting but + /// no config form of its value is known (an SDRF crosslinker cell). + pub fn value(&self, id: &str) -> Option<&Value> { + self.set.get(id).and_then(|(_, v)| v.as_ref()) + } +} + +/// Every search setting given on the command line, as the config value that would set it: a +/// list for an argument that takes several values (and for the modification and crosslinker +/// lists, split as their parsers split them), a boolean for a switch, a number for a numeric +/// unit when the text is one, otherwise the raw text. Text that is not UTF-8 records the source +/// alone and is noted as unwritable. +pub fn from_command_line(m: &clap::ArgMatches) -> ParamSources { + let mut cmd = crate::TopCli::command(); + cmd.build(); + let mut out = ParamSources::default(); + for p in PARAMS { + let Some(arg) = cmd.get_arguments().find(|a| a.get_id() == p.id) else { + debug_assert!(false, "`{}` has a row but no clap argument", p.id); + continue; + }; + let given = matches!(m.try_contains_id(p.id), Ok(true)) + && m.value_source(p.id) == Some(ValueSource::CommandLine); + if !given { + continue; + } + let value = if let Ok(Some(flag)) = m.try_get_one::(p.id) { + Value::Bool(*flag) + } else { + let delimiter = arg.get_value_delimiter(); + let Some(raw) = utf8_values(m, p.id) else { + out.record_without_value(p.id, Source::CommandLine); + out.unwritable + .push(format!("`{}`: the command-line value is not UTF-8 text", p.id)); + continue; + }; + let raw: Vec = match delimiter { + Some(d) => raw.iter().flat_map(|r| r.split(d)).map(str::to_string).collect(), + None => raw, + }; + let typed = |t: &String| typed_text(p.unit, t); + if matches!(p.id, "fixed_mods" | "variable_mods") { + let joined = raw.join(", "); + let items = model::mod_spec::split_list(&joined) + .map(|v| v.into_iter().map(|i| Value::from(i.trim())).collect::>()); + Value::Sequence(items.unwrap_or_else(|_| raw.iter().map(typed).collect())) + } else if p.id == "xl" { + let items = raw.iter().flat_map(|r| crate::cli_parse::split_xl(r)); + Value::Sequence(items.map(Value::from).collect()) + } else if takes_several(arg) { + Value::Sequence(raw.iter().map(typed).collect()) + } else { + raw.first().map_or(Value::Bool(true), typed) + } + }; + out.record(p.id, Source::CommandLine, value); + } + out +} + +/// The raw command-line texts of `id`; `None` when one of them is not UTF-8. +fn utf8_values(m: &clap::ArgMatches, id: &str) -> Option> { + m.get_raw(id).map_or(Some(Vec::new()), |vals| { + vals.map(|v| v.to_str().map(str::to_string)).collect() + }) +} + +/// Whether clap collects more than one value for the argument. +pub(crate) fn takes_several(arg: &clap::Arg) -> bool { + matches!(arg.get_action(), ArgAction::Append) + || arg.get_value_delimiter().is_some() + || arg.get_num_args().is_some_and(|n| n.max_values() > 1) +} + +/// A YAML number when the unit is numeric (a charge range such as `2..5` stays text) and the +/// text is a number, otherwise the text. Integers are tried as `u64`, then `i64`, then the +/// text as a finite `f64`, so every integer the CLI accepts stays an integer. +pub(crate) fn typed_text(unit: Unit, text: &str) -> Value { + let numeric = matches!( + unit, + Unit::Count + | Unit::Number + | Unit::Fraction + | Unit::Gb + | Unit::Seconds + | Unit::Ppm + | Unit::Da + | Unit::Charge + ); + let number = || { + if let Ok(u) = text.parse::() { + return Some(Value::from(u)); + } + if let Ok(i) = text.parse::() { + return Some(Value::from(i)); + } + text.parse::().ok().filter(|f| f.is_finite()).map(Value::from) + }; + if numeric { + number().unwrap_or_else(|| Value::from(text)) + } else { + Value::from(text) + } +} diff --git a/crates/andes/src/params.rs b/crates/andes/src/params.rs new file mode 100644 index 00000000..115b3585 --- /dev/null +++ b/crates/andes/src/params.rs @@ -0,0 +1,288 @@ +//! The search command's parameter table: what clap cannot hold about each argument. +//! +//! clap declares the flag, its value type, parser, default and help text. This table adds the +//! config-file section and key, the unit, the accepted range as short text, what an unset value +//! means when clap has no default, the legacy form of the flag, and an optional example. One row +//! exists for every argument of the search command, and the tests in +//! `tests/params_table.rs` keep the table and the CLI in step. `params_render` reads the table +//! through [`spec`] and [`PARAMS`] to write `config.example.yaml`, the DOCS.md flag tables and +//! `--print-config`. + +/// The `RunConfig` section a parameter belongs to; the YAML name is the field name of +/// `RunConfig`. `CliOnly` arguments have no config key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Section { + Io, + Search, + Scoring, + Decoys, + Chimeric, + Refine, + Rescoring, + Glyco, + Quant, + CliOnly, +} + +impl Section { + /// The YAML section name, or `None` for a command-line-only argument. + pub fn yaml_name(self) -> Option<&'static str> { + match self { + Section::Io => Some("io"), + Section::Search => Some("search"), + Section::Scoring => Some("scoring"), + Section::Decoys => Some("decoys"), + Section::Chimeric => Some("chimeric"), + Section::Refine => Some("refine"), + Section::Rescoring => Some("rescoring"), + Section::Glyco => Some("glyco"), + Section::Quant => Some("quant"), + Section::CliOnly => None, + } + } +} + +/// The unit of a numeric value, or the kind of a path; `None` for a name, a list or a switch. +/// `Count` is an integer, `Number` a plain real number without a unit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unit { + None, + Ppm, + Da, + PpmOrDa, + Seconds, + Gb, + Fraction, + Count, + Number, + Charge, + Path, +} + +/// What an argument means when no value is given and clap holds no default. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unset { + /// clap holds the default; `--help` shows it. + ClapDefault, + /// The value is worked out at run time; the text says how, for documentation. + Auto(&'static str), + /// The feature is off. + Off, + /// The run cannot start without a value. + Required, +} + +/// One search argument: the clap id and what clap cannot declare about it. +#[derive(Debug, Clone, Copy)] +pub struct ParamSpec { + pub id: &'static str, + pub section: Section, + /// The YAML key inside the section, usually the id. + pub key: &'static str, + pub unit: Unit, + /// The accepted values as short text, such as `">= 1"` or `"0..1"`; `None` for an + /// argument with clap possible values, which the renderers list from clap. + pub range: Option<&'static str>, + pub unset: Unset, + /// The Java-form text of the DOCS.md "Legacy form" column. + pub legacy: Option<&'static str>, + /// A worked example value for documentation. + pub example: Option<&'static str>, + /// Comment lines written under the row in `config.example.yaml`, without the `# ` prefix: + /// the worked multi-line forms of a config-only setting. + pub example_block: Option<&'static str>, +} + +const fn row( + id: &'static str, + section: Section, + key: &'static str, + unit: Unit, + range: Option<&'static str>, + unset: Unset, + legacy: Option<&'static str>, +) -> ParamSpec { + ParamSpec { + id, + section, + key, + unit, + range, + unset, + legacy, + example: None, + example_block: None, + } +} + +const fn with_example(mut p: ParamSpec, example: &'static str) -> ParamSpec { + p.example = Some(example); + p +} + +const fn with_block(mut p: ParamSpec, block: &'static str) -> ParamSpec { + p.example_block = Some(block); + p +} + +/// The row of the argument with clap id `id`. +pub fn spec(id: &str) -> Option<&'static ParamSpec> { + PARAMS.iter().find(|p| p.id == id) +} + +const MODS_BLOCK: &str = "\ +A list item is the command-line string or a map that adds the config-only settings (example): +variable_mods: + - Oxidation (M) + - {name: Phospho, sites: STY, neutral_loss: [97.976896], loss_class: phospho} + - {name: GlyGly, sites: K, cleavage: blocked, diagnostic_ions: [215.1502, 198.1237]} + - {name: Phospho, sites: Y, restrict_to: annotated} # only at sites a UniProt XML database annotates + - {name: MyTag, mass: 123.4567, sites: N-term} # a custom mass, no UNIMOD lookup"; + +const XL_BLOCK: &str = "\ +A reagent the table (resources/crosslinkers.yaml) lacks is an entry of that file's schema (example): +xl: + name: MyLinker + sites: K, Protein N-term # one end, or \"end / end\" for a heterobifunctional linker + intact: {mass: 158.003765} # or {composition: \"H(6) C(6) O(3) S\"} or {unimod: \"Xlink:DSSO[158]\"} + stubs: [{name: alkene, mass: 54.010565}, {name: thiol, mass: 85.982635}] # MS-cleavage stubs + doublets: [[alkene, thiol]] # reporter doublets, [light, heavy] stub names + monolinks: [{name: water, mass: 176.01433}]"; + +/// Every argument of the search command, grouped by config section. +#[rustfmt::skip] +pub const PARAMS: &[ParamSpec] = &[ + row("uniprot_variants", Section::Io, "uniprot_variants", Unit::None, None, Unset::Off, None), + row("uniprot_isoforms", Section::Io, "uniprot_isoforms", Unit::None, None, Unset::Off, None), + row("uniprot_chains", Section::Io, "uniprot_chains", Unit::None, None, Unset::Off, None), + row("uniprot_evidence", Section::Io, "uniprot_evidence", Unit::None, None, Unset::ClapDefault, None), + with_example(row("annotations", Section::Io, "annotations", Unit::Path, None, Unset::Off, None), "db.annotations.parquet"), + row("knockoffs", Section::Io, "knockoffs", Unit::Count, None, Unset::ClapDefault, None), + with_example(row("sdrf", Section::Io, "sdrf", Unit::Path, None, Unset::Off, None), "design.sdrf.tsv"), + with_example(row("spectrum", Section::Io, "spectrum", Unit::Path, None, Unset::Required, Some("Java -s ")), "sample.mzML"), + with_example(row("database", Section::Io, "database", Unit::Path, None, Unset::Required, Some("Java -d ")), "human.fasta"), + with_example(row("output_pin", Section::Io, "output_pin", Unit::Path, None, Unset::Auto("required unless --rescore"), Some("Java -o (when -outputFormat pin)")), "out.pin"), + with_example(row("output_tsv", Section::Io, "output_tsv", Unit::Path, None, Unset::Off, Some("Java -outputFormat 1 with output path")), "out.tsv"), + with_example(row("output_parquet", Section::Io, "output_parquet", Unit::Path, None, Unset::Off, None), "out.idparquet"), + with_example(row("temp_dir", Section::Io, "temp_dir", Unit::Path, None, Unset::Auto("the directory of the outputs"), None), "tmp"), + row("enzyme", Section::Search, "enzyme", Unit::None, None, Unset::ClapDefault, Some("Java -e")), + with_example(row("fixed_mods", Section::Search, "fixed_mods", Unit::None, Some("list of Name (sites)"), Unset::Auto("Carbamidomethyl (C)"), Some("Java -mod ")), "Carbamidomethyl (C)"), + with_block(with_example(row("variable_mods", Section::Search, "variable_mods", Unit::None, Some("list of Name (sites)"), Unset::Auto("Oxidation (M), Acetyl (Protein N-term)"), Some("Java -mod ")), "Oxidation (M)"), MODS_BLOCK), + row("precursor_tol", Section::Search, "precursor_tol", Unit::PpmOrDa, Some("> 0, VALUE+unit, e.g. 20ppm or 0.02da"), Unset::ClapDefault, Some("Java -t 20ppm")), + row("charge", Section::Search, "charge", Unit::Charge, Some("MIN..MAX, 1..50, MIN <= MAX"), Unset::ClapDefault, Some("no direct Java flag; set via param file in Java")), + with_example(row("isotope_error", Section::Search, "isotope_error", Unit::None, Some("MIN..MAX, MIN <= MAX"), Unset::Auto("-1..2, 0..2 with --glyco or --xl"), Some("Java -ti -1,2")), "0..1"), + row("open_search", Section::Search, "open_search", Unit::None, None, Unset::Off, None), + row("open_search_delta", Section::Search, "open_search_delta", Unit::Da, Some("MIN..MAX in Da, contains 0, width <= 2000"), Unset::ClapDefault, None), + row("open_search_top_k", Section::Search, "open_search_top_k", Unit::Count, None, Unset::ClapDefault, None), + row("optimize", Section::Search, "optimize", Unit::None, None, Unset::Off, None), + row("optimize_sample", Section::Search, "optimize_sample", Unit::Count, None, Unset::ClapDefault, None), + row("max_missed_cleavages", Section::Search, "max_missed_cleavages", Unit::Count, None, Unset::ClapDefault, Some("Java -maxMissedCleavages 2")), + row("enzyme_specificity", Section::Search, "enzyme_specificity", Unit::None, None, Unset::ClapDefault, Some("Java -ntt")), + row("min_length", Section::Search, "min_length", Unit::Count, None, Unset::ClapDefault, Some("Java -minLength 6")), + row("max_length", Section::Search, "max_length", Unit::Count, None, Unset::ClapDefault, Some("Java -maxLength 40")), + row("max_mods", Section::Search, "max_mods", Unit::Count, None, Unset::ClapDefault, None), + row("min_peaks", Section::Search, "min_peaks", Unit::Count, None, Unset::ClapDefault, Some("Java -minNumPeaks 10")), + row("top_n", Section::Search, "top_n", Unit::Count, None, Unset::ClapDefault, Some("Java -n 10")), + row("dia", Section::Search, "dia", Unit::None, None, Unset::Off, None), + row("dia_mobility_slices", Section::Search, "dia_mobility_slices", Unit::Count, None, Unset::ClapDefault, None), + row("dia_ms1_tol_ppm", Section::Search, "dia_ms1_tol_ppm", Unit::Ppm, None, Unset::ClapDefault, None), + with_example(row("localize", Section::Search, "localize", Unit::None, None, Unset::Off, None), "ipf"), + with_block(with_example(row("xl", Section::Search, "xl", Unit::None, None, Unset::Off, None), "DSSO (K, Protein N-term)"), XL_BLOCK), + row("xl_linear_only", Section::Search, "xl_linear_only", Unit::None, None, Unset::Off, None), + row("fragment_index", Section::Search, "fragment_index", Unit::None, None, Unset::ClapDefault, None), + with_example(row("fragment_index_slice_da", Section::Search, "fragment_index_slice_da", Unit::Da, None, Unset::Auto("from the memory budget"), None), "80"), + with_example(row("index_cache_dir", Section::Search, "index_cache_dir", Unit::Path, None, Unset::Auto("the directory of the outputs"), None), "cache"), + with_example(row("threads", Section::Scoring, "threads", Unit::Count, None, Unset::Auto("the number of logical CPUs"), Some("Java -thread N")), "8"), + row("precursor_cal", Section::Scoring, "precursor_cal", Unit::None, None, Unset::ClapDefault, Some("Java -precursorCal auto|on|off")), + row("score", Section::Scoring, "score", Unit::None, None, Unset::ClapDefault, None), + row("fragmentation", Section::Scoring, "fragmentation", Unit::None, None, Unset::ClapDefault, Some("Java -m")), + row("protocol", Section::Scoring, "protocol", Unit::None, None, Unset::ClapDefault, Some("Java -protocol")), + with_example(row("fragment_tol_ppm", Section::Scoring, "fragment_tol_ppm", Unit::Ppm, Some("> 0"), Unset::Auto("measured per run"), None), "20"), + with_example(row("fragment_tol_da", Section::Scoring, "fragment_tol_da", Unit::Da, Some("> 0"), Unset::Auto("measured per run"), None), "0.5"), + with_example(row("peak_filter", Section::Scoring, "peak_filter", Unit::None, Some("WINDOW_DA:PEAKS"), Unset::Auto("100:20 for isobaric data, else off"), None), "100:20"), + row("ethcd_activation", Section::Scoring, "ethcd_activation", Unit::None, None, Unset::ClapDefault, None), + row("ms_level", Section::Scoring, "ms_level", Unit::Count, None, Unset::ClapDefault, None), + with_example(row("model_store", Section::Scoring, "model_store", Unit::Path, None, Unset::Auto("the bundled store"), None), "models.parquet"), + with_example(row("model_id_override", Section::Scoring, "model", Unit::None, None, Unset::Auto("selected from the data"), None), "hcd_qexactive_tryp"), + with_example(row("gbdt_max_trees", Section::Scoring, "gbdt_max_trees", Unit::Count, None, Unset::Auto("100; all with --glyco"), None), "100"), + row("max_spectra", Section::Scoring, "max_spectra", Unit::Count, None, Unset::ClapDefault, None), + row("precursor_mono", Section::Scoring, "precursor_mono", Unit::None, None, Unset::ClapDefault, None), + row("decoy_prefix", Section::Decoys, "prefix", Unit::None, None, Unset::ClapDefault, None), + with_example(row("decoy_suffix", Section::Decoys, "suffix", Unit::None, None, Unset::Off, None), "rev"), + row("decoy_strategy", Section::Decoys, "strategy", Unit::None, None, Unset::ClapDefault, None), + row("decoy_seed", Section::Decoys, "seed", Unit::Count, None, Unset::ClapDefault, None), + row("chimeric", Section::Chimeric, "enabled", Unit::None, None, Unset::Off, None), + row("chimeric_max_coisolated", Section::Chimeric, "max_coisolated", Unit::Count, None, Unset::ClapDefault, None), + row("chimeric_max_kl", Section::Chimeric, "max_kl", Unit::Number, Some(">= 0"), Unset::ClapDefault, None), + row("refine", Section::Refine, "enabled", Unit::None, None, Unset::Off, None), + with_example(row("refine_config", Section::Refine, "config", Unit::Path, None, Unset::Auto("the built-in tier"), None), "refine_tiers.yaml"), + with_example(row("psm_fdr", Section::Rescoring, "psm_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("0.01"), None), "0.01"), + with_example(row("protein_fdr", Section::Rescoring, "protein_fdr", Unit::Fraction, Some("0..1"), Unset::Off, None), "0.01"), + row("rescore", Section::Rescoring, "enabled", Unit::None, None, Unset::Off, None), + with_example(row("rescore_memory_gb", Section::Rescoring, "memory_gb", Unit::Gb, Some(">= 1"), Unset::Auto("what the PIN needs to stay in memory, at most 16 GB and at most the memory free to the job or machine less a margin"), None), "16"), + with_example(row("pep", Section::Rescoring, "pep", Unit::Fraction, Some("0..1"), Unset::Off, None), "0.05"), + with_example(row("percolator_bin", Section::Rescoring, "percolator_bin", Unit::Path, None, Unset::Off, None), "percolator"), + row("percolator_docker", Section::Rescoring, "percolator_docker", Unit::None, None, Unset::Off, None), + row("percolator_image", Section::Rescoring, "percolator_image", Unit::None, None, Unset::ClapDefault, None), + with_example(row("percolator_args", Section::Rescoring, "percolator_args", Unit::None, None, Unset::Auto("no extra arguments"), None), "--testFDR 0.05"), + row("keep_pin", Section::Rescoring, "keep_pin", Unit::None, None, Unset::ClapDefault, None), + row("predict", Section::Rescoring, "predict", Unit::None, None, Unset::ClapDefault, None), + with_example(row("predictor_models", Section::Rescoring, "predictor_models", Unit::Path, None, Unset::Off, None), "models/"), + row("predictor_backend", Section::Rescoring, "predictor_backend", Unit::None, None, Unset::ClapDefault, None), + with_example(row("predictor_nce", Section::Rescoring, "predictor_nce", Unit::Number, None, Unset::Auto("28 on Q Exactive, else 30"), None), "28"), + with_example(row("predictor_instrument", Section::Rescoring, "predictor_instrument", Unit::None, None, Unset::Auto("from the instrument"), None), "QE"), + row("predictor_batch", Section::Rescoring, "predictor_batch", Unit::Count, None, Unset::ClapDefault, None), + with_example(row("proteoform_fdr", Section::Rescoring, "proteoform_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("the larger of --psm-fdr and 0.05"), None), "0.05"), + row("glyco", Section::Glyco, "enabled", Unit::None, None, Unset::Off, None), + with_example(row("glyco_species", Section::Glyco, "species", Unit::None, None, Unset::Off, None), "human"), + with_example(row("glyco_glycan_gdb", Section::Glyco, "glycan_gdb", Unit::Path, None, Unset::Off, None), "glycans.gdb"), + with_example(row("glyco_glycan_wurcs", Section::Glyco, "glycan_wurcs", Unit::Path, None, Unset::Off, None), "glycans.csv"), + row("glyco_core", Section::Glyco, "core", Unit::None, None, Unset::ClapDefault, None), + row("glyco_tol_ppm", Section::Glyco, "tol_ppm", Unit::Ppm, Some("> 0"), Unset::ClapDefault, None), + row("glyco_min_core_y", Section::Glyco, "min_core_y", Unit::Count, None, Unset::ClapDefault, None), + row("glyco_hcd_pair", Section::Glyco, "hcd_pair", Unit::None, None, Unset::ClapDefault, None), + row("glyco_max_peaks", Section::Glyco, "max_peaks", Unit::Count, None, Unset::ClapDefault, None), + with_example(row("glyco_cz_max_charge", Section::Glyco, "cz_max_charge", Unit::Charge, None, Unset::Auto("from whether the spectrum is deconvoluted"), None), "1"), + row("glyco_y_max_charge", Section::Glyco, "y_max_charge", Unit::Charge, None, Unset::ClapDefault, None), + with_example(row("glyco_retrieval_tol_ppm", Section::Glyco, "retrieval_tol_ppm", Unit::Ppm, Some("> 0"), Unset::Auto("--glyco-tol-ppm on high-res MS2, 0.5 Da on low-res"), None), "20"), + row("glyco_peptide_first", Section::Glyco, "peptide_first", Unit::None, None, Unset::Off, None), + row("glyco_index_sequon_only", Section::Glyco, "index_sequon_only", Unit::None, None, Unset::Off, None), + row("debug_glyco", Section::Glyco, "debug", Unit::None, None, Unset::Off, None), + with_example(row("quant_fdr", Section::Quant, "quant_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("0.01"), None), "0.01"), + with_example(row("tmt", Section::Quant, "tmt", Unit::None, None, Unset::Off, None), "tmt10"), + row("lfq", Section::Quant, "lfq", Unit::None, None, Unset::Off, None), + with_example(row("label", Section::Quant, "label", Unit::None, Some("preset or one bracket per channel"), Unset::Off, None), "silac2"), + row("mbr", Section::Quant, "mbr", Unit::None, None, Unset::Off, None), + with_example(row("quant_dir", Section::Quant, "dir", Unit::Path, None, Unset::Off, None), "quant_out"), + with_example(row("tmt_level", Section::Quant, "tmt_level", Unit::Count, Some("2 or 3"), Unset::Auto("3 for SPS-MS3 data, else 2"), None), "3"), + with_example(row("tmt_tol", Section::Quant, "tmt_tol", Unit::PpmOrDa, Some("> 0, VALUE+unit, e.g. 20ppm or 0.003da"), Unset::Auto("20ppm (10ppm for tmt32/tmt35), 0.3da on ion-trap MS2"), None), "20ppm"), + with_example(row("tmt_correction", Section::Quant, "tmt_correction", Unit::Path, None, Unset::Off, None), "lot.txt"), + row("tmt_min_purity", Section::Quant, "tmt_min_purity", Unit::Fraction, Some("0..1"), Unset::ClapDefault, None), + row("tmt_min_sn", Section::Quant, "tmt_min_sn", Unit::Number, Some(">= 0"), Unset::ClapDefault, None), + row("tmt_unmix", Section::Quant, "tmt_unmix", Unit::None, None, Unset::ClapDefault, None), + row("mbr_wrong_log2", Section::Quant, "mbr_wrong_log2", Unit::Number, Some("> 0"), Unset::ClapDefault, None), + with_example(row("lfq_tol", Section::Quant, "lfq_tol", Unit::PpmOrDa, Some("> 0, VALUE+unit, e.g. 20ppm or 0.02da"), Unset::Auto("10ppm"), None), "10ppm"), + with_example(row("lfq_rt_window", Section::Quant, "lfq_rt_window", Unit::Seconds, Some("> 0"), Unset::Auto("60; 120 with --glyco"), None), "60"), + with_example(row("lfq_gaussian_width", Section::Quant, "lfq_gaussian_width", Unit::Seconds, Some("> 0"), Unset::Auto("Savitzky-Golay smoothing"), None), "12"), + row("lfq_min_cosine", Section::Quant, "lfq_min_cosine", Unit::Fraction, Some("0..1"), Unset::ClapDefault, None), + row("label_reference", Section::Quant, "label_reference", Unit::Count, Some(">= 1"), Unset::ClapDefault, None), + row("label_arg_pro", Section::Quant, "label_arg_pro", Unit::None, None, Unset::Off, None), + row("label_2h_enrichment_silac", Section::Quant, "label_2h_enrichment_silac", Unit::Fraction, Some("0..1"), Unset::ClapDefault, None), + row("label_2h_enrichment_chemical", Section::Quant, "label_2h_enrichment_chemical", Unit::Fraction, Some("0..1"), Unset::ClapDefault, None), + row("label_heavy_enrichment", Section::Quant, "label_heavy_enrichment", Unit::Fraction, Some("0..1"), Unset::ClapDefault, None), + with_example(row("mbr_donor_fdr", Section::Quant, "mbr_donor_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("inherits --psm-fdr"), None), "0.01"), + with_example(row("quant_transfer_fdr", Section::Quant, "quant_transfer_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("inherits --quant-fdr"), None), "0.01"), + with_example(row("quant_channel_fdr", Section::Quant, "quant_channel_fdr", Unit::Fraction, Some("0..1"), Unset::Auto("inherits --quant-fdr"), None), "0.05"), + row("config", Section::CliOnly, "config", Unit::Path, None, Unset::Off, None), + row("print_config", Section::CliOnly, "print_config", Unit::Path, None, Unset::Off, None), + row("ipf_debug", Section::CliOnly, "ipf_debug", Unit::None, None, Unset::Off, None), + row("xl_oracle", Section::CliOnly, "xl_oracle", Unit::Count, None, Unset::ClapDefault, None), + row("xl_rescore_intra", Section::CliOnly, "xl_rescore_intra", Unit::None, None, Unset::Off, None), + row("xl_rescore_inter", Section::CliOnly, "xl_rescore_inter", Unit::None, None, Unset::Off, None), + row("cal_min_spec_keys", Section::CliOnly, "cal_min_spec_keys", Unit::Count, None, Unset::Auto("10000"), None), + row("precursor_mono_dump", Section::CliOnly, "precursor_mono_dump", Unit::Path, None, Unset::Off, None), + row("glyco_scans", Section::CliOnly, "glyco_scans", Unit::Path, None, Unset::Off, None), + row("glyco_mbr_match_train", Section::CliOnly, "glyco_mbr_match_train", Unit::Path, None, Unset::Off, None), + row("quiet", Section::CliOnly, "quiet", Unit::None, None, Unset::Off, None), + row("verbose", Section::CliOnly, "verbose", Unit::None, None, Unset::Off, None), +]; diff --git a/crates/andes/src/params_render.rs b/crates/andes/src/params_render.rs new file mode 100644 index 00000000..dbd504f4 --- /dev/null +++ b/crates/andes/src/params_render.rs @@ -0,0 +1,604 @@ +//! Renders the search parameters from their one declaration: `config.example.yaml`, the DOCS.md +//! flag tables and the `--print-config` YAML. +//! +//! The declaration is the search command's clap arguments (flag, default, help, visibility, +//! heading) joined with the `PARAMS` table (section, key, unit, range, unset meaning, legacy +//! form, example). Nothing here holds a flag name or a default of its own. A hidden argument is +//! internal and is never advertised; an argument hidden from the short help is "(advanced)". +//! The values an enumerated argument accepts come from its clap possible values. + +use clap::{Arg, ArgAction, CommandFactory}; +use serde_yaml::Value; + +use crate::param_sources::{takes_several, typed_text, ParamSources, Source}; +use crate::params::{ParamSpec, Section, Unit, Unset, PARAMS}; + +const EXAMPLE_HEADER: &str = r##"# andes run configuration: `andes --config this-file.yaml`. +# +# Every key is optional; a key left out keeps its default. A flag on the command line wins over +# this file (command line > config > default). Unknown keys are an error. +# Values are written as on the command line ("20ppm", "2..5", auto). Every key below is commented +# out and shows its default, or an example value marked "(example)" when it has none; uncomment a +# key to set it. Only the example input and output paths are uncommented. +# Each comment names the key's flag; "advanced" flags are listed by `andes --help` only, +# "internal" ones by neither help. DOCS.md §1b describes the file. + +"##; + +const EXAMPLE_TAIL: &str = r##"# Read by `andes cohort plan` and `andes cohort run`; a search ignores this section. The sections above are the +# settings every run of the cohort shares; each run's own settings come from its SDRF row. +# cohort: +# name: human-xl # the default output folder, / next to this file +# data_dir: /data/raw # spectrum files, any layout; // is used when present +# output_dir: /data/human-xl # runs//, groups// and plan.json +# sdrfs: # one entry per project; paths relative to this file +# - {project: PXD019110, sdrf: PXD019110.sdrf.tsv} +# - {project: PXD059766, sdrf: PXD059766.sdrf.tsv} +# run_name: "{project}.{stem}" # unique run name; {project} and {stem} are filled in +# overrides: # replace or fill in what a project's SDRF gives +# - project: PXD019110 +# search: {precursor_tol: 10ppm} # keys: enzyme, precursor_tol, fixed_mods, variable_mods, xl +# exclude: [] # projects listed above but left out of the plan +"##; + +/// The section banners of `config.example.yaml`: the sections a banner covers and its title. +const BANNERS: &[(&[Section], &str)] = &[ + (&[Section::Io], "Input and output"), + (&[Section::Search], "Search"), + (&[Section::Scoring], "Calibration, model and runtime"), + (&[Section::Decoys], "Decoys"), + (&[Section::Chimeric, Section::Refine], "Modes"), + (&[Section::Rescoring], "Rescoring and FDR"), + (&[Section::Glyco], "Glycopeptides"), + (&[Section::Quant], "Quantification"), +]; + +/// The order of the DOCS.md flag tables by help heading; a heading missing here follows in +/// declaration order, and arguments without a heading come last under [`NO_HEADING`]. +const HEADING_ORDER: &[&str] = &[ + crate::cli::H_IO, + crate::cli::H_SEARCH, + crate::cli::H_DATABASE, + crate::cli::H_FDR, + crate::cli::H_MODES, + crate::cli::H_QUANT, + crate::cli::H_RESCORING, + crate::cli::H_PREDICTION, + crate::cli::H_ISOBARIC, + crate::cli::H_LFQ, + crate::cli::H_LABEL, + crate::cli::H_GLYCO, + crate::cli::H_RUNTIME, + crate::cli::ADVANCED_FDR, + crate::cli::H_ADVANCED, +]; + +/// The DOCS.md heading of arguments clap lists under no heading (its own "Options"). +const NO_HEADING: &str = "Options"; + +/// Command-line-only arguments that do not change what a run computes; `--print-config` does +/// not list them. +const NOT_RUN_SETTINGS: &[&str] = &["config", "print_config", "quiet", "verbose"]; + +/// Widest key text that the comments of a section line up behind. +const ALIGN_CAP: usize = 40; + +/// One written setting: the key text (with its `# ` when commented), the trailing comment and +/// the comment block under it. +struct Line { + key: String, + note: String, + block: Option<&'static str>, +} + +fn command() -> clap::Command { + let mut cmd = crate::TopCli::command(); + cmd.build(); + cmd +} + +fn is_builtin(arg: &Arg) -> bool { + matches!(arg.get_id().as_str(), "help" | "version") +} + +fn flag(arg: &Arg) -> String { + arg.get_long() + .map_or_else(|| arg.get_id().to_string(), |l| format!("--{l}")) +} + +fn collapsed(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// The first sentence of `help` without its closing period; an `e.g.` or `i.e.` does not end it. +fn first_sentence(help: &str) -> String { + let text = collapsed(help); + let bytes = text.as_bytes(); + for (i, _) in text.match_indices('.') { + let ends = !matches!(bytes.get(i + 1), Some(b) if *b != b' '); + let abbreviation = text[..i].ends_with("e.g") || text[..i].ends_with("i.e"); + if ends && !abbreviation { + return text[..i].to_string(); + } + } + text +} + +fn help_of(arg: &Arg) -> String { + arg.get_help().map(ToString::to_string).unwrap_or_default() +} + +/// The visible values clap accepts for an argument that takes a value; empty for a switch or +/// free text. +fn possible_values(arg: &Arg) -> Vec { + if matches!( + arg.get_action(), + ArgAction::SetTrue | ArgAction::SetFalse | ArgAction::Count + ) { + return Vec::new(); + } + arg.get_possible_values() + .iter() + .filter(|v| !v.is_hide_set()) + .map(|v| v.get_name().to_string()) + .collect() +} + +/// The accepted values: clap's possible values as `a | b | c`, else the row's range text. +fn range_text(arg: &Arg, p: &ParamSpec) -> Option { + let values = possible_values(arg); + if values.is_empty() { + p.range.map(str::to_string) + } else { + Some(values.join(" | ")) + } +} + +fn is_list(arg: &Arg, p: &ParamSpec) -> bool { + takes_several(arg) || matches!(p.id, "fixed_mods" | "variable_mods") +} + +/// The config value of the argument's own text or texts: a number for a numeric unit, a +/// boolean for `true` and `false`, a list when the argument takes several values. +fn value_of(arg: &Arg, p: &ParamSpec, texts: &[String]) -> Value { + let one = |t: &String| match t.as_str() { + "true" => Value::Bool(true), + "false" => Value::Bool(false), + _ => typed_text(p.unit, t), + }; + if is_list(arg, p) { + Value::Sequence(texts.iter().map(one).collect()) + } else { + texts.first().map_or(Value::Null, one) + } +} + +/// The clap default as a config value; `None` when clap holds none or hides it (a default that +/// depends on the machine). A switch defaults to off. +fn default_value(arg: &Arg, p: &ParamSpec) -> Option { + match arg.get_action() { + ArgAction::SetTrue => return Some(Value::Bool(false)), + ArgAction::SetFalse => return Some(Value::Bool(true)), + _ => {} + } + if arg.is_hide_default_value_set() { + return None; + } + let mut texts: Vec = Vec::new(); + for d in arg.get_default_values() { + let d = d.to_string_lossy(); + match arg.get_value_delimiter() { + Some(sep) => texts.extend(d.split(sep).map(str::to_string)), + None => texts.push(d.into_owned()), + } + } + (!texts.is_empty()).then(|| value_of(arg, p, &texts)) +} + +fn example_value(arg: &Arg, p: &ParamSpec) -> Option { + p.example.map(|e| value_of(arg, p, &[e.to_string()])) +} + +fn unset_text(unset: Unset) -> String { + match unset { + Unset::ClapDefault | Unset::Off => "off".to_string(), + Unset::Auto(text) => text.to_string(), + Unset::Required => "required".to_string(), + } +} + +fn scalar(s: &str) -> String { + let word = |c: char| c.is_ascii_alphanumeric() || "_./+-".contains(c); + let first_ok = s + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == '/'); + let lower = s.to_ascii_lowercase(); + let reserved = matches!( + lower.as_str(), + "true" | "false" | "null" | "yes" | "no" | "on" | "off" | "y" | "n" | "~" + ) || lower.starts_with("0x") + || lower.starts_with("0o") + || lower.starts_with("0b") + || lower.starts_with('.'); + if first_ok && s.chars().all(word) && !reserved && s.parse::().is_err() { + s.to_string() + } else { + double_quoted(s) + } +} + +/// `s` as a YAML double-quoted scalar: backslash, quote and every control character escaped, +/// so any string reads back unchanged. +fn double_quoted(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}' | '\u{feff}') => { + out.push_str(&format!("\\u{:04X}", u32::from(c))); + } + c => out.push(c), + } + } + out.push('"'); + out +} + +/// One-line YAML of a value: scalars plain where that is safe, lists and maps in flow style. +fn flow(v: &Value) -> String { + match v { + Value::Null => "null".to_string(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => n.to_string(), + Value::String(s) => scalar(s), + Value::Sequence(items) => { + let items: Vec = items.iter().map(flow).collect(); + format!("[{}]", items.join(", ")) + } + Value::Mapping(m) => { + let pairs: Vec = m + .iter() + .map(|(k, v)| format!("{}: {}", flow(k), flow(v))) + .collect(); + format!("{{{}}}", pairs.join(", ")) + } + Value::Tagged(t) => flow(&t.value), + } +} + +/// The lines of one config section, comments lined up and comment blocks under their rows. +fn write_section(out: &mut String, name: &str, lines: &[Line]) { + out.push_str(name); + out.push_str(":\n"); + let width = lines + .iter() + .map(|l| l.key.len()) + .filter(|w| *w <= ALIGN_CAP) + .max() + .unwrap_or(0); + for l in lines { + let pad = width.saturating_sub(l.key.len()) + 1; + out.push_str(&format!(" {}{}# {}\n", l.key, " ".repeat(pad), l.note)); + for b in l.block.into_iter().flat_map(str::lines) { + if b.is_empty() { + out.push_str(" #\n"); + } else { + out.push_str(&format!(" # {b}\n")); + } + } + } +} + +/// The banner-and-section body of a config file; `line_for` turns one row into its line, or +/// `None` to leave it out. +fn write_sections( + cmd: &clap::Command, + line_for: &dyn Fn(&Arg, &ParamSpec) -> Option, +) -> String { + let mut out = String::new(); + for (i, (sections, title)) in BANNERS.iter().enumerate() { + if i > 0 { + out.push('\n'); + } + out.push_str(&format!("# ── {title} ")); + let used = out.lines().last().map_or(0, |l| l.chars().count()); + out.push_str(&"─".repeat(78usize.saturating_sub(used))); + out.push('\n'); + for (j, section) in sections.iter().enumerate() { + if j > 0 { + out.push('\n'); + } + let lines: Vec = PARAMS + .iter() + .filter(|p| p.section == *section) + .filter_map(|p| { + let arg = cmd.get_arguments().find(|a| a.get_id() == p.id)?; + line_for(arg, p) + }) + .collect(); + write_section(&mut out, section.yaml_name().unwrap_or_default(), &lines); + } + } + out +} + +/// The whole `config.example.yaml`: every public parameter on one line, set to its default, or +/// commented out with an example value when it has none. Only the tests that keep the committed +/// file in step call it. +#[allow(dead_code)] +pub fn config_example() -> String { + let cmd = command(); + let body = write_sections(&cmd, &|arg, p| { + if arg.is_hide_set() { + return None; + } + let default = default_value(arg, p); + let path = matches!(p.id, "spectrum" | "database" | "output_pin"); + let (value, example, commented) = match (default, example_value(arg, p)) { + (Some(d), _) => (flow(&d), false, true), + (None, Some(e)) => (flow(&e), true, !path), + (None, None) => ("...".to_string(), false, true), + }; + let advanced = if arg.is_hide_short_help_set() { + " (advanced)" + } else { + "" + }; + let is_default = matches!(p.unset, Unset::Auto(a) if Some(a) == p.example); + let marker = if example && !is_default { + " (example)" + } else { + "" + }; + let values = possible_values(arg); + let values = if values.is_empty() { + String::new() + } else { + format!("; {}", values.join(" | ")) + }; + Some(Line { + key: format!("{}{}: {value}", if commented { "# " } else { "" }, p.key), + note: format!( + "{}{advanced}: {}{values}{marker}", + flag(arg), + first_sentence(&help_of(arg)) + ), + block: p.example_block, + }) + }); + format!("{EXAMPLE_HEADER}{body}\n{EXAMPLE_TAIL}") +} + +fn unit_text(unit: Unit) -> &'static str { + match unit { + Unit::None => "", + Unit::Ppm => "ppm", + Unit::Da => "Da", + Unit::PpmOrDa => "ppm or Da", + Unit::Seconds => "s", + Unit::Gb => "GB", + Unit::Fraction => "fraction", + Unit::Count => "count", + Unit::Number => "number", + Unit::Charge => "charge", + Unit::Path => "path", + } +} + +fn cell(text: &str) -> String { + text.replace('|', "\\|") +} + +fn code_cell(text: Option<&str>) -> String { + text.map_or_else( + || "—".to_string(), + |t| { + if t.contains('`') { + format!("`` {} ``", cell(t)) + } else { + format!("`{}`", cell(t)) + } + }, + ) +} + +fn default_cell(arg: &Arg, p: &ParamSpec) -> String { + if matches!(arg.get_action(), ArgAction::SetTrue | ArgAction::SetFalse) { + return "*(off)*".to_string(); + } + let defaults: Vec = arg + .get_default_values() + .iter() + .map(|d| d.to_string_lossy().into_owned()) + .collect(); + if defaults.is_empty() || arg.is_hide_default_value_set() { + format!("*({})*", cell(&unset_text(p.unset))) + } else { + format!("`{}`", cell(&defaults.join(","))) + } +} + +/// The short help, then the paragraphs the long help adds after it, whitespace collapsed. +fn description(arg: &Arg) -> String { + let mut text = collapsed(&help_of(arg)); + let long = arg.get_long_help().map(ToString::to_string).unwrap_or_default(); + for paragraph in long.split("\n\n").skip(1) { + let paragraph = collapsed(paragraph); + if !paragraph.is_empty() { + text.push(' '); + text.push_str(¶graph); + } + } + cell(&text) +} + +/// The position of a help heading in [`HEADING_ORDER`]; unlisted headings, then arguments +/// without one, sort after it. +fn heading_rank(heading: &str) -> usize { + match HEADING_ORDER.iter().position(|h| *h == heading) { + Some(i) => i, + None if heading == NO_HEADING => HEADING_ORDER.len() + 1, + None => HEADING_ORDER.len(), + } +} + +/// The DOCS.md flag tables: one per help heading, in [`HEADING_ORDER`], public flags only, rows +/// in declaration order. Only the tests that keep DOCS.md in step call it. +#[allow(dead_code)] +pub fn docs_reference() -> String { + let cmd = command(); + let mut tables: Vec<(String, Vec)> = Vec::new(); + for arg in cmd.get_arguments().filter(|a| !is_builtin(a) && !a.is_hide_set()) { + let Some(p) = PARAMS.iter().find(|p| arg.get_id() == p.id) else { + continue; + }; + let heading = arg.get_help_heading().unwrap_or(NO_HEADING).to_string(); + let advanced = if arg.is_hide_short_help_set() { + " (advanced)" + } else { + "" + }; + let cli_only = if p.section == Section::CliOnly { + " (command line only)" + } else { + "" + }; + let unit = unit_text(p.unit); + let row = format!( + "| `{}`{advanced}{cli_only} | {} | {} | {} | {} | {} |", + flag(arg), + if unit.is_empty() { "—" } else { unit }, + default_cell(arg, p), + code_cell(range_text(arg, p).as_deref()), + description(arg), + code_cell(p.legacy), + ); + match tables.iter_mut().find(|(h, _)| *h == heading) { + Some((_, rows)) => rows.push(row), + None => tables.push((heading, vec![row])), + } + } + tables.sort_by_key(|(heading, _)| heading_rank(heading)); + let rendered: Vec = tables + .iter() + .map(|(heading, rows)| { + format!( + "### {heading}\n\n| Flag | Unit | Default | Range | Description | Legacy form |\n\ + |---|---|---|---|---|---|\n{}\n", + rows.join("\n") + ) + }) + .collect(); + rendered.join("\n") +} + +fn source_text(source: Source) -> &'static str { + match source { + Source::Default => "default", + Source::Config => "config", + Source::Sdrf => "SDRF", + Source::CommandLine => "command line", + } +} + +/// The command-line-only settings that change the run and were set, as the command-line text +/// that sets them again (`--xl-oracle 5`). A config file has no key for them. +pub fn command_line_only(sources: &ParamSources) -> Vec { + let cmd = command(); + PARAMS + .iter() + .filter(|p| p.section == Section::CliOnly && !NOT_RUN_SETTINGS.contains(&p.id)) + .filter(|p| sources.source(p.id) != Source::Default) + .filter_map(|p| { + let arg = cmd.get_arguments().find(|a| a.get_id() == p.id)?; + Some(command_line_text(arg, sources.value(p.id))) + }) + .collect() +} + +/// The flag and value text of one setting, a list as the flag repeated. +fn command_line_text(arg: &Arg, value: Option<&Value>) -> String { + let flag = flag(arg); + let switch = matches!(arg.get_action(), ArgAction::SetTrue); + match value { + None => flag, + Some(Value::Bool(true)) if switch => flag, + Some(Value::Sequence(items)) => items + .iter() + .map(|v| format!("{flag} {}", flow(v))) + .collect::>() + .join(" "), + Some(v) => format!("{flag} {}", flow(v)), + } +} + +/// The `--print-config` YAML: every config parameter under its section with the value the run +/// uses (the recorded value, else the clap default) and a comment naming its source. Only a +/// value some source set is written as a key; a default is commented out, so that replaying the +/// file keeps every default and its auto-adjustment. A parameter with no value is commented out +/// with what unset means. Internal parameters appear only when something set them. The +/// command-line-only settings that were set close the file as comments, since no key holds +/// them. A setting whose value has no config form is an error: the file would not reproduce the +/// run. `--print-config` writes it. +pub fn effective_config(sources: &ParamSources) -> Result { + if !sources.unwritable().is_empty() { + return Err(format!( + "--print-config: no config form of {}", + sources.unwritable().join("; ") + )); + } + let cmd = command(); + let body = write_sections(&cmd, &|arg, p| { + let source = sources.source(p.id); + if arg.is_hide_set() && source == Source::Default { + return None; + } + let value = sources + .value(p.id) + .cloned() + .or_else(|| default_value(arg, p)) + .filter(|_| source == Source::Default || sources.value(p.id).is_some()); + let (key, note) = match value { + Some(v) if source == Source::Default => ( + format!("# {}: {}", p.key, flow(&v)), + source_text(source).to_string(), + ), + Some(v) => ( + format!("{}: {}", p.key, flow(&v)), + source_text(source).to_string(), + ), + None if source == Source::Default => ( + format!("# {}:", p.key), + format!("unset: {}", unset_text(p.unset)), + ), + None => ( + format!("# {}:", p.key), + format!("{}; no config form of the value", source_text(source)), + ), + }; + Some(Line { + key, + note, + block: None, + }) + }); + let mut text = format!( + "# The settings this run uses (`--print-config`); each comment names where the value came from.\n\n{body}" + ); + let cli_only = command_line_only(sources); + if !cli_only.is_empty() { + text.push('\n'); + for flag in cli_only { + text.push_str(&format!( + "# set on the command line, no config key (pass again to reproduce): {flag}\n" + )); + } + } + Ok(text) +} diff --git a/crates/andes/src/sdrf.rs b/crates/andes/src/sdrf.rs index c3e6e652..dbaa832c 100644 --- a/crates/andes/src/sdrf.rs +++ b/crates/andes/src/sdrf.rs @@ -3,6 +3,8 @@ use std::path::{Path, PathBuf}; use model::activation::ActivationMethod; +use crate::param_sources::{ParamSources, Source}; + #[derive(Debug, Clone, PartialEq)] pub enum Quant { Lfq, @@ -663,31 +665,6 @@ fn dissociation_of(v: &str) -> Option { } } -#[derive(Debug, Default, Clone, Copy)] -pub struct ConfigKeys { - spectrum: bool, - enzyme: bool, - fixed_mods: bool, - variable_mods: bool, - precursor_tol: bool, - quant: bool, - xl: bool, -} - -impl ConfigKeys { - pub fn of(cfg: &crate::config::RunConfig) -> Self { - ConfigKeys { - spectrum: cfg.io.spectrum.is_some(), - enzyme: cfg.search.enzyme.is_some(), - fixed_mods: cfg.search.fixed_mods.is_some(), - variable_mods: cfg.search.variable_mods.is_some(), - precursor_tol: cfg.search.precursor_tol.is_some(), - quant: cfg.quant.tmt.is_some() || cfg.quant.lfq.is_some() || cfg.quant.label.is_some(), - xl: cfg.search.xl.is_some(), - } - } -} - /// Two crosslinker definitions that link the same way: equal once each end's residues are /// taken as a set (`TA=K,S` and `TA=S,K`). fn same_linker(a: &xl::crosslinker::Crosslinker, b: &xl::crosslinker::Crosslinker) -> bool { @@ -706,9 +683,11 @@ pub fn apply( s: &SdrfSettings, args: &mut crate::SearchArgs, m: &clap::ArgMatches, - cfg: ConfigKeys, + src: &mut ParamSources, ) -> Result, String> { - let cli = |id: &str| crate::config::cli_set(m, id); + let held = |src: &ParamSources, id: &str| { + crate::config::cli_set(m, id) || src.source(id) == Source::Config + }; let mut applied = Vec::new(); let mut kept = Vec::new(); let mut warnings = Vec::new(); @@ -720,7 +699,7 @@ pub fn apply( } }; - if cli("spectrum") || cfg.spectrum { + if held(src, "spectrum") { let sdrf_stems: BTreeSet<_> = s.data_files.iter().filter_map(|p| p.file_stem()).collect(); let extra: Vec = args .spectrum @@ -749,62 +728,70 @@ pub fn apply( )); } args.spectrum = s.data_files.clone(); + src.record_as("spectrum", Source::Sdrf, &s.data_files); applied.push(format!("{} data files", s.data_files.len())); } if let Some(e) = &s.enzyme { - if cli("enzyme") || cfg.enzyme { + if held(src, "enzyme") { kept.push("enzyme"); } else { args.db.enzyme = crate::cli::parse_enzyme_list(e)?; + src.record_as("enzyme", Source::Sdrf, e); applied.push(format!("enzyme {e}")); } } if let Some(t) = &s.precursor_tol { - if cli("precursor_tol") || cfg.precursor_tol { + if held(src, "precursor_tol") { kept.push("precursor_tol"); } else { args.precursor_tol = crate::parse_precursor_tol(t)?; + src.record_as("precursor_tol", Source::Sdrf, t); applied.push(format!("precursor tolerance {t}")); } } if let Some(f) = &s.fixed_mods { - if cli("fixed_mods") || cfg.fixed_mods { + if held(src, "fixed_mods") { kept.push("fixed_mods"); } else { args.db.fixed_mods = Some(crate::cli::parse_fixed_mods(&f.join(", "))?); + src.record_as("fixed_mods", Source::Sdrf, f); applied.push(format!("fixed mods {}", names(f))); } } if let Some(v) = &s.variable_mods { - if cli("variable_mods") || cfg.variable_mods { + if held(src, "variable_mods") { kept.push("variable_mods"); } else { args.db.variable_mods = Some(crate::cli::parse_variable_mods(&v.join(", "))?); + src.record_as("variable_mods", Source::Sdrf, v); applied.push(format!("variable mods {}", names(v))); } } if let Some(q) = &s.quant { - if cli("tmt") || cli("lfq") || cli("label") || cfg.quant { + if ["tmt", "lfq", "label"].iter().any(|&id| held(src, id)) { kept.push("quantification"); } else { match q { Quant::Lfq => { args.lfq = true; + src.record_as("lfq", Source::Sdrf, &true); applied.push("label-free quantification (--lfq)".into()); } Quant::Isobaric(p) => { args.tmt = Some(quant::Plex::parse(p)?); + src.record_as("tmt", Source::Sdrf, p); applied.push(format!("--tmt {p}")); } Quant::Label(spec) => { args.label = Some(spec.clone()); + src.record_as("label", Source::Sdrf, spec); applied.push(format!("--label {spec}")); } } } } if !s.xl.is_empty() { - if cli("xl") || cfg.xl { + if held(src, "xl") { kept.push("xl"); } else { let mut set: Vec = Vec::new(); @@ -830,6 +817,7 @@ pub fn apply( .collect(); applied.push(format!("crosslink search --xl {}", names.join("; "))); args.xl = Some(crate::cli::XlSet(set)); + src.record_without_value("xl", Source::Sdrf); } } args.sdrf_dissociation = s.dissociation; @@ -1367,13 +1355,12 @@ mod tests { .try_get_matches_from(base.iter().chain(extra)) .unwrap(); let mut a = crate::SearchArgs::from_arg_matches(&m).unwrap(); - let mut keys = ConfigKeys::default(); + let mut src = ParamSources::default(); if let Some(y) = yaml { let c = crate::config::RunConfig::from_yaml_str(y).unwrap(); - keys = ConfigKeys::of(&c); - crate::config::apply(c, &mut a, &m).unwrap(); + crate::config::apply(c, &mut a, &m, &mut src).unwrap(); } - apply(&s, &mut a, &m, keys).unwrap(); + apply(&s, &mut a, &m, &mut src).unwrap(); a }; let x = run(&[], None).xl.unwrap().0.remove(0); @@ -1410,7 +1397,7 @@ mod tests { ]; let m = crate::TopCli::command().try_get_matches_from(base).unwrap(); let mut a = crate::SearchArgs::from_arg_matches(&m).unwrap(); - apply(&s, &mut a, &m, ConfigKeys::default())?; + apply(&s, &mut a, &m, &mut ParamSources::default())?; Ok(a.xl.unwrap().0.into_iter().map(|x| x.name).collect()) }; assert_eq!( @@ -1443,7 +1430,7 @@ mod tests { ]; let m = crate::TopCli::command().try_get_matches_from(base).unwrap(); let mut a = crate::SearchArgs::from_arg_matches(&m).unwrap(); - let lines = apply(&s, &mut a, &m, ConfigKeys::default()).unwrap(); + let lines = apply(&s, &mut a, &m, &mut ParamSources::default()).unwrap(); assert!(!lines[0].contains("WARN"), "{lines:?}"); assert!( lines diff --git a/crates/andes/src/tests/params_render.rs b/crates/andes/src/tests/params_render.rs new file mode 100644 index 00000000..aa380d74 --- /dev/null +++ b/crates/andes/src/tests/params_render.rs @@ -0,0 +1,212 @@ +//! Keeps the generated files in step with the declaration: `config.example.yaml`, the DOCS.md +//! flag tables between their markers, and the `--print-config` text. + +use clap::CommandFactory; + +use crate::config::RunConfig; +use crate::param_sources::{ParamSources, Source}; +use crate::params::{Section, PARAMS}; +use crate::params_render::{config_example, docs_reference, effective_config}; + +const START: &str = ""; +const END: &str = ""; + +fn repo_file(name: &str) -> String { + format!("{}/../../{name}", env!("CARGO_MANIFEST_DIR")) +} + +/// The byte range of DOCS.md between the marker lines. +fn generated_span(docs: &str) -> (usize, usize) { + let start = docs.find(START).expect("DOCS.md has the start marker") + START.len() + 1; + let end = docs.find(END).expect("DOCS.md has the end marker"); + assert!(start <= end, "the start marker comes before the end marker"); + (start, end) +} + +/// Whether `text` names `flag` as a whole flag (`--xl` is not in `--xl-oracle`). +fn mentions(text: &str, flag: &str) -> bool { + text.match_indices(flag).any(|(i, _)| { + text[i + flag.len()..] + .chars() + .next() + .is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '-' || c == '_')) + }) +} + +#[test] +fn config_example_is_generated() { + let committed = std::fs::read_to_string(repo_file("config.example.yaml")) + .expect("read config.example.yaml") + .replace("\r\n", "\n"); + assert!( + committed == config_example(), + "config.example.yaml is out of date; run `cargo test -p andes write_config_example -- --ignored`" + ); +} + +#[test] +fn docs_reference_is_generated() { + let docs = std::fs::read_to_string(repo_file("DOCS.md")) + .expect("read DOCS.md") + .replace("\r\n", "\n"); + let (start, end) = generated_span(&docs); + assert!( + docs[start..end] == docs_reference(), + "DOCS.md flag tables are out of date; run `cargo test -p andes write_docs_reference -- --ignored`" + ); +} + +#[test] +fn generated_example_config_parses() { + RunConfig::from_yaml_str(&config_example()).expect("the generated example parses"); +} + +#[test] +fn internal_flags_are_not_advertised() { + let mut cmd = crate::TopCli::command(); + cmd.build(); + let example = config_example(); + let docs = docs_reference(); + let mut leaks = Vec::new(); + for arg in cmd.get_arguments().filter(|a| a.is_hide_set()) { + let Some(long) = arg.get_long() else { continue }; + let flag = format!("--{long}"); + if mentions(&example, &flag) || mentions(&docs, &flag) { + leaks.push(flag.clone()); + } + let key = PARAMS + .iter() + .find(|p| arg.get_id() == p.id && p.section != Section::CliOnly) + .map(|p| p.key); + if let Some(key) = key { + let written = example.lines().any(|l| { + let l = l.trim_start().trim_start_matches('#').trim_start(); + l.starts_with(&format!("{key}:")) + }); + if written { + leaks.push(format!("key {key} of {flag}")); + } + } + } + assert!(leaks.is_empty(), "hidden flags advertised: {leaks:?}"); +} + +#[test] +fn effective_config_parses() { + let text = effective_config(&ParamSources::default()).expect("printable"); + RunConfig::from_yaml_str(&text).expect("the default effective config parses"); +} + +#[test] +fn effective_config_names_sources() { + let mut sources = ParamSources::default(); + sources.record_as("psm_fdr", Source::CommandLine, &0.02); + sources.record_as("max_spectra", Source::Config, &5u64); + let text = effective_config(&sources).expect("printable"); + let line = |key: &str| text.lines().find(|l| l.trim_start().starts_with(key)); + assert!(line("psm_fdr: 0.02").is_some_and(|l| l.contains("# command line"))); + assert!(line("max_spectra: 5").is_some_and(|l| l.contains("# config"))); + assert!(line("# min_length: 6").is_some_and(|l| l.contains("# default"))); + assert!(line("# xl:").is_some_and(|l| l.contains("unset: off"))); + RunConfig::from_yaml_str(&text).expect("an effective config with set values parses"); +} + +#[test] +fn effective_config_leaves_defaults_unset() { + let mut sources = ParamSources::default(); + sources.record_as("top_n", Source::CommandLine, &7u64); + let text = effective_config(&sources).expect("printable"); + let cfg = RunConfig::from_yaml_str(&text).expect("parses"); + assert_eq!(cfg.search.max_missed_cleavages, None); + assert_eq!(cfg.search.top_n, Some(7)); +} + +#[test] +fn example_config_sets_only_the_paths() { + let cfg = RunConfig::from_yaml_str(&config_example()).expect("parses"); + assert_eq!(cfg.search.max_missed_cleavages, None); +} + +#[test] +fn effective_config_hides_internal_flags_until_set() { + let text = effective_config(&ParamSources::default()).expect("printable"); + assert!(!text.contains("max_spectra"), "internal key shown by default"); +} + +#[test] +fn printed_strings_read_back_unchanged() { + let texts = [ + "line\nbreak", + "tab\there", + "quote \" and \\ backslash", + "yes", + "- dash", + "#hash", + "colon: space", + "ünïcode", + "bell\u{7}", + "123", + "", + ]; + for text in texts { + let mut sources = ParamSources::default(); + sources.record_as("percolator_image", Source::CommandLine, text); + let printed = effective_config(&sources).expect("printable"); + let cfg = RunConfig::from_yaml_str(&printed) + .unwrap_or_else(|e| panic!("{text:?}: {e}\n{printed}")); + assert_eq!( + cfg.rescoring.percolator_image.as_deref(), + Some(text), + "{printed}" + ); + } +} + +#[test] +fn printed_config_closes_with_the_command_line_only_flags() { + let mut sources = ParamSources::default(); + sources.record_as("xl_oracle", Source::CommandLine, &5u64); + sources.record_as("ipf_debug", Source::CommandLine, &true); + sources.record_as("quiet", Source::CommandLine, &true); + let text = effective_config(&sources).expect("printable"); + let note = "# set on the command line, no config key (pass again to reproduce): "; + assert!(text.contains(&format!("{note}--xl-oracle 5\n")), "{text}"); + assert!(text.contains(&format!("{note}--ipf-debug\n")), "{text}"); + assert!(!text.contains("--quiet"), "{text}"); + RunConfig::from_yaml_str(&text).expect("the closing comments keep the YAML valid"); +} + +/// A value whose serialisation always fails, as a value YAML cannot hold. +struct Unwritable; + +impl serde::Serialize for Unwritable { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("no YAML form")) + } +} + +#[test] +fn a_value_without_config_form_refuses_to_print() { + let mut sources = ParamSources::default(); + sources.record_as("percolator_image", Source::CommandLine, &Unwritable); + assert_eq!(sources.source("percolator_image"), Source::CommandLine); + assert_eq!(sources.unwritable().len(), 1); + assert!(effective_config(&sources).is_err()); +} + +#[test] +#[ignore = "writes config.example.yaml; run on the build host and commit the file"] +fn write_config_example() { + std::fs::write(repo_file("config.example.yaml"), config_example()) + .expect("write config.example.yaml"); +} + +#[test] +#[ignore = "writes DOCS.md between its markers; run on the build host and commit the file"] +fn write_docs_reference() { + let path = repo_file("DOCS.md"); + let docs = std::fs::read_to_string(&path).expect("read DOCS.md"); + let (start, end) = generated_span(&docs); + let updated = format!("{}{}{}", &docs[..start], docs_reference(), &docs[end..]); + std::fs::write(&path, updated).expect("write DOCS.md"); +} diff --git a/crates/andes/src/tests/params_sources.rs b/crates/andes/src/tests/params_sources.rs new file mode 100644 index 00000000..8941132f --- /dev/null +++ b/crates/andes/src/tests/params_sources.rs @@ -0,0 +1,439 @@ +//! Tests that `ParamSources` records where each search setting came from, with the value as +//! written, through the same merge order the search command uses. + +use clap::{CommandFactory, FromArgMatches}; +use serde_yaml::Value; + +use crate::config::{apply, RunConfig}; +use crate::param_sources::{from_command_line, ParamSources, Source}; +use crate::params_render::effective_config; +use crate::sdrf::{self, SdrfSettings}; + +fn baseline_matches(extra: &[&str]) -> clap::ArgMatches { + let base = [ + "andes", + "--spectrum", + "x", + "--database", + "y", + "--output-pin", + "o", + ]; + crate::TopCli::command() + .try_get_matches_from(base.iter().chain(extra)) + .expect("parse args") +} + +/// The sources after the command line, the config text and an SDRF setting (when given) are +/// merged in the order of the search command. +fn merged(yaml: &str, extra: &[&str], sdrf: Option) -> ParamSources { + let m = baseline_matches(extra); + let mut a = crate::SearchArgs::from_arg_matches(&m).unwrap(); + let mut sources = from_command_line(&m); + let cfg = RunConfig::from_yaml_str(yaml).unwrap(); + apply(cfg, &mut a, &m, &mut sources).unwrap(); + if let Some(s) = sdrf { + sdrf::apply(&s, &mut a, &m, &mut sources).unwrap(); + } + sources +} + +fn text(v: &str) -> Value { + Value::String(v.to_string()) +} + +#[test] +fn command_line_value_is_recorded_as_command_line() { + let s = merged("{}", &["--precursor-tol", "10ppm"], None); + assert_eq!(s.source("precursor_tol"), Source::CommandLine); + assert_eq!(s.value("precursor_tol"), Some(&text("10ppm"))); +} + +#[test] +fn config_value_is_recorded_with_its_yaml_value() { + let s = merged("search:\n precursor_tol: 10ppm\n", &[], None); + assert_eq!(s.source("precursor_tol"), Source::Config); + assert_eq!(s.value("precursor_tol"), Some(&text("10ppm"))); +} + +#[test] +fn command_line_beats_config_in_sources() { + let s = merged( + "search:\n precursor_tol: 10ppm\n", + &["--precursor-tol", "5ppm"], + None, + ); + assert_eq!(s.source("precursor_tol"), Source::CommandLine); + assert_eq!(s.value("precursor_tol"), Some(&text("5ppm"))); +} + +#[test] +fn config_beats_sdrf_in_sources() { + let settings = SdrfSettings { + precursor_tol: Some("30ppm".to_string()), + enzyme: Some("trypsin".to_string()), + ..SdrfSettings::default() + }; + let s = merged("search:\n precursor_tol: 10ppm\n", &[], Some(settings)); + assert_eq!(s.source("precursor_tol"), Source::Config); + assert_eq!(s.value("precursor_tol"), Some(&text("10ppm"))); + assert_eq!(s.source("enzyme"), Source::Sdrf); + assert_eq!(s.value("enzyme"), Some(&text("trypsin"))); +} + +#[test] +fn untouched_flag_is_default() { + let s = merged("{}", &[], None); + assert_eq!(s.source("precursor_tol"), Source::Default); + assert_eq!(s.value("precursor_tol"), None); +} + +/// The YAML text `
:\n : ` that would set `id` to its recorded value. +fn config_text(id: &str, value: &Value) -> Option { + let p = crate::params::spec(id)?; + let mut inner = serde_yaml::Mapping::new(); + inner.insert(text(p.key), value.clone()); + let mut outer = serde_yaml::Mapping::new(); + outer.insert(text(p.section.yaml_name()?), Value::Mapping(inner)); + serde_yaml::to_string(&Value::Mapping(outer)).ok() +} + +#[test] +fn recorded_values_parse_as_config() { + let cases: [&[&str]; 4] = [ + &["--spectrum", "a.mzML"], + &["--spectrum", "a.mzML", "--spectrum", "b.mzML"], + &["--fixed-mods", "Carbamidomethyl (C)", "--lfq"], + &["--min-peaks", "10", "--tmt-min-purity", "0.5", "--precursor-tol", "20ppm"], + ]; + for args in cases { + let all: Vec<&str> = ["andes", "--database", "y", "--output-pin", "o"] + .into_iter() + .chain(args.iter().copied()) + .collect(); + let m = crate::TopCli::command().try_get_matches_from(all).unwrap(); + let sources = from_command_line(&m); + for p in crate::params::PARAMS { + let Some(value) = sources.value(p.id) else { + continue; + }; + let Some(yaml) = config_text(p.id, value) else { + continue; + }; + let cfg = RunConfig::from_yaml_str(&yaml) + .unwrap_or_else(|e| panic!("{} recorded as {yaml:?}: {e}", p.id)); + match p.id { + "spectrum" => { + let want: Vec = args + .iter() + .enumerate() + .filter(|(i, _)| *i > 0 && args[i - 1] == "--spectrum") + .map(|(_, a)| std::path::PathBuf::from(a)) + .collect(); + assert_eq!(cfg.io.spectrum, Some(want)); + } + "fixed_mods" => { + assert_eq!(cfg.search.fixed_mods, Some(vec![text("Carbamidomethyl (C)")])); + } + "lfq" => assert_eq!(cfg.quant.lfq, Some(true)), + "min_peaks" => assert_eq!(value, &Value::from(10)), + "tmt_min_purity" => assert_eq!(value, &Value::from(0.5)), + "precursor_tol" => assert_eq!(value, &text("20ppm")), + _ => {} + } + } + } +} + +/// Parameters whose sample cannot be given alone, with the reason; none today. +const EXEMPT: &[(&str, &str)] = &[]; + +/// Arguments a parameter's sample needs beside it (clap `requires`), in the sample run and in +/// the baseline it is replayed onto. +const COMPANIONS: &[(&str, &[&str])] = &[("xl_linear_only", &["--xl", "DSSO"])]; + +/// The arguments every sample run has, except the sampled flag itself. +const BASE: [(&str, &str); 3] = [ + ("--database", "y"), + ("--output-pin", "o"), + ("--spectrum", "x"), +]; + +fn flag_text(arg: &clap::Arg) -> Option { + arg.get_long().map(|l| format!("--{l}")) +} + +/// Values worth trying for an argument, most specific first: the row's example, defaults, the +/// listed possible +/// values (`false` before `true`), then a sample of the unit. +fn candidates(arg: &clap::Arg, unit: crate::params::Unit, example: Option<&str>) -> Vec { + let mut out: Vec = example.map(String::from).into_iter().collect(); + out.extend( + arg.get_default_values() + .iter() + .map(|v| v.to_string_lossy().into_owned()), + ); + let mut possible: Vec = arg + .get_possible_values() + .iter() + .map(|v| v.get_name().to_string()) + .collect(); + possible.sort_by_key(|v| v != "false"); + out.extend(possible); + out.push(crate::params_table::unit_sample(unit).to_string()); + out.extend(["x", "1", "0.5", "20ppm"].map(String::from)); + out +} + +fn takes_no_value(arg: &clap::Arg) -> bool { + arg.get_num_args().is_some_and(|n| n.max_values() == 0) +} + +/// The command line of a sample run without the sample: `andes`, the base arguments other than +/// `flag`, and the companions of `id`. +fn baseline_args(flag: &str, id: &str) -> Vec { + let mut all: Vec = vec!["andes".to_string()]; + for &(f, v) in BASE.iter().filter(|b| b.0 != flag) { + all.extend([f.to_string(), v.to_string()]); + } + if let Some((_, extra)) = COMPANIONS.iter().find(|c| c.0 == id) { + all.extend(extra.iter().map(|e| e.to_string())); + } + all +} + +/// The matches of the first sample of `p` that clap accepts, with the flag text. With +/// `changed_first` the candidates that differ from the clap default are tried first, so that a +/// replayed value has something to change. +fn sample( + cmd: &clap::Command, + p: &crate::params::ParamSpec, + changed_first: bool, +) -> Result<(clap::ArgMatches, String), String> { + let arg = cmd + .get_arguments() + .find(|a| a.get_id() == p.id) + .ok_or_else(|| format!("{}: no clap argument", p.id))?; + let flag = flag_text(arg).ok_or_else(|| format!("{}: no long flag", p.id))?; + let delimiter = arg.get_value_delimiter(); + let mut tried: Vec> = Vec::new(); + if takes_no_value(arg) { + tried.push(vec![flag.clone()]); + } else { + let mut pieces = candidates(arg, p.unit, p.example); + if changed_first { + let defaults: Vec = arg + .get_default_values() + .iter() + .map(|v| v.to_string_lossy().into_owned()) + .collect(); + pieces.sort_by_key(|piece| defaults.contains(piece)); + } + for (i, piece) in pieces.iter().enumerate() { + let value = match delimiter { + Some(d) => format!("{piece}{d}{}", pieces.get(i + 1).unwrap_or(piece)), + None => piece.clone(), + }; + tried.push(vec![flag.clone(), value]); + } + } + let mut last_error = String::new(); + for t in &tried { + let mut all = baseline_args(&flag, p.id); + all.extend(t.iter().cloned()); + match crate::TopCli::command().try_get_matches_from(all) { + Ok(m) => return Ok((m, flag)), + Err(e) => last_error = e.to_string(), + } + } + Err(format!("{}: no sample parses ({last_error})", p.id)) +} + +/// The rows the exhaustive tests cover: every config parameter not exempted. +fn sampled_rows() -> impl Iterator { + crate::params::PARAMS.iter().filter(|p| { + p.section != crate::params::Section::CliOnly && !EXEMPT.iter().any(|(id, _)| *id == p.id) + }) +} + +#[test] +fn every_cli_value_records_as_a_config_value() { + let mut cmd = crate::TopCli::command(); + cmd.build(); + let mut failures = Vec::new(); + for p in sampled_rows() { + let (m, _) = match sample(&cmd, p, false) { + Ok(s) => s, + Err(e) => { + failures.push(e); + continue; + } + }; + let delimited = cmd + .get_arguments() + .find(|a| a.get_id() == p.id) + .is_some_and(|a| a.get_value_delimiter().is_some()); + let sources = from_command_line(&m); + let Some(value) = sources.value(p.id) else { + failures.push(format!("{}: nothing recorded", p.id)); + continue; + }; + if delimited && !matches!(value, Value::Sequence(v) if v.len() == 2) { + failures.push(format!("{}: a delimited list recorded as {value:?}", p.id)); + } + let Some(yaml) = config_text(p.id, value) else { + failures.push(format!("{}: no config text", p.id)); + continue; + }; + if let Err(e) = RunConfig::from_yaml_str(&yaml) { + failures.push(format!("{}: recorded {yaml:?}: {e}", p.id)); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// Parameters whose settings cannot be compared through `Debug` after a replay, with the +/// reason; none today. +const REPLAY_EXEMPT: &[(&str, &str)] = &[]; + +/// The first lines where two pretty `Debug` dumps differ, for a readable failure. +fn first_differences(a: &str, b: &str) -> String { + let differing: Vec = a + .lines() + .zip(b.lines()) + .filter(|(x, y)| x != y) + .take(3) + .map(|(x, y)| format!(" command line: {}\n replayed: {}", x.trim(), y.trim())) + .collect(); + if differing.is_empty() { + " the dumps differ in length".to_string() + } else { + differing.join("\n") + } +} + +#[test] +fn every_cli_value_has_the_same_meaning_after_replay() { + let mut cmd = crate::TopCli::command(); + cmd.build(); + let mut failures = Vec::new(); + for p in sampled_rows().filter(|p| !REPLAY_EXEMPT.iter().any(|(id, _)| *id == p.id)) { + let (m, flag) = match sample(&cmd, p, true) { + Ok(s) => s, + Err(e) => { + failures.push(e); + continue; + } + }; + let direct = match crate::SearchArgs::from_arg_matches(&m) { + Ok(a) => a, + Err(e) => { + failures.push(format!("{}: {e}", p.id)); + continue; + } + }; + let sources = from_command_line(&m); + let Some(yaml) = sources.value(p.id).and_then(|v| config_text(p.id, v)) else { + failures.push(format!("{}: nothing recorded", p.id)); + continue; + }; + let base_args = baseline_args(&flag, p.id); + let baseline = match crate::TopCli::command().try_get_matches_from(base_args) { + Ok(m) => m, + Err(e) => { + failures.push(format!("{}: the baseline does not parse: {e}", p.id)); + continue; + } + }; + let replayed = crate::SearchArgs::from_arg_matches(&baseline) + .map_err(|e| e.to_string()) + .and_then(|mut a| { + let cfg = RunConfig::from_yaml_str(&yaml)?; + apply(cfg, &mut a, &baseline, &mut ParamSources::default())?; + Ok(a) + }); + let replayed = match replayed { + Ok(a) => a, + Err(e) => { + failures.push(format!("{}: replaying {yaml:?}: {e}", p.id)); + continue; + } + }; + let (a, b) = (format!("{direct:#?}"), format!("{replayed:#?}")); + if a != b { + failures.push(format!( + "{}: {flag} and the replayed {yaml:?} differ:\n{}", + p.id, + first_differences(&a, &b) + )); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// An SDRF of one label-free run: protease, a fixed and a variable modification, the +/// tolerances and the dissociation method. +const REPLAY_SDRF: &str = "source name\tcomment[data file]\tcomment[label]\t\ +comment[cleavage agent details]\tcomment[modification parameters]\t\ +comment[modification parameters]\tcomment[precursor mass tolerance]\t\ +comment[fragment mass tolerance]\tcomment[dissociation method]\n\ +s1\ta.raw\tlabel free sample\tNT=Trypsin;AC=MS:1001251\t\ +NT=Carbamidomethyl;AC=UNIMOD:4;TA=C;MT=Fixed;PP=Anywhere\t\ +NT=Phospho;TA=S,T,Y;MT=Variable;PP=Anywhere\t10 ppm\t0.02 Da\tNT=HCD;AC=PRIDE:0000590\n"; + +/// The settings of a search merged from `m`, the config text and the SDRF fixture, with their +/// sources, in the order of the search command. +fn merged_with_sdrf(m: &clap::ArgMatches, yaml: &str) -> (crate::SearchArgs, ParamSources) { + let settings = + sdrf::parse(REPLAY_SDRF, std::path::Path::new("/d")).expect("the SDRF fixture parses"); + let mut a = crate::SearchArgs::from_arg_matches(m).expect("search args"); + let mut sources = from_command_line(m); + let cfg = RunConfig::from_yaml_str(yaml).unwrap_or_else(|e| panic!("{e}\n{yaml}")); + apply(cfg, &mut a, m, &mut sources).expect("the config applies"); + sdrf::apply(&settings, &mut a, m, &mut sources).expect("the SDRF applies"); + (a, sources) +} + +#[test] +fn config_and_sdrf_replay_gives_the_same_settings() { + let m = baseline_matches(&[ + "--sdrf", + "design.sdrf.tsv", + "--precursor-tol", + "5ppm", + "--top-n", + "7", + "--xl", + "DSSO; DSBU", + ]); + let yaml = "search:\n max_missed_cleavages: 1\n enzyme: chymotrypsin\n\ + quant:\n lfq_rt_window: 90\n"; + let (first, sources) = merged_with_sdrf(&m, yaml); + let printed = effective_config(&sources).expect("printable"); + + let again_m = crate::TopCli::command() + .try_get_matches_from(["andes"]) + .expect("parse args"); + let (again, again_sources) = merged_with_sdrf(&again_m, &printed); + assert_eq!( + format!("{first:#?}"), + format!("{again:#?}"), + "the replay of this config differs:\n{printed}" + ); + for id in ["precursor_tol", "enzyme", "fixed_mods", "lfq", "xl"] { + assert_eq!( + again_sources.source(id), + Source::Config, + "{id} is read from the printed config" + ); + } +} + +#[test] +fn several_crosslinkers_record_as_a_list() { + let s = merged("{}", &["--xl", "DSSO; DSBU ;"], None); + assert_eq!( + s.value("xl"), + Some(&Value::Sequence(vec![text("DSSO"), text("DSBU")])) + ); +} diff --git a/crates/andes/src/tests/params_table.rs b/crates/andes/src/tests/params_table.rs new file mode 100644 index 00000000..5b1f50a7 --- /dev/null +++ b/crates/andes/src/tests/params_table.rs @@ -0,0 +1,243 @@ +//! Keeps the parameter table in `params.rs` consistent with the search command's clap +//! declaration and with the config file schema. + +use std::collections::BTreeSet; + +use clap::{Arg, ArgAction, CommandFactory}; + +use crate::config::RunConfig; +use crate::params::{spec, ParamSpec, Section, Unit, Unset, PARAMS}; + +fn search_command() -> clap::Command { + let mut cmd = crate::TopCli::command(); + cmd.build(); + cmd +} + +fn is_builtin(arg: &Arg) -> bool { + matches!(arg.get_id().as_str(), "help" | "version") +} + +fn cli_ids(cmd: &clap::Command) -> BTreeSet { + cmd.get_arguments() + .filter(|a| !is_builtin(a)) + .map(|a| a.get_id().to_string()) + .collect() +} + +fn yaml_scalar(v: &str) -> String { + if v.parse::().is_ok() || v == "true" || v == "false" { + v.to_string() + } else { + format!("\"{}\"", v.replace('"', "\\\"")) + } +} + +pub(crate) fn unit_sample(unit: Unit) -> &'static str { + match unit { + Unit::PpmOrDa => "20ppm", + Unit::Fraction => "0.5", + Unit::Path | Unit::None => "x", + Unit::Ppm + | Unit::Da + | Unit::Seconds + | Unit::Gb + | Unit::Count + | Unit::Number + | Unit::Charge => "1", + } +} + +fn config_value(arg: &Arg, p: &ParamSpec) -> String { + if matches!(p.id, "fixed_mods" | "variable_mods") { + return "[\"Oxidation (M)\"]".to_string(); + } + let action = arg.get_action(); + if matches!(action, ArgAction::SetTrue) { + return "true".to_string(); + } + let defaults: Vec = arg + .get_default_values() + .iter() + .map(|v| yaml_scalar(&v.to_string_lossy())) + .collect(); + let scalar = defaults + .first() + .cloned() + .unwrap_or_else(|| unit_sample(p.unit).to_string()); + if matches!(action, ArgAction::Append) { + let items = if defaults.is_empty() { + scalar + } else { + defaults.join(", ") + }; + return format!("[{items}]"); + } + scalar +} + +#[test] +fn every_search_arg_has_one_param_row() { + let cmd = search_command(); + let cli = cli_ids(&cmd); + let mut rows = BTreeSet::new(); + let mut duplicated = Vec::new(); + for p in PARAMS { + if !rows.insert(p.id.to_string()) { + duplicated.push(p.id); + } + } + let without_row: Vec<&String> = cli.difference(&rows).collect(); + let without_arg: Vec<&String> = rows.difference(&cli).collect(); + assert!( + duplicated.is_empty() && without_row.is_empty() && without_arg.is_empty(), + "params.rs and the CLI disagree\n arguments with no row: {without_row:?}\n \ + rows with no argument: {without_arg:?}\n ids with two rows: {duplicated:?}" + ); +} + +#[test] +fn every_config_key_parses() { + let cmd = search_command(); + let mut failures = Vec::new(); + for p in PARAMS.iter().filter(|p| p.section != Section::CliOnly) { + let Some(arg) = cmd.get_arguments().find(|a| a.get_id().as_str() == p.id) else { + failures.push(format!("{}: no such argument", p.id)); + continue; + }; + let Some(section) = p.section.yaml_name() else { + continue; + }; + let yaml = format!("{section}:\n {}: {}\n", p.key, config_value(arg, p)); + if let Err(e) = RunConfig::from_yaml_str(&yaml) { + failures.push(format!("{}: {e} in {yaml:?}", p.id)); + } + } + assert!( + failures.is_empty(), + "config keys that do not parse:\n{}", + failures.join("\n") + ); +} + +#[test] +fn every_search_arg_is_documented() { + let cmd = search_command(); + let mut problems = Vec::new(); + for arg in cmd.get_arguments().filter(|a| !is_builtin(a)) { + let id = arg.get_id().as_str(); + let help = arg.get_help().map(|h| h.to_string()).unwrap_or_default(); + let long = arg + .get_long_help() + .map(|h| h.to_string()) + .unwrap_or_default(); + if help.trim().is_empty() && long.trim().is_empty() { + problems.push(format!("{id}: no help text")); + } + let has_default = !arg.get_default_values().is_empty(); + let unset = spec(id).map(|p| p.unset); + if !has_default && unset == Some(Unset::ClapDefault) { + problems.push(format!( + "{id}: no clap default, so its row needs Auto, Off or Required" + )); + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); +} + +#[test] +fn units_match_flag_names() { + for p in PARAMS { + let expected = if p.id.ends_with("_ppm") { + Some(Unit::Ppm) + } else if p.id.ends_with("_da") { + Some(Unit::Da) + } else if p.id.ends_with("_gb") { + Some(Unit::Gb) + } else { + None + }; + if let Some(unit) = expected { + assert_eq!(p.unit, unit, "{}: the id names its unit", p.id); + } + } +} + +#[test] +fn cli_only_matches_config_mapping() { + let mut keys = BTreeSet::new(); + for p in PARAMS { + match p.section.yaml_name() { + None => assert_eq!(p.key, p.id, "{}: a CLI-only row keeps its id as key", p.id), + Some(section) => assert!( + keys.insert((section, p.key)), + "{}: config key {section}.{} is used by two rows", + p.id, + p.key + ), + } + } + let cli_only: Vec<&str> = PARAMS + .iter() + .filter(|p| p.section == Section::CliOnly) + .map(|p| p.id) + .collect(); + assert!( + cli_only.contains(&"config") && cli_only.contains(&"quiet"), + "CliOnly rows: {cli_only:?}" + ); +} + +/// The value a help text states as `[default: X]`, whitespace collapsed. +fn stated_default(help: &str) -> Option { + let text = help.split_whitespace().collect::>().join(" "); + let start = text.find("[default: ")? + "[default: ".len(); + let end = text[start..].find(']')? + start; + Some(text[start..end].to_string()) +} + +#[test] +fn help_defaults_match_the_table() { + let cmd = search_command(); + let mut mismatches = Vec::new(); + for p in PARAMS { + let Unset::Auto(phrase) = p.unset else { + continue; + }; + let Some(arg) = cmd.get_arguments().find(|a| a.get_id().as_str() == p.id) else { + continue; + }; + let help = format!( + "{} {}", + arg.get_help().map(|h| h.to_string()).unwrap_or_default(), + arg.get_long_help().map(|h| h.to_string()).unwrap_or_default() + ); + if let Some(stated) = stated_default(&help) { + if stated != phrase { + mismatches.push(format!("{}: --help says {stated:?}, the table {phrase:?}", p.id)); + } + } + } + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn possible_values_come_from_clap() { + let cmd = search_command(); + let mut problems = Vec::new(); + for p in PARAMS { + if p.range == Some("enum") { + problems.push(format!("{}: the range is the placeholder \"enum\"", p.id)); + } + let Some(arg) = cmd.get_arguments().find(|a| a.get_id().as_str() == p.id) else { + continue; + }; + if !arg.get_possible_values().is_empty() && p.range.is_some() { + problems.push(format!( + "{}: clap lists the possible values, so the row's range {:?} repeats them", + p.id, p.range + )); + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); +} diff --git a/crates/andes/tests/print_config.rs b/crates/andes/tests/print_config.rs new file mode 100644 index 00000000..106fbb2b --- /dev/null +++ b/crates/andes/tests/print_config.rs @@ -0,0 +1,282 @@ +//! `--print-config` end to end: the printed config parses, names each value's source, keeps +//! defaults and internal flags out, round-trips lists, modifications, crosslinkers and odd +//! paths, lists the command-line-only flags it cannot hold, and reproduces the run's PIN byte +//! for byte when replayed with `--config`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const SPECTRUM: &str = "test-fixtures/test.mgf.gz"; +const DATABASE: &str = "test-fixtures/BSA.fasta"; + +fn fixture(rel: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../..") + .join(rel) + .canonicalize() + .unwrap_or_else(|e| panic!("canonicalize {rel}: {e}")) +} + +fn andes(args: &[&std::ffi::OsStr]) -> Output { + Command::new(env!("CARGO_BIN_EXE_andes")) + .args(args) + .output() + .expect("run andes") +} + +fn os(s: &str) -> &std::ffi::OsStr { + std::ffi::OsStr::new(s) +} + +fn printed(args: &[&std::ffi::OsStr]) -> String { + let mut all: Vec<&std::ffi::OsStr> = args.to_vec(); + all.push(os("--print-config")); + all.push(os("-")); + let out = andes(&all); + assert!( + out.status.success(), + "print-config failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).expect("utf-8 config") +} + +fn parse(text: &str) -> serde_yaml::Value { + serde_yaml::from_str(text).unwrap_or_else(|e| panic!("printed config is not YAML: {e}\n{text}")) +} + +fn key_line<'a>(text: &'a str, key: &str) -> Option<&'a str> { + let prefix = format!("{key}:"); + text.lines().find(|l| l.trim_start().starts_with(&prefix)) +} + +const NON_DEFAULT: [&str; 6] = [ + "--precursor-tol", + "10ppm", + "--max-missed-cleavages", + "1", + "--fixed-mods", + "Carbamidomethyl (C)", +]; + +#[test] +fn printed_config_reproduces_the_run() { + let dir = tempfile::tempdir().expect("tempdir"); + let pin_direct = dir.path().join("direct.pin"); + let pin_replay = dir.path().join("replay.pin"); + let printed_path = dir.path().join("printed.yaml"); + let spectrum = fixture(SPECTRUM); + let database = fixture(DATABASE); + + let common = |pin: &Path| -> Vec { + let mut v: Vec = vec![ + "--spectrum".into(), + spectrum.clone().into(), + "--database".into(), + database.clone().into(), + "--output-pin".into(), + pin.into(), + ]; + v.extend(NON_DEFAULT.iter().map(std::ffi::OsString::from)); + v + }; + + let direct = common(&pin_direct); + let direct_refs: Vec<&std::ffi::OsStr> = direct.iter().map(|s| s.as_os_str()).collect(); + let out = andes(&direct_refs); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + + let mut print = common(&pin_replay); + print.push("--print-config".into()); + print.push(printed_path.clone().into()); + let print_refs: Vec<&std::ffi::OsStr> = print.iter().map(|s| s.as_os_str()).collect(); + let out = andes(&print_refs); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(!pin_replay.exists(), "--print-config must not search"); + assert!(printed_path.exists(), "config not written"); + + let out = andes(&[os("--config"), printed_path.as_os_str()]); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + + let a = std::fs::read(&pin_direct).expect("direct pin"); + let b = std::fs::read(&pin_replay).expect("replayed pin"); + assert!(a.len() > 100, "PIN looks empty"); + assert!(a == b, "the replayed PIN differs from the direct run's PIN"); +} + +#[test] +fn print_config_round_trips_lists_and_mods() { + let dir = tempfile::tempdir().expect("tempdir"); + let first = fixture(SPECTRUM); + let second = dir.path().join("second.mgf.gz"); + std::fs::copy(&first, &second).expect("copy spectrum"); + let database = fixture(DATABASE); + let pin = dir.path().join("out.pin"); + let args = [ + os("--spectrum"), + first.as_os_str(), + os("--spectrum"), + second.as_os_str(), + os("--database"), + database.as_os_str(), + os("--output-pin"), + pin.as_os_str(), + os("--fixed-mods"), + os("Carbamidomethyl (C), TMT6plex (K)"), + os("--variable-mods"), + os("Oxidation (M), Phospho (STY)"), + ]; + let text = printed(&args); + let doc = parse(&text); + + let spectra = doc["io"]["spectrum"].as_sequence().expect("spectrum list"); + let got: Vec<&str> = spectra.iter().filter_map(|v| v.as_str()).collect(); + assert_eq!( + got, + vec![first.to_str().expect("utf-8"), second.to_str().expect("utf-8")] + ); + for (key, name) in [("fixed_mods", "Carbamidomethyl"), ("variable_mods", "Oxidation")] { + let items = doc["search"][key].as_sequence().expect(key); + assert_eq!(items.len(), 2, "{key}: {text}"); + let first_item = serde_yaml::to_string(&items[0]).expect("yaml"); + assert!(first_item.contains(name), "{key}[0] = {first_item}"); + } + + let cfg = dir.path().join("printed.yaml"); + std::fs::write(&cfg, &text).expect("write config"); + let again = parse(&printed(&[os("--config"), cfg.as_os_str()])); + assert_eq!(doc["io"], again["io"]); + assert_eq!(doc["search"], again["search"]); +} + +#[test] +fn print_config_quotes_paths() { + let dir = tempfile::tempdir().expect("tempdir"); + let odd = dir.path().join("my db: v1.fasta"); + std::fs::copy(fixture(DATABASE), &odd).expect("copy database"); + let spectrum = fixture(SPECTRUM); + let pin = dir.path().join("out.pin"); + let text = printed(&[ + os("--spectrum"), + spectrum.as_os_str(), + os("--database"), + odd.as_os_str(), + os("--output-pin"), + pin.as_os_str(), + ]); + let doc = parse(&text); + assert_eq!(doc["io"]["database"].as_str(), odd.to_str()); + + let cfg = dir.path().join("printed.yaml"); + std::fs::write(&cfg, &text).expect("write config"); + let again = parse(&printed(&[os("--config"), cfg.as_os_str()])); + assert_eq!(again["io"]["database"].as_str(), odd.to_str()); +} + +#[test] +fn print_config_omits_default_internal_flags() { + let dir = tempfile::tempdir().expect("tempdir"); + let spectrum = fixture(SPECTRUM); + let database = fixture(DATABASE); + let pin = dir.path().join("out.pin"); + let base = [ + os("--spectrum"), + spectrum.as_os_str(), + os("--database"), + database.as_os_str(), + os("--output-pin"), + pin.as_os_str(), + ]; + let text = printed(&base); + for key in ["optimize_sample", "max_spectra", "seed"] { + assert!(key_line(&text, key).is_none(), "{key} printed:\n{text}"); + } + assert!(!text.contains("print_config")); + let doc = parse(&text); + assert!(doc["io"]["config"].is_null() && doc["io"]["print_config"].is_null()); + assert!(doc["config"].is_null()); + + let mut set = base.to_vec(); + set.push(os("--max-spectra")); + set.push(os("100")); + let text = printed(&set); + let line = key_line(&text, "max_spectra").expect("max_spectra printed once set"); + assert!(!line.trim_start().starts_with('#'), "{line}"); +} + +#[test] +fn print_config_names_sources() { + let dir = tempfile::tempdir().expect("tempdir"); + let cfg = dir.path().join("in.yaml"); + std::fs::write(&cfg, "search:\n max_missed_cleavages: 2\n").expect("write config"); + let spectrum = fixture(SPECTRUM); + let database = fixture(DATABASE); + let pin = dir.path().join("out.pin"); + let text = printed(&[ + os("--config"), + cfg.as_os_str(), + os("--spectrum"), + spectrum.as_os_str(), + os("--database"), + database.as_os_str(), + os("--output-pin"), + pin.as_os_str(), + os("--precursor-tol"), + os("10ppm"), + ]); + let line = key_line(&text, "max_missed_cleavages").expect("config key"); + assert!(!line.trim_start().starts_with('#') && line.trim_end().ends_with("# config"), "{line}"); + let line = key_line(&text, "precursor_tol").expect("cli key"); + assert!( + !line.trim_start().starts_with('#') && line.trim_end().ends_with("# command line"), + "{line}" + ); + assert!(!text.contains("print_config")); +} + +#[test] +fn print_config_lists_command_line_only_flags() { + let dir = tempfile::tempdir().expect("tempdir"); + let spectrum = fixture(SPECTRUM); + let database = fixture(DATABASE); + let pin = dir.path().join("out.pin"); + let mut args = vec![ + os("--spectrum"), + spectrum.as_os_str(), + os("--database"), + database.as_os_str(), + os("--output-pin"), + pin.as_os_str(), + os("--xl"), + os("DSSO; DSBU"), + os("--xl-linear-only"), + os("--xl-oracle"), + os("5"), + ]; + let text = printed(&args); + let note = "# set on the command line, no config key (pass again to reproduce): "; + assert!(text.contains(&format!("{note}--xl-oracle 5")), "{text}"); + let doc = parse(&text); + assert_eq!(doc["search"]["xl_linear_only"].as_bool(), Some(true), "{text}"); + let linkers: Vec<&str> = doc["search"]["xl"] + .as_sequence() + .expect("xl list") + .iter() + .filter_map(|v| v.as_str()) + .collect(); + assert_eq!(linkers, vec!["DSSO", "DSBU"], "{text}"); + + args.push(os("--print-config")); + args.push(os("-")); + let out = andes(&args); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("--xl-oracle 5") && stderr.contains("no config key"), + "no warning naming the flag: {stderr}" + ); + + let cfg = dir.path().join("printed.yaml"); + std::fs::write(&cfg, &text).expect("write config"); + let again = parse(&printed(&[os("--config"), cfg.as_os_str()])); + assert_eq!(doc["search"], again["search"]); +} diff --git a/crates/andes/tests/ratchets/file_lines.tsv b/crates/andes/tests/ratchets/file_lines.tsv index 8120fc83..1fd085e5 100644 --- a/crates/andes/tests/ratchets/file_lines.tsv +++ b/crates/andes/tests/ratchets/file_lines.tsv @@ -15,8 +15,7 @@ crates/andes/src/bin/andes/quant_run/label_run.rs 1998 crates/andes/src/bin/andes/search.rs 2704 crates/andes/src/bin/andes/search/resolve.rs 2062 crates/andes/src/bin/andes/train.rs 1748 -crates/andes/src/config.rs 1585 -crates/andes/src/sdrf.rs 1604 +crates/andes/src/sdrf.rs 1591 crates/andes/src/transfer_fdr.rs 1846 crates/input/src/mzml.rs 4146 crates/input/src/uniprot.rs 1756