Skip to content

Add CCS (collisional cross section) support for ion mobility data - #8735

Merged
timosachsenberg merged 4 commits into
developfrom
claude/cherry-pick-757e57b-cT0wV
Feb 4, 2026
Merged

timosachsenberg merged 4 commits into
developfrom
claude/cherry-pick-757e57b-cT0wV

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

ProteoWizard/MSConvert v3.0.26007+ changed ion mobility representation
from 1/K0 (MS:1002815) to CCS (MS:1002954). This breaks NuXL and other
tools that rely on ion mobility data from mzML files.

Changes:

  • Add CCS to DriftTimeUnit enum (IMTypes.h)
  • Add IM_CCS to DIM_UNIT enum (CommonEnums.h)
  • Parse MS:1002954 (CCS) in mzML reader (MzMLHandler.cpp)
  • Write CCS values back to mzML with correct CV terms
  • Update IMDataConverter to recognize CCS from CV terms
  • Skip CCS conversion in NuXL when data is already CCS
  • Make IonMobilityScoring epsilon scale-invariant for CCS compatibility
  • Update parameter documentation to mention CCS units
  • Add CCS to Python bindings (IMTypes.pxd, MSSpectrum.pyx)

Fixes: #8732

(cherry picked from commit 757e57b)

https://claude.ai/code/session_01MiYNbe4sAxvwNYk4eoPLKu

Summary by CodeRabbit

  • New Features

    • Added support for Collisional Cross Section (CCS) as a recognized ion-mobility/drift-time unit (read, store, write, convert).
  • User-facing behavior

    • One-time warnings now alert when CCS data is used with unusually small IM tolerances to avoid misconfiguration.
    • Ion-mobility scoring now uses a scale-aware threshold, which may affect IM matching behavior.
  • Documentation

    • Updated parameter/help text and examples to describe CCS units and recommended tolerances.
  • Chores

    • Added a user parameter key for inverse reduced ion mobility.

ProteoWizard/MSConvert v3.0.26007+ changed ion mobility representation
from 1/K0 (MS:1002815) to CCS (MS:1002954). This breaks NuXL and other
tools that rely on ion mobility data from mzML files.

Changes:
- Add CCS to DriftTimeUnit enum (IMTypes.h)
- Add IM_CCS to DIM_UNIT enum (CommonEnums.h)
- Parse MS:1002954 (CCS) in mzML reader (MzMLHandler.cpp)
- Write CCS values back to mzML with correct CV terms
- Update IMDataConverter to recognize CCS from CV terms
- Skip CCS conversion in NuXL when data is already CCS
- Make IonMobilityScoring epsilon scale-invariant for CCS compatibility
- Update parameter documentation to mention CCS units
- Add CCS to Python bindings (IMTypes.pxd, MSSpectrum.pyx)

Fixes: #8732

(cherry picked from commit 757e57b)

https://claude.ai/code/session_01MiYNbe4sAxvwNYk4eoPLKu
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

If you could comment if something else needs to be changed/adapted to support ccs

@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds CCS (collisional cross section, square angstrom) as a supported ion-mobility/drift-time unit across enums, parsing/writing, conversions, Python bindings, warnings/help text, and runtime checks; also makes IM scoring eps scale with the IM range.

Changes

Cohort / File(s) Summary
Enums & Constants
src/openms/include/OpenMS/CONCEPT/CommonEnums.h, src/openms/include/OpenMS/IONMOBILITY/IMTypes.h, src/openms/source/IONMOBILITY/IMTypes.cpp, src/openms/include/OpenMS/CONCEPT/Constants.h
Added DIM_UNIT::IM_CCS and DriftTimeUnit::CCS, updated DIM name arrays and INVERSE_REDUCED_ION_MOBILITY constant; mapped DriftTimeUnit::CCS ↔ DIM_UNIT::IM_CCS.
mzML I/O & Conversion
src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp, src/openms/source/IONMOBILITY/IMDataConverter.cpp
Recognize and emit CCS CVs (MS:1002954, UO:0000324), extend prefix/CV checks, and map CCS to internal DIM_UNIT for parsing and serialization.
IM Types / Python bindings
src/pyOpenMS/pxds/IMTypes.pxd, src/pyOpenMS/addons/MSSpectrum.pyx
Expose CCS in Python DriftTimeUnit and update docstring to include the new enum value.
Analysis & Scoring
src/openms/source/ANALYSIS/OPENSWATH/IonMobilityScoring.cpp
Replace fixed eps (1e-5) with scale‑invariant eps = max(1e-8, im_range.getSpan()*1e-5) in drift-scoring functions.
Warnings & Tolerance Guidance
src/openms/source/PROCESSING/CENTROIDING/PeakPickerIM.cpp, src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp, src/openms/source/FEATUREFINDER/FeatureFinderIdentificationAlgorithm.cpp, src/openms/source/FEATUREFINDER/MassTraceDetection.cpp, src/openms/source/APPLICATIONS/OpenSwathBase.cpp
Add CCS-detection helpers and one-time warnings when user tolerances/windows are likely too small for CCS units; update help/parameter text; add per-instance warning guard in PeakPickerIM.
Topp Apps & Workflows
src/topp/OpenNuXL.cpp, src/topp/OpenSwathWorkflow.cpp
Set/guard drift-time unit handling to CCS where appropriate and update CLI/help text to reference CCS examples.
Other / Minor
src/openms/include/OpenMS/PROCESSING/CENTROIDING/PeakPickerIM.h, src/tests/topp/MassTraceExtractor_3_expected.ini, various sources
Added ccs_warning_shown_ member, small includes/formatting and doc tweaks, and updated test help text descriptions.

Sequence Diagram(s)

sequenceDiagram
    participant File as mzML File
    participant Handler as MzMLHandler
    participant Converter as IMDataConverter
    participant Types as IMTypes
    participant Core as Internal Data (PeakMap/Spectrum)

    File->>Handler: read spectrum / selectedIon CV terms
    Handler->>Converter: request IM unit detection for array/scan
    Converter->>Types: check CVs/prefixes (MS:1002954, UO:0000324, "collision cross section")
    Types-->>Converter: DriftTimeUnit::CCS
    Converter-->>Handler: return CCS mapping (DIM_UNIT::IM_CCS)
    Handler->>Core: store IM values with unit CCS
    Core->>Handler: on write, request unit serialization
    Handler->>Types: map DIM_UNIT::IM_CCS -> MS:1002954 + "square angstrom"
    Handler->>File: write CCS CV and value
Loading

Possibly related PRs

Suggested labels

enhancement, Review effort [1-5]: 3

Suggested reviewers

  • alhigaylan
  • jpfeuffer

Poem

🐇
I nibble through the ion-mobility log,
CCS now hops from mist to fog,
Enums aligned and handlers sing,
One gentle warning—then take wing,
Hooray for angstroms, bounce and jog! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.88% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 change: adding CCS (collisional cross section) support for ion mobility data, which is the primary focus of the entire changeset.
Linked Issues check ✅ Passed The PR fully addresses the requirements from issue #8732: added CCS enum support, updated mzML parsing/writing for MS:1002954, modified IMDataConverter for CCS recognition, updated NuXL for conditional conversion, and made scoring scale-invariant.
Out of Scope Changes check ✅ Passed All changes are within scope of adding CCS support: enums, parsing logic, data conversion, warnings, and documentation. Parameter descriptions and Python bindings updates directly support CCS adoption.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/cherry-pick-757e57b-cT0wV

Important

Action Needed: IP Allowlist Update

If your organization protects your Git platform with IP whitelisting, please add the new CodeRabbit IP address to your allowlist:

  • ✨ 136.113.208.247/32 (new)
  • 34.170.211.100/32
  • 35.222.179.152/32

Reviews will stop working after February 8, 2026 if the new IP is not added to your allowlist.


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

Caution

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

⚠️ Outside diff range comments (1)
src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp (1)

3868-3887: ⚠️ Potential issue | 🟠 Major

Handle FAIMS compensation voltage when writing precursor drift time.
FAIMS_COMPENSATION_VOLTAGE currently falls into the default branch and is serialized as milliseconds, which is incorrect if a precursor carries FAIMS data. Please add an explicit case mirroring the scan-level output.

💡 Suggested fix
           switch (precursor.getDriftTimeUnit())
           {
             default:
               // assume milliseconds, but warn
               warning(STORE, String("Precursor drift time unit not set, assume milliseconds"));
               [[fallthrough]];
             case DriftTimeUnit::MILLISECOND:
               os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002476\" name=\"ion mobility drift time\" value=\"" << precursor.getDriftTime()
                   << "\" unitAccession=\"UO:0000028\" unitName=\"millisecond\" unitCvRef=\"UO\" />\n";
               break;
             case DriftTimeUnit::VSSC:
               os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002815\" name=\"inverse reduced ion mobility\" value=\"" << precursor.getDriftTime()
                   << "\" unitAccession=\"MS:1002814\" unitName=\"volt-second per square centimeter\" unitCvRef=\"MS\" />\n";
               break;
+            case DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE:
+              os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1001581\" name=\"FAIMS compensation voltage\" value=\"" << precursor.getDriftTime()
+                  << "\" unitAccession=\"UO:000218\" unitName=\"volt\" unitCvRef=\"UO\" />\n";
+              break;
             case DriftTimeUnit::CCS:
               os << "\t\t\t\t\t\t\t\t<cvParam cvRef=\"MS\" accession=\"MS:1002954\" name=\"collisional cross sectional area\" value=\"" << precursor.getDriftTime()
                   << "\" unitAccession=\"UO:0000324\" unitName=\"square angstrom\" unitCvRef=\"UO\" />\n";
               break;
           }
🤖 Fix all issues with AI agents
In `@src/topp/OpenNuXL.cpp`:
- Around line 5196-5204: The conversion code calls convertVSSCToCCS(spectra) but
does not update the ion-mobility unit, leaving getDriftTimeUnit() returning
DriftTimeUnit::VSSC; update the unit to DriftTimeUnit::CCS after conversion
(either inside convertVSSCToCCS or immediately after the call) so metadata
matches the transformed values; specifically ensure convertVSSCToCCS or the
caller sets the spectra's drift-time unit to DriftTimeUnit::CCS (so
getDriftTimeUnit() reflects the change) and add a short comment documenting the
update.
🧹 Nitpick comments (1)
src/openms/source/ANALYSIS/OPENSWATH/IonMobilityScoring.cpp (1)

432-434: Consistent scale-invariant epsilon computation.

The pattern matches the implementation in driftScoringMS1Contrast. This ensures consistent behavior across all ion mobility scoring functions.

Consider extracting the eps computation to a small helper function to centralize this logic and reduce duplication across the three scoring methods:

♻️ Optional: Extract helper function
// Could be added as a private static method or free function
inline double computeScaleInvariantEps(double im_span)
{
  return std::max(1e-8, im_span * 1e-5);
}

Comment thread src/topp/OpenNuXL.cpp Resolved
@alhigaylan

Copy link
Copy Markdown
Collaborator

Overall it looks good for CSS. I think while we are at it, we should add support for "inverse reduced ion mobility" which is another name for 1/k ion mobility arrays from MSConvert. It uses the same MS CV term MS:1002815

@alhigaylan alhigaylan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Allow IMDataConverter type to detect 'inverse reduced ion mobility' array. And maybe add that term as a new constant. It was flagged as TODO in constants.h

/** MetaValue key for raw TimsTOF ion mobility array (from MSConvert).
* Note: TODO check. I saw files with other names as well (e.g. mean inverse ion mobility).
* PeakPickerIM expects to find 'Ion Mobility' array and will treat it as raw timsTOF data.
*/
inline const std::string ION_MOBILITY = "Ion Mobility";

@singjc singjc 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.

Looks good to me. I like the scale invariant epsilon. For OpenSwath, we only use inverse ion mobility, so I'm not sure how it would work if the expected float data array was CCS instead. Would probably need to check and convert to inverse ion mobility.

Although, I've only ever used mzML files converted with MOBI-DIK (diapysef) for timsTOF data, but would probably be worth while testing that it still works as expected with MSConvert. @jcharkow I think at one point you were testing msconverts mzML with OpenSwath in the early stages of diaPASEF?

- Fix metadata consistency in OpenNuXL.cpp: set DriftTimeUnit::CCS after
  VSSC→CCS conversion
- Add INVERSE_REDUCED_ION_MOBILITY constant for MSConvert compatibility
- Extend IMDataConverter::getIMUnit() to recognize MSConvert naming
- Add CCS detection warnings to OpenSwath (expects 1/K0 units)
- Add CCS warnings with tolerance checks to PeakPickerIM, MassTraceDetection,
  Biosaur2Algorithm, and FeatureFinderIdentificationAlgorithm
- Update documentation for IM tolerance parameters to include CCS typical values

All warnings use proper CV term-based unit detection via DriftTimeUnit enum.

Co-Authored-By: Claude Opus 4.5 <[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: 3

Caution

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

⚠️ Outside diff range comments (1)
src/openms/source/IONMOBILITY/IMDataConverter.cpp (1)

333-367: ⚠️ Potential issue | 🟠 Major

Add CCS mapping in setIMUnit/annotateAsIM to prevent runtime exceptions.

getIMUnit can now yield DriftTimeUnit::CCS, but annotateAsIM and setIMUnit still throw for CCS. Paths like processDriftTimeStack() call setIMUnit(new_spec.getDriftTimeUnit()), so CCS frames will fail at runtime. Please add CCS mapping to the CCS CV term (MS:1002954).

🛠️ Proposed fix
--- a/src/openms/source/IONMOBILITY/IMDataConverter.cpp
+++ b/src/openms/source/IONMOBILITY/IMDataConverter.cpp
@@
   switch (unit)
   {
     case DriftTimeUnit::MILLISECOND:
       term = &cv.getTerm("MS:1002816");
       break;
     case DriftTimeUnit::VSSC:
       term = &cv.getTerm("MS:1003008");
       break;
+    case DriftTimeUnit::CCS:
+      term = &cv.getTerm("MS:1002954");
+      break;
     default:
       throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unit cannot be converted into CV term.", driftTimeUnitToString(unit));
   }
@@
   switch (unit)
   {
     case DriftTimeUnit::MILLISECOND: 
       fda.setName(cv.getTerm("MS:1002816").name); // MS:1002816 ! mean ion mobility array
       return;
     case DriftTimeUnit::VSSC:
       fda.setName(cv.getTerm("MS:1003008").name); // MS:1003008 ! raw inverse reduced ion mobility array
       return;
+    case DriftTimeUnit::CCS:
+      fda.setName(cv.getTerm("MS:1002954").name); // MS:1002954 ! collisional cross section
+      return;
     default:
       throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unit is not a valid IM unit for float data arrays", driftTimeUnitToString(unit));
   }
🤖 Fix all issues with AI agents
In `@src/openms/include/OpenMS/CONCEPT/Constants.h`:
- Around line 253-257: The Doxygen comment for the constant
INVERSE_REDUCED_ION_MOBILITY is missing a required `@brief` tag; update the
comment block immediately above the inline const std::string
INVERSE_REDUCED_ION_MOBILITY declaration to include a single-line `@brief`
description, followed by a blank line and then the existing detailed sentence
(keeping the CV term note), so it conforms to the project's Doxygen style.

In `@src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp`:
- Around line 35-52: The static flag returned by getBiosaur2CCSWarningShown() is
not thread-safe under OpenMP; change it from a plain static bool to a static
std::atomic_bool and update warnIfCCSWithSmallTolerance(DriftTimeUnit, double)
to perform a single atomic test-and-set using atomic.exchange(true) so only the
first thread logs the warning. Modify getBiosaur2CCSWarningShown() to return the
atomic_bool (or a reference to it) and replace the current boolean check/write
in warnIfCCSWithSmallTolerance with a call to exchange to ensure atomic
check-and-set semantics; include the appropriate <atomic> header where needed.

In `@src/openms/source/PROCESSING/CENTROIDING/PeakPickerIM.cpp`:
- Around line 42-58: The code uses a static mutable bool via
getCCSWarningShown() which is not thread-safe; replace that pattern with a
static std::once_flag (e.g., static std::once_flag ccs_warning_once;) and call
std::call_once(ccs_warning_once, [&]{ OPENMS_LOG_WARN << ... << '\n'; }); inside
warnIfCCSWithSmallTolerance so the warning runs exactly once in a thread-safe
way; also change the logging terminator from std::endl to '\n' and add the
required `#include` <mutex>.
🧹 Nitpick comments (1)
src/openms/source/APPLICATIONS/OpenSwathBase.cpp (1)

30-60: Avoid missing CCS warnings when spectrum 0 lacks data arrays.

The helper always returns after inspecting getSpectrumById(0) of the first map with spectra. If spectrum 0 has no data arrays, CCS present later won’t trigger a warning. Consider scanning until you hit the first spectrum that actually has data arrays (cap to a small N for cost).

🔧 Possible adjustment
-        // Get the first spectrum and check its data arrays for CCS indicators
-        auto spectrum = swath_map.sptr->getSpectrumById(0);
-        if (spectrum)
-        {
-          for (const auto& arr : spectrum->getDataArrays())
-          {
-            ...
-          }
-        }
-        return; // Only check first map with spectra
+        // Check the first spectrum that actually has data arrays (cap to a small N)
+        const Size max_check = std::min<Size>(swath_map.sptr->getNrSpectra(), 10);
+        for (Size idx = 0; idx < max_check; ++idx)
+        {
+          auto spectrum = swath_map.sptr->getSpectrumById(idx);
+          if (!spectrum || spectrum->getDataArrays().empty()) continue;
+          for (const auto& arr : spectrum->getDataArrays())
+          {
+            ...
+          }
+          return; // Only warn once
+        }
+        return; // Only check first map with spectra

Comment on lines +253 to +257
/** MetaValue key for inverse reduced ion mobility array (alternative name for 1/K0 from MSConvert).
* Uses the same CV term MS:1002815 as ION_MOBILITY.
*/
inline const std::string INVERSE_REDUCED_ION_MOBILITY = "inverse reduced ion mobility";

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

Add @brief to the new Doxygen block.

The new header doc comment should include a @brief line to match the required Doxygen style.

Proposed doc fix
-      /** MetaValue key for inverse reduced ion mobility array (alternative name for 1/K0 from MSConvert).
-       * Uses the same CV term MS:1002815 as ION_MOBILITY.
-       */
+      /** `@brief` MetaValue key for inverse reduced ion mobility array (alternative name for 1/K0 from MSConvert).
+       *
+       * Uses the same CV term MS:1002815 as ION_MOBILITY.
+       */
       inline const std::string INVERSE_REDUCED_ION_MOBILITY = "inverse reduced ion mobility";

As per coding guidelines: “Use Doxygen documentation with @brief tag (required), followed by blank line and details; use @param[in], @param[out], or @param[in,out] for all parameters”.

📝 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
/** MetaValue key for inverse reduced ion mobility array (alternative name for 1/K0 from MSConvert).
* Uses the same CV term MS:1002815 as ION_MOBILITY.
*/
inline const std::string INVERSE_REDUCED_ION_MOBILITY = "inverse reduced ion mobility";
/** `@brief` MetaValue key for inverse reduced ion mobility array (alternative name for 1/K0 from MSConvert).
*
* Uses the same CV term MS:1002815 as ION_MOBILITY.
*/
inline const std::string INVERSE_REDUCED_ION_MOBILITY = "inverse reduced ion mobility";
🤖 Prompt for AI Agents
In `@src/openms/include/OpenMS/CONCEPT/Constants.h` around lines 253 - 257, The
Doxygen comment for the constant INVERSE_REDUCED_ION_MOBILITY is missing a
required `@brief` tag; update the comment block immediately above the inline const
std::string INVERSE_REDUCED_ION_MOBILITY declaration to include a single-line
`@brief` description, followed by a blank line and then the existing detailed
sentence (keeping the CV term note), so it conforms to the project's Doxygen
style.

Comment on lines +35 to +52
// Helper to warn once if CCS data is detected with small IM tolerance
static bool& getBiosaur2CCSWarningShown()
{
static bool shown = false;
return shown;
}

static void warnIfCCSWithSmallTolerance(DriftTimeUnit unit, double im_tolerance)
{
if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0 && !getBiosaur2CCSWarningShown())
{
OPENMS_LOG_WARN << "Warning: Ion mobility data is in CCS units (square angstroms), but "
<< "paseftol = " << im_tolerance
<< " appears to be set for 1/K0 data. "
<< "For CCS data, consider using larger values (e.g., 5-20)." << std::endl;
getBiosaur2CCSWarningShown() = 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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file and surrounding context
head -60 src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp | tail -30

Repository: OpenMS/OpenMS

Length of output: 1012


🏁 Script executed:

# Search for calls to warnIfCCSWithSmallTolerance or centroidPASEFData_
rg "warnIfCCSWithSmallTolerance|centroidPASEFData" -A 3 -B 3

Repository: OpenMS/OpenMS

Length of output: 7048


🏁 Script executed:

# Search for OpenMP directives in the file
rg "#pragma omp|omp parallel" src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp -B 3 -A 3

Repository: OpenMS/OpenMS

Length of output: 515


🏁 Script executed:

# Check the header file for the algorithm class
fd "Biosaur2Algorithm.h" -x cat {}

Repository: OpenMS/OpenMS

Length of output: 35788


Make the CCS warning flag thread-safe under OpenMP.

The static bool returned by getBiosaur2CCSWarningShown() has a data race when accessed from the OpenMP-parallel run() method. The function centroidPASEFData_() is called concurrently from multiple FAIMS processing threads, each potentially reading and writing the flag without synchronization. Use std::atomic_bool with .exchange(true) to ensure thread-safe check-and-set semantics:

Thread-safe variant using atomic
--- a/src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
+++ b/src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp
@@
-  static bool& getBiosaur2CCSWarningShown()
-  {
-    static bool shown = false;
-    return shown;
-  }
+  static std::atomic_bool& getBiosaur2CCSWarningShown()
+  {
+    static std::atomic_bool shown{false};
+    return shown;
+  }
@@
-    if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0 && !getBiosaur2CCSWarningShown())
+    if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0 &&
+        !getBiosaur2CCSWarningShown().exchange(true))
     {
       OPENMS_LOG_WARN << "Warning: Ion mobility data is in CCS units (square angstroms), but "
                       << "paseftol = " << im_tolerance
                       << " appears to be set for 1/K0 data. "
                       << "For CCS data, consider using larger values (e.g., 5-20)." << std::endl;
-      getBiosaur2CCSWarningShown() = true;
     }
🤖 Prompt for AI Agents
In `@src/openms/source/FEATUREFINDER/Biosaur2Algorithm.cpp` around lines 35 - 52,
The static flag returned by getBiosaur2CCSWarningShown() is not thread-safe
under OpenMP; change it from a plain static bool to a static std::atomic_bool
and update warnIfCCSWithSmallTolerance(DriftTimeUnit, double) to perform a
single atomic test-and-set using atomic.exchange(true) so only the first thread
logs the warning. Modify getBiosaur2CCSWarningShown() to return the atomic_bool
(or a reference to it) and replace the current boolean check/write in
warnIfCCSWithSmallTolerance with a call to exchange to ensure atomic
check-and-set semantics; include the appropriate <atomic> header where needed.

Comment on lines +42 to +58
// Helper to warn once if CCS data is detected with small IM tolerances
static bool& getCCSWarningShown()
{
static bool shown = false;
return shown;
}

static void warnIfCCSWithSmallTolerance(DriftTimeUnit unit, double im_tolerance, const String& param_name)
{
if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0 && !getCCSWarningShown())
{
OPENMS_LOG_WARN << "Warning: Ion mobility data is in CCS units (square angstroms), but " << param_name
<< " = " << im_tolerance << " appears to be set for 1/K0 data. "
<< "For CCS data, consider using larger values (e.g., 10-20 for clustering, 1.0 for summing)." << std::endl;
getCCSWarningShown() = 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 | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the actual code in PeakPickerIM.cpp around lines 42-58
sed -n '35,65p' src/openms/source/PROCESSING/CENTROIDING/PeakPickerIM.cpp

Repository: OpenMS/OpenMS

Length of output: 1130


🏁 Script executed:

# Search for parallel/concurrent usage patterns of PeakPickerIM
rg -n "PeakPickerIM|#pragma omp|std::thread|std::async|pickIMTraces|pickIMCluster" src/openms --type cpp --type hpp -A 2 -B 2 | head -100

Repository: OpenMS/OpenMS

Length of output: 84


🏁 Script executed:

# Check if PeakPickerIM or related functions are called within OpenMP parallel regions
rg -n "#pragma omp\s*(parallel|for)" src/openms --type cpp -A 10 | grep -A 10 "PeakPickerIM\|pickIM"

Repository: OpenMS/OpenMS

Length of output: 39


🏁 Script executed:

# Look for threading patterns and async operations in the codebase to assess if thread-safety is a real concern
fd -e cpp -e hpp | xargs grep -l "std::thread\|std::async\|#pragma omp parallel" | head -20

Repository: OpenMS/OpenMS

Length of output: 1140


🏁 Script executed:

# Check the PeakPickerIM class definition and documentation for thread-safety mentions
sed -n '1,150p' src/openms/source/PROCESSING/CENTROIDING/PeakPickerIM.cpp | grep -A 5 -B 5 "class PeakPickerIM\|thread\|concurrent\|parallel\|Thread"

Repository: OpenMS/OpenMS

Length of output: 39


🏁 Script executed:

# Check the header file for the class
find src/openms -name "PeakPickerIM.h" -exec head -100 {} \;

Repository: OpenMS/OpenMS

Length of output: 4524


🏁 Script executed:

# Look for OpenMS logging practices in similar files to confirm std::endl issue is systematic
rg "OPENMS_LOG_WARN.*std::endl" src/openms --type cpp | head -20

Repository: OpenMS/OpenMS

Length of output: 3835


🏁 Script executed:

# Search for std::once_flag usage patterns in existing codebase to check if it's already used
rg "std::once_flag|std::call_once" src/openms --type cpp -B 2 -A 2

Repository: OpenMS/OpenMS

Length of output: 39


Replace static mutable state with std::once_flag and change std::endl to '\n'.

The getCCSWarningShown() pattern introduces a data race if warnIfCCSWithSmallTolerance() is called from multiple threads, and std::endl violates the coding guideline (prefer '\n' for performance in logging).

Suggested fix
+#include <mutex>
+
     static void warnIfCCSWithSmallTolerance(DriftTimeUnit unit, double im_tolerance, const String& param_name)
     {
-      static bool& getCCSWarningShown()
-      {
-        static bool shown = false;
-        return shown;
-      }
-      if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0 && !getCCSWarningShown())
+      static std::once_flag warn_once;
+      if (unit == DriftTimeUnit::CCS && im_tolerance < 1.0)
       {
-        OPENMS_LOG_WARN << "Warning: Ion mobility data is in CCS units (square angstroms), but " << param_name
-                        << " = " << im_tolerance << " appears to be set for 1/K0 data. "
-                        << "For CCS data, consider using larger values (e.g., 10-20 for clustering, 1.0 for summing)." << std::endl;
-        getCCSWarningShown() = true;
+        std::call_once(warn_once, [&]()
+        {
+          OPENMS_LOG_WARN << "Warning: Ion mobility data is in CCS units (square angstroms), but " << param_name
+                          << " = " << im_tolerance << " appears to be set for 1/K0 data. "
+                          << "For CCS data, consider using larger values (e.g., 10-20 for clustering, 1.0 for summing)." << '\n';
+        });
       }
     }
🤖 Prompt for AI Agents
In `@src/openms/source/PROCESSING/CENTROIDING/PeakPickerIM.cpp` around lines 42 -
58, The code uses a static mutable bool via getCCSWarningShown() which is not
thread-safe; replace that pattern with a static std::once_flag (e.g., static
std::once_flag ccs_warning_once;) and call std::call_once(ccs_warning_once, [&]{
OPENMS_LOG_WARN << ... << '\n'; }); inside warnIfCCSWithSmallTolerance so the
warning runs exactly once in a thread-safe way; also change the logging
terminator from std::endl to '\n' and add the required `#include` <mutex>.

timosachsenberg and others added 2 commits February 4, 2026 00:43
Move CCS tolerance warning checks from parallel code paths to
single-threaded algorithm entry points:

- Biosaur2Algorithm: Check in run() before OpenMP parallel loop
- MassTraceDetection: Check at start of run() before processing
- FeatureFinderIdentificationAlgorithm: Inline check in run()
- PeakPickerIM: Use mutable member variable for per-instance tracking

This eliminates potential race conditions from static bool flags
accessed in parallel code, simplifies the code, and places
configuration validation at algorithm startup where it belongs.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
The ion_mobility_tolerance parameter description was updated in
MassTraceDetection.cpp to include guidance for CCS data, but the
test expected file was not updated accordingly.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@timosachsenberg
timosachsenberg merged commit 4fb67c5 into develop Feb 4, 2026
49 of 51 checks passed
@timosachsenberg
timosachsenberg deleted the claude/cherry-pick-757e57b-cT0wV branch February 4, 2026 12:05
@jcharkow

jcharkow commented Feb 4, 2026

Copy link
Copy Markdown
Collaborator

Looks good to me. I like the scale invariant epsilon. For OpenSwath, we only use inverse ion mobility, so I'm not sure how it would work if the expected float data array was CCS instead. Would probably need to check and convert to inverse ion mobility.

Although, I've only ever used mzML files converted with MOBI-DIK (diapysef) for timsTOF data, but would probably be worth while testing that it still works as expected with MSConvert. @jcharkow I think at one point you were testing msconverts mzML with OpenSwath in the early stages of diaPASEF?

Yes I was it works for the most part however I was experiencing something where OpenSwath would just randomly stop if using "cacheWorkingInMemory" (was working fine with normal reading).

I ultimately kept using diapysef because msconvert encodes ion mobility as base64 which makes the files bigger.

@jcharkow jcharkow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good. I know it is already merged but just wanted bring the eps change up as a point of discussion.


// Compute eps as a fraction of the IM range to be scale-invariant across different IM units
// For VSSC (~0.8-1.5 range), this gives ~1e-5; for CCS (~300-500 range), this gives ~0.002
double eps = std::max(1e-8, im_range.getSpan() * 1e-5);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@singjc is this going to mess up some of your ion mobility scoring or it seems reasonable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the comment. Yeah I can't really judge if this breaks things. Safest bet would be to error out or (rather costly) convert the data. Happy to implement suggestions.

timosachsenberg added a commit that referenced this pull request Feb 5, 2026
)

* Add CCS (collisional cross section) support for ion mobility data

ProteoWizard/MSConvert v3.0.26007+ changed ion mobility representation
from 1/K0 (MS:1002815) to CCS (MS:1002954). This breaks NuXL and other
tools that rely on ion mobility data from mzML files.

Changes:
- Add CCS to DriftTimeUnit enum (IMTypes.h)
- Add IM_CCS to DIM_UNIT enum (CommonEnums.h)
- Parse MS:1002954 (CCS) in mzML reader (MzMLHandler.cpp)
- Write CCS values back to mzML with correct CV terms
- Update IMDataConverter to recognize CCS from CV terms
- Skip CCS conversion in NuXL when data is already CCS
- Make IonMobilityScoring epsilon scale-invariant for CCS compatibility
- Update parameter documentation to mention CCS units
- Add CCS to Python bindings (IMTypes.pxd, MSSpectrum.pyx)

Fixes: #8732

(cherry picked from commit 757e57b)

https://claude.ai/code/session_01MiYNbe4sAxvwNYk4eoPLKu

* Address PR review comments for CCS ion mobility support

- Fix metadata consistency in OpenNuXL.cpp: set DriftTimeUnit::CCS after
  VSSC→CCS conversion
- Add INVERSE_REDUCED_ION_MOBILITY constant for MSConvert compatibility
- Extend IMDataConverter::getIMUnit() to recognize MSConvert naming
- Add CCS detection warnings to OpenSwath (expects 1/K0 units)
- Add CCS warnings with tolerance checks to PeakPickerIM, MassTraceDetection,
  Biosaur2Algorithm, and FeatureFinderIdentificationAlgorithm
- Update documentation for IM tolerance parameters to include CCS typical values

All warnings use proper CV term-based unit detection via DriftTimeUnit enum.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Refactor CCS warning checks to avoid race conditions

Move CCS tolerance warning checks from parallel code paths to
single-threaded algorithm entry points:

- Biosaur2Algorithm: Check in run() before OpenMP parallel loop
- MassTraceDetection: Check at start of run() before processing
- FeatureFinderIdentificationAlgorithm: Inline check in run()
- PeakPickerIM: Use mutable member variable for per-instance tracking

This eliminates potential race conditions from static bool flags
accessed in parallel code, simplifies the code, and places
configuration validation at algorithm startup where it belongs.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Update MassTraceExtractor test expected output for CCS description

The ion_mobility_tolerance parameter description was updated in
MassTraceDetection.cpp to include guidance for CCS data, but the
test expected file was not updated accordingly.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

---------

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.

msconvert: representation of ion mobility changed

5 participants