Skip to content

Feature/imaging multi region - #9521

Merged
timosachsenberg merged 7 commits into
OpenMS:developfrom
patrick-bo:feature/imaging-multi-region
Jun 18, 2026
Merged

timosachsenberg merged 7 commits into
OpenMS:developfrom
patrick-bo:feature/imaging-multi-region

Conversation

@patrick-bo

@patrick-bo patrick-bo commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Adds multi-region support to the IMAGING module, so an MSI
dataset split into multiple disconnected acquisition areas can be modeled,
queried, and processed per region while keeping every region in the global
pixel coordinate system.

New MSImagingRegion — a pure-geometry value class for one region
footprint in global coords: axis-aligned Rectangle or bbox-local Mask.
Built via rectangle() / fromMask() factories (validated; rejects
inverted bounds, zero/mismatched mask dims, all-false masks). Exposes
contains(), area(), bbox accessors, getShape(), getMask().

MSImagingGeometry region overlay — a separable std::vector<MSImagingRegion>
plus an id→index map. addRegion / removeRegion / regionOf /
getRegionPixels / getRegionSpectrumIndices / getRegion(s) /
getNumberOfRegions / clearRegions. Key design properties:

  • Decoupled overlay: Pixel is unchanged; membership is derived on
    demand via contains() over the acquired pixel set — never cached, so it
    cannot go stale (a pixel added after a region is still resolved correctly).
  • Disjoint partition: addRegion rejects overlap on any acquired pixel,
    so pixel→region lookup is singular.
  • Zero regions ⇒ unchanged whole-image behavior. Global coords
    throughout; footprints may extend beyond the declared image (for
    microscopy alignment) and simply contribute no members where unacquired.

MSImagingExperiment — per-region extractIonImage(mz, tolerance_ppm, region_id) overload (sizes the image to full global dimensions, writes only
the region's pixels → cells outside the region stay masked) and
getRegionSpectrumIndices(). The shared m/z-window summation core is
refactored into a private extractIntoImage_() used by both the
whole-image and per-region paths (behavior preserved).

pyOpenMS — bindings for MSImagingRegion (incl. nested Shape enum and
a uint8 get_mask()), the geometry region methods, NO_REGION, and
overload_cast for the two extractIonImage overloads. The existing
get_pixels_struct() itemsize == 16 zero-copy view is unaffected.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)### How can I get additional information on failed tests during CI
Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

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

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

Summary by CodeRabbit

Release Notes

  • New Features
    • Multi-region MSI imaging support with a new region abstraction (rectangular and mask-based).
    • Imaging geometry now supports full region lifecycle and queries (add/remove/clear, region lookup, and region-specific pixel/spectrum indices).
    • Ion image extraction can be restricted to a region.
    • Added PyOpenMS bindings for region objects and region-aware imaging APIs.
  • Documentation
    • Updated the changelog with an imaging entry for this release.
  • Tests
    • Extended unit tests (including PyOpenMS) for region creation/validation, geometry region queries, and region-restricted extraction.

Add MSImagingRegion (Rectangle/Mask footprint), a decoupled region
overlay on MSImagingGeometry with derived (uncached) membership, a
per-region MSImagingExperiment::extractIonImage overload, pyOpenMS
bindings, and C++/Python tests.
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: d7232d18-2f46-4b45-9dbc-b981dbecd173

📥 Commits

Reviewing files that changed from the base of the PR and between 14898c7 and 27c6690.

📒 Files selected for processing (2)
  • src/openms/source/IMAGING/MSImagingRegion.cpp
  • src/tests/class_tests/openms/executables.cmake
💤 Files with no reviewable changes (1)
  • src/openms/source/IMAGING/MSImagingRegion.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/class_tests/openms/executables.cmake

📝 Walkthrough

Walkthrough

Introduces MSImagingRegion, a new class supporting rectangular bounding-box and per-pixel mask regions. MSImagingGeometry gains region lifecycle and spatial query APIs with disjointness enforcement. MSImagingExperiment gets a region-scoped extractIonImage overload and a getRegionSpectrumIndices accessor. All APIs are exposed via nanobind pyOpenMS bindings and covered by C++ and Python unit tests.

Changes

MSI Multi-Region Support

Layer / File(s) Summary
MSImagingRegion class: declaration and implementation
src/openms/include/OpenMS/IMAGING/MSImagingRegion.h, src/openms/source/IMAGING/MSImagingRegion.cpp, src/openms/include/OpenMS/IMAGING/sources.cmake, src/openms/source/IMAGING/sources.cmake
Defines the new MSImagingRegion exported class with a Shape enum (Rectangle, Mask), two static factory methods (rectangle, fromMask) with input validation, bbox/mask/area/contains query APIs, and registers both the header and source in their respective CMake lists.
MSImagingGeometry region lifecycle and query APIs
src/openms/include/OpenMS/IMAGING/MSImagingGeometry.h, src/openms/source/IMAGING/MSImagingGeometry.cpp
Extends MSImagingGeometry with a NO_REGION sentinel, addRegion (validates no duplicate/overlapping regions), removeRegion, clearRegions, getRegions, getRegion, getNumberOfRegions, regionOf, getRegionPixels, and getRegionSpectrumIndices; updates clear() to also reset region state; adds out-of-line constexpr NO_REGION definition for nanobind compatibility.
MSImagingExperiment region-scoped ion image extraction
src/openms/include/OpenMS/IMAGING/MSImagingExperiment.h, src/openms/source/IMAGING/MSImagingExperiment.cpp
Adds extractIonImage(mz, tolerance_ppm, region_id) overload that restricts pixel iteration to geometry_.getRegionPixels(region_id); refactors the existing overload to share a new private extractIntoImage_ helper; adds getRegionSpectrumIndices as a direct forwarder to geometry.
nanobind pyOpenMS bindings for imaging region types
src/pyOpenMS/bindings/bind_experiment.cpp
Adds MSImagingRegion nanobind class with Shape enum, factory methods, bbox/mask/area/contains accessors, and get_mask() returning a 2D uint8 numpy array; updates MSImagingGeometry bindings with all new region APIs; extends MSImagingExperiment bindings with the region-scoped extractIonImage overload.
C++ and Python unit tests for region support
src/tests/class_tests/openms/source/MSImagingRegion_test.cpp, src/tests/class_tests/openms/source/MSImagingGeometry_test.cpp, src/tests/class_tests/openms/source/MSImagingExperiment_test.cpp, src/tests/class_tests/openms/executables.cmake, src/pyOpenMS/tests/unittests/test_imaging.py, CHANGELOG
Adds MSImagingRegion_test.cpp for construction, factory validation, and error cases; extends geometry and experiment C++ test files with region lifecycle, spatial query, and region-scoped extraction scenarios; adds corresponding Python unit tests for MSImagingRegion, MSImagingGeometry region management, and MSImagingExperiment.extractIonImage with region id; wires MSImagingRegion_test into CMake; documents the feature in CHANGELOG.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant MSImagingExperiment
  participant MSImagingGeometry
  participant MSImagingRegion
  participant extractIntoImage_

  User->>MSImagingRegion: rectangle(id, name, min_x, min_y, max_x, max_y)
  MSImagingRegion-->>User: MSImagingRegion instance

  User->>MSImagingGeometry: addRegion(region)
  MSImagingGeometry->>MSImagingRegion: contains(x,y) for each existing pixel
  MSImagingGeometry-->>User: ok (disjoint validated)

  User->>MSImagingExperiment: extractIonImage(mz, ppm, region_id)
  MSImagingExperiment->>MSImagingGeometry: getRegionPixels(region_id)
  MSImagingGeometry->>MSImagingRegion: contains(x,y) for each pixel
  MSImagingGeometry-->>MSImagingExperiment: pixel_indices[]
  MSImagingExperiment->>extractIntoImage_: pixel_indices, mz_lo, mz_hi, IonImage&
  extractIntoImage_-->>MSImagingExperiment: IonImage with region pixels filled
  MSImagingExperiment-->>User: IonImage
Loading

Possibly related PRs

  • OpenMS/OpenMS#9381: Introduced the core IonImage, MSImagingGeometry, and MSImagingExperiment data structures that this PR directly extends with region support and new extractIonImage overloads.

🐇 A region is drawn on the grid so neat,
Rectangle or mask, each pixel's a feat.
extractIonImage knows just where to look,
Disjoint and valid — no pixels forsook!
In pyOpenMS too, the numpy arrays gleam,
Multi-region imaging: a bunny's dream! 🔬✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Feature/imaging multi region' is vague and uses non-descriptive branch-naming convention rather than a clear summary of the primary change. Replace with a more descriptive title that summarizes the main feature, such as 'Add multi-region imaging support to MSImagingGeometry and MSImagingExperiment' or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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 unit tests (beta)
  • Create PR with unit tests

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

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

485-485: Wrap fromMask to accept numpy boolean arrays for better MSI workflow ergonomics.

The C++ signature expects std::vector<bool> for the mask parameter. While nanobind can convert Python lists, most MSI workflows work with numpy arrays. Adding a lambda wrapper to accept numpy arrays is a straightforward improvement:

♻️ Suggested wrapper
-        .def_static("fromMask", &OpenMS::MSImagingRegion::fromMask, "id"_a, "name"_a, "origin_x"_a, "origin_y"_a, "width"_a, "height"_a, "mask"_a)
+        .def_static("fromMask",
+          [](OpenMS::Size id, const OpenMS::String& name, OpenMS::UInt origin_x, OpenMS::UInt origin_y,
+             OpenMS::UInt width, OpenMS::UInt height, nb::ndarray<bool, nb::ndim<1>> mask_arr) {
+            std::vector<bool> mask(mask_arr.size());
+            const bool* ptr = mask_arr.data();
+            for (size_t i = 0; i < mask_arr.size(); ++i) mask[i] = ptr[i];
+            return OpenMS::MSImagingRegion::fromMask(id, name, origin_x, origin_y, width, height, mask);
+          },
+          "id"_a, "name"_a, "origin_x"_a, "origin_y"_a, "width"_a, "height"_a, "mask"_a,
+          "Create a region from a 1D boolean mask array (row-major, size = width * height).")
🤖 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_experiment.cpp` at line 485, The `fromMask` static
method binding currently only accepts std::vector<bool>, which is inconvenient
for typical MSI workflows that use numpy arrays. Replace the direct reference to
&OpenMS::MSImagingRegion::fromMask in the .def_static() call with a lambda
wrapper that accepts numpy boolean arrays, converts them to std::vector<bool>,
and then delegates to the original fromMask method. This wrapper should extract
the boolean values from the numpy array and construct the appropriate vector for
the C++ function.
src/openms/include/OpenMS/IMAGING/MSImagingGeometry.h (1)

125-125: 💤 Low value

Fix Doxygen tag spacing.

The comment has an extra space: /// @ throws should be ///@throws to match Doxygen syntax conventions.

✏️ Proposed fix
-  /// @ throws ElementNotFound unknown id
+  ///@throws ElementNotFound unknown id
🤖 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/include/OpenMS/IMAGING/MSImagingGeometry.h` at line 125, Fix the
Doxygen tag spacing in the ElementNotFound documentation comment. The comment
currently has `/// @ throws` with spaces around the @ symbol, but Doxygen syntax
requires `///@throws` with no spaces. Remove the extra spaces between `///` and
`@throws` to match proper Doxygen formatting conventions for the throws tag.
src/openms/include/OpenMS/IMAGING/MSImagingRegion.h (1)

46-46: 💤 Low value

Clarify comment: mask storage applies only to Mask shape.

The comment states "empty if shape_ is set" which is ambiguous. It should clarify that the mask vector is empty for Rectangle shape and populated for Mask shape.

📝 Suggested clarification
-  std::vector<bool> mask_; // empty if shape_ is set, otherwise rect is bounding box
+  std::vector<bool> mask_; // empty for Rectangle shape; populated for Mask shape
🤖 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/include/OpenMS/IMAGING/MSImagingRegion.h` at line 46, The comment
for the mask_ member variable is ambiguous about when the vector is populated
versus empty. Update the comment to explicitly clarify that the mask_ vector is
empty when the shape is Rectangle and populated when the shape is Mask, making
it clear under which conditions the vector contains data versus being empty.
This removes the vagueness of the current phrasing "empty if shape_ is set".
src/openms/source/IMAGING/MSImagingGeometry.cpp (1)

144-166: Consider the performance characteristics of disjointness validation.

The disjointness check iterates all pixels in the geometry, and for each pixel contained in the new region, it checks containment against all existing regions. This is O(total_pixels × existing_regions) in the worst case.

For datasets with millions of acquired pixels and many regions, addRegion() could become slow. However, since regions are typically added infrequently (during dataset initialization), and the implementation prioritizes simplicity and correctness, this tradeoff appears intentional per the PR description's "decoupled and uncached" membership model.

If future profiling reveals this as a bottleneck, consider spatial indexing (e.g., R-tree or grid-based lookup) to accelerate the overlap check.

🤖 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/IMAGING/MSImagingGeometry.cpp` around lines 144 - 166, The
disjointness validation in the addRegion() method currently has O(total_pixels ×
existing_regions) worst-case complexity due to the nested loops checking each
pixel against all existing regions. While this is intentional given the
decoupled membership model and acceptable for typical dataset initialization
scenarios, be aware this could become a bottleneck with millions of pixels and
many regions. No immediate change is required, but document this performance
characteristic, and if future profiling reveals addRegion() as a bottleneck,
consider implementing spatial indexing such as R-tree or grid-based lookup to
accelerate the overlap detection between the new region and existing regions.
🤖 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/IMAGING/MSImagingExperiment.h`:
- Around line 175-180: The Doxygen documentation block for the
getRegionSpectrumIndices method is missing the required `@brief` tag. Add a `@brief`
line at the beginning of the comment block that concisely describes what the
method does (e.g., "Gets the spectrum indices within a region"), followed by a
blank line, then the existing `@return` and `@throws` documentation. Ensure the
format matches the standard Doxygen structure used elsewhere in the
MSImagingExperiment.h header file.

In `@src/openms/include/OpenMS/IMAGING/MSImagingRegion.h`:
- Around line 17-51: The MSImagingRegion class and all its public methods are
missing required Doxygen documentation. Add Doxygen comments to the class
definition itself with a `@brief` tag describing its purpose, then add Doxygen
comments to each public method: the static factory methods rectangle and
fromMask should include `@param` tags for each parameter and `@throws` tags for any
exceptions, while the getter methods (getName, contains, getShape, getId,
getMinX, getMinY, getMaxX, getMaxY, getBBoxWidth, getBBoxHeight, getMask, area)
should include `@brief` descriptions of what they return or do. Follow the format:
/** `@brief` description */, a blank line, and then details with appropriate tags.

In `@src/pyOpenMS/tests/unittests/test_imaging.py`:
- Around line 231-233: The test case for overlap rejection in the rectangle call
uses ID 1, which is likely already used in a previous region addition, causing
the test to fail on duplicate-ID validation instead of testing the overlap
detection logic. Change the ID parameter in the MSImagingRegion.rectangle call
from 1 to a different unused ID to ensure the test validates the intended
overlap rejection path.

---

Nitpick comments:
In `@src/openms/include/OpenMS/IMAGING/MSImagingGeometry.h`:
- Line 125: Fix the Doxygen tag spacing in the ElementNotFound documentation
comment. The comment currently has `/// @ throws` with spaces around the @
symbol, but Doxygen syntax requires `///@throws` with no spaces. Remove the
extra spaces between `///` and `@throws` to match proper Doxygen formatting
conventions for the throws tag.

In `@src/openms/include/OpenMS/IMAGING/MSImagingRegion.h`:
- Line 46: The comment for the mask_ member variable is ambiguous about when the
vector is populated versus empty. Update the comment to explicitly clarify that
the mask_ vector is empty when the shape is Rectangle and populated when the
shape is Mask, making it clear under which conditions the vector contains data
versus being empty. This removes the vagueness of the current phrasing "empty if
shape_ is set".

In `@src/openms/source/IMAGING/MSImagingGeometry.cpp`:
- Around line 144-166: The disjointness validation in the addRegion() method
currently has O(total_pixels × existing_regions) worst-case complexity due to
the nested loops checking each pixel against all existing regions. While this is
intentional given the decoupled membership model and acceptable for typical
dataset initialization scenarios, be aware this could become a bottleneck with
millions of pixels and many regions. No immediate change is required, but
document this performance characteristic, and if future profiling reveals
addRegion() as a bottleneck, consider implementing spatial indexing such as
R-tree or grid-based lookup to accelerate the overlap detection between the new
region and existing regions.

In `@src/pyOpenMS/bindings/bind_experiment.cpp`:
- Line 485: The `fromMask` static method binding currently only accepts
std::vector<bool>, which is inconvenient for typical MSI workflows that use
numpy arrays. Replace the direct reference to &OpenMS::MSImagingRegion::fromMask
in the .def_static() call with a lambda wrapper that accepts numpy boolean
arrays, converts them to std::vector<bool>, and then delegates to the original
fromMask method. This wrapper should extract the boolean values from the numpy
array and construct the appropriate vector for the C++ function.
🪄 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: 03899612-c69a-44d0-8db0-ac112b2e1257

📥 Commits

Reviewing files that changed from the base of the PR and between ed2a1b8 and c764084.

📒 Files selected for processing (15)
  • CHANGELOG
  • src/openms/include/OpenMS/IMAGING/MSImagingExperiment.h
  • src/openms/include/OpenMS/IMAGING/MSImagingGeometry.h
  • src/openms/include/OpenMS/IMAGING/MSImagingRegion.h
  • src/openms/include/OpenMS/IMAGING/sources.cmake
  • src/openms/source/IMAGING/MSImagingExperiment.cpp
  • src/openms/source/IMAGING/MSImagingGeometry.cpp
  • src/openms/source/IMAGING/MSImagingRegion.cpp
  • src/openms/source/IMAGING/sources.cmake
  • src/pyOpenMS/bindings/bind_experiment.cpp
  • src/pyOpenMS/tests/unittests/test_imaging.py
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/MSImagingExperiment_test.cpp
  • src/tests/class_tests/openms/source/MSImagingGeometry_test.cpp
  • src/tests/class_tests/openms/source/MSImagingRegion_test.cpp

@github-actions

Copy link
Copy Markdown
Contributor

@patrick-bo The following names might be missing from the AUTHORS file:

  • patrick-bo

Please consider applying the following patch:

--- AUTHORS	2026-06-15 11:00:06.846894468 +0000
+++ AUTHORS.new	2026-06-15 11:00:12.258327696 +0000
@@ -22,8 +22,8 @@
  - Chirag Dave
  - Chris Bauer
  - Chris Bielow
- - Christie Mathews
  - Christian Ehrlich
+ - Christie Mathews
  - Clemens Groepl
  - Cornelia Friedle
  - Daniel Jameson
@@ -98,6 +98,7 @@
  - Oliver Kohlbacher
  - Pasquale Domenico Colaianni
  - Patricia Scheil
+ - patrick-bo
  - Patrick Boschmann
  - Peter J. Jones
  - Peter Kunszt

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

Review — multi-region imaging support

Solid, well-structured feature: MSImagingRegion as a pure-geometry value type, a decoupled (never-cached) region overlay on MSImagingGeometry, a per-region extractIonImage overload that cleanly refactors the shared summation into extractIntoImage_(), plus complete pyOpenMS bindings and C++/Python tests. The whole-image path is behavior-preserving and "zero regions ⇒ unchanged behavior" holds. Comments below, roughly in priority order.

Blocking / merge state

  • Branch currently has a merge conflict with develop — needs a rebase/merge before it can land.
  • AUTHORS: the commit identity patrick-bo isn't listed (only "Patrick Boschmann"); add the alias or commit under the matching name.

Correctness — disjointness invariant is not actually enforced

The PR advertises two properties that are in tension:

  1. "a pixel added after a region is still resolved correctly" (pixels may be added after regions), and
  2. "addRegion rejects overlap on any acquired pixel, so pixel→region lookup is singular."

addRegion (MSImagingGeometry.cpp:154-163) only scans the pixels that exist at call time. So:

  • Define regions A and B whose footprints overlap geometrically, but at coordinates that have no pixel yet (regions are often defined independent of acquisition, and footprints "may extend beyond the declared image").
  • addRegion(B) passes — no acquired pixel is in the overlap.
  • Later addPixel(x,y) lands in the overlap. Now regionOf(x,y) returns the first region in regions_ (arbitrary), and both getRegionPixels(A) and getRegionPixels(B) include it → the pixel is double-counted across per-region ion images and the partition is no longer singular.

Suggested fix: validate disjointness on the footprints, not the acquired pixels. A shape-agnostic check that reuses contains() over the integer bbox-intersection of the new region vs. each existing one is simple and at most O(overlap-bbox area):

// overlap iff some integer cell in the bbox intersection is contained by both
UInt lo_x = std::max(a.getMinX(), b.getMinX()), hi_x = std::min(a.getMaxX(), b.getMaxX());
UInt lo_y = std::max(a.getMinY(), b.getMinY()), hi_y = std::min(a.getMaxY(), b.getMaxY());
if (lo_x <= hi_x && lo_y <= hi_y)
  for (UInt y = lo_y; y <= hi_y; ++y)
    for (UInt x = lo_x; x <= hi_x; ++x)
      if (a.contains(x, y) && b.contains(x, y)) /* throw "Regions must be disjoint" */;

For the common rect/rect case this short-circuits to a bbox-intersection test. If a true partition is not intended, then weaken the docs/CHANGELOG (drop "disjoint partition … singular") and define regionOf explicitly as "first matching region" — but enforcing the footprint invariant matches the stated intent and is the cleaner choice. Either way, please add a regression test (two geometrically-overlapping regions added while the overlap is unacquired, then acquire a pixel there).

State / lifetime / persistence

  • The on-demand (never-cached) membership model is the right call for an overlay — the only crack is the disjointness gap above.
  • Binding lifetime: getRegion/getRegions use nb::rv_policy::reference_internal (bind_experiment.cpp:586-587). A Python handle to a returned region/vector dangles if a later addRegion/removeRegion reallocates regions_ (and removeRegion rebuilds the vector wholesale). Worth at least a docstring caveat, or return by value.
  • Persistence: MSImagingRegion is runtime-only — not serialized to/from imzML or any format yet. Fine for this phase, but a one-line note in the header/CHANGELOG would set expectations.

Extensibility — polygon ROIs

Shape is {Rectangle, Mask}. Polygon/freehand ROIs are common in MSI, and currently the only way to represent one is to rasterize into a Mask (O(bbox area) memory, vector geometry lost). Two options worth deciding now, while the enum is young:

  • Document that polygon ROIs are represented by rasterizing to Mask (so getShape() semantics are clear and get_mask() for a Rectangle returning all-1s isn't surprising), or
  • Add a Polygon shape storing vertices with a point-in-polygon contains(). Note ConvexHull2D::encloses() already exists but is convex-only, so concave/freehand ROIs would need a general even-odd/winding test; area() and the get_mask() binding would each need a polygon branch.

If polygons are near-term, adding the shape now avoids API churn once regions are persisted/bound.

Code quality / docs

  • MSImagingRegion has no Doxygen (class + all public methods) — required by the include/**/*.h guidelines.
  • MSImagingGeometry region methods are under-documented. Critically, getRegionPixels returns pixel indices into getPixels() while getRegionSpectrumIndices returns spectrum indices — both are std::vector<Size> and easy to confuse. Document both, and consider renaming getRegionPixels → getRegionPixelIndices.
  • MSImagingExperiment.h:175-180 (getRegionSpectrumIndices) uses a Javadoc block with no @brief, inconsistent with the rest of the file.
  • Duplication: the two extractIonImage overloads repeat the finite/non-negative validation and dm/mz_lo/mz_hi setup (MSImagingExperiment.cpp:79-86 vs 100-107). Factor the window setup into a small private helper.
  • addRegion(const MSImagingRegion&) copies into the vector; a by-value + std::move param avoids one copy.
  • constexpr Size MSImagingGeometry::NO_REGION; out-of-line definition (MSImagingGeometry.cpp:184): in C++20 a constexpr static member is implicitly inline and needs no out-of-line definition even when its address is taken by def_ro_static — the redundant definition is deprecated and can trip -Wdeprecated. Try removing it; if a toolchain genuinely needs it, keep it but fix the "nanobind compat" comment.

Tests

  • Good coverage overall; the C++ addRegion test correctly uses a distinct id for the overlap case.
  • Python overlap test is ineffective (test_imaging.py:231-232): it reuses id 1, which already exists, so it throws on duplicate-id and never reaches the overlap path. Use an unused id.
  • pyOpenMS docstring coverage is ~1.4% (most new .defs lack docstrings); adding short docstrings would also help the missing-Doxygen item.

Bottom line

Before merge I'd want: (1) resolve the merge conflict; (2) fix disjointness enforcement (or downgrade the docs claim) + regression test; (3) add the missing Doxygen and clarify getRegionPixels vs getRegionSpectrumIndices; (4) a decision on polygon ROIs. The Python overlap-test id, duplicated validation, and deprecated NO_REGION definition are quick follow-ups.


Generated by Claude Code

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

I found one correctness issue in the region disjointness validation.

patrick-bo and others added 3 commits June 16, 2026 12:40
- addRegion now rejects geometrically overlapping region footprints via
  MSImagingRegion::intersects(), independent of acquired pixels (Timo)
- add Doxygen to MSImagingRegion and the MSImagingGeometry region API;
  add @brief to MSImagingExperiment::getRegionSpectrumIndices (CodeRabbit)
- bind intersects and add 1D/2D numpy bool-array overloads for
  fromMask (2D infers width/height from shape)
- tests: intersects unit test, pixel-independent overlap rejection,
  numpy fromMask paths incl. non-contiguous; fix overlap-test region id

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

Copy link
Copy Markdown
Contributor

Adversarial review result: I did not find a blocking behavioral issue in the imaging region/API changes from static inspection. The region membership helpers, geometry lookup, pyOpenMS bindings, and added tests line up with the intended region-overlay model.

Cleanup required: git diff --check reports trailing whitespace in src/openms/source/IMAGING/MSImagingRegion.cpp at line 122.

No source/test comments with tracker-style issue references stood out in this diff.

I did not build or run the tests locally.

Copy link
Copy Markdown
Contributor

One edge case worth guarding in MSImagingRegion::fromMask(): the inclusive bbox calculation can overflow UInt before assigning max_x_ / max_y_.

This is unlikely for normal MSI grids, but as a public factory it should either create a valid region or throw. For example, with 32-bit UInt, origin_x = UINT_MAX, width = 2 wraps origin_x + width - 1 to 0, leaving min_x > max_x and making the region silently unusable. The related unsigned <= loops in intersects() are also fragile when hi_x or hi_y is UInt max.

Suggested fix:

#include <limits>
const UInt max_uint = std::numeric_limits<UInt>::max();
if (origin_x > max_uint - (width - 1) || origin_y > max_uint - (height - 1))
{
  throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
                                "Mask bounding box exceeds UInt coordinate range",
                                "origin=(" + StringUtils::toStr(origin_x) + "," + StringUtils::toStr(origin_y) +
                                  "), size=(" + StringUtils::toStr(width) + "," + StringUtils::toStr(height) + ")");
}

reg.max_x_ = origin_x + width - 1;
reg.max_y_ = origin_y + height - 1;

And avoid incrementing past the unsigned maximum in intersects():

for (UInt y = lo_y;; ++y)
{
  for (UInt x = lo_x;; ++x)
  {
    if (contains(x, y) && other.contains(x, y))
    {
      return true;
    }
    if (x == hi_x)
    {
      break;
    }
  }

  if (y == hi_y)
  {
    break;
  }
}

A regression test can keep the intended boundary behavior clear:

const UInt umax = std::numeric_limits<UInt>::max();
TEST_EXCEPTION(Exception::InvalidValue,
               MSImagingRegion::fromMask(1, "overflow", umax, 0, 2, 1,
                                          std::vector<bool>{true, true}))

This still allows valid boundary cases like origin_x = UINT_MAX, width = 1, and rejects only masks whose inclusive bbox cannot be represented.

@timosachsenberg
timosachsenberg merged commit 1f17b57 into OpenMS:develop Jun 18, 2026
38 checks passed
timosachsenberg added a commit that referenced this pull request Jun 19, 2026
Add entries for all substantive non-test PRs merged since the last
changelog update:

- #9623 ThermoRawFile full mzML metadata extraction + polarity fix
- #9602 New FileInfo library class usable from C++ and pyOpenMS
- #9521 IMAGING multi-region support (add missing PR reference)
- #9620 Deisotoper::isToleranceSupported + ProSE/SSE crash fix on low-res data
- #9610 DistanceMatrix::setValue cached-minimum guard fix
- #9497 DistanceMatrix::operator==, ClusteringGrid, File path guard fixes
- #9583 LogStreamBuf thread-safety fix
- #9514 CI Windows migration to Visual Studio 2026


Claude-Session: https://claude.ai/code/session_01YLg6pWyjyTxpWAU6mgrDzC

Co-authored-by: Claude <[email protected]>
timosachsenberg added a commit that referenced this pull request Jun 20, 2026
…o decoy mode) (#9637)

Two recently merged PRs were missing from the 3.6.0 changelog:
- #9521: MSImagingRegion + multi-region support in MSImagingGeometry/MSImagingExperiment
- #9634: ProSE Search:decoys three-way enum (auto/generate/ignore) replacing the boolean


Claude-Session: https://claude.ai/code/session_01Kd4QCxoucuh5b3U5gSQtH1

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants