Skip to content

feature: split experiments by FAIMS CV - #7851

Merged
timosachsenberg merged 5 commits into
developfrom
split_FAIMS_CV
Sep 26, 2025
Merged

timosachsenberg merged 5 commits into
developfrom
split_FAIMS_CV

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Feb 24, 2025 •

Copy link
Copy Markdown
Contributor

Description

Add splitting by FAIMS CV to IonMobilityBinning.

Questions to @cbielow

  • do MS2 have FAIMS CVs annotated? if not how to keep them?
  • currently using getCompensationVoltages to determine the set of discrete FAIMS CVs is the same as splitByFAIMSCV. But this is potentially not safe for the future.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

Click to expand
  • /reformat (experimental) applies the clang-format style changes as additional commit. Note: your branch must have a different name (e.g., yourrepo:feature/XYZ) than the receiving branch (e.g., OpenMS:develop). Otherwise, reformat fails to push.
  • setting the label "NoJenkins" will skip tests for this PR on jenkins (saves resources e.g., on edits that do not affect tests)
  • commenting with rebuild jenkins will retrigger Jenkins-based CI builds

⚠️ Note: Once you opened a PR try to minimize the number of pushes to it as every push will trigger CI (automated builds and test) and is rather heavy on our infrastructure (e.g., if several pushes per day are performed).

Summary by CodeRabbit

  • New Features
    • Ion Mobility Binning now auto-detects FAIMS datasets, splits data by compensation voltage, and writes separate mzML outputs per CV; falls back to regular IM binning when FAIMS is absent.
  • Bug Fixes
    • Improved handling of invalid or missing FAIMS entries and corrected bin counts across FAIMS vs regular IM modes.
  • Documentation
    • Updated usage notes to describe Regular IM vs FAIMS modes and output naming.
  • Tests
    • Added tests covering FAIMS CV detection, splitting behavior, and missing-FAIMS error handling.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

@cbielow, do you know the current status of a “split, process, and merge” workflow for FAIMS and IM data in OpenMS?

I think official support for such a workflow would be really helpful. However, I'm not entirely sure whether we can already:

  • Split an MSExperiment by FAIMS CV and later merge it back while preserving the original acquisition order (i.e., keeping all MS levels intact, both with and without FAIMS CV).
  • Merge result files (e.g., featureXML, idXML) correctly so that we end up with a single, consistent ProteinIdentification run.

Could you shed some light on whether this is currently feasible or if there are any known workarounds?

@cbielow

cbielow commented Feb 28, 2025

Copy link
Copy Markdown
Contributor

@cbielow, do you know the current status of a “split, process, and merge” workflow for FAIMS and IM data in OpenMS?

I think official support for such a workflow would be really helpful. However, I'm not entirely sure whether we can already:

* Split an MSExperiment by FAIMS CV and later merge it back while preserving the original acquisition order (i.e., keeping all MS levels intact, both with and without FAIMS CV).

* Merge result files (e.g., featureXML, idXML) correctly so that we end up with a single, consistent ProteinIdentification run.

Could you shed some light on whether this is currently feasible or if there are any known workarounds?

splitByFAIMSCV was not used anywhere (except for tests), so was not exposed, until this PR.
I don't think we have a working prototype workflow for this, even though it should not be hard to craft.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

What do we need to support?

  • Split MSExperiment to run e.g. feature finders? while passing e.g. original file into search engine?
    Is probably the most common one?

@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds FAIMS-aware processing to IonMobilityBinning: detects FAIMS CVs, filters invalid entries, splits data per CV, computes IM ranges, and writes per-CV mzML outputs with encoded names. Falls back to existing regular IM binning when no FAIMS is present. Updates documentation comments accordingly.

Changes

Cohort / File(s) Summary
TOPP tool: IonMobilityBinning (FAIMS branch)
src/topp/IonMobilityBinning.cpp
Adds FAIMS detection via FAIMSHelper::getCompensationVoltages; adds processFAIMSData_(PeakMap&&) to detect CVs, split by CV and build IM ranges; adds writeOutputFiles_(...) to write per-CV mzMLs with prefix/CV range in filenames; branches between FAIMS and regular splitExperimentByIonMobility; updates docs/comments.
FAIMS helper interface & behavior
src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h
Documentation updated to clarify getCompensationVoltages now collects unique compensation voltages from spectra with FAIMS_COMPENSATION_VOLTAGE, ignores sentinel DRIFTTIME_NOT_SET with a warning, and returns empty set when none found.
FAIMS runtime logic
src/openms/source/IONMOBILITY/FAIMSHelper.cpp
Replaced first-spectrum heuristic with full-scan detection of FAIMS spectra; collects CVs only from spectra with FAIMS CVs; removes sentinel CVs and warns; early-return when no FAIMS spectra.
IM data conversion (per-CV splitting)
src/openms/include/OpenMS/IONMOBILITY/IMDataConverter.h, src/openms/source/IONMOBILITY/IMDataConverter.cpp
Docs updated for splitByFAIMSCV; implementation enhanced to track last_faims_cv, assign MS2+ spectra without explicit CV to last seen CV, warn/skip spectra without context, and validate CVs against detected set.
Tests: FAIMS & IMDataConverter
src/tests/class_tests/openms/source/FAIMSHelper_test.cpp, src/tests/class_tests/openms/source/IMDataConverter_test.cpp
Added tests to verify CV detection beyond first spectrum and sentinel handling; tests for splitByFAIMSCV behavior (assignment of MS2 without CV, ordering, exception on missing FAIMS).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Tool as TOPPIonMobilityBinning
  participant FAIMS as FAIMSHelper
  participant IM as IM Binning
  participant IO as Writer

  User->>Tool: Run IonMobilityBinning
  Tool->>FAIMS: getCompensationVoltages(experiment)
  FAIMS-->>Tool: CV list

  alt CVs present
    Note over Tool: FAIMS branch
    Tool->>Tool: processFAIMSData_(experiment)\n- detect/filter CVs\n- split PeakMap per CV (use last_faims_cv for MS2)\n- compute IM ranges
    Tool->>IO: writeOutputFiles_(bins, im_ranges, out_prefix, n_bins)
    IO-->>User: Per-CV mzML files (names include CV range)
  else No CVs
    Note over Tool: Regular IM branch
    Tool->>IM: splitExperimentByIonMobility(experiment)
    Tool->>IO: write standard IM-binned outputs
    IO-->>User: IM-binned mzML files
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • cbielow
  • jcharkow

Poem

I sniff the volts that steer the breeze,
Split clouds of ions by FAIMS degrees.
Bins hop neatly, hop by CV,
Names all labeled, clear to see.
Thump-thump—my paws approve this art.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly describes the primary change of adding split-by-FAIMS-CV functionality, which aligns with the main addition of FAIMS-based splitting in the IonMobilityBinning tool. It clearly conveys the feature being introduced without extraneous detail.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch split_FAIMS_CV

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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/topp/IonMobilityBinning.cpp (1)

130-139: Remove stale pre-FAIMS path: causes redefinition and use-after-move.

  • experiment is moved here and then used again at Line 141 → use-after-move.
  • Structured bindings define mzML_bins/im_ranges which are redeclared at Lines 145–146 → compile error.
  • This block no longer stores the results (no storeExperiment call) → dead code.

Apply this diff to delete the obsolete block:

-    auto [mzML_bins, im_ranges] = IMDataConverter::splitExperimentByIonMobility(std::move(experiment), bins, bin_extension_abs, mz_binning_width, mz_binning_width_unit);
-    
-    const Size width = String(bins).size();
-    for (Size counter = 0; counter < (Size)bins; ++counter)
-    {
-      ostringstream out_name;
-      out_name << out_prefix << "_part" << setw(width) << setfill('0') << (1+counter) << "of" << bins << "_" << im_ranges[counter].getMin() << "-"
-               << im_ranges[counter].getMax() << ".mzML ";
-      addDataProcessing_(mzML_bins[counter], getProcessingInfo_(DataProcessing::ION_MOBILITY_BINNING));
-    }
🧹 Nitpick comments (3)
src/topp/IonMobilityBinning.cpp (3)

29-42: Docs: Clarify output naming/prefix semantics and FAIMS fallback.

  • Mention how output filenames are formed (prefix + part index + CV/min-max).
  • Note the fallback to regular IM binning when no valid FAIMS CVs are detected (after filtering invalid/sentinel values).

95-114: Output naming is fine; consider directory handling and numeric formatting.

  • If “out” is a directory, join paths robustly (File::concat) to avoid double slashes or missing separators.
  • Optional: format min/max with fixed precision for stable filenames.

149-151: Resolve open TODOs before merge (MS2 CV annotation & ordering).

  • Confirm whether MS2 spectra carry FAIMS CV and how split/merge should preserve them.
  • Eliminate reliance on ordering equivalence; derive CV from each bin (see earlier fix) or sort consistently by CV with explicit mapping.

I can add a robust mapping (derive CV per bin, assert single CV per bin, and warn otherwise) and/or implement a merge strategy preserving MS2 if unannotated. Want me to draft that?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6bfe9dd and 7a57d8e.

📒 Files selected for processing (1)
  • src/topp/IonMobilityBinning.cpp (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: cppcheck-test
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
🔇 Additional comments (2)
src/topp/IonMobilityBinning.cpp (2)

13-13: Good addition: FAIMSHelper include.

Required for FAIMS CV detection; import looks correct.


141-143: Verify the sentinel used for invalid FAIMS CVs.

You erase IMTypes::DRIFTTIME_NOT_SET. Confirm that FAIMSHelper::getCompensationVoltages returns this sentinel for “not set” CVs.

Comment on lines +78 to +93
std::pair<std::vector<PeakMap>, Math::BinContainer> processFAIMSData_(PeakMap&& experiment)
{
set<double> faims_cvs = FAIMSHelper::getCompensationVoltages(experiment);
auto mzML_bins = IMDataConverter::splitByFAIMSCV(std::move(experiment));
Size n_bins = mzML_bins.size();

Math::BinContainer im_ranges;
for (Size i = 0; i < n_bins; ++i)
{
double faims_cv = *std::next(faims_cvs.begin(), i);
im_ranges[i].setMax(faims_cv);
im_ranges[i].setMin(faims_cv);
}

return {std::move(mzML_bins), std::move(im_ranges)};
}

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 | 🔴 Critical

Fix out-of-bounds access and ordering assumptions in FAIMS bin metadata.

  • im_ranges is indexed without being sized; operator[] is undefined. Resize before use.
  • Mapping CVs by relying on std::set iteration order to match splitByFAIMSCV output is unsafe. Derive the CV per bin from the split bins themselves to avoid ordering assumptions.

Apply this minimal safety fix to prevent out-of-bounds and drop invalid CVs:

-  std::pair<std::vector<PeakMap>, Math::BinContainer> processFAIMSData_(PeakMap&& experiment)
+  std::pair<std::vector<PeakMap>, Math::BinContainer> processFAIMSData_(PeakMap&& experiment)
   {
-    set<double> faims_cvs = FAIMSHelper::getCompensationVoltages(experiment);
-    auto mzML_bins = IMDataConverter::splitByFAIMSCV(std::move(experiment));
-    Size n_bins = mzML_bins.size();
-    
-    Math::BinContainer im_ranges;
-    for (Size i = 0; i < n_bins; ++i)
-    {
-      double faims_cv = *std::next(faims_cvs.begin(), i);
-      im_ranges[i].setMax(faims_cv);
-      im_ranges[i].setMin(faims_cv);
-    }
-    
-    return {std::move(mzML_bins), std::move(im_ranges)};
+    auto mzML_bins = IMDataConverter::splitByFAIMSCV(std::move(experiment));
+    const Size n_bins = mzML_bins.size();
+
+    Math::BinContainer im_ranges;
+    im_ranges.resize(n_bins); // prevent out-of-bounds
+    for (Size i = 0; i < n_bins; ++i)
+    {
+      // Determine the CV for this bin from the bin contents to avoid relying on global ordering
+      auto cvs = FAIMSHelper::getCompensationVoltages(mzML_bins[i]);
+      cvs.erase(IMTypes::DRIFTTIME_NOT_SET); // drop invalid/sentinel
+      // Expect exactly one CV per FAIMS bin
+      const double cv = cvs.empty() ? 0.0 : *cvs.begin();
+      im_ranges[i].setMin(cv);
+      im_ranges[i].setMax(cv);
+    }
+
+    return {std::move(mzML_bins), std::move(im_ranges)};
   }

Comment thread src/topp/IonMobilityBinning.cpp Resolved

@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 (2)
src/openms/source/IONMOBILITY/FAIMSHelper.cpp (1)

27-37: Consider normalizing CVs to tolerate minor float jitter.

Some vendors may encode CVs with tiny float deviations; consider bucketing or rounding (e.g., to 0.1 V) before collecting into the set to avoid spurious bins.

src/topp/IonMobilityBinning.cpp (1)

99-118: Improve numeric formatting of CVs in filenames (optional).

Consider fixed precision (e.g., 1–2 decimals) to avoid long floats in file names.

Apply minimally:

-      out_name << out_prefix << "_part" 
+      out_name << out_prefix << "_part" 
         << setw(width) << setfill('0') << (1+i) 
         << "of" << n_bins << "_"
-        << im_ranges[i].getMin() << "-"
-        << im_ranges[i].getMax() << ".mzML";
+        << std::fixed << std::setprecision(1)
+        << im_ranges[i].getMin() << "-"
+        << im_ranges[i].getMax() << ".mzML";
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a57d8e and 996fc85.

📒 Files selected for processing (8)
  • CHANGELOG (2 hunks)
  • src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h (1 hunks)
  • src/openms/include/OpenMS/IONMOBILITY/IMDataConverter.h (1 hunks)
  • src/openms/source/IONMOBILITY/FAIMSHelper.cpp (1 hunks)
  • src/openms/source/IONMOBILITY/IMDataConverter.cpp (1 hunks)
  • src/tests/class_tests/openms/source/FAIMSHelper_test.cpp (2 hunks)
  • src/tests/class_tests/openms/source/IMDataConverter_test.cpp (1 hunks)
  • src/topp/IonMobilityBinning.cpp (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/openms/include/OpenMS/IONMOBILITY/IMDataConverter.h
🧰 Additional context used
📓 Path-based instructions (3)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h
  • src/openms/source/IONMOBILITY/IMDataConverter.cpp
  • src/openms/source/IONMOBILITY/FAIMSHelper.cpp
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/IMDataConverter_test.cpp
  • src/tests/class_tests/openms/source/FAIMSHelper_test.cpp
🧠 Learnings (4)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/source/IMDataConverter_test.cpp
  • src/tests/class_tests/openms/source/FAIMSHelper_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/source/IMDataConverter_test.cpp
📚 Learning: 2025-04-07T21:16:06.557Z
Learnt from: jpfeuffer
PR: OpenMS/OpenMS#7970
File: src/pyOpenMS/addons/MSSpectrum.pyx:24-28
Timestamp: 2025-04-07T21:16:06.557Z
Learning: In OpenMS, the proper way to access ion mobility data in MSSpectrum is to use the `getIMData()` method, which returns a tuple with (position, unit). The position corresponds to the index in the FloatDataArrays where the ion mobility data is stored. Always use this method rather than assuming the first FloatDataArray contains ion mobility data.

Applied to files:

  • src/tests/class_tests/openms/source/FAIMSHelper_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/tests/class_tests/openms/source/FAIMSHelper_test.cpp
🧬 Code graph analysis (3)
src/tests/class_tests/openms/source/IMDataConverter_test.cpp (2)
src/openms/source/IONMOBILITY/IMDataConverter.cpp (2)
  • splitByFAIMSCV (25-89)
  • splitByFAIMSCV (25-25)
src/openms/source/CONCEPT/Exception.cpp (1)
  • MissingInformation (257-260)
src/topp/IonMobilityBinning.cpp (2)
src/openms/source/IONMOBILITY/FAIMSHelper.cpp (2)
  • getCompensationVoltages (18-54)
  • getCompensationVoltages (18-18)
src/openms/source/IONMOBILITY/IMDataConverter.cpp (4)
  • splitByFAIMSCV (25-89)
  • splitByFAIMSCV (25-25)
  • splitExperimentByIonMobility (147-224)
  • splitExperimentByIonMobility (147-151)
src/tests/class_tests/openms/source/FAIMSHelper_test.cpp (1)
src/tests/class_tests/openms/source/IMDataConverter_test.cpp (4)
  • START_SECTION (74-74)
  • START_SECTION (89-89)
  • START_SECTION (120-144)
  • START_SECTION (186-186)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: cppcheck-test
🔇 Additional comments (12)
src/tests/class_tests/openms/source/IMDataConverter_test.cpp (2)

190-238: Good coverage for MS2 CV inheritance.

Test correctly asserts MS2 assignment to the last seen FAIMS CV and bin ordering by CV.


239-251: Non-FAIMS exception test is correct.

Matches IMDataConverter::splitByFAIMSCV behavior on datasets without FAIMS.

src/tests/class_tests/openms/source/FAIMSHelper_test.cpp (3)

18-18: Include addition is appropriate.

IMTypes is needed for DRIFTTIME_NOT_SET in tests.


61-87: Robust FAIMS CV detection tests.

Validates detection beyond first spectrum and ignoring sentinel; aligns with implementation.


89-105: Empty result on non‑FAIMS is correct.

Ensures expected empty set for non‑FAIMS data.

CHANGELOG (2)

39-41: Changelog entry is clear.

Accurately describes FAIMS split capability in IonMobilityBinning.


66-68: Library feature notes are accurate.

Summarizes FAIMSHelper and IMDataConverter updates succinctly.

src/openms/source/IONMOBILITY/FAIMSHelper.cpp (1)

47-52: Warning on sentinel is fine; avoid poisoning downstream CV context.

Works as written; combined with the IMDataConverter fix (see separate comment) ensures sentinel does not overwrite last seen CV context.

Ensure IMDataConverter does not update last_faims_cv when encountering this sentinel; see proposed patch in IMDataConverter.cpp comment.

src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h (1)

30-39: Docs reflect current behavior.

Clear, matches implementation details (dataset-wide scan, sentinel handling).

src/topp/IonMobilityBinning.cpp (3)

29-43: User doc updates look good.

Covers both modes and MS2 inheritance behavior succinctly.


79-97: Resize im_ranges and avoid brittle ordering assumptions.

  • im_ranges is indexed without resize; operator[] is unsafe.
  • Mapping bins to set iteration order is fragile.

Use CVs derived from each bin and resize first.

Apply this safer diff:

   std::pair<std::vector<PeakMap>, Math::BinContainer> processFAIMSData_(PeakMap&& experiment)
   {
-    set<double> faims_cvs = FAIMSHelper::getCompensationVoltages(experiment);
-    auto mzML_bins = IMDataConverter::splitByFAIMSCV(std::move(experiment));
-    Size n_bins = mzML_bins.size();
-
-    // The order of bins produced by IMDataConverter::splitByFAIMSCV() is defined
-    // by the ascending order of the unique FAIMS CVs (std::set iteration order).
-    // We therefore map i-th bin to i-th element of 'faims_cvs'.
-    Math::BinContainer im_ranges;
-    for (Size i = 0; i < n_bins; ++i)
-    {
-      const double faims_cv = *std::next(faims_cvs.begin(), i);
-      im_ranges[i].setMax(faims_cv);
-      im_ranges[i].setMin(faims_cv);
-    }
+    // Split into FAIMS bins
+    auto mzML_bins = IMDataConverter::splitByFAIMSCV(std::move(experiment));
+    const Size n_bins = mzML_bins.size();
+
+    // Derive the CV for each bin from its content to avoid relying on global ordering
+    Math::BinContainer im_ranges;
+    im_ranges.resize(n_bins);
+    for (Size i = 0; i < n_bins; ++i)
+    {
+      auto cvs = FAIMSHelper::getCompensationVoltages(mzML_bins[i]);
+      cvs.erase(IMTypes::DRIFTTIME_NOT_SET);
+      const double cv = cvs.empty() ? 0.0 : *cvs.begin();
+      im_ranges[i].setMin(cv);
+      im_ranges[i].setMax(cv);
+    }
 
     return {std::move(mzML_bins), std::move(im_ranges)};
   }

140-156: Set n_bins from actual split result (not input parameter).

Else-branch uses the requested bin count; use the produced bin count for consistency with FAIMS branch.

Apply this diff:

-      n_bins = bins;
+      n_bins = mzML_bins.size();

Comment on lines +55 to 85
// Keep MS2 spectra which might not carry a FAIMS CV by assigning them to the last seen FAIMS CV (nearest previous in run order)
double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
for (MSSpectrum& spec : exp)
{
split_peakmap[cv2index[it.getDriftTime()]].addSpectrum(std::move(it));
if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
{
last_faims_cv = spec.getDriftTime();
const auto idx_it = cv2index.find(last_faims_cv);
if (idx_it == cv2index.end())
{
OPENMS_LOG_WARN << "Encountered spectrum with unexpected FAIMS CV (not in detected set): " << last_faims_cv << std::endl;
continue;
}
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}

// No FAIMS CV on spectrum: if it's MS2+ and we have a prior FAIMS CV context, assign it to that bin
if (!std::isnan(last_faims_cv) && spec.getMSLevel() > 1)
{
const auto idx_it = cv2index.find(last_faims_cv);
if (idx_it != cv2index.end())
{
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}
}

// Otherwise skip with a warning
OPENMS_LOG_WARN << "Skipping spectrum without FAIMS CV (no prior FAIMS CV context or unexpected layout)." << std::endl;
}

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 | 🔴 Critical

Do not overwrite last_faims_cv with invalid/unexpected CV.

Currently last_faims_cv is set before verifying membership in cv2index. If a spectrum has a sentinel or unexpected CV, MS2 assignment will be corrupted. Update last_faims_cv only after successful lookup.

Apply this diff:

-    // Keep MS2 spectra which might not carry a FAIMS CV by assigning them to the last seen FAIMS CV (nearest previous in run order)
-    double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
+    // Keep MS2 spectra which might not carry a FAIMS CV by assigning them to the last seen FAIMS CV (nearest previous in run order)
+    double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
     for (MSSpectrum& spec : exp)
     {
       if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
       {
-        last_faims_cv = spec.getDriftTime();
-        const auto idx_it = cv2index.find(last_faims_cv);
+        const double cur_cv = spec.getDriftTime();
+        const auto idx_it = cv2index.find(cur_cv);
         if (idx_it == cv2index.end())
         {
           OPENMS_LOG_WARN << "Encountered spectrum with unexpected FAIMS CV (not in detected set): " << last_faims_cv << std::endl;
           continue;
         }
+        last_faims_cv = cur_cv;
         split_peakmap[idx_it->second].addSpectrum(std::move(spec));
         continue;
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Keep MS2 spectra which might not carry a FAIMS CV by assigning them to the last seen FAIMS CV (nearest previous in run order)
double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
for (MSSpectrum& spec : exp)
{
split_peakmap[cv2index[it.getDriftTime()]].addSpectrum(std::move(it));
if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
{
last_faims_cv = spec.getDriftTime();
const auto idx_it = cv2index.find(last_faims_cv);
if (idx_it == cv2index.end())
{
OPENMS_LOG_WARN << "Encountered spectrum with unexpected FAIMS CV (not in detected set): " << last_faims_cv << std::endl;
continue;
}
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}
// No FAIMS CV on spectrum: if it's MS2+ and we have a prior FAIMS CV context, assign it to that bin
if (!std::isnan(last_faims_cv) && spec.getMSLevel() > 1)
{
const auto idx_it = cv2index.find(last_faims_cv);
if (idx_it != cv2index.end())
{
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}
}
// Otherwise skip with a warning
OPENMS_LOG_WARN << "Skipping spectrum without FAIMS CV (no prior FAIMS CV context or unexpected layout)." << std::endl;
}
// Keep MS2 spectra which might not carry a FAIMS CV by assigning them to the last seen FAIMS CV (nearest previous in run order)
double last_faims_cv = std::numeric_limits<double>::quiet_NaN();
for (MSSpectrum& spec : exp)
{
if (spec.getDriftTimeUnit() == DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)
{
const double cur_cv = spec.getDriftTime();
const auto idx_it = cv2index.find(cur_cv);
if (idx_it == cv2index.end())
{
OPENMS_LOG_WARN << "Encountered spectrum with unexpected FAIMS CV (not in detected set): " << last_faims_cv << std::endl;
continue;
}
last_faims_cv = cur_cv;
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}
// No FAIMS CV on spectrum: if it's MS2+ and we have a prior FAIMS CV context, assign it to that bin
if (!std::isnan(last_faims_cv) && spec.getMSLevel() > 1)
{
const auto idx_it = cv2index.find(last_faims_cv);
if (idx_it != cv2index.end())
{
split_peakmap[idx_it->second].addSpectrum(std::move(spec));
continue;
}
}
// Otherwise skip with a warning
OPENMS_LOG_WARN << "Skipping spectrum without FAIMS CV (no prior FAIMS CV context or unexpected layout)." << std::endl;
}
🤖 Prompt for AI Agents
In src/openms/source/IONMOBILITY/IMDataConverter.cpp around lines 55 to 85,
last_faims_cv is currently updated before checking whether the spectrum's FAIMS
CV exists in cv2index, which allows sentinel/unexpected CVs to overwrite the
prior valid context and corrupt MS2 assignment; change the logic so you first
look up spec.getDriftTime() in cv2index, and only if the lookup succeeds update
last_faims_cv and add the spectrum to the corresponding split_peakmap; if the
lookup fails, log the warning and continue without modifying last_faims_cv.

@timosachsenberg timosachsenberg changed the title Split_FAIMS_CV feature: split experiments by FAIMS CV Sep 26, 2025
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Ok I think it is good to go. I added some tests. Ultimately, we need to see more FAIMS data to further refine it.

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