Skip to content

feat(pyOpenMS): expose BrukerTimsFile loader via nanobind - #9379

Merged
timosachsenberg merged 1 commit into
developfrom
feat/pyopenms-bruker-tims
May 19, 2026
Merged

timosachsenberg merged 1 commit into
developfrom
feat/pyopenms-bruker-tims

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds nanobind bindings for OpenMS::BrukerTimsFile in src/pyOpenMS/bindings/bind_format.cpp: load() (default + explicit Config), readDIAMetadata() returning (DIAStreamingMetadata, ExperimentalSettings), plus the nested Config struct, the three nested enums (ExportMode, TimsCalibrationStrategy, PressureCompensation), and DIAStreamingMetadata.
  • Bindings are gated on #ifdef WITH_OPENTIMS so the class is only exposed when OpenMS was built with -DWITH_OPENTIMS=ON (the project default). No new CMake change was needed for propagation — target_compile_definitions(OpenMS PUBLIC WITH_OPENTIMS=1) already inherits into _pyopenms_format via the public link to OpenMS.
  • Mirrors the C++ BrukerTimsFile_test data-fixture pattern: src/pyOpenMS/CMakeLists.txt now forwards configure-time OPENTIMS_DDA_TEST_DATA / OPENTIMS_DIA_TEST_DATA paths as environment variables to the pyopenms_unittests ctest, and the new tests/unittests/test_BrukerTimsFile.py skips real-data tests cleanly when those env vars are absent.
  • Streaming consumer paths (loadDIAStreaming, transform) are intentionally deferred to a follow-up — binding IMSDataConsumer / FullSwathFileConsumer trampolines is its own scope.

Packaging notes

  • The Bruker SDK (timsdata.dll / libtimsdata.so) is not bundled in the wheel; users supply it at runtime via OPENMS_BRUKER_SDK_PATH env var or BrukerTimsFile.Config.bruker_sdk_path. The docstring on the class spells this out.
  • opentims itself is built as a static archive (OPENTIMS_BUILD_LIB=ON, OPENTIMS_LINK_SQLITE_STATICALLY=ON) and its symbols are absorbed into libOpenMS.so, so no new shared lib needs to be copied beyond what wheel packaging already handles.
  • CI wheel verification (that the cibuildwheel containers actually link opentims under the default WITH_OPENTIMS=ON) is deferred — flagging here so it can be checked in a follow-up if needed.

Test plan

  • cmake --build OpenMS-build --target pyopenms -j$(nproc) succeeds
  • test_BrukerTimsFile.py: 7 pass / 3 skip without env vars
  • test_BrukerTimsFile.py: 10/10 pass in ~20s with OPENTIMS_DDA_TEST_DATA and OPENTIMS_DIA_TEST_DATA pointed at the fetched opentims test fixtures
  • CI: confirm pyopenms_unittests keeps passing on all platforms (real-data tests will skip in CI since the env vars are not forwarded there yet)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added support for loading Bruker TIMS data files with configurable export modes and calibration strategies.
    • Added capability to read DIA streaming metadata from TIMS datasets.
    • Configuration options now available for calibration, centroiding, and SDK path customization.
    • Feature requires the Bruker SDK to be provided at runtime via environment variable or configuration.

Review Change Stack

Adds bindings for OpenMS::BrukerTimsFile (load + readDIAMetadata) with
the nested Config struct, ExportMode/TimsCalibrationStrategy/
PressureCompensation enums, and DIAStreamingMetadata. Gated by
#ifdef WITH_OPENTIMS; feature-detectable via hasattr(pyopenms,
"BrukerTimsFile"). The Bruker SDK is not bundled in the wheel and
is dlopen'd at runtime from OPENMS_BRUKER_SDK_PATH or
Config.bruker_sdk_path.

Tests skip cleanly when WITH_OPENTIMS is off; real-data tests gate
on OPENTIMS_DDA_TEST_DATA / OPENTIMS_DIA_TEST_DATA env vars,
mirroring the BrukerTimsFile_test CMake pattern. The pyopenms
ctest registration now forwards those CMake variables to the pytest
environment when set.

Streaming consumer paths (loadDIAStreaming, transform) are deferred.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR adds Python (nanobind) bindings for OpenMS's BrukerTimsFile loader, enabling Python users to load Bruker TIMS .d mass spectrometry data via load() and read DIA metadata via readDIAMetadata(), with configurable options and enum-based parameters. The bindings are conditional on WITH_OPENTIMS and include comprehensive unit tests with real-data integration points.

Changes

BrukerTimsFile Python Bindings

Layer / File(s) Summary
BrukerTimsFile nanobind binding definitions
src/pyOpenMS/bindings/bind_format.cpp
Header include and nanobind class declarations for BrukerTimsFile, exposing load() and readDIAMetadata() methods, nested Config struct with configuration fields and enums (ExportMode, TimsCalibrationStrategy, PressureCompensation), nested DIAStreamingMetadata for DIA SWATH metadata, and ProgressLogger support.
Test coverage for BrukerTimsFile bindings
src/pyOpenMS/tests/unittests/test_BrukerTimsFile.py
Comprehensive unit tests validating Config defaults and field assignment, enum value sets, DIAStreamingMetadata defaults, error handling for invalid paths, and environment-gated DDA/DIA integration tests loading real data; includes module-level guard to skip all tests when BrukerTimsFile binding is unavailable.
CMake test environment configuration
src/pyOpenMS/CMakeLists.txt
Conditional forwarding of OPENTIMS_DDA_TEST_DATA and OPENTIMS_DIA_TEST_DATA environment variables to the pyopenms_unittests CTest entry, enabling integration tests to locate optional real-data datasets at runtime.
Feature documentation
CHANGELOG
Documents the new BrukerTimsFile bindings, their methods, nested types, WITH_OPENTIMS build gating, feature detection via hasattr(), Bruker SDK runtime provisioning, and deferred streaming consumer paths.

Possibly Related PRs

  • OpenMS/OpenMS#9126: Both PRs introduce Bruker OpenTims .d support via the OpenMS::BrukerTimsFile API—main PR adds the pyOpenMS nanobind BrukerTimsFile class (load()/readDIAMetadata() and Config), while the retrieved PR extends CometAdapter to load .d inputs through BrukerTimsFile::load() and constructs a BrukerTimsFile::Config from new CLI options.
  • OpenMS/OpenMS#9022: The main PR adds Python (nanobind) bindings for BrukerTimsFile—including load()/readDIAMetadata() and BrukerTimsFile::Config enums/fields—while the retrieved PR updates PeakPickerIM to load Bruker .d inputs via the same BrukerTimsFile::load(...) API and construct BrukerTimsFile::Config from CLI options.
  • OpenMS/OpenMS#9019: Both PRs center on BrukerTimsFile loading of Bruker TIMS .d data—main PR adds pyOpenMS bindings exposing BrukerTimsFile.load()/readDIAMetadata(), while retrieved PR integrates the same loader into OpenSwath via SwathFile::loadBrukerTdf() calling BrukerTimsFile::load() and downstream swath partitioning.

Suggested Reviewers

  • jpfeuffer
  • poshul
  • jcharkow

Poem

🐰 Hops through TIMS data with glee,
Bruker formats now dance in Python free,
Config and enums, a rabbit's delight,
DIA metadata streaming—the tests shining bright!
Nanobind bindings, a tunnel so deep. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 PR title 'feat(pyOpenMS): expose BrukerTimsFile loader via nanobind' directly and clearly describes the main change: adding nanobind bindings to expose the BrukerTimsFile loader in pyOpenMS, which is precisely what the changeset implements.
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/pyopenms-bruker-tims

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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/pyOpenMS/bindings/bind_format.cpp`:
- Around line 153-170: The BrukerTimsFile binding (and its nested types
BrukerTimsFile::Config and BrukerTimsFile::DIAStreamingMetadata) currently only
expose default construction; add copy construction and Python copy/deepcopy
support similar to other bindings: add nb::init<const OpenMS::BrukerTimsFile&>()
for BrukerTimsFile (and nb::init<const OpenMS::BrukerTimsFile::Config&>() /
nb::init<const OpenMS::BrukerTimsFile::DIAStreamingMetadata&>() for the nested
classes), and implement __copy__ and __deepcopy__ that return a new instance
constructed from the const& copy (use the same pattern used for
CachedmzML/ChromeleonFile bindings). Ensure the __deepcopy__ accepts a memo arg
and ignores it, and register these on the same nb::class_ declarations for
BrukerTimsFile, Config, and DIAStreamingMetadata.

In `@src/pyOpenMS/tests/unittests/test_BrukerTimsFile.py`:
- Around line 48-63: The tests currently use tautological assertions (comparing
a set to itself) in test_export_mode_enum_values,
test_calibration_strategy_enum_values, and
test_pressure_compensation_enum_values; replace those with assertions that
compare the observed enum members to an explicit expected set (e.g., build
expected = {pyopenms.BrukerTimsFile.Config.ExportMode.AUTO,
pyopenms.BrukerTimsFile.Config.ExportMode.SPECTRUM,
pyopenms.BrukerTimsFile.Config.ExportMode.FRAME} and assert observed ==
expected), doing the same for Config.TimsCalibrationStrategy and
Config.PressureCompensation so the tests fail if members are removed or renamed.
🪄 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: 1015890b-d8ac-4c7f-8ed0-d153d11aa9e4

📥 Commits

Reviewing files that changed from the base of the PR and between ca61ce6 and 2cc1a6c.

📒 Files selected for processing (4)
  • CHANGELOG
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/bindings/bind_format.cpp
  • src/pyOpenMS/tests/unittests/test_BrukerTimsFile.py

Comment on lines +153 to +170
auto brukertimsfile_class = nb::class_<OpenMS::BrukerTimsFile>(m, "BrukerTimsFile",
R"doc(
Reader for Bruker TimsTOF .d directories via opentims.

Supports DDA-PASEF, DIA-PASEF, and raw frame-level 4D access.
Ion mobility data is stored in VSSC (1/K0) units using IM_PEAK format
for MS1 and DIA MS2, and scalar drift times for DDA MS2.

This class is only available when OpenMS is built with
``WITH_OPENTIMS=ON`` (the default). The Bruker SDK
(``timsdata.dll`` / ``libtimsdata.so``) is not bundled with pyOpenMS;
supply it via the ``OPENMS_BRUKER_SDK_PATH`` environment variable or
``Config.bruker_sdk_path``.

Use ``hasattr(pyopenms, "BrukerTimsFile")`` to feature-detect at
runtime.
)doc");
brukertimsfile_class

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

cd src/pyOpenMS/bindings && head -300 bind_format.cpp | tail -150

Repository: OpenMS/OpenMS

Length of output: 11956


Add missing copy constructor and copy/deepcopy bindings for BrukerTimsFile and nested classes.

BrukerTimsFile, BrukerTimsFile.Config, and BrukerTimsFile.DIAStreamingMetadata currently expose only default construction. Per coding guidelines, add nb::init<const ...&>(), __copy__, and __deepcopy__ for consistency with other bindings in this file (e.g., CachedmzML, ChromeleonFile).

Proposed patch
     brukertimsfile_class
         .def(nb::init<>())
+        .def(nb::init<const OpenMS::BrukerTimsFile&>())
+        .def("__copy__", [](const OpenMS::BrukerTimsFile& self) { return OpenMS::BrukerTimsFile(self); })
+        .def("__deepcopy__", [](const OpenMS::BrukerTimsFile& self, nb::dict) { return OpenMS::BrukerTimsFile(self); }, "memo"_a)
         .def("load", [](OpenMS::BrukerTimsFile& self, const OpenMS::String& path) {
             OpenMS::MSExperiment exp; self.load(path, exp); return exp;
         }, "path"_a, "Load a .d directory into a new MSExperiment using default configuration")
@@
     auto brukertimsfile_config = nb::class_<OpenMS::BrukerTimsFile::Config>(brukertimsfile_class, "Config",
         "Processing and export configuration for BrukerTimsFile.load() and readDIAMetadata()")
         .def(nb::init<>())
+        .def(nb::init<const OpenMS::BrukerTimsFile::Config&>())
+        .def("__copy__", [](const OpenMS::BrukerTimsFile::Config& self) { return OpenMS::BrukerTimsFile::Config(self); })
+        .def("__deepcopy__", [](const OpenMS::BrukerTimsFile::Config& self, nb::dict) { return OpenMS::BrukerTimsFile::Config(self); }, "memo"_a)
         .def_rw("calibration_tolerance", &OpenMS::BrukerTimsFile::Config::calibration_tolerance, "m/z recalibration tolerance in Da (0 = default 0.1 Da)")
@@
     nb::class_<OpenMS::BrukerTimsFile::DIAStreamingMetadata>(brukertimsfile_class, "DIAStreamingMetadata",
         "Metadata describing DIA SWATH layout for streaming consumers")
         .def(nb::init<>())
+        .def(nb::init<const OpenMS::BrukerTimsFile::DIAStreamingMetadata&>())
+        .def("__copy__", [](const OpenMS::BrukerTimsFile::DIAStreamingMetadata& self) { return OpenMS::BrukerTimsFile::DIAStreamingMetadata(self); })
+        .def("__deepcopy__", [](const OpenMS::BrukerTimsFile::DIAStreamingMetadata& self, nb::dict) { return OpenMS::BrukerTimsFile::DIAStreamingMetadata(self); }, "memo"_a)
         .def_rw("boundaries", &OpenMS::BrukerTimsFile::DIAStreamingMetadata::boundaries, "One SwathMap per DIA window (MS2 only)")

Also applies to: 192-194, 233-235

🤖 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 153 - 170, The
BrukerTimsFile binding (and its nested types BrukerTimsFile::Config and
BrukerTimsFile::DIAStreamingMetadata) currently only expose default
construction; add copy construction and Python copy/deepcopy support similar to
other bindings: add nb::init<const OpenMS::BrukerTimsFile&>() for BrukerTimsFile
(and nb::init<const OpenMS::BrukerTimsFile::Config&>() / nb::init<const
OpenMS::BrukerTimsFile::DIAStreamingMetadata&>() for the nested classes), and
implement __copy__ and __deepcopy__ that return a new instance constructed from
the const& copy (use the same pattern used for CachedmzML/ChromeleonFile
bindings). Ensure the __deepcopy__ accepts a memo arg and ignores it, and
register these on the same nb::class_ declarations for BrukerTimsFile, Config,
and DIAStreamingMetadata.

Comment on lines +48 to +63
def test_export_mode_enum_values():
Em = pyopenms.BrukerTimsFile.Config.ExportMode
assert {Em.AUTO, Em.SPECTRUM, Em.FRAME} == {Em.AUTO, Em.SPECTRUM, Em.FRAME}


def test_calibration_strategy_enum_values():
Cs = pyopenms.BrukerTimsFile.Config.TimsCalibrationStrategy
assert {Cs.AUTO, Cs.BRUKER_SDK, Cs.RATIONAL, Cs.LINEAR} == {
Cs.AUTO, Cs.BRUKER_SDK, Cs.RATIONAL, Cs.LINEAR
}


def test_pressure_compensation_enum_values():
Pc = pyopenms.BrukerTimsFile.Config.PressureCompensation
assert {Pc.NONE, Pc.GLOBAL, Pc.PER_FRAME} == {Pc.NONE, Pc.GLOBAL, Pc.PER_FRAME}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Enum value tests are tautologies and won’t catch regressions.

These assertions compare each set to itself, so they always pass even if the binding changes.

Proposed fix
 def test_export_mode_enum_values():
     Em = pyopenms.BrukerTimsFile.Config.ExportMode
-    assert {Em.AUTO, Em.SPECTRUM, Em.FRAME} == {Em.AUTO, Em.SPECTRUM, Em.FRAME}
+    assert hasattr(Em, "AUTO")
+    assert hasattr(Em, "SPECTRUM")
+    assert hasattr(Em, "FRAME")
+    assert len({Em.AUTO, Em.SPECTRUM, Em.FRAME}) == 3
@@
 def test_calibration_strategy_enum_values():
     Cs = pyopenms.BrukerTimsFile.Config.TimsCalibrationStrategy
-    assert {Cs.AUTO, Cs.BRUKER_SDK, Cs.RATIONAL, Cs.LINEAR} == {
-        Cs.AUTO, Cs.BRUKER_SDK, Cs.RATIONAL, Cs.LINEAR
-    }
+    assert hasattr(Cs, "AUTO")
+    assert hasattr(Cs, "BRUKER_SDK")
+    assert hasattr(Cs, "RATIONAL")
+    assert hasattr(Cs, "LINEAR")
+    assert len({Cs.AUTO, Cs.BRUKER_SDK, Cs.RATIONAL, Cs.LINEAR}) == 4
@@
 def test_pressure_compensation_enum_values():
     Pc = pyopenms.BrukerTimsFile.Config.PressureCompensation
-    assert {Pc.NONE, Pc.GLOBAL, Pc.PER_FRAME} == {Pc.NONE, Pc.GLOBAL, Pc.PER_FRAME}
+    assert hasattr(Pc, "NONE")
+    assert hasattr(Pc, "GLOBAL")
+    assert hasattr(Pc, "PER_FRAME")
+    assert len({Pc.NONE, Pc.GLOBAL, Pc.PER_FRAME}) == 3
🤖 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/tests/unittests/test_BrukerTimsFile.py` around lines 48 - 63,
The tests currently use tautological assertions (comparing a set to itself) in
test_export_mode_enum_values, test_calibration_strategy_enum_values, and
test_pressure_compensation_enum_values; replace those with assertions that
compare the observed enum members to an explicit expected set (e.g., build
expected = {pyopenms.BrukerTimsFile.Config.ExportMode.AUTO,
pyopenms.BrukerTimsFile.Config.ExportMode.SPECTRUM,
pyopenms.BrukerTimsFile.Config.ExportMode.FRAME} and assert observed ==
expected), doing the same for Config.TimsCalibrationStrategy and
Config.PressureCompensation so the tests fail if members are removed or renamed.

@timosachsenberg
timosachsenberg merged commit 3627469 into develop May 19, 2026
43 of 44 checks passed
@timosachsenberg
timosachsenberg deleted the feat/pyopenms-bruker-tims branch May 19, 2026 14:27
timosachsenberg added a commit that referenced this pull request May 20, 2026
…) and IMAGING module (#9381) (#9385)

Two recent feature commits (both merged Tue May 19 2026) did not have
CHANGELOG entries in the 3.6.0 section:

- #9380: BrukerTimsFile IM-axis hill-based centroiding (PASEFHillCentroider)
  with new Config fields for hill params, isotopic prefilter, and per-mode
  centroid-algorithm selection; Greedy2D path retained as back-compat default.

- #9381: New OpenMS/IMAGING module — IonImage, MSImagingGeometry,
  MSImagingExperiment — providing in-memory data structures for imaging MS;
  first phase of imzML/MSI support.

Also adds the missing (#9379) PR reference tag to the existing pyOpenMS
BrukerTimsFile bindings line so the entry is traceable.

Co-authored-by: GitHub Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: timosachsenberg <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
1 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant