Repository navigation
Add on-disc extractIonImage for imzML - #9654
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds shared ion-image extraction logic, reuses it from in-memory and on-disc experiments, and exposes new on-disc extraction overloads to Python. Tests cover whole-dataset, region-scoped extraction, and invalid-input cases. ChangesIon image extraction from on-disc ImzML
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp (1)
257-305: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReduce duplication between the two
extractIonImageoverloads.The validation, ppm-window computation,
IonImageallocation, andsetMzRangeare copied verbatim. Consider extracting a private helper that returns the configured image (andmz_lo/mz_hi), so both overloads only differ in the pixel set passed toextractIntoImage_.♻️ Sketch
// in Impl: IonImage makeWindowedImage_(double mz, double tolerance_ppm, double& mz_lo, double& mz_hi) const { if (!std::isfinite(mz) || !std::isfinite(tolerance_ppm) || mz < 0.0 || tolerance_ppm < 0.0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "mz and tolerance_ppm must be finite and non-negative", "mz=" + StringUtils::toStr(mz) + ", tolerance_ppm=" + StringUtils::toStr(tolerance_ppm)); } if (!ibd_) { throw Exception::FileNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, ibd_path_); } const double dm = mz * tolerance_ppm * 1e-6; mz_lo = mz - dm; mz_hi = mz + dm; IonImage image(geometry_.getWidth(), geometry_.getHeight()); image.setMzRange(RangeMZ(mz_lo, mz_hi)); return image; }🤖 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/KERNEL/OnDiscImzMLExperiment.cpp` around lines 257 - 305, Both `OnDiscImzMLExperiment::extractIonImage` overloads duplicate the same validation, ppm window calculation, `IonImage` construction, and `setMzRange` setup. Extract that shared logic into a private helper (for example in the impl/pimpl alongside `extractIntoImage_`) that returns the prepared image and the computed `mz_lo`/`mz_hi`, then have each overload only fetch its pixel range (`geom.getPixels()` vs `geom.getRegionPixels(region_id)`) and call `extractIntoImage_`.src/tests/class_tests/openms/source/ImzMLFile_test.cpp (1)
262-306: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for the
extractIonImage(mz, tolerance_ppm, region_id)overload.This section currently validates only the 2-argument overload, so the new region-restricted API path is still unguarded.
As per coding guidelines, "Write unit tests for new functionality and ensure existing tests pass before suggesting changes."
🤖 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/ImzMLFile_test.cpp` around lines 262 - 306, Add coverage for the new region-restricted IonImage API by extending the existing extractIonImage test section to exercise the three-argument overload on OnDiscImzMLExperiment. Use the same setup already in extractIonImage(double mz, double tolerance_ppm) const, but call extractIonImage(mz, tolerance_ppm, region_id) with a valid region from the loaded data and verify the returned image dimensions and pixel masks/intensities against the expected region-limited result. Keep the existing invalid-argument checks for the new overload as well so the region_id path is also guarded.Source: Coding guidelines
src/pyOpenMS/tests/unittests/test_ImzMLFile.py (1)
110-112: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAlso assert negative
tolerance_ppmraises in the Python binding test.The C++ API validates both parameters; this test currently covers only negative
mz.✅ Minimal addition
with self.assertRaises(Exception): od.extractIonImage(-1.0, tol_ppm) + with self.assertRaises(Exception): + od.extractIonImage(mz, -1.0)🤖 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_ImzMLFile.py` around lines 110 - 112, In the test method in test_ImzMLFile.py that currently only checks negative mz via extractIonImage, add a second assertion that a negative tolerance_ppm value also raises an Exception so the Python binding test matches the C++ API validation for both parameters. Keep the change in the same test case and use the existing od.extractIonImage call to verify the negative tolerance_ppm path.
🤖 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/tests/class_tests/openms/source/ImzMLFile_test.cpp`:
- Line 275: The boolean assertions in the ImzMLFile class test should use the
OpenMS-specific boolean macros instead of equality checks. Update the checks in
the ImzMLFile test case to replace `TEST_EQUAL(..., false)` and `TEST_EQUAL(...,
true)` with the corresponding `TEST_FALSE(...)` and `TEST_TRUE(...)` forms,
keeping the same expressions and test intent. Use the existing test symbols in
`ImzMLFile_test.cpp` around the `first` and related assertions to locate the
affected cases.
---
Nitpick comments:
In `@src/openms/source/KERNEL/OnDiscImzMLExperiment.cpp`:
- Around line 257-305: Both `OnDiscImzMLExperiment::extractIonImage` overloads
duplicate the same validation, ppm window calculation, `IonImage` construction,
and `setMzRange` setup. Extract that shared logic into a private helper (for
example in the impl/pimpl alongside `extractIntoImage_`) that returns the
prepared image and the computed `mz_lo`/`mz_hi`, then have each overload only
fetch its pixel range (`geom.getPixels()` vs `geom.getRegionPixels(region_id)`)
and call `extractIntoImage_`.
In `@src/pyOpenMS/tests/unittests/test_ImzMLFile.py`:
- Around line 110-112: In the test method in test_ImzMLFile.py that currently
only checks negative mz via extractIonImage, add a second assertion that a
negative tolerance_ppm value also raises an Exception so the Python binding test
matches the C++ API validation for both parameters. Keep the change in the same
test case and use the existing od.extractIonImage call to verify the negative
tolerance_ppm path.
In `@src/tests/class_tests/openms/source/ImzMLFile_test.cpp`:
- Around line 262-306: Add coverage for the new region-restricted IonImage API
by extending the existing extractIonImage test section to exercise the
three-argument overload on OnDiscImzMLExperiment. Use the same setup already in
extractIonImage(double mz, double tolerance_ppm) const, but call
extractIonImage(mz, tolerance_ppm, region_id) with a valid region from the
loaded data and verify the returned image dimensions and pixel masks/intensities
against the expected region-limited result. Keep the existing invalid-argument
checks for the new overload as well so the region_id path is also guarded.
🪄 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: 7ff747b9-d3fe-41ad-a3b4-3a14d7d6a25e
📒 Files selected for processing (5)
src/openms/include/OpenMS/KERNEL/OnDiscImzMLExperiment.hsrc/openms/source/KERNEL/OnDiscImzMLExperiment.cppsrc/pyOpenMS/bindings/bind_kernel.cppsrc/pyOpenMS/tests/unittests/test_ImzMLFile.pysrc/tests/class_tests/openms/source/ImzMLFile_test.cpp
|
|
||
| // Pick a real m/z present in the data (first peak of pixel 0) and a wide tolerance window. | ||
| const MSSpectrum first = od.getSpectrum(0); | ||
| TEST_EQUAL(first.empty(), false) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use boolean-specific OpenMS test macros on Line 275 and Line 300.
Prefer TEST_FALSE/TEST_TRUE over TEST_EQUAL(..., false/true) in class tests.
♻️ Suggested update
- TEST_EQUAL(first.empty(), false)
+ TEST_FALSE(first.empty())
...
- TEST_EQUAL(masks_match, true)
+ TEST_TRUE(masks_match)As per coding guidelines, "Prefer TEST_TRUE(expr) and TEST_FALSE(expr) over TEST_EQUAL(expr, true) and TEST_EQUAL(expr, false) for boolean assertions."
Also applies to: 300-300
🤖 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/ImzMLFile_test.cpp` at line 275, The
boolean assertions in the ImzMLFile class test should use the OpenMS-specific
boolean macros instead of equality checks. Update the checks in the ImzMLFile
test case to replace `TEST_EQUAL(..., false)` and `TEST_EQUAL(..., true)` with
the corresponding `TEST_FALSE(...)` and `TEST_TRUE(...)` forms, keeping the same
expressions and test intent. Use the existing test symbols in
`ImzMLFile_test.cpp` around the `first` and related assertions to locate the
affected cases.
Source: Coding guidelines
patrick-bo
left a comment
There was a problem hiding this comment.
Overall a very sensible addition, thank you for the work.
I have some conceptual concerns with this as OnDiscImzMlExperiment is in my opinion mostly an access class so I would suggest to refactor this as well as the in memory ion image extraction into a common function with wrappers around those, they are already mostly identical and I see this leading to issues downstream where one is refactored and the other forgotten.
Lift into a single extraction layer which parameterizes over how individual spectra are obtained (in-memory, no copy and on-disc with lifetime on this function).
extractIonImage should be a function over either spectrum source not duplicated onto multiple containers.
Additional point to this is that extracting Ion Images and pretty much all other individual spectra based tasks in imaging are basically a textbook example of parallelizable work. I would love to see the groundwork laid for generalizing such operations in the OnDiscImzMlExperiment, easiest implementation should be threading blocks of pixel indices while making sure no races occur in our output structures (std::vector used for the mask is packed).
|
Building on @patrick-bo's review — I agree the duplication is the main thing to resolve here, and "parameterize over the spectrum source" is the right shape. Here's a concrete proposal for where the shared layer should live and how to keep no-copy on the in-memory path. Why this is worth doingThe new on-disc const MSSpectrum& spec = experiment_[p.spectrum_index]; // in-memory: reference, no copy
const MSSpectrum spec = decodeSpectrum(p.spectrum_index); // on-disc: decoded value, function lifetimeOn top of that, both public overloads in both classes duplicate the validation, the Where the shared helper livesThe layering already allows this with no new dependency edge: Since it has to be a template, it can't hide in a The key trick that preserves no-copy: the accessor returns either // OpenMS/IMAGING/IonImageExtraction.h — internal, header-only
namespace OpenMS::Internal
{
/// Build an IonImage by summing peak intensities in the ppm window for the given
/// pixel subset. get_spectrum(spectrum_index) yields one pixel's spectrum — either
/// `const MSSpectrum&` (in-memory, no copy) or `MSSpectrum` by value (on-disc).
template <typename GetSpectrum>
IonImage extractIonImage(const MSImagingGeometry& geom,
double mz, double tolerance_ppm,
const std::vector<Size>& pixel_indices,
Size n_spectra,
GetSpectrum&& get_spectrum)
{
if (!std::isfinite(mz) || !std::isfinite(tolerance_ppm) || mz < 0.0 || tolerance_ppm < 0.0)
throw Exception::InvalidValue(/* ... */);
const double dm = mz * tolerance_ppm * 1e-6;
IonImage image(geom.getWidth(), geom.getHeight());
image.setMzRange(RangeMZ(mz - dm, mz + dm));
const auto& pixels = geom.getPixels();
for (Size i : pixel_indices)
{
const auto& p = pixels[i];
if (p.spectrum_index >= n_spectra) throw Exception::InvalidValue(/* ... */);
const auto& spec = get_spectrum(p.spectrum_index); // ref binds; value lifetime-extends
double sum = 0.0;
for (auto it = spec.MZBegin(mz - dm); it != spec.MZEnd(mz + dm); ++it)
sum += static_cast<double>(it->getIntensity());
image.setIntensity(p.x, p.y, sum);
}
return image;
}
}Both classes' methods then collapse to thin wrappers differing only in the pixel-index list and the accessor: // MSImagingExperiment.cpp
IonImage MSImagingExperiment::extractIonImage(double mz, double tol) const {
std::vector<Size> all(geometry_.getNumberOfPixels());
std::iota(all.begin(), all.end(), Size(0));
return Internal::extractIonImage(geometry_, mz, tol, all, experiment_.getNrSpectra(),
[this](Size i) -> const MSSpectrum& { return experiment_[i]; }); // explicit ref return — required!
}
// OnDiscImzMLExperiment.cpp
IonImage OnDiscImzMLExperiment::extractIonImage(double mz, double tol) const {
std::vector<Size> all(pimpl_->geometry_.getNumberOfPixels());
std::iota(all.begin(), all.end(), Size(0));
return Internal::extractIonImage(pimpl_->geometry_, mz, tol, all, pimpl_->index_.size(),
[this](Size i) -> MSSpectrum { return pimpl_->decodeSpectrum(i); });
}The region overloads are identical except they pass
Why a free template and not the alternatives
On parallelizationAgree it's a textbook embarrassingly-parallel workload and the bit-packed I'd suggest scoping the actual threading (plus a mask-storage change and thread-safe on-disc I/O) as a separate follow-up, since the serial implementation isn't a regression. The refactor above is exactly the groundwork for it: it leaves a single loop to parallelize and one place to fix the mask race, rather than two divergent copies. Suggested actionable scope for this PR
|
…d in-memory processing - Added extractIonImage function in IonImageExtraction.h for extracting ion images based on m/z values. - Updated MSImagingExperiment and OnDiscImzMLExperiment to utilize the new extraction method. - Removed legacy extractIntoImage_ methods to streamline the code. - Added unit tests to validate the functionality of the new extraction method.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/tests/class_tests/openms/source/ImzMLFile_test.cpp`:
- Around line 856-878: The ROI comparison in the ImzMLFile test is currently
vacuous because the hard-coded rectangle region may contribute no pixels, so the
check can pass on two empty masks. Update the test around the extractIonImage
comparisons for img and od to include one explicit positive assertion that at
least one pixel matched inside region 1, using the existing mem/ disc traversal
and masks_match logic so the test only passes when the ROI actually covers
acquired data.
🪄 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: bd5a6111-cef2-4a39-a63b-9f3985cfb37f
📒 Files selected for processing (6)
src/openms/include/OpenMS/IMAGING/IonImageExtraction.hsrc/openms/include/OpenMS/IMAGING/MSImagingExperiment.hsrc/openms/include/OpenMS/KERNEL/OnDiscImzMLExperiment.hsrc/openms/source/IMAGING/MSImagingExperiment.cppsrc/openms/source/KERNEL/OnDiscImzMLExperiment.cppsrc/tests/class_tests/openms/source/ImzMLFile_test.cpp
💤 Files with no reviewable changes (1)
- src/openms/include/OpenMS/IMAGING/MSImagingExperiment.h
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
|
@timosachsenberg @patrick-bo This PR is ready for review. I have incorporated your suggestions by refactoring the extractIonImage() logic into a shared implementation, removing the duplication between in-memory and on-disc implementations. |
|
looks good to me! |
- #9654: on-disc extractIonImage for imzML (IonImageExtraction.h shared kernel, OnDiscImzMLExperiment::extractIonImage without full dataset load) - #9683: perf fix for three O(N²)/O(P²) hotspots in PeptideAndProteinQuant::quantifyProteins that caused hangs on large isobaric inputs (~7M PSMs) - #9511: vcpkg integration (GSOC 2026) — vcpkg.json, CMakePresets.json, and CI workflow for reproducible dependency management Claude-Session: https://claude.ai/code/session_01KNeJXnuadWQJgwm5kXVQjo Co-authored-by: Claude <[email protected]>
Description
Adds extractIonImage() to OnDiscImzMLExperiment, enabling direct extraction of ion images for a specified m/z and ppm tolerance range from on-disk imzML data. The implementation avoids loading the entire dataset into memory, making visualization and analysis of large datasets more memory efficient.
What Changed
Added two overloads to
OnDiscImzMLExperiment:Extracts an ion image over the entire dataset by summing peak intensities within the window:
where:
Performs the same extraction but restricts processing to a specific acquisition region.
Implementation
.ibdfile one pixel at a time using the existingdecodeSpectrum()path.MSImagingGeometrymapping built duringopen(), ensuring pixel placement is consistent with the in-memoryMSImagingExperiment::extractIonImage()implementation.Tests
MSImagingExperiment::extractIonImage()pixel-for-pixel.Summary by CodeRabbit
region_id).mzandtolerance_ppm, and clearer errors when data is unavailable or whenregion_idis unknown.