Skip to content

GSoC 2026: imzML Parser in OpenMS - #9454

Merged
timosachsenberg merged 30 commits into
OpenMS:developfrom
Aditya-Sarna:develop
Jun 15, 2026
Merged

timosachsenberg merged 30 commits into
OpenMS:developfrom
Aditya-Sarna:develop

Conversation

@Aditya-Sarna

@Aditya-Sarna Aditya-Sarna commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Important

API updated (maintainer follow-up). This branch was rebased on develop and imzML is now a first-class imaging format: I/O goes through ImzMLFile ↔ MSImagingExperiment (not the generic FileHandler / a flat MSExperiment), consistent with BrukerTimsImagingFile. The original task write-up below predates this — see the full change summary. Current API:

Read

  • ImzMLFile().load(file, MSImagingExperiment&) — full in-memory load; getMSExperiment() exposes the flat spectra, getGeometry() the pixel grid.
  • ImzMLFile().load(file, IMSDataConsumer&) — streaming; loadSpectraIndex(...) + OnDiscImzMLExperiment — on-disc random access.
  • MSImagingGeometry is the source of truth for coordinates: built directly from the parsed index (not imzml:x/y MetaValues), via one shared builder for the in-memory and on-disc paths.
  • FileHandler::loadExperiment() throws InvalidFileType for imzML (getType / getTypeByContent still detect it).

Write

  • ImzMLFile().store(file, MSImagingExperiment&) — geometry-driven (coordinates/dimensions/pixel size from MSImagingGeometry); works for any imaging experiment, including geometry-only ones (e.g. Bruker-loaded).
  • ImzMLFile().store(file, MSExperiment&) — low-level path (spectra must carry imzml:x/y).
  • FileHandler::storeExperiment() no longer stores imzML.

Removed/changed vs. the description below: the load(MSExperiment&) overload, imzML routing in FileHandler, and the demo_imzML_*.py scripts. Task 4 ("integrate with MSExperiment/MSSpectrum") is realized via MSImagingExperiment.


This PR is in reference to the project titled “imzML Parser in OpenMS” under the theme “Data Formats and Interoperability” for Google Summer of Code 2026.

Mentee: Aditya Sarna
Mentor: Timo Sachsenberg

Tasks listed on the OpenMS website

1)Implement a C++ imzML reader capable of parsing both continuous and processed imzML formats.
2) Implement an imzML writer to enable export of imaging mass spectrometry data.
3) Add support for common imzML metadata, including coordinates, pixel size, and spectrum parameters.
4) Integrate the parser with existing OpenMS data structures such as MSExperiment and MSSpectrum.
5) Write comprehensive unit tests and validate functionality against reference imzML datasets.
6) Document the newly added functionality and provide usage examples.

Task completion

Task 1- Implement a C++ imzML reader capable of parsing both continuous and processed imzML formats

The reader was implemented as ImzMLFile with an internal ImzMLHandler that extends OpenMS’s existing MzMLHandler, reusing the mzML 1.1.0 SAX parser while intercepting Imaging MS (IMS) controlled vocabulary terms.

Both encoding modes are supported through a unified decode path. In continuous mode (IMS:1000030), all pixels share one m/z axis stored once in the .ibd file; each spectrum references the same m/z offset and stores only its own intensity block. In processed mode (IMS:1000031), every pixel carries independent m/z and intensity arrays. For each spectrum, the handler records byte offsets, element counts, and scalar types; ImzMLBinaryIO then seeks into the .ibd file and decodes the arrays into peak data on an MSSpectrum.

Multiple load strategies are provided: full in-memory load, streaming via IMSDataConsumer (batched after the spectrumList section is parsed, same as MzMLHandler), index-only parsing via loadSpectraIndex() for on-disc random access (OnDiscImzMLExperiment), and in-memory pixel lookup via MSImagingExperiment. Validation is available through isValid(). The reader was verified against reference continuous and processed example files from the imzML project.

Tests: ImzMLFile_test.cpp (load, streaming, on-disc, processed, validation), ImzMLFile_all_modes_test.cpp (load modes 1–6, buildImagingGeometry, cross-mode consistency, processed encoding), test_ImzMLFile.py, test_ImzMLFile_modes.py

Fixtures: ImzMLFile_1_Example_Continuous.{imzML,ibd}, ImzMLFile_2_Example_Processed.{imzML,ibd}
Demos: doc/code_examples/Tutorial_ImzMLFile.cpp → Tutorial_ImzMLFile, src/pyOpenMS/demo_imzML_modes.py

Screenshot 2026-06-06 at 9 58 00 PM

Task 2 — Implement an imzML writer to enable export of imaging mass spectrometry data

An imzML export path was added through ImzMLFile::store(), backed by Internal::ImzMLWriter. The writer serializes an MSExperiment into a valid .imzML XML document and a companion .ibd file with external binary arrays (IMS:1000101).

The writer automatically selects continuous or processed mode based on imzml:imaging_mode metadata or by checking whether all spectra share an identical m/z axis. Continuous export stores the m/z array once and writes per-pixel intensity blocks; processed export writes separate m/z and intensity arrays for each spectrum. Binary precision is configurable through PeakFileOptions (float32/float64 for m/z and intensity). Optional spectrum and peak filtering (MS level, RT range, m/z range, sort order) is honored during export. Round-trip tests confirm that exported files reload correctly and pass schema validation.

Tests: ImzMLFile_test.cpp (store round-trip, isValid, reject invalid input, precision/filter options), test_ImzMLFile.py (store/isValid/reject/filter/precision)
Demo: Tutorial_ImzMLFile Mode 7 (store + reload)

Screenshot 2026-06-07 at 3 22 01 AM

Task 3 — Add support for common imzML metadata, including coordinates, pixel size, and spectrum parameters

Dataset-level imaging metadata is captured in the ImzMLMeta structure and mirrored as MetaValues on MSExperiment after load (e.g. imzml:imaging_mode, imzml:max_count_x/y, imzml:pixel_size_x/y, UUID, MD5/SHA-1 checksums, scan pattern, scan direction, line scan direction, polarity, and binary array data types).

Per-spectrum metadata is attached to each MSSpectrum: pixel coordinates as imzml:x, imzml:y, and imzml:z (1-based, matching the imzML convention), along with standard mzML fields such as retention time and MS level where present in the source file. On export, this metadata is written back into the XML when available. ImzMLSpectrumIndex records per-spectrum binary layout (offsets, lengths, types, coordinates) for efficient on-disc access without reloading the full dataset.

Tests: ImzMLFile_test.cpp (dataset metadata mirrored on MSExperiment after load, store metadata round-trip), test_ImzMLFile.py (test_load_dataset_metadata_mirrored_on_experiment, test_load_spectra_index, test_on_disc_index_and_meta, test_store_metadata_round_trip)
Demos: src/pyOpenMS/demo_imzML_metadata.py, tools/run_imzML_metadata_demo.sh, metadata block in Tutorial_ImzMLFile Mode 1

Screenshot 2026-06-06 at 11 22 32 PM

Task 4 — Integrate the parser with existing OpenMS data structures such as MSExperiment and MSSpectrum

Rather than introducing a separate imzML-specific spectrum type, each imzML pixel maps directly to an existing MSSpectrum with m/z–intensity peaks and imaging MetaValues. A full dataset loads into MSExperiment (OpenMS’s standard in-memory MS container).

Integration extends beyond the kernel types: FileTypes::IMZML was registered and FileHandler dispatches imzML load/store through ImzMLFile, enabling generic FileHandler().loadExperiment("file.imzML", exp) and FileHandler().storeExperiment("file.imzML", exp) usage. For imaging-specific workflows, MSImagingExperiment supports in-memory lookup by pixel coordinate, and OnDiscImzMLExperiment provides lazy, index-based spectrum retrieval analogous to indexed mzML. pyOpenMS bindings expose the main public API (ImzMLFile, ImzMLMeta, ImzMLSpectrumIndex, OnDiscImzMLExperiment, MSImagingExperiment, FileType.IMZML) so Python workflows use the same data structures as C++.

Tests: ImzMLFile_all_modes_test.cpp, FileHandler_test.cpp, FileTypes_test.cpp, test_ImzMLFile.py (FileHandler, imaging, geometry), test_ImzMLFile_modes.py, test_FileTypes.py

Demos: Tutorial_ImzMLFile, demo_imzML_modes.py

Task 5 — Write comprehensive unit tests and validate functionality against reference imzML datasets

C++ tests in ImzMLFile_test.cpp and ImzMLFile_all_modes_test.cpp cover the reader, writer, metadata round-trip, validation, FileHandler/FileTypes integration, and seven access patterns: full in-memory load, FileHandler dispatch, streaming consumer, index-only parsing (loadSpectraIndex), on-disc random access (OnDiscImzMLExperiment), in-memory pixel lookup (MSImagingExperiment), and geometry build (buildImagingGeometry). Additional sections test cross-mode peak-count consistency and processed-mode encoding. Tests use imzML-style reference fixtures: ImzMLFile_1_Example_Continuous (shared m/z axis, 3×3 grid, 9 spectra) and ImzMLFile_2_Example_Processed (per-spectrum m/z, same grid layout).

Python unit tests mirror this coverage in test_ImzMLFile.py and test_ImzMLFile_modes.py, including store round-trip, metadata preservation, precision options, continuous-mode compatibility checks, and processed-mode encoding. Tests assert correct imaging mode detection, pixel coordinate assignment, spectrum counts, peak data integrity, and on-disc coordinate lookup. All imzML-specific C++ and Python tests pass locally against the reference datasets.

Task 6 — Document the newly added functionality and provide usage examples

Public classes and methods are documented with Doxygen (@ brief, @. param, @ throws, cross-references to related classes). Key public APIs include ImzMLFile, ImzMLMeta, ImzMLSpectrumIndex, and OnDiscImzMLExperiment. Export is via ImzMLFile::store() (implemented by Internal::ImzMLWriter).

A C++ tutorial (doc/code_examples/Tutorial_ImzMLFile.cpp) demonstrates load modes 1–6 (full load, FileHandler, streaming, loadSpectraIndex, on-disc access, imaging lookup), metadata inspection in Mode 1, and export round-trip (Mode 7). It is built as the Tutorial_ImzMLFile executable. Python demo scripts (src/pyOpenMS/demo_imzML_modes.py, demo_imzML_metadata.py, tools/run_imzML_metadata_demo.sh) show equivalent load and metadata workflows from pyOpenMS; export round-trip is demonstrated in the C++ tutorial only. The CHANGELOG entry summarizes the new feature for release notes. Together, the documentation covers what imzML is, how continuous and processed modes differ, which OpenMS classes to use for each access pattern, and how to load, inspect, export, and validate imzML data in both C++ and Python.

Examples: Tutorial_ImzMLFile.cpp, demo_imzML_modes.py, demo_imzML_metadata.py, run_imzML_metadata_demo.sh

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 unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

Commits

[FEATURE,TEST,API] Add imzML read and write support
[FEATURE,TEST] Extend ImzML writer with options, metadata, precision
[TEST,DOC] Add imzML dataset metadata tests and demo scripts
[DOC] Correct imzML export precision documentation
[FIX,TEST] Fix imzML max_dim export and align modes tests
[DOC] Fix max_dim unit label in imzML metadata demo

Summary by CodeRabbit

  • New Features

    • Full imzML imaging support: import/export, in-memory loading, batched streaming, on-disk random access, pixel lookup, configurable export precision and filtering; pyOpenMS bindings for imzML and on-disc access.
  • Documentation

    • Added a tutorial demonstrating six imzML load/store workflows.
  • Tests

    • Comprehensive unit/integration tests and fixtures covering imzML modes, IO, validation, and round-trips.
  • Chores

    • Added contributor to AUTHORS and updated changelog.

@github-actions

github-actions Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Welcome @Aditya-Sarna and thank you for your contribution to OpenMS! To help us better understand our userbase and contributors, we would appreciate if you could complete the survey at the link below. Completing this survey will help us get to your PR sooner. Thank you for your participation!

Survey

@github-actions

github-actions Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

@Aditya-Sarna The following names might be missing from the AUTHORS file:

  • Aditya Sarna

Please consider applying the following patch:

--- AUTHORS	2026-06-06 22:38:02.456977621 +0000
+++ AUTHORS.new	2026-06-06 22:38:07.690047192 +0000
@@ -23,8 +23,8 @@
  - Chirag Dave
  - Chris Bauer
  - Chris Bielow
- - Christie Mathews
  - Christian Ehrlich
+ - Christie Mathews
  - Clemens Groepl
  - Cornelia Friedle
  - Daniel Jameson

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds full imzML (.imzML + .ibd) support: FileTypes::IMZML, SAX-based imzML parsing with IMS CV handling, endian-aware .ibd binary IO, ImzMLFile loader/writer, OnDiscImzMLExperiment, pyOpenMS bindings, tutorial/example assets, and extensive C++/Python tests and fixtures.

Changes

imzML format implementation and rollout

Layer / File(s) Summary
Complete imzML support
src/openms/include/OpenMS/FORMAT/*, src/openms/source/FORMAT/*, src/openms/source/KERNEL/*, src/pyOpenMS/*, doc/code_examples/*, src/tests/*, AUTHORS, CHANGELOG
Adds FileTypes::IMZML; declares and implements ImzMLMeta, ImzMLSpectrumIndex, ImzMLBinaryIO, ImzMLHandler, ImzMLWriter::store, ImzMLFile (load/index/store/isValid/buildImagingGeometry), OnDiscImzMLExperiment (on‑disc access), pyOpenMS bindings, tutorial/example data and executable, and comprehensive C++/Python tests and fixtures.

Possibly related PRs

  • OpenMS/OpenMS#9381: Related MSI core types and imaging structures used by this imzML integration.
  • OpenMS/OpenMS#9139: Overlapping ZIP/gzip decompression and getTypeByContent detection changes.

Suggested reviewers

  • timosachsenberg
  • jpfeuffer

🐰 I hopped through pixels, peaks in tow,
reading .imzML where spectra glow.
On‑disc or in RAM, I fetch each frame —
write UUIDs, checksums, and call them by name.
Hooray — imzML now leaps into our flow!

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

@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: 11

🧹 Nitpick comments (4)
src/pyOpenMS/bindings/bind_format.cpp (1)

750-783: ⚡ Quick win

Add the standard copy hooks to the new value bindings.

ImzMLMeta and ImzMLSpectrumIndex are exposed as public value objects, but unlike the surrounding pyOpenMS bindings they do not define __copy__/__deepcopy__. That makes these new return types inconsistent to use from Python.

Suggested change
     nb::class_<OpenMS::ImzMLMeta>(m, "ImzMLMeta", "Dataset-level imzML imaging metadata")
         .def(nb::init<>())
+        .def("__copy__", [](const OpenMS::ImzMLMeta& self) { return OpenMS::ImzMLMeta(self); })
+        .def("__deepcopy__", [](const OpenMS::ImzMLMeta& self, nb::dict) { return OpenMS::ImzMLMeta(self); }, "memo"_a)
         .def_ro("max_count_x", &OpenMS::ImzMLMeta::max_count_x)
         .def_ro("max_count_y", &OpenMS::ImzMLMeta::max_count_y)
         .def_ro("max_count_z", &OpenMS::ImzMLMeta::max_count_z)
@@
     nb::class_<OpenMS::ImzMLSpectrumIndex>(m, "ImzMLSpectrumIndex",
         "Per-spectrum .ibd byte-offset index entry for on-disc imzML access")
         .def(nb::init<>())
+        .def("__copy__", [](const OpenMS::ImzMLSpectrumIndex& self) { return OpenMS::ImzMLSpectrumIndex(self); })
+        .def("__deepcopy__", [](const OpenMS::ImzMLSpectrumIndex& self, nb::dict) { return OpenMS::ImzMLSpectrumIndex(self); }, "memo"_a)
         .def_ro("index", &OpenMS::ImzMLSpectrumIndex::index)
         .def_ro("x", &OpenMS::ImzMLSpectrumIndex::x)
         .def_ro("y", &OpenMS::ImzMLSpectrumIndex::y)

Based on learnings, hand-maintained pyOpenMS bindings should define class bindings with a constructor, __copy__, and __deepcopy__.

🤖 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/pyOpenMS/bindings/bind_format.cpp` around lines 750 - 783, ImzMLMeta and
ImzMLSpectrumIndex are value objects but lack Python copy hooks; add __copy__
and __deepcopy__ bindings for both classes (in the same nb::class_<...> blocks
that already have nb::init<>()), implementing __copy__ to return the object
by-value and __deepcopy__ to return the object by-value while accepting the memo
parameter (e.g. def("__copy__", [](const OpenMS::ImzMLMeta &s){ return s; }) and
def("__deepcopy__", [](const OpenMS::ImzMLMeta &s, py::dict){ return s; }) — do
the analogous additions for ImzMLSpectrumIndex) so Python code can copy these
value types consistently.

Sources: Coding guidelines, Learnings

src/openms/source/FORMAT/HANDLERS/ImzMLHandler.cpp (1)

147-151: ⚡ Quick win

Fail fast on spectrum-to-IMS snapshot desynchronization.

When spec_idx_ exceeds spec_ims_.size(), the code silently skips IMS annotation/indexing and still forwards the spectrum. That can produce partially-corrupted output state without an explicit failure.

Suggested hardening
-    const ImzMLHandler::SpecIMS* ims = nullptr;
-    if (idx < static_cast<int>(handler_.spec_ims_.size()))
-      ims = &handler_.spec_ims_[idx];
+    if (idx >= static_cast<int>(handler_.spec_ims_.size()))
+    {
+      throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+                                  handler_.meta_.ibd_file_path,
+                                  "Mismatch between delivered spectra and captured imzML IMS state");
+    }
+    const ImzMLHandler::SpecIMS* ims = &handler_.spec_ims_[idx];
🤖 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/HANDLERS/ImzMLHandler.cpp` around lines 147 - 151,
The code lets spec_idx_ advance past handler_.spec_ims_.size() and silently
omits IMS annotation; change this to fail fast: after computing const int idx =
spec_idx_++; check if idx is out of range (idx < 0 || idx >=
static_cast<int>(handler_.spec_ims_.size())) and immediately report an error or
throw (e.g., runtime_error) rather than continuing, so the mismatch between
spec_idx_ and handler_.spec_ims_ is detected; update handling around
ImzMLHandler::SpecIMS pointer resolution (the ims variable) to assume a valid
index once the check passes.
src/tests/class_tests/openms/source/FileHandler_test.cpp (1)

309-318: ⚡ Quick win

Add processed imzML coverage in this FileHandler load smoke test.

This section currently validates only the continuous fixture. Adding one processed fixture load here would protect FileHandler::loadExperiment dispatch for both supported imzML encodings.

Suggested addition
 START_SECTION((void loadExperiment(const String& filename, PeakMap& exp) imzML))
   FileHandler fh_imz;
   PeakMap exp_imz;
   fh_imz.loadExperiment(OPENMS_GET_TEST_DATA_PATH("ImzMLFile_1_Example_Continuous.imzML"), exp_imz);
   TEST_EQUAL(exp_imz.getNrSpectra() > 0, true)
   if (exp_imz.getNrSpectra() > 0)
   {
     TEST_EQUAL(exp_imz[0].size() > 0, true)
   }
+  fh_imz.loadExperiment(OPENMS_GET_TEST_DATA_PATH("ImzMLFile_2_Example_Processed.imzML"), exp_imz);
+  TEST_EQUAL(exp_imz.getNrSpectra() > 0, true)
 END_SECTION

Based on learnings, src/tests/class_tests/**/*_test.cpp should include unit tests for new functionality.

🤖 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/FileHandler_test.cpp` around lines 309 -
318, Add a second imzML load for the processed encoding to cover dispatch in
FileHandler::loadExperiment: after the existing continuous test using fh_imz and
exp_imz, create a new PeakMap (e.g. exp_imz_processed) and call
fh_imz.loadExperiment with the processed imzML fixture path, then assert
exp_imz_processed.getNrSpectra() > 0 and that exp_imz_processed[0].size() > 0
(mirroring the existing checks) so both continuous and processed imzML encodings
are exercised.

Source: Learnings

src/tests/class_tests/openms/source/FileTypes_test.cpp (1)

157-157: ⚡ Quick win

Avoid hard-coding the total readable-type count.

Line 157 is brittle: any unrelated new readable type will break this test. Prefer asserting inclusion of expected types (e.g., IMZML) and optionally a lower bound.

Suggested refactor
-    TEST_EQUAL(g.getTypes().size(), 49);
+    TEST_EQUAL(g.contains(FileTypes::IMZML), true);
+    TEST_EQUAL(g.getTypes().size() >= 49, 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/FileTypes_test.cpp` at line 157, The test
currently asserts an exact count with TEST_EQUAL(g.getTypes().size(), 49) which
is brittle; change it to check for inclusion of specific known readable types
instead and optionally a lower bound. Locate the test using TEST_EQUAL and
g.getTypes(), replace the exact-size assertion with an assertion that
g.getTypes() contains expected entries (e.g., "IMZML" or the enum/identifier
used for IMZML) and, if desired, assert g.getTypes().size() >= N to allow
growth. Ensure you reference the same getTypes() call and keep other test logic
intact.
🤖 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 `@doc/code_examples/Tutorial_ImzMLFile.cpp`:
- Around line 32-37: The code prints spectrum info using std::cout/std::cerr
(e.g., lines that output spec[i].getMZ() and spec[i].getIntensity(), and other
blocks mentioned) which violates the project logging policy; replace all
std::cout and std::cerr usages in this file with OpenMS logging (e.g., LOG_INFO,
LOG_ERROR or OpenMS::LogStream/OpenMS::Logger) so messages go through OpenMS's
log routing and respect verbosity controls, formatting the same text that
currently uses spec, getMZ(), getIntensity(), and any other variables passed to
std::cout; ensure multi-line or repeated prints use the appropriate log level
and remove direct std::ostream usage throughout the file.

In `@src/openms/include/OpenMS/KERNEL/OnDiscImzMLExperiment.h`:
- Around line 66-67: The move constructor
OnDiscImzMLExperiment(OnDiscImzMLExperiment&&) and move assignment
OnDiscImzMLExperiment& operator=(OnDiscImzMLExperiment&&) are declared noexcept
but their bodies allocate with other.pimpl_ = std::make_unique<Impl>() which can
throw; remove the noexcept specifier from both declarations (or alternatively
change the implementations to guarantee non-throwing allocation via a noexcept
swap/steal pattern or try/catch and fallback) so that exceptions from
std::make_unique do not trigger std::terminate; update both the declaration and
any corresponding definition signatures for
OnDiscImzMLExperiment::OnDiscImzMLExperiment and
OnDiscImzMLExperiment::operator= accordingly.

In `@src/openms/source/FORMAT/FileHandler.cpp`:
- Around line 954-960: The IMZML load path currently only hashes the XML side
(SHA1(filename)) in the generic rewrite_source_file logic, which misses the
companion .ibd payload; update the FileTypes::IMZML case in FileHandler.cpp
(where ImzMLFile f; f.load(filename, exp); is used) to special-case checksum
computation by including the associated .ibd binary when producing the
SourceFile checksum (either compute SHA1 over both the .imzML XML and its .ibd
companion or call an ImzML-aware helper that returns a combined hash) so
rewritten SourceFile entries uniquely reflect both XML and binary payloads
instead of reusing the single-file hashing path.

In `@src/openms/source/FORMAT/HANDLERS/ImzMLHandlerHelper.cpp`:
- Around line 259-262: The early return when 'ibd' is null (and count == 0) in
ImzMLHandlerHelper.cpp silently treats a failed .ibd write as success; replace
the silent return with proper error reporting: when 'ibd' is nullptr (or write
fails), emit a clear error (throw a std::runtime_error or use the project's
existing error reporting mechanism) with a message that includes context (e.g.
"ibd FILE* is null while attempting to write binary data" and relevant
identifiers) and ensure the caller receives a non-success status; apply the same
change to the second occurrence handling the same 'ibd' null-check.

In `@src/openms/source/FORMAT/HANDLERS/ImzMLWriter.cpp`:
- Around line 368-370: The code accepts partial parses from std::strtoul (e.g.,
"1g") because it only checks if no digit was parsed; update the validation
around the call that parses byte_str (in ImzMLWriter code path where byte_str is
parsed) to ensure the entire string was consumed and that the input length is
exactly the expected hex byte length: check byte_str.size()==2 (or the expected
length) and that end points to the end of byte_str (i.e., end ==
byte_str.c_str() + byte_str.size()), and keep the existing range check value <=
255; reject the input if these conditions fail so partially parsed hex strings
are not accepted.
- Around line 479-482: spectraShareMz_ currently skips empty spectra (by
continuing) but doesn't mark them as incompatible with continuous-mode sharing,
which later allows a non-zero shared m/z count to be assigned for empty spectra;
update the logic in the loop that checks s.empty() (the code populating
spectraShareMz_) to explicitly mark empty spectra as incompatible for sharing
(e.g., set spectraShareMz_[index] = 0 or flip the same incompatibility flag used
for non-matching m/z lists) instead of just continuing, and also ensure the
later assignment code that sets the shared m/z count (the block around the
shared m/z assignment at line ~1188) checks spectraShareMz_ (or the
incompatibility flag) and skips or leaves the count zero for entries that were
marked incompatible/empty.

In `@src/openms/source/FORMAT/ImzMLFile.cpp`:
- Around line 99-120: The GlobalLogSilencer currently removes all sinks from the
global warn/error loggers in its constructor and later restores only std::cerr
in the destructor, which drops previously configured sinks; change
GlobalLogSilencer (constructor/destructor) to capture and store the existing
sink list/streams from getGlobalLogWarn() and getGlobalLogError() before muting,
then restore that exact list on destruction (rather than calling
insert(std::cerr)); ensure you preserve and restore both levels and all
previously registered streams so logging state is fully reverted after
GlobalLogSilencer goes out of scope.
- Around line 322-330: The catch blocks for xercesc::XMLException and
xercesc::SAXException leak memory because xercesc::XMLString::transcode(...)
returns a char* that must be released; update both catch blocks (the throw sites
in ImzMLFile.cpp handling XMLException and SAXException) to store the result of
XMLString::transcode(e.getMessage()) in a local char* variable, use that pointer
to build the OpenMS String message, then call xercesc::XMLString::release(&ptr)
before throwing the Exception::ParseError so the transcoded memory is freed.

In `@src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp`:
- Around line 234-243: In OnDiscImzMLExperiment::getSpectrumAtCoord, before
using pimpl_->coord_map_ (and before calling pimpl_->buildCoordMap()), add the
same .ibd-open guard used in getSpectrum() to verify the underlying .ibd file is
open; if not open, throw the file-not-open error rather than proceeding and
possibly raising Exception::ElementNotFound. Concretely, insert the identical
check/guard from getSpectrum() (the .ibd guard) immediately after the
coord_map_built_ check and before calling pimpl_->coord_map_.find(key), so the
method uses the same file-open validation as getSpectrum().

In `@src/pyOpenMS/bindings/bind_format.cpp`:
- Around line 823-838: The calls to OpenMS::ImzMLFile::loadSpectraIndex and
::isValid hold the Python GIL during blocking file/XML work; wrap the blocking
sections with a GIL release (use nanobind's nb::gil_scoped_release) so other
Python threads aren't stalled. For loadSpectraIndex, create the ImzMLMeta and
index vector, then release the GIL before calling
self.loadSpectraIndex(filename, meta, index) and reacquire when building the
nb::list to return; for isValid, release the GIL while calling
self.isValid(filename, os) and then return the tuple (ok, os.str()) after
reacquiring the GIL. Ensure you reference the lambda wrappers for
"loadSpectraIndex" and "isValid" when making the change.

In `@src/tests/class_tests/openms/data/ImzMLFile_2_Example_Processed.imzML`:
- Around line 49-51: The MS1 fixture is inconsistent: the cvParam with accession
"MS:1000511" and name "ms level" is set to value="0" while the neighboring
cvParam declares an "MS1 spectrum"; update that cvParam's value from "0" to "1"
so the MS1 spectrum's ms level is semantically correct (ensure the cvParam with
accession MS:1000511 / name "ms level" reflects value="1").

---

Nitpick comments:
In `@src/openms/source/FORMAT/HANDLERS/ImzMLHandler.cpp`:
- Around line 147-151: The code lets spec_idx_ advance past
handler_.spec_ims_.size() and silently omits IMS annotation; change this to fail
fast: after computing const int idx = spec_idx_++; check if idx is out of range
(idx < 0 || idx >= static_cast<int>(handler_.spec_ims_.size())) and immediately
report an error or throw (e.g., runtime_error) rather than continuing, so the
mismatch between spec_idx_ and handler_.spec_ims_ is detected; update handling
around ImzMLHandler::SpecIMS pointer resolution (the ims variable) to assume a
valid index once the check passes.

In `@src/pyOpenMS/bindings/bind_format.cpp`:
- Around line 750-783: ImzMLMeta and ImzMLSpectrumIndex are value objects but
lack Python copy hooks; add __copy__ and __deepcopy__ bindings for both classes
(in the same nb::class_<...> blocks that already have nb::init<>()),
implementing __copy__ to return the object by-value and __deepcopy__ to return
the object by-value while accepting the memo parameter (e.g. def("__copy__",
[](const OpenMS::ImzMLMeta &s){ return s; }) and def("__deepcopy__", [](const
OpenMS::ImzMLMeta &s, py::dict){ return s; }) — do the analogous additions for
ImzMLSpectrumIndex) so Python code can copy these value types consistently.

In `@src/tests/class_tests/openms/source/FileHandler_test.cpp`:
- Around line 309-318: Add a second imzML load for the processed encoding to
cover dispatch in FileHandler::loadExperiment: after the existing continuous
test using fh_imz and exp_imz, create a new PeakMap (e.g. exp_imz_processed) and
call fh_imz.loadExperiment with the processed imzML fixture path, then assert
exp_imz_processed.getNrSpectra() > 0 and that exp_imz_processed[0].size() > 0
(mirroring the existing checks) so both continuous and processed imzML encodings
are exercised.

In `@src/tests/class_tests/openms/source/FileTypes_test.cpp`:
- Line 157: The test currently asserts an exact count with
TEST_EQUAL(g.getTypes().size(), 49) which is brittle; change it to check for
inclusion of specific known readable types instead and optionally a lower bound.
Locate the test using TEST_EQUAL and g.getTypes(), replace the exact-size
assertion with an assertion that g.getTypes() contains expected entries (e.g.,
"IMZML" or the enum/identifier used for IMZML) and, if desired, assert
g.getTypes().size() >= N to allow growth. Ensure you reference the same
getTypes() call and keep other test logic intact.
🪄 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: eefb85bc-de76-49db-aca8-424c38ce5e92

📥 Commits

Reviewing files that changed from the base of the PR and between d8fd0a0 and 564064b.

📒 Files selected for processing (42)
  • AUTHORS
  • CHANGELOG
  • doc/code_examples/CMakeLists.txt
  • doc/code_examples/Tutorial_ImzMLFile.cpp
  • doc/code_examples/executables.cmake
  • src/openms/include/OpenMS/FORMAT/FileTypes.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/ImzMLHandler.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/ImzMLHandlerHelper.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/ImzMLWriter.h
  • src/openms/include/OpenMS/FORMAT/HANDLERS/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ImzMLFile.h
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/include/OpenMS/KERNEL/OnDiscImzMLExperiment.h
  • src/openms/include/OpenMS/KERNEL/sources.cmake
  • src/openms/source/FORMAT/FileHandler.cpp
  • src/openms/source/FORMAT/FileTypes.cpp
  • src/openms/source/FORMAT/HANDLERS/ImzMLHandler.cpp
  • src/openms/source/FORMAT/HANDLERS/ImzMLHandlerHelper.cpp
  • src/openms/source/FORMAT/HANDLERS/ImzMLWriter.cpp
  • src/openms/source/FORMAT/HANDLERS/sources.cmake
  • src/openms/source/FORMAT/ImzMLFile.cpp
  • src/openms/source/FORMAT/sources.cmake
  • src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp
  • src/openms/source/KERNEL/sources.cmake
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/bindings/bind_kernel.cpp
  • src/pyOpenMS/demo_imzML_metadata.py
  • src/pyOpenMS/demo_imzML_modes.py
  • src/pyOpenMS/tests/test_data_paths.py
  • src/pyOpenMS/tests/unittests/test_FileTypes.py
  • src/pyOpenMS/tests/unittests/test_ImzMLFile.py
  • src/pyOpenMS/tests/unittests/test_ImzMLFile_modes.py
  • src/tests/class_tests/openms/data/ImzMLFile_1_Example_Continuous.ibd
  • src/tests/class_tests/openms/data/ImzMLFile_1_Example_Continuous.imzML
  • src/tests/class_tests/openms/data/ImzMLFile_2_Example_Processed.ibd
  • src/tests/class_tests/openms/data/ImzMLFile_2_Example_Processed.imzML
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/FileHandler_test.cpp
  • src/tests/class_tests/openms/source/FileTypes_test.cpp
  • src/tests/class_tests/openms/source/ImzMLFile_all_modes_test.cpp
  • src/tests/class_tests/openms/source/ImzMLFile_test.cpp
  • tools/run_imzML_metadata_demo.sh

Comment thread src/openms/source/FORMAT/ImzMLFile.cpp Resolved
Comment thread src/openms/source/FORMAT/ImzMLFile.cpp Resolved
Comment thread src/pyOpenMS/bindings/bind_format.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.

🧹 Nitpick comments (1)
src/openms/source/FORMAT/FileHandler.cpp (1)

553-564: 💤 Low value

Redundant line-by-line check after full-string check.

The isImzMLContent(decompressed_preview) check at line 549 already uses hasSubstring() on the entire buffer. Splitting by newlines and checking each line individually won't find markers that the full-string check missed.

♻️ Suggested simplification
       if (!decompressed_preview.empty() && isImzMLContent(decompressed_preview))
       {
         return FileTypes::IMZML;
       }
-      if (!decompressed_preview.empty())
-      {
-        vector<String> preview_lines;
-        decompressed_preview.split('\n', preview_lines);
-        for (const String& line : preview_lines)
-        {
-          if (isImzMLContent(line))
-          {
-            return FileTypes::IMZML;
-          }
-        }
-      }
       if (is_uncompressed)
🤖 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/FileHandler.cpp` around lines 553 - 564, The loop
that splits decompressed_preview into preview_lines and checks each line with
isImzMLContent is redundant because isImzMLContent(decompressed_preview) already
examines the full buffer; remove the split and per-line loop (preview_lines, for
(const String& line ...)) and instead rely on the existing
isImzMLContent(decompressed_preview) check to return FileTypes::IMZML (or, if
that prior check is absent, replace the entire block with a single direct check
of isImzMLContent(decompressed_preview) and return FileTypes::IMZML).
🤖 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.

Nitpick comments:
In `@src/openms/source/FORMAT/FileHandler.cpp`:
- Around line 553-564: The loop that splits decompressed_preview into
preview_lines and checks each line with isImzMLContent is redundant because
isImzMLContent(decompressed_preview) already examines the full buffer; remove
the split and per-line loop (preview_lines, for (const String& line ...)) and
instead rely on the existing isImzMLContent(decompressed_preview) check to
return FileTypes::IMZML (or, if that prior check is absent, replace the entire
block with a single direct check of isImzMLContent(decompressed_preview) and
return FileTypes::IMZML).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7e74897b-8128-40e1-8e00-d32bebb2759a

📥 Commits

Reviewing files that changed from the base of the PR and between cd600cf and 541b3c9.

📒 Files selected for processing (2)
  • src/openms/source/FORMAT/FileHandler.cpp
  • src/tests/class_tests/openms/source/FileHandler_test.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/class_tests/openms/source/FileHandler_test.cpp

@timosachsenberg

Copy link
Copy Markdown
Contributor

@patrick-bo maybe you can give it a first pass reviewing it

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

Caution

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

⚠️ Outside diff range comments (3)
src/openms/source/FORMAT/ImzMLFile.cpp (3)

270-272: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't require the sibling .ibd just to build the index.

loadSpectraIndex() is used by OnDiscImzMLExperiment::open() before ibd_path_override is applied, so opening inferIbdPath_(filename) here makes relocated companions fail even when the caller supplies a valid override later. The XML already contains the offsets/types needed for ImzMLMeta and ImzMLSpectrumIndex; defer openIBD() to the non-index paths.

Suggested fix
   const String ibd_path = inferIbdPath_(filename);
-  handler.openIBD(ibd_path);
+  if (!index_only)
+  {
+    handler.openIBD(ibd_path);
+  }
   handler.getImzMLMeta().ibd_file_path = ibd_path;
🤖 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/ImzMLFile.cpp` around lines 270 - 272, The code
currently calls inferIbdPath_(filename), handler.openIBD(ibd_path) and sets
handler.getImzMLMeta().ibd_file_path while building the index, which forces
requiring the sibling .ibd before callers (e.g. OnDiscImzMLExperiment::open /
loadSpectraIndex()) have a chance to apply ibd_path_override; change the logic
so loadSpectraIndex()/index-building does NOT call handler.openIBD or set
ibd_file_path from inferIbdPath_. Instead defer opening the .ibd and assigning
ImzMLMeta::ibd_file_path to the actual open/code paths that load spectra (the
non-index paths) or only do so when an explicit ibd_path_override is already
known; in short, remove or guard the handler.openIBD(ibd_path) and
handler.getImzMLMeta().ibd_file_path = ibd_path lines in the index-building code
and ensure the .ibd is opened later when the real data-access path runs.

179-187: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast on multi-slice data instead of dropping it.

load(const String&, MSImagingExperiment&) keeps every spectrum in the moved MSExperiment, but buildImagingGeometry() silently skips any spectrum with imzml:z != 1. For 3-D imzML this leaves part of the dataset unmapped in the geometry, so pixel lookup no longer reflects the loaded experiment. If MSImagingExperiment is intentionally 2-D here, throw a clear exception instead of continue.

Suggested fix
     if (spec.metaValueExists("imzml:z"))
     {
       z_imz = spec.getMetaValue("imzml:z");
     }
     if (z_imz != 1)
     {
-      continue;
+      throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
+                                    "MSImagingExperiment currently supports only z == 1",
+                                    String(z_imz) + " at spectrum " + i);
     }
🤖 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/ImzMLFile.cpp` around lines 179 - 187, The code in
buildImagingGeometry()/ImzMLFile.cpp currently ignores spectra with meta key
"imzml:z" != 1 (variable z_imz) which leaves 3-D imzML datasets partially
unmapped; change this to fail fast by throwing a clear exception from load(const
String&, MSImagingExperiment&) (or from buildImagingGeometry() caller) when any
spec.getMetaValue("imzml:z") yields a value other than 1 so the caller knows
multi-slice data is unsupported, include the offending z value and spectrum
identifier in the exception message, and remove the silent continue path that
drops spectra from MSImagingExperiment.

247-289: ⚠️ Potential issue | 🟠 Major

Translate Xerces setup failures too.

In ImzMLFile::loadImpl_, the try only wraps reader->parse(src). Failures from XercesPlatformGuard (calls xercesc::XMLPlatformUtils::Initialize()), xercesc::XMLReaderFactory::createXMLReader(), and the setFeature() calls happen outside the try, so they bypass the existing xercesc::XMLException/xercesc::SAXException → Exception::ParseError translation.

🤖 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/ImzMLFile.cpp` around lines 247 - 289, The Xerces
initialization and reader setup (XercesPlatformGuard construction,
XMLReaderFactory::createXMLReader(), and reader->setFeature(...) calls) occur
outside the existing try block in ImzMLFile::loadImpl_, so Xerces exceptions
there aren't translated; wrap the entire Xerces setup and reader
creation/configuration (including XercesPlatformGuard,
Internal::StringManager/sr c creation, std::unique_ptr<xercesc::SAX2XMLReader>
reader = XMLReaderFactory::createXMLReader(), and all
reader->setFeature()/setContentHandler()/setErrorHandler() calls) in the same
try that calls reader->parse(src), or add a surrounding try/catch that catches
xercesc::XMLException and xercesc::SAXException and rethrows as
Exception::ParseError with the same error message/path to ensure all Xerces
failures are translated consistently.
🤖 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.

Outside diff comments:
In `@src/openms/source/FORMAT/ImzMLFile.cpp`:
- Around line 270-272: The code currently calls inferIbdPath_(filename),
handler.openIBD(ibd_path) and sets handler.getImzMLMeta().ibd_file_path while
building the index, which forces requiring the sibling .ibd before callers (e.g.
OnDiscImzMLExperiment::open / loadSpectraIndex()) have a chance to apply
ibd_path_override; change the logic so loadSpectraIndex()/index-building does
NOT call handler.openIBD or set ibd_file_path from inferIbdPath_. Instead defer
opening the .ibd and assigning ImzMLMeta::ibd_file_path to the actual open/code
paths that load spectra (the non-index paths) or only do so when an explicit
ibd_path_override is already known; in short, remove or guard the
handler.openIBD(ibd_path) and handler.getImzMLMeta().ibd_file_path = ibd_path
lines in the index-building code and ensure the .ibd is opened later when the
real data-access path runs.
- Around line 179-187: The code in buildImagingGeometry()/ImzMLFile.cpp
currently ignores spectra with meta key "imzml:z" != 1 (variable z_imz) which
leaves 3-D imzML datasets partially unmapped; change this to fail fast by
throwing a clear exception from load(const String&, MSImagingExperiment&) (or
from buildImagingGeometry() caller) when any spec.getMetaValue("imzml:z") yields
a value other than 1 so the caller knows multi-slice data is unsupported,
include the offending z value and spectrum identifier in the exception message,
and remove the silent continue path that drops spectra from MSImagingExperiment.
- Around line 247-289: The Xerces initialization and reader setup
(XercesPlatformGuard construction, XMLReaderFactory::createXMLReader(), and
reader->setFeature(...) calls) occur outside the existing try block in
ImzMLFile::loadImpl_, so Xerces exceptions there aren't translated; wrap the
entire Xerces setup and reader creation/configuration (including
XercesPlatformGuard, Internal::StringManager/sr c creation,
std::unique_ptr<xercesc::SAX2XMLReader> reader =
XMLReaderFactory::createXMLReader(), and all
reader->setFeature()/setContentHandler()/setErrorHandler() calls) in the same
try that calls reader->parse(src), or add a surrounding try/catch that catches
xercesc::XMLException and xercesc::SAXException and rethrows as
Exception::ParseError with the same error message/path to ensure all Xerces
failures are translated consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a9bb3033-1ac0-4da7-a9c7-c04102fae0f9

📥 Commits

Reviewing files that changed from the base of the PR and between 3503214 and 345a2eb.

📒 Files selected for processing (5)
  • src/openms/source/FORMAT/HANDLERS/ImzMLHandlerHelper.cpp
  • src/openms/source/FORMAT/HANDLERS/ImzMLWriter.cpp
  • src/openms/source/FORMAT/ImzMLFile.cpp
  • src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp
  • src/pyOpenMS/bindings/bind_format.cpp
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/openms/source/FORMAT/HANDLERS/ImzMLWriter.cpp
  • src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/openms/source/FORMAT/HANDLERS/ImzMLHandlerHelper.cpp

Aditya-Sarna and others added 18 commits June 11, 2026 12:06
Add ImzMLFile with full load, streaming, on-disc random access, RAM pixel
lookup, and export via store() (float32 external arrays, UUID-linked .ibd);
register FileTypes::IMZML at end of enum with FileHandler integration;
expose pyOpenMS bindings, tests, tutorial, and demo.

Harden IBD I/O, IMS CV parsing, imaging metadata, schema validation, and
on-disc thread safety. Address review feedback across multiple rounds:
coordinate/z lookups, test guards, batched consumer docs, SAX file parsing,
full ImzMLMeta on load, WRITEABLE file type, big-endian fix, UUID .ibd
header, collision-safe pixel map, streaming MD5, RAII .ibd writes,
continuous-mode validation, hybrid array decode, required pixel coords,
compressed imzML detection, mzML XML ordering, safe move semantics, and
balanced Xerces init/terminate.

Co-authored-by: Cursor <[email protected]>
Apply PeakFileOptions on store (filtering, sort, metadata-only), round-trip
imaging metadata and spectrum RT/MS level, and support float32/float64 .ibd
export via getMz32Bit/getIntensity32Bit with MD5 and SHA-1 checksums.

Co-authored-by: Cursor <[email protected]>
Verify ImzMLMeta is mirrored on MSExperiment for continuous and processed
reference fixtures. Add demo_imzML_metadata.py, a shell runner, and extend
Tutorial_ImzMLFile to print dataset metadata after load.

Co-authored-by: Cursor <[email protected]>
Clarify that ImzMLFile::store() supports float32/float64 via
PeakFileOptions, not float32-only. Update scan_direction CV comment.

Co-authored-by: Cursor <[email protected]>
Correct max_dim_x/y scaling on export (micrometer units). Align Python
all_modes tests with ImzMLFile_all_modes_test.cpp and assert max_dim
round-trip in C++ and Python metadata store tests.

Co-authored-by: Cursor <[email protected]>
Use micrometers (um) for max_dim_x/y output to match imzML convention
and ImzMLWriter export units.

Co-authored-by: Cursor <[email protected]>
Moved-from state allocates a new Impl via make_unique, which may throw;
do not mark move ctor/assignment as noexcept.

Co-authored-by: Cursor <[email protected]>
When rewrite_source_file and compute_hash are enabled, imzML datasets
now get a SHA1 over both the .imzML XML and its .ibd binary file,
matching the two-file nature of the format.

Co-authored-by: Cursor <[email protected]>
writeFloat32Array and writeFloat64Array no longer treat a null FILE*
as success; invalid handles fail fast instead of producing broken
.imzML/.ibd file pairs.

Co-authored-by: Cursor <[email protected]>
uuidStringToBytes_ now requires strtoul to consume the full two-character
hex byte, rejecting inputs like "1g" instead of silently truncating.

Co-authored-by: Cursor <[email protected]>
spectraShareMz_ now returns false when any spectrum is empty, preventing
continuous export from assigning a shared m/z count to empty pixels.

Co-authored-by: Cursor <[email protected]>
The guard removed global WARN/ERROR sinks but only restored std::cerr,
which could drop user-configured log destinations. It also did not
suppress handler warnings because OPENMS_LOG_* uses thread-local streams.

Co-authored-by: Cursor <[email protected]>
Use Internal::StringManager::convert() for XML/SAX exception text so
transcoded Xerces buffers are released on parse error paths.

Co-authored-by: Cursor <[email protected]>
Throw FileNotFound when the .ibd is not open before coordinate lookup,
matching getSpectrum() instead of misleading ElementNotFound errors.

Co-authored-by: Cursor <[email protected]>
loadSpectraIndex and isValid now use gil_scoped_release for blocking
C++ I/O, consistent with the other ImzMLFile pyOpenMS bindings.

Co-authored-by: Cursor <[email protected]>
MSVC does not provide POSIX fseeko; use _fseeki64 on WIN32 and keep
fseeko elsewhere. Also include cstdio explicitly in the .cpp translation unit.

Co-authored-by: Cursor <[email protected]>
Mark data and count as [[maybe_unused]] because they are only referenced
inside the OPENMS_IS_BIG_ENDIAN branch; on Windows (little-endian) MSVC
treats the unused parameters as errors.

Co-authored-by: Cursor <[email protected]>
…agingGeometry reuse

Follow-up to the rebase of the imzML PR onto develop, making it compile and
correct against current develop and integrating it with the IMAGING module.

Migration (post OpenMS#9450 / OpenMS#9468, which removed OpenMS::String):
- Port all imzML sources, the FileHandler imzML helpers, the pyOpenMS bindings
  and the tests to std::string + StringUtils/StringConversions.

Correctness fixes:
- ImzMLHandler: only snapshot per-spectrum IMS state for spectra MzMLHandler
  actually delivers (gate on !skip_spectrum_) — fixes silent coordinate/.ibd
  offset corruption when PeakFileOptions skip any spectrum.
- ImzMLFile: add an advisory .ibd UUID integrity check (16-byte header vs
  IMS:1000080); accept dashed and brace-wrapped UUIDs.
- Reject negative IMS:1000102/1000103 offset/count values (std::stoull wraps).
- Thread the .ibd path override through loadSpectraIndex so the override file
  (not an inferred sibling) is the one validated and read.
- Regenerate the malformed continuous test fixture: prepend the 16-byte UUID
  header, shift external offsets by 16, fix the declared md5 and dataset hash.

OnDiscImzMLExperiment: reuse the shared IMAGING module instead of a bespoke
coordinate map.
- Build an MSImagingGeometry eagerly in open() (in-memory pass; only peak decode
  stays lazy) and route getSpectrumAtCoord through it; delete PixelKey/coord_map_.
- Add getGeometry() (+ pyOpenMS binding) returning the 0-based 2D geometry.

Lenient loading: a UUID mismatch, an out-of-grid pixel, or a <1 coordinate are
now warnings (the dataset still loads); duplicate coordinates remain a hard error.

Cleanup: remove dev scaffolding (demo_imzML_*.py, run_imzML_metadata_demo.sh);
relocate test_data_paths.py into tests/unittests with depth-independent resolution.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Follow the existing code-examples convention instead of a bespoke mechanism.
Other file-loading tutorials (Tutorial_FileIO_mzML, Tutorial_GaussFilter, ...)
load a committed input from doc/code_examples/data/ via the global OPENMS_DOC_PATH
macro and need no per-example build wiring.

- Add the example dataset doc/code_examples/data/Tutorial_ImzMLFile.{imzML,ibd}
  (force-added; the dir is .gitignored like the other tutorial fixtures).
- Use OPENMS_DOC_PATH + "/code_examples/data/Tutorial_ImzMLFile.imzML" as the
  default input (argv[1] still overrides); drop the OPENMS_IMZML_TUTORIAL_FILE
  macro and the now-dead usage/empty-path branch.
- Remove the if(i STREQUAL "Tutorial_ImzMLFile") target_compile_definitions block
  from doc/code_examples/CMakeLists.txt -- it was the only per-example special-case
  in the examples loop.

The no-argument ctest passes against the bundled dataset (all 7 imzML modes run).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
timosachsenberg and others added 2 commits June 11, 2026 15:44
…format)

imzML is a mass spectrometry imaging format, so its canonical in-memory target is
MSImagingExperiment, matching BrukerTimsImagingFile (which is likewise imaging-only
and not reachable through the generic FileHandler). Stop treating imzML as a flat
mzML-like MSExperiment.

- Remove ImzMLFile::load(const std::string&, MSExperiment&); load(MSImagingExperiment&)
  now decodes the spectra and builds the geometry directly. Callers that only need the
  flat spectra use MSImagingExperiment::getMSExperiment(). load(consumer),
  loadSpectraIndex() and store(MSExperiment) are unchanged.
- FileHandler::loadExperiment() no longer loads imzML: it throws Exception::InvalidFileType
  with guidance to use ImzMLFile. Drop the imzML dataset-hash branch and its now-unused
  helpers (computeImzMLDatasetHash_, inferImzMLIbdPath_); FileHandler::getType /
  getTypeByContent still detect imzML.
- pyOpenMS: drop the load(MSExperiment&) binding (keep load(MSImagingExperiment&)).
- Update tests, the tutorial, and the Python tests: flat loads go through
  MSImagingExperiment::getMSExperiment(); FileHandler-loads-imzML cases now assert the
  InvalidFileType throw; the tutorial drops its FileHandler load mode.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rom FileHandler

Make storing symmetric with loading and consistent with how the imaging model is
populated. BrukerTimsImagingFile builds MSImagingGeometry directly (no imzml:* MetaValues);
the imzML writer, however, reads coordinates from per-spectrum imzml:x/y MetaValues, so a
geometry-only MSImagingExperiment (e.g. a Bruker-loaded one) could not be stored as imzML.

- Add ImzMLFile::store(const std::string&, const MSImagingExperiment&): the geometry is the
  source of truth for pixel coordinates, grid dimensions and pixel size. They are derived
  from exp.getGeometry() onto a copy of the wrapped experiment, so this works for any
  MSImagingExperiment regardless of whether the spectra carry imzml:x/y MetaValues. The
  low-level store(MSExperiment&) (MetaValue-driven) stays for building imzML from raw spectra.
- FileHandler::storeExperiment() no longer stores imzML: it throws Exception::InvalidFileType
  (symmetric with loadExperiment). imzML I/O now goes exclusively through ImzMLFile, matching
  BrukerTimsImagingFile (which is also absent from the generic FileHandler). Removed the
  now-unused ImzMLFile.h include from FileHandler.cpp.
- pyOpenMS: bind store(MSImagingExperiment&).
- Test: store a geometry-only MSImagingExperiment with NO imzml:x/y MetaValues and verify the
  coordinates round-trip from the geometry.

Co-Authored-By: Claude Opus 4.8 <[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)
doc/code_examples/Tutorial_ImzMLFile.cpp (1)

183-188: ⚡ Quick win

Consider storing MSImagingExperiment directly to demonstrate geometry-driven round-trip.

Mode 6 currently stores the MSExperiment exp extracted at line 111, which only preserves pixel coordinates via per-spectrum imzml:x/y/z MetaValues. The PR adds ImzMLFile::store(const MSImagingExperiment&) specifically to enable geometry-driven stores that "round-trip coordinates even when per-spectrum MetaValues are absent." For a tutorial showcasing this new capability, storing img directly would better demonstrate the geometry-preserving feature.

📚 Suggested adjustment
  std::cout << "\n=== Mode 6: ImzMLFile::store round-trip ===\n";
  std::string tmp_imzml = File::getTemporaryFile("Tutorial_ImzMLFile_export.imzML");
- loader.store(tmp_imzml, exp);
+ loader.store(tmp_imzml, img);  // Store MSImagingExperiment to preserve geometry
  MSImagingExperiment reloaded_img;
  loader.load(tmp_imzml, reloaded_img);

Alternatively, if both code paths are valuable for demonstration, consider splitting this into two separate modes (6a: store MSExperiment, 6b: store MSImagingExperiment) with clarifying comments about the difference.

🤖 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 `@doc/code_examples/Tutorial_ImzMLFile.cpp` around lines 183 - 188, Replace the
current geometry-losing round-trip (calling loader.store(tmp_imzml, exp)) with
the geometry-preserving API by storing the MSImagingExperiment directly: call
ImzMLFile::store with the MSImagingExperiment instance (img) so the round-trip
preserves geometry even when per-spectrum MetaValues are absent; alternatively,
if you want to show both behaviors, add two modes (e.g., Mode 6a:
loader.store(tmp_imzml, exp) and Mode 6b: loader.store(tmp_imzml, img)) with
brief comments explaining that loader.store(const MSImagingExperiment&)
preserves geometry while loader.store(const MSExperiment&) relies on
per-spectrum imzml:x/y/z MetaValues.
🤖 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.

Nitpick comments:
In `@doc/code_examples/Tutorial_ImzMLFile.cpp`:
- Around line 183-188: Replace the current geometry-losing round-trip (calling
loader.store(tmp_imzml, exp)) with the geometry-preserving API by storing the
MSImagingExperiment directly: call ImzMLFile::store with the MSImagingExperiment
instance (img) so the round-trip preserves geometry even when per-spectrum
MetaValues are absent; alternatively, if you want to show both behaviors, add
two modes (e.g., Mode 6a: loader.store(tmp_imzml, exp) and Mode 6b:
loader.store(tmp_imzml, img)) with brief comments explaining that
loader.store(const MSImagingExperiment&) preserves geometry while
loader.store(const MSExperiment&) relies on per-spectrum imzml:x/y/z MetaValues.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 777abf44-d5c6-4d16-8fca-acfb5247f385

📥 Commits

Reviewing files that changed from the base of the PR and between 5a54178 and 2e20317.

📒 Files selected for processing (10)
  • doc/code_examples/Tutorial_ImzMLFile.cpp
  • src/openms/include/OpenMS/FORMAT/ImzMLFile.h
  • src/openms/source/FORMAT/FileHandler.cpp
  • src/openms/source/FORMAT/ImzMLFile.cpp
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/tests/unittests/test_ImzMLFile.py
  • src/pyOpenMS/tests/unittests/test_ImzMLFile_modes.py
  • src/tests/class_tests/openms/source/FileHandler_test.cpp
  • src/tests/class_tests/openms/source/ImzMLFile_all_modes_test.cpp
  • src/tests/class_tests/openms/source/ImzMLFile_test.cpp
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/tests/class_tests/openms/source/ImzMLFile_all_modes_test.cpp
  • src/pyOpenMS/tests/unittests/test_ImzMLFile_modes.py
  • src/tests/class_tests/openms/source/ImzMLFile_test.cpp
  • src/pyOpenMS/tests/unittests/test_ImzMLFile.py

… shared builder)

Make the geometry the source of truth on the read side too, like BrukerTimsImagingFile.
Previously ImzMLFile::load(MSImagingExperiment&) reconstructed the geometry by reading
imzml:x/y MetaValues back off the spectra, while OnDiscImzMLExperiment built it directly
from the parsed index — two implementations, and an unnecessary MetaValue dependency.

- Add ImzMLFile::buildImagingGeometry(const std::vector<ImzMLSpectrumIndex>&, const ImzMLMeta&,
  MSImagingGeometry&): derives the pixel grid straight from the per-spectrum coordinates
  captured during parsing (1-based -> 0-based, z==1 plane, dims/pixel-size from meta;
  out-of-grid/<1 coords warned and skipped, duplicates throw). No MetaValue reads.
- ImzMLFile::load(MSImagingExperiment&) now captures the parsed index/meta and builds the
  geometry with that overload instead of buildImagingGeometry(MSExperiment&).
- OnDiscImzMLExperiment::buildGeometry_ delegates to the shared builder (deletes its
  duplicated logic + now-unused includes), so the in-memory and on-disc paths cannot diverge.
- Keep buildImagingGeometry(MSExperiment&) as a public utility for experiments that carry
  imzml:x/y MetaValues; disambiguate its pyOpenMS binding (now overloaded).
- Test: build a geometry from a hand-built index with no MSExperiment and no imzml:* MetaValues.

imzml:x/y MetaValues are still attached to spectra as per-spectrum provenance, but the
geometry no longer depends on them — it is built directly from the parsed coordinates.

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

Copy link
Copy Markdown
Contributor

Maintainer follow-up: rebased on develop + reworked imzML into a first-class imaging format

I rebased this branch onto current develop and made a series of follow-up changes so imzML is handled consistently with the MS-imaging data model (MSImagingExperiment / MSImagingGeometry, #9381) and with BrukerTimsImagingFile. The original description above predates these changes and should be updated; summary of what's new on top of the original work:

Rebase / build

imzML is now treated as an imaging format (⚠️ API change)

  • imzML I/O goes exclusively through ImzMLFile ↔ MSImagingExperiment, mirroring BrukerTimsImagingFile (imaging-only, not routed through the generic FileHandler).
  • Load: ImzMLFile::load(MSExperiment&) was removed — load into an MSImagingExperiment (use getMSExperiment() for the flat spectra). FileHandler::loadExperiment() now throws InvalidFileType for imzML (with guidance); getType/getTypeByContent still detect it.
  • Store: added geometry-driven ImzMLFile::store(MSImagingExperiment&); FileHandler::storeExperiment() no longer stores imzML. The low-level store(MSExperiment&) is kept.

MSImagingGeometry is the source of truth for coordinates

  • The reader builds the geometry directly from the parsed spectrum index (no longer reconstructed from imzml:x/y MetaValues), via a single shared ImzMLFile::buildImagingGeometry(index, meta, geom) used by both the in-memory and on-disc paths.
  • OnDiscImzMLExperiment now reuses MSImagingGeometry (its bespoke coordinate map was removed) and exposes getGeometry().
  • Store derives coordinates/dimensions/pixel size from the geometry, so any MSImagingExperiment — including geometry-only ones with no imzml:x/y MetaValues (e.g. Bruker-loaded) — can be written.

Correctness fixes

  • Fixed a coordinate / .ibd-offset desync when PeakFileOptions skip spectra.
  • Added a .ibd UUID integrity check (against IMS:1000080); reject negative external offset/count values.
  • Regenerated the malformed continuous test fixture (added the mandatory 16-byte UUID header, corrected offsets + checksums).
  • Non-conformant inputs (UUID mismatch, out-of-grid / <1 coordinates) are now warnings (the dataset still loads); duplicate coordinates remain a hard error.

Cleanup

  • Removed dev scaffolding (demo_imzML_*.py, tools/run_imzML_metadata_demo.sh); relocated test_data_paths.py into tests/unittests; the tutorial loads its bundled dataset via OPENMS_DOC_PATH (dropping a per-example CMake special-case).

For the description update

Notably Task 4 ("integrate with MSExperiment/MSSpectrum") is now realized via MSImagingExperiment; the removed demo scripts, the load(MSExperiment&) overload, and the FileHandler imzML routing no longer apply.

All changes verified: full project build green; the C++ class tests (ImzMLFile_test, ImzMLFile_all_modes_test, FileHandler_test) and the 27 pyOpenMS unit tests pass.

🤖 Generated with Claude Code

…ing_test)

The ibd_path parameter added to ImzMLFile::loadSpectraIndex was missing a @PARAM entry,
which Doxygen flags and Doxygen_Warning_test treats as a failure.

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

timosachsenberg commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

@Aditya-Sarna Thanks for the PR I made some edits to blend it with the design (MSImagingExperiment / MSImagingGeometry) we came up when we recently loaded Bruker raw MALDI imaging files.
I think this is already a great basis.
If you or @patrick-bo find some time to review those changes would be great. Just such that everyone is on the same page.

timosachsenberg and others added 4 commits June 12, 2026 09:47
The imzML changelog line still described the pre-rework API. Update it to
match the merged code: loads into MSImagingExperiment (imaging-only, like
BrukerTimsImagingFile) with the geometry built from the parsed spectrum
index; geometry-driven store(MSImagingExperiment) plus low-level
store(MSExperiment); FileHandler detects imzML but rejects flat load/store.

Co-authored-by: Cursor <[email protected]>
The ImzMLFile class-level "Loading modes" comment and the pyOpenMS ImzMLFile
docstring still described a load-into-MSExperiment mode that was removed when
imzML became imaging-only. Point both at load(MSImagingExperiment&) (with
getMSExperiment() for the flat spectra), matching the current API.

Co-authored-by: Cursor <[email protected]>
The XercesPlatformGuard destructor called XMLPlatformUtils::Terminate(),
which is not noexcept and may throw. Since destructors are implicitly
noexcept, a throw during cleanup invoked std::terminate(), crashing the
process. On Windows/MSVC this surfaced as a __fastfail with exit code
0xC0000409 (3221226505) during the pyOpenMS wheel tests, killing the run
at the first in-memory imzML parse (test_imaging_experiment_ram_lookup);
macOS and Linux wheels were unaffected because Terminate() does not throw
there.

It also tore down the process-global Xerces state shared with every other
OpenMS XML reader. OpenMS initializes Xerces once process-wide via the
guard in CONCEPT/Init.cpp (ticket OpenMS#352), and no other parser pairs
Initialize() with a per-operation Terminate(). Drop the per-load
Terminate(); keep the idempotent, reference-counted Initialize() to match
Internal::XMLFile. The existing test_imaging_experiment_ram_lookup covers
the regression.

Co-authored-by: Cursor <[email protected]>
@Aditya-Sarna

Copy link
Copy Markdown
Contributor Author

@timosachsenberg Thanks for the set of changes. They look good to me.
I've updated the documentation that had stale comments about usage with MSExperiment.
The pyOpenMS Windows build was failing due to a crash around Xerces termination, which I've fixed by removing the early Terminate() call. Architecturally, that was a bit unsound as Xerces is used by other XML readers as well. Hopefully the build succeeds this time.

Aditya-Sarna and others added 2 commits June 13, 2026 03:48
imzML's companion .ibd files mean the inline <binary> elements are empty
placeholders, yet the spectrum still declares defaultArrayLength = N (the
external element count).  MzMLHandler::populateSpectraWithData_() runs
inside a `#pragma omp parallel for`; for every spectrum it compared the
0 decoded values against the declared N and emitted

  "array has size 0 but should have size N (defaultArrayLength)"

via OPENMS_LOG_WARN.  LogStreamBuf is not thread-safe (shared streambuf,
static line buffer, incomplete_line_ string, message cache), so those
concurrent writes from multiple OpenMP threads corrupt the heap —
observed as a non-deterministic 0xC0000374 abort in both the Windows
C++ class test (ImzMLFile_test) and the Windows pyOpenMS wheel tests.

Fix: at binaryDataArray end, zero bin_data_.back().size for external
arrays so decodeBase64Arrays sees a length-0 array (no mismatch, no
warning).  At spectrum end, zero default_array_length_ when either array
is external — this is the value MzMLHandler snapshots into the batch
before the parallel populate pass.  ImzMLInterceptConsumer fills the real
peaks from the .ibd afterwards using the external offsets/counts, which
are independent of these fields.

Co-authored-by: Cursor <[email protected]>
@timosachsenberg

Copy link
Copy Markdown
Contributor

Xercex and heap corruption are two things I need to find time to investigate

@timosachsenberg
timosachsenberg merged commit 7b97a4c into OpenMS:develop Jun 15, 2026
37 of 38 checks passed
timosachsenberg added a commit that referenced this pull request Jun 16, 2026
#9515)

OPENMS_LOG_* routes through thread-local LogStream/LogStreamBuf instances,
but three shared resources survived the thread-local refactor (#8620/#8596)
and corrupt the heap when logging from OpenMP parallel regions (0xC0000374
on Windows; hit in practice by the imzML reader in #9454):

1. syncLF_() assembled lines through a function-local
   `static char buf[BUFFER_LENGTH]` shared across every thread. Replaced
   with direct std::string::append into incomplete_line_/outstring, so there
   is no scratch buffer (and no out-of-bounds read when a racing thread
   overwrites the trailing NUL).

2. distribute_() wrote to the shared sink (std::cerr/std::cout) and mutated
   the shared global Colorizer (yellow/red/magenta -- its std::stringstream
   and flags) from multiple threads without synchronization. Both are now
   serialized by a single global std::mutex held around the whole
   distribute_() body. The mutex is intentionally leaked so it stays valid
   during static teardown (a std::mutex, unlike the former OpenMP critical
   section, does not depend on the OpenMP runtime). Notifier callbacks run
   after the lock is released to avoid self-deadlock.

3. expandPrefix_() used non-reentrant std::localtime (shared static tm).
   Replaced with localtime_r/localtime_s.

Also corrects the stale LogStream.h note that claimed the macros are
protected by OPENMS_THREAD_CRITICAL (they are not -- safety comes from
thread-local buffers plus the new sink mutex), and adds a regression test
that logs 5000 unique messages from an 8-thread OpenMP region and asserts
each arrives exactly once and intact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
timosachsenberg added a commit that referenced this pull request Jun 16, 2026
#9515)

OPENMS_LOG_* routes through thread-local LogStream/LogStreamBuf instances,
but three shared resources survived the thread-local refactor (#8620/#8596)
and corrupt the heap when logging from OpenMP parallel regions (0xC0000374
on Windows; hit in practice by the imzML reader in #9454):

1. syncLF_() assembled lines through a function-local
   `static char buf[BUFFER_LENGTH]` shared across every thread. Replaced
   with direct std::string::append into incomplete_line_/outstring, so there
   is no scratch buffer (and no out-of-bounds read when a racing thread
   overwrites the trailing NUL).

2. distribute_() wrote to the shared sink (std::cerr/std::cout) and mutated
   the shared global Colorizer (yellow/red/magenta -- its std::stringstream
   and flags) from multiple threads without synchronization. Both are now
   serialized by a single global std::mutex held around the whole
   distribute_() body. The mutex is intentionally leaked so it stays valid
   during static teardown (a std::mutex, unlike the former OpenMP critical
   section, does not depend on the OpenMP runtime). Notifier callbacks run
   after the lock is released to avoid self-deadlock.

3. expandPrefix_() used non-reentrant std::localtime (shared static tm).
   Replaced with localtime_r/localtime_s.

Also corrects the stale LogStream.h note that claimed the macros are
protected by OPENMS_THREAD_CRITICAL (they are not -- safety comes from
thread-local buffers plus the new sink mutex), and adds a regression test
that logs 5000 unique messages from an 8-thread OpenMP region and asserts
each arrives exactly once and intact.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
timosachsenberg added a commit that referenced this pull request Jun 17, 2026
#9515) (#9583)

OPENMS_LOG_* routes through thread-local LogStream/LogStreamBuf instances,
but three shared resources survived the thread-local refactor (#8620/#8596)
and corrupt the heap when logging from OpenMP parallel regions (0xC0000374
on Windows; hit in practice by the imzML reader in #9454):

1. syncLF_() assembled lines through a function-local
   `static char buf[BUFFER_LENGTH]` shared across every thread. Replaced
   with direct std::string::append into incomplete_line_/outstring, so there
   is no scratch buffer (and no out-of-bounds read when a racing thread
   overwrites the trailing NUL).

2. distribute_() wrote to the shared sink (std::cerr/std::cout) and mutated
   the shared global Colorizer (yellow/red/magenta -- its std::stringstream
   and flags) from multiple threads without synchronization. Both are now
   serialized by a single global std::mutex held around the whole
   distribute_() body. The mutex is intentionally leaked so it stays valid
   during static teardown (a std::mutex, unlike the former OpenMP critical
   section, does not depend on the OpenMP runtime). Notifier callbacks run
   after the lock is released to avoid self-deadlock.

3. expandPrefix_() used non-reentrant std::localtime (shared static tm).
   Replaced with localtime_r/localtime_s.

Also corrects the stale LogStream.h note that claimed the macros are
protected by OPENMS_THREAD_CRITICAL (they are not -- safety comes from
thread-local buffers plus the new sink mutex), and adds a regression test
that logs 5000 unique messages from an 8-thread OpenMP region and asserts
each arrives exactly once and intact.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants