Skip to content

[FEAT] ThermoRawFile: extract full mzML metadata + fix polarity - #9623

Merged
timosachsenberg merged 1 commit into
OpenMS:developfrom
timosachsenberg:thermo-raw-metadata
Jun 18, 2026
Merged

timosachsenberg merged 1 commit into
OpenMS:developfrom
timosachsenberg:thermo-raw-metadata

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

What

Extends the in-process Thermo RAW reader (ThermoRawFile, the WITH_THERMO_RAW path) to populate the MSExperiment with the metadata msconvert/ProteoWizard writes, all mapped to their PSI-MS CV terms so it round-trips to mzML identically to how OpenMS reads an msconvert file:

  • Per spectrum: total ion current (MS:1000285), base peak m/z + intensity (MS:1000504/505), lowest/highest observed m/z (MS:1000528/527), scan filter string, scan window (parsed from the filter), ion injection time (stored on an Acquisition so it serializes as MS:1000927 under <scan>), and FAIMS compensation voltage (setDriftTime + DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE → MS:1001581).
  • Instrument: ion source, mass analyzer(s), ion detector(s) (detector derived from analyzer type), software version.
  • Experiment: creation date, sample name.
  • A total ion current chromatogram.

Bug fix: spectrum polarity

The bridge's polarity() returns the raw Thermo PolarityType enum — Negative=0, Positive=1, Any=2 — which is the opposite of what the bridge's own header comment and cv_polarity() helper claim. The previous mapping (1→POSITIVE, 2→NEGATIVE) mislabeled negative/any scans. Verified empirically: all 1775 positive-mode scans of the test file return 1.

Activation methods are now mapped independently of collision energy (so zero-CE ETD scans keep their method), and PQD was added.

Validation

Built with the real .NET 8 managed bridge (no stubs) and ran ThermoRawFile_test against the real Angiotensin_AllScans.raw (1775 scans, positive ESI, FTMS/Orbitrap, HCD/ETD): passes, including new assertions for every field above and their mzML round-trip. mzML serialization of each CV param was separately verified.

Notes

  • Only affects the WITH_THERMO_RAW build; the default build is unchanged.
  • OpenMS represents a single Instrument per experiment, so Thermo's multiple instrument configurations (e.g. FTMS + ion trap) collapse into one component list (union of analyzers); per-spectrum instrumentConfigurationRef is not representable.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced Thermo RAW file metadata extraction including instrument configuration, scan filter parsing, and expanded spectrum metadata collection.
    • Improved total ion current chromatogram generation from raw file data.
  • Bug Fixes

    • Corrected polarity detection and precursor activation method mapping in mass spectrometry processing.
    • Enhanced metadata retention during mzML format conversions.
  • Tests

    • Added comprehensive test coverage for instrument metadata extraction and round-trip file format conversion validation.

Extend the in-process Thermo RAW reader to populate the MSExperiment with the
metadata msconvert/ProteoWizard writes, all mapped to their PSI-MS CV terms:

- per spectrum: total ion current, base peak m/z + intensity, lowest/highest
  observed m/z, scan filter string, scan window (parsed from the filter),
  ion injection time (stored on an Acquisition so it serializes as MS:1000927
  under <scan>), and FAIMS compensation voltage (driftTime +
  FAIMS_COMPENSATION_VOLTAGE)
- instrument: ion source, mass analyzer(s), ion detector(s), software version
- experiment: creation date, sample name
- a total ion current chromatogram

Fix the spectrum polarity mapping: the bridge returns the raw Thermo
PolarityType enum (Negative=0, Positive=1, Any=2); the previous mapping
(1->POSITIVE, 2->NEGATIVE) mislabeled negative/any scans. Verified empirically
against real RAW data.

Also map activation independently of collision energy (so zero-CE ETD scans
keep their activation method) and add PQD.

Extend ThermoRawFile_test with assertions covering the new metadata and its
mzML round-trip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

ThermoRawFile.cpp gains anonymous-namespace helpers for case-insensitive matching, strict numeric parsing, trailer-extra lookup, and Thermo→OpenMS analyzer/ionization/detector mapping. ThermoRawFile::load is expanded to populate instrument/sample-level metadata, richer per-scan metadata (polarity, filter string, scan window, scan statistics, injection time, FAIMS CV), fixed MSn activation mapping, m/z range meta, consolidated instrument components, and a TIC chromatogram. Tests validate metadata survival across a raw→mzML→reload round-trip.

Changes

ThermoRawFile metadata enrichment and TIC chromatogram

Layer / File(s) Summary
Anonymous-namespace helper utilities
src/openms/source/FORMAT/ThermoRawFile.cpp
Adds includes and helper functions: case-insensitive substring search, strict double parsing, trailer-extra label/value extraction, Thermo analyzer string→OpenMS enum, ionization mode string→OpenMS enum, analyzer→detector inference, and scan-window extraction from a bracketed filter string.
Instrument/sample-level metadata and per-file accumulators
src/openms/source/FORMAT/ThermoRawFile.cpp
Reworks pre-scan metadata population to fill instrument model/name/serial, software version, sample name, creation date, and file description from bridge accessors; introduces per-file analyzer-string set and ionization mode string for later instrument-component construction.
Per-scan metadata expansion
src/openms/source/FORMAT/ThermoRawFile.cpp
Updates polarity mapping; stores filter string and parses a ScanWindow; accumulates analyzer/ionization strings; records total ion current, base peak m/z, base peak intensity; parses trailer-extra injection time into Acquisition meta and FAIMS CV into drift-time.
MSn activation, m/z range meta, instrument config, and TIC chromatogram
src/openms/source/FORMAT/ThermoRawFile.cpp
Fixes activation method selection to use activation type string alone with CID fallback; tracks lowest/highest observed m/z per spectrum; builds consolidated InstrumentConfiguration from accumulated analyzer/ionization data; emits a TIC MSChromatogram.
Round-trip test coverage
src/tests/class_tests/openms/source/ThermoRawFile_test.cpp
Adds MSChromatogram.h include and asserts instrument metadata (analyzers, ion sources, detectors, software version, ORBITRAP presence), per-spectrum fields (filter string, scan statistics, scan windows, injection time), and TIC chromatogram presence and metadata survival after mzML round-trip.

Poem

A rabbit hops through raw Thermo files with glee,
Sniffing out filter strings and FAIMS CV,
The TIC chromatogram blooms from the bridge,
Injection times logged along every ridge.
Orbitrap mapped, polarity set just right—
Round-trip metadata shines bright! 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: extracting full mzML metadata and fixing the polarity mapping bug in ThermoRawFile, which aligns with the primary objectives.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@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/FORMAT/ThermoRawFile.cpp (1)

56-72: 💤 Low value

Consider using OpenMS::String for locale-independent parsing.

std::stod respects the current C locale, so on systems where the decimal separator is comma (e.g., German locale), strings like "12.34" may parse incorrectly. OpenMS::String::toDouble() is locale-independent.

♻️ Suggested change
     bool parseDouble(const std::string& s, double& out)
     {
       if (s.empty()) { return false; }
       try
       {
-        size_t pos = 0;
-        out = std::stod(s, &pos);
-        // Reject trailing garbage (e.g. "12.3abc") but tolerate surrounding whitespace.
-        while (pos < s.size() && std::isspace(static_cast<unsigned char>(s[pos]))) { ++pos; }
-        return pos == s.size();
+        out = OpenMS::String(s).trim().toDouble();
+        return true;
       }
-      catch (...)
+      catch (const Exception::ConversionError&)
       {
         return false;
       }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/openms/source/FORMAT/ThermoRawFile.cpp` around lines 56 - 72, The
parseDouble function uses std::stod for parsing doubles, which is
locale-dependent and will fail in locales where the decimal separator is comma
instead of dot (e.g., German locale). Replace the std::stod call in the
parseDouble function with OpenMS::String::toDouble(), which is
locale-independent and will correctly parse double values regardless of the
system locale setting.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tests/class_tests/openms/source/ThermoRawFile_test.cpp`:
- Around line 143-144: The test currently validates the TIC type for the
reloaded object only but does not explicitly validate the TIC type for the
original object. After the TEST_EQUAL statement that checks if
original.getChromatograms() is not empty, add a type-specific assertion that
validates the TIC type of the original object (mirroring the validation already
in place for reloaded) to ensure the extraction contract is explicitly tested
for both the original and reloaded chromatogram objects.

---

Nitpick comments:
In `@src/openms/source/FORMAT/ThermoRawFile.cpp`:
- Around line 56-72: The parseDouble function uses std::stod for parsing
doubles, which is locale-dependent and will fail in locales where the decimal
separator is comma instead of dot (e.g., German locale). Replace the std::stod
call in the parseDouble function with OpenMS::String::toDouble(), which is
locale-independent and will correctly parse double values regardless of the
system locale setting.
🪄 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: 05348132-5230-4329-91e2-3c2e28030d17

📥 Commits

Reviewing files that changed from the base of the PR and between 4df7c64 and 866e971.

📒 Files selected for processing (2)
  • src/openms/source/FORMAT/ThermoRawFile.cpp
  • src/tests/class_tests/openms/source/ThermoRawFile_test.cpp

Comment on lines +143 to +144
TEST_EQUAL(original.getChromatograms().empty(), false)
TEST_EQUAL(reloaded.getChromatograms().empty(), false)

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 | ⚡ Quick win

Assert TIC type in original, not only non-empty chromatograms.

This currently validates TIC type for reloaded only. Add a type-specific assertion for original as well so the extraction contract is explicitly covered.

Suggested test tightening
-  TEST_EQUAL(original.getChromatograms().empty(), false)
-  TEST_EQUAL(reloaded.getChromatograms().empty(), false)
+  TEST_EQUAL(original.getChromatograms().empty(), false)
+  TEST_EQUAL(reloaded.getChromatograms().empty(), false)
+  bool original_has_tic = false;
+  for (const MSChromatogram& c : original.getChromatograms())
+  {
+    if (c.getChromatogramType() == ChromatogramSettings::ChromatogramType::TOTAL_ION_CURRENT_CHROMATOGRAM)
+    {
+      original_has_tic = true;
+    }
+  }
+  TEST_EQUAL(original_has_tic, true)
   bool reloaded_has_tic = false;
   for (const MSChromatogram& c : reloaded.getChromatograms())
   {
     if (c.getChromatogramType() == ChromatogramSettings::ChromatogramType::TOTAL_ION_CURRENT_CHROMATOGRAM)
     {
       reloaded_has_tic = true;
     }
   }
   TEST_EQUAL(reloaded_has_tic, true)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/class_tests/openms/source/ThermoRawFile_test.cpp` around lines 143
- 144, The test currently validates the TIC type for the reloaded object only
but does not explicitly validate the TIC type for the original object. After the
TEST_EQUAL statement that checks if original.getChromatograms() is not empty,
add a type-specific assertion that validates the TIC type of the original object
(mirroring the validation already in place for reloaded) to ensure the
extraction contract is explicitly tested for both the original and reloaded
chromatogram objects.

@timosachsenberg
timosachsenberg merged commit 283e61d into OpenMS:develop Jun 18, 2026
41 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 19, 2026
timosachsenberg added a commit that referenced this pull request Jun 19, 2026
Add entries for all substantive non-test PRs merged since the last
changelog update:

- #9623 ThermoRawFile full mzML metadata extraction + polarity fix
- #9602 New FileInfo library class usable from C++ and pyOpenMS
- #9521 IMAGING multi-region support (add missing PR reference)
- #9620 Deisotoper::isToleranceSupported + ProSE/SSE crash fix on low-res data
- #9610 DistanceMatrix::setValue cached-minimum guard fix
- #9497 DistanceMatrix::operator==, ClusteringGrid, File path guard fixes
- #9583 LogStreamBuf thread-safety fix
- #9514 CI Windows migration to Visual Studio 2026


Claude-Session: https://claude.ai/code/session_01YLg6pWyjyTxpWAU6mgrDzC

Co-authored-by: Claude <[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.

1 participant