Skip to content

feat(FORMAT): Bruker .d MALDI imaging loader (Phase 2) - #9383

Merged
timosachsenberg merged 14 commits into
developfrom
feat/imaging-d-loading
May 20, 2026
Merged

timosachsenberg merged 14 commits into
developfrom
feat/imaging-d-loading

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stacks on #9381 (Phase 1 imaging in-memory model). Adds BrukerTimsImagingFile, a loader that ingests Bruker timsTOF MALDI imaging .d datasets into the MSImagingExperiment introduced by Phase 1.

  • New class BrukerTimsImagingFile in FORMAT/ (parallels BrukerTimsFile).
  • Pixel coordinates are read from analysis.tdf SQL tables (GlobalMetadata.MaldiApplicationType, MaldiFrameInfo.{Frame, XIndexPos, YIndexPos[, ZIndexPos]}) — no Bruker MALDI SDK calls; we follow the same SQL-only approach that timsconvert / pyTDFSDK use.
  • Frame data is delegated to BrukerTimsFile in FRAME export mode; per-frame nativeID="frame=<id>" is parsed to map pixels to spectrum indices.
  • Internal coordinates are zero-based (raw XIndexPos/YIndexPos are normalized by the observed minimum); pixel size is filled from MaldiSpotSize_um when present, defaulting to 1 µm.
  • Strict by default: rejects SingleSpectra (dried-droplet) datasets with Exception::InvalidValue.

Files

  • src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h
  • src/openms/source/FORMAT/BrukerTimsImagingFile.cpp
  • src/openms/source/FORMAT/sources.cmake (added under WITH_OPENTIMS)
  • src/tests/class_tests/openms/source/BrukerTimsImagingFile_test.cpp
  • src/tests/class_tests/openms/executables.cmake

Test plan

  • Unit test passes (BrukerTimsImagingFile_test, 0.6s) — synthesizes analysis.tdf SQLite fixtures in temp dirs, covers isImagingDataset, readGlobalMetadataValue, readMaldiFrameInfo (with and without ZIndexPos), missing-file errors, and SingleSpectra rejection.
  • Phase 1 imaging tests still pass (IonImage_test, MSImagingGeometry_test, MSImagingExperiment_test).
  • FORMAT regression slice run (123 tests). Imaging-area tests all pass. Four pre-existing failures are unrelated to this PR (BrukerTimsFile_test opentims integration timeout, OSWFileInference_test executable not built, Percolator_subprocess_parity_test known divergence, SwathMapMassCorrection_test std::bad_alloc in unrelated SWATH correctMZ).
  • Smoke test against a real Bruker MALDI imaging .d (deferred — no public fixture wired up yet; pattern to follow is ENABLE_OPENTIMS_TESTS in the root CMakeLists.txt).

Explicitly out of scope (follow-up phases)

  • ImzMLFile (load and store)
  • FileConverter TOPP wiring for .d → imzML
  • iprm-PASEF / DIA-PASEF MALDI imaging
  • pyOpenMS bindings
  • Dried-droplet (SingleSpectra) geometry

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Support for loading Bruker TimsTOF MALDI imaging datasets into the imaging experiment view.
    • Retrieval of imaging geometry, pixel coordinates, spot size (with sensible fallback) and global metadata.
    • Non-destructive dataset detection and validation with clear errors/warnings for unsupported or inconsistent datasets.
  • Tests

    • Added unit tests covering detection, metadata reading, pixel parsing and validation behavior.

Review Change Stack

claude and others added 12 commits May 19, 2026 12:15
Introduces a new OpenMS/IMAGING module so the rest of the imaging MS
work (Phase 2: ImzMLFile, etc.) has an in-memory target to populate.

- IonImage: dense W x H x D intensity grid with per-pixel validity mask
  and the m/z window the image was extracted from.
- MSImagingGeometry: pixel list and (x,y,z) -> spectrum_index lookup,
  with image dimensions and pixel-size metadata. Coordinates are
  zero-based; bit-packed into a 21/21/21 uint64 key for the lookup, with
  out-of-range and duplicate insertions rejected up-front.
- MSImagingExperiment: owns an MSExperiment and an MSImagingGeometry,
  exposes pixel-based spectrum access, sum-based ion-image extraction
  reusing MSSpectrum::MZBegin/MZEnd, and a basic validate() check.

Registered via existing sources.cmake pattern (peer to IONMOBILITY) and
covered by three class tests under src/tests/class_tests/openms/source.
imzML's "position z" exists for 3D stacks but the spec has no z extent
and no z pixel size CV term; in practice each tissue section is its own
acquisition. Modeling 3D as an internal dimension was overkill for the
common (and CV-supported) case.

- IonImage, MSImagingGeometry, MSImagingExperiment: 2D-only API.
- MSImagingGeometry::Pixel drops `z`.
- Bit-pack key is now y<<32 | x; no axis-range limit needed.
- 3D / serial-section experiments are intended to be modeled as a
  collection of MSImagingExperiment objects (one per section).
- extractIonImage rejects negative/NaN mz or tolerance_ppm up front,
  preventing inverted m/z windows that silently return an all-zero image.
- getSpectrum bounds-checks the spectrum_index returned by the geometry
  and throws InvalidValue on stale references instead of UB via operator[].
- addPixel rejects coordinates outside [0, width) x [0, height) once
  dimensions are set; pre-dimension insertion still works for callers
  that build the geometry incrementally.

Tests cover the three new failure modes plus extractIonImage on an
empty experiment and an m/z window outside all peaks.
…bit review)

Match the FAIMSHelper / IMTypes style: every public method has @brief plus
explicit @PARAM[in] entries, @return for non-void getters, and existing
@throws clauses; Pixel struct fields get short inline descriptions.

No behavior changes.
…m MSExperiment

Lets callers wrap an MSExperiment in a fresh MSImagingExperiment shell
(empty geometry, populated by the caller) without going through the
two-step default-construct + setMSExperiment dance.

- explicit ctor takes MSExperiment by value, moves into experiment_.
- operator= takes MSExperiment by value, moves into experiment_, and
  clears geometry_ since the previous geometry's spectrum_indices were
  tied to the previous experiment's spectrum order. setMSExperiment()
  is the no-clear variant if a caller wants to keep the geometry.
…agingExperiment

Mirrors the MSSpectrum binding patterns:
- IonImage.get_data() returns a zero-copy 2D numpy view (shape (H, W),
  dtype float64) of the row-major intensity buffer, scoped to the
  IonImage's lifetime via reference_internal.
- IonImage.get_validity() returns a 2D uint8 array (1 = valid). std::vector<bool>
  is bit-packed so the validity mask is materialized as a copy.
- MSImagingGeometry.get_pixels_struct() returns a zero-copy structured
  numpy array (fields x: uint32, y: uint32, spectrum_index: uint64),
  backed by the C++ pixel vector. Layout guarded by static_asserts.
- MSImagingExperiment.extractIonImage() returns a fresh IonImage; pixel
  spectrum access goes through getSpectrum(x, y) with reference_internal.
Eleven tests covering the new IonImage / MSImagingGeometry /
MSImagingExperiment bindings:

- IonImage: construction, getWidth/Height/Intensity, OOB raises
- IonImage.get_data() zero-copy: write through the returned 2D float64
  view is reflected in subsequent getIntensity() calls
- IonImage.get_validity() 2D uint8 mask round-trip
- MSImagingGeometry: setDimensions, setPixelSize, addPixel/hasPixel/
  getSpectrumIndex, duplicate + OOB rejection
- MSImagingGeometry.get_pixels_struct(): structured dtype names, itemsize,
  per-field values match insertion order
- MSImagingExperiment.extractIonImage() on the 2x2 fixture: intensity
  grid [[30, 0], [100, 0]], validity at the missing corner, mz range
- extractIonImage rejects negative mz and ppm
- getSpectrum lookup and missing-pixel error path
- constructor(MSExperiment) vs setMSExperiment() geometry semantics
- IonImage::getValidity() -> getMask(); private member valid_pixels_ -> mask_
- Python: IonImage.get_validity() -> get_mask()
- Doxygen / docstrings updated to "per-pixel mask" / "masked-out" wording
- Tests renamed accordingly (test_ion_image_get_mask_copy, local mask var)

No behavior change.
std::vector<bool>::operator[] returns a proxy reference, not a bool;
Apple Clang/libc++ in Xcode 15.4 trips the TEST_EQUAL macro path in
ClassTest.h on that proxy and the macOS build-and-test job has been
red since the initial commit because of it. Switching to TEST_TRUE
on the proxy works on every libc++ / libstdc++ we ship against.
Reads pixel coordinates from analysis.tdf (GlobalMetadata,
MaldiFrameInfo) and binds them to per-frame spectra produced by
BrukerTimsFile in FRAME mode, populating MSImagingExperiment +
MSImagingGeometry. Pure SQL — no proprietary MALDI SDK calls
required. Internal coordinates are zero-based (raw Bruker
XIndexPos/YIndexPos are normalized via the observed min).

Tests build synthetic analysis.tdf files with hand-crafted
GlobalMetadata and MaldiFrameInfo to exercise isImagingDataset,
readGlobalMetadataValue, readMaldiFrameInfo (including the
optional ZIndexPos column), and the SingleSpectra rejection path
without requiring a real .d binary.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the feat/imaging-d-loading branch from 042411a to e14996b Compare May 19, 2026 18:52
Base automatically changed from claude/refine-local-plan-jC6LT to develop May 19, 2026 19:31
@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d1e1cca0-2a71-4932-8382-f948454a9a43

📥 Commits

Reviewing files that changed from the base of the PR and between f46a732 and e87b2bb.

📒 Files selected for processing (3)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h
  • src/openms/source/FORMAT/BrukerTimsImagingFile.cpp
  • src/tests/class_tests/openms/source/BrukerTimsImagingFile_test.cpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/tests/class_tests/openms/source/BrukerTimsImagingFile_test.cpp
  • src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h
  • src/openms/source/FORMAT/BrukerTimsImagingFile.cpp

📝 Walkthrough

Walkthrough

Adds BrukerTimsImagingFile: a WITH_OPENTIMS-gated reader that reads MALDI imaging .d SQLite metadata (frame pixels, global metadata), validates single-section imaging datasets, loads spectra via BrukerTimsFile, computes geometry (bounding box, pixel size), and populates an MSImagingExperiment.

Changes

Bruker TimsTOF MALDI Imaging Loader

Layer / File(s) Summary
API contract and data shapes
src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h
Declares BrukerTimsImagingFile with nested MaldiPixel and Config, public load overloads, isImagingDataset, readMaldiFrameInfo, readGlobalMetadataValue, and private helpers for bounding-box and tdf-path resolution.
Implementation helpers and SQLite probes
src/openms/source/FORMAT/BrukerTimsImagingFile.cpp (top)
Adds file-level guard/includes, parseFrameId, resolveTdfPath_, isImagingDataset (non-throwing probe), and readGlobalMetadataValue helper.
Pixel I/O and bounding-box
src/openms/source/FORMAT/BrukerTimsImagingFile.cpp
Implements readMaldiFrameInfo to load ordered Frame/XIndexPos/YIndexPos rows and computeBoundingBox_ to compute inclusive width/height from X/Y extents; throws on missing/empty tables.
Core load flow
src/openms/source/FORMAT/BrukerTimsImagingFile.cpp
Adds forwarding load(path, exp) and full load(path, exp, config): path validation, optional strict imaging check, reject multi-section via distinct ZIndexPos, read pixels, load spectra via BrukerTimsFile (frame export, MS1 forced), map frame IDs to spectra, compute pixel size from MaldiSpotSize_um/ImagingAreaSpotSize_um, drop pixels with missing frames (warning), set experiment+geometry, and call exp.validate().
Build integration
src/openms/source/FORMAT/sources.cmake, src/tests/class_tests/openms/executables.cmake
Registers BrukerTimsImagingFile.cpp in sources list and BrukerTimsImagingFile_test in test executables under WITH_OPENTIMS.
Unit tests and validation
src/tests/class_tests/openms/source/BrukerTimsImagingFile_test.cpp
Tests using temporary fake .d directories with SQLite analysis.tdf: isImagingDataset, readGlobalMetadataValue, readMaldiFrameInfo behavior and errors, and load error cases (missing path/tdf, non-imaging under strict mode, multi-section rejection).

Sequence Diagram

sequenceDiagram
  participant Client
  participant BrukerTimsImagingFile
  participant SQLiteDB as SQLite (analysis.tdf)
  participant BrukerTimsFile
  participant MSImagingExp as MSImagingExperiment
  Client->>BrukerTimsImagingFile: load(path, exp, config)
  BrukerTimsImagingFile->>SQLiteDB: read MaldiApplicationType (isImagingDataset)
  BrukerTimsImagingFile->>SQLiteDB: read MaldiFrameInfo (Frame, XIndexPos, YIndexPos)
  BrukerTimsImagingFile->>SQLiteDB: read MaldiSpotSize_um / ImagingAreaSpotSize_um
  BrukerTimsImagingFile->>BrukerTimsFile: load spectra (frame-export mode, load_ms1=true)
  BrukerTimsFile-->>BrukerTimsImagingFile: MSExperiment with spectra (nativeIDs contain frame=<id>)
  BrukerTimsImagingFile->>BrukerTimsImagingFile: parse frame IDs, map to spectrum indices
  BrukerTimsImagingFile->>BrukerTimsImagingFile: compute bounding box and pixel size
  BrukerTimsImagingFile->>MSImagingExp: set experiment + imaging geometry (pixels -> spectrum indices)
  MSImagingExp-->>Client: validated MSImagingExperiment
Loading

Possibly related PRs

  • OpenMS/OpenMS#9381: Introduces MSImagingExperiment / MSImagingGeometry types used by this loader.
  • OpenMS/OpenMS#9160: Changes/affects BrukerTimsFile behavior/config that this loader depends on for frame-export spectra and MS1 loading.

Suggested reviewers

  • jpfeuffer
  • singjc
  • jcharkow

Poem

🐰
I nibble rows from SQLite ground,
map frames to pixels all around,
compute the box and size with care,
drop missing frames with just a stare,
imaging data stitched with flair. 🎨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% 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: introducing a Bruker MALDI imaging loader class for Phase 2 of the imaging feature.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/imaging-d-loading

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

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

Inline comments:
In `@src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h`:
- Around line 1-3: Add the missing OpenMS header preamble to the top of the
BrukerTimsImagingFile.h header: insert the standardized comment block containing
the $Maintainer:$ and $Authors:$ markers (with the proper names/email for the
maintainer and authors) above the existing copyright/SPDX lines so the
class/definitions in BrukerTimsImagingFile.h include the required
maintainer/author metadata.
- Around line 20-35: Update the Doxygen contract for the BrukerTimsImagingFile
API: add a full class-level docblock including `@ingroup` and ensure the existing
`@brief` remains, then for each public method (e.g., the class constructor,
load/read methods exposed by BrukerTimsImagingFile referenced later in the
header) add complete Doxygen tags including `@brief`, `@param`[in/out] for each
parameter, `@return` for non-void results, and `@throws` for exceptions that the
method can raise; make these changes both in the class comment at the top of
BrukerTimsImagingFile and for the public method comments appearing around the
later declarations (the block noted in the review), so all public API entries
conform to the required contract format.

In `@src/openms/source/FORMAT/BrukerTimsImagingFile.cpp`:
- Around line 154-158: The current strict-imaging check calls
isImagingDataset(path) which swallows I/O errors and returns false, causing an
InvalidValue to be thrown and hiding FileNotReadable; change the logic so that
I/O failures are preserved: have isImagingDataset either propagate I/O
exceptions (so the caller sees FileNotReadable) or have
BrukerTimsImagingFile.cpp check for the presence/readability of analysis.tdf
before calling isImagingDataset and explicitly rethrow or throw
Exception::FileNotReadable when that check fails, otherwise keep the
InvalidValue for a genuine non-imaging dataset; reference isImagingDataset and
the strict_imaging_only branch where Exception::InvalidValue is currently
thrown.
🪄 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: 341074f7-2348-40f0-ba1a-ada923b8652f

📥 Commits

Reviewing files that changed from the base of the PR and between 7d7e900 and f46a732.

📒 Files selected for processing (5)
  • src/openms/include/OpenMS/FORMAT/BrukerTimsImagingFile.h
  • src/openms/source/FORMAT/BrukerTimsImagingFile.cpp
  • src/openms/source/FORMAT/sources.cmake
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/BrukerTimsImagingFile_test.cpp

…/O surfacing)

- Add the standard $Maintainer:$ / $Authors:$ preamble block.
- Class gains @InGroup FileIO; all public methods now use full Doxygen
  with @PARAM[in/out], @return, and @throws blocks instead of /// shorthand.
- load() now resolves analysis.tdf eagerly before calling isImagingDataset(),
  so a missing analysis.tdf surfaces as Exception::FileNotReadable instead of
  being masked as InvalidValue by the strict-imaging probe (which swallows
  I/O errors to behave as a non-throwing duck-type check).
- Add a regression test: .d folder present, analysis.tdf missing -> FileNotReadable.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@timosachsenberg
timosachsenberg merged commit aedb815 into develop May 20, 2026
40 of 41 checks passed
@timosachsenberg
timosachsenberg deleted the feat/imaging-d-loading branch May 20, 2026 04:21
timosachsenberg pushed a commit that referenced this pull request May 21, 2026
- FeatureFinderMetaboIdent: adduct support via optional TSV column (#9382)
- BrukerTimsImagingFile: new Bruker .d MALDI imaging loader (#9383)
- BrukerTimsFile: frame_id/RT range filter in Config (#9387)
- Fix: SwathMapMassCorrection null-pointer and memory leak (#9386)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants