Repository navigation
Wnetalign - #8992
Wnetalign#8992
Conversation
|
looks good. |
|
I can push some small fixes |
Code ReviewThe trivial fixes (SSH→HTTPS URLs, deprecated FetchContent pattern, missing Remaining issues that need author decisions1. [CRITICAL] No
|
| Consensus element | m/z values grouped | Spread |
|---|---|---|
e_2927519776102075938 |
876.8, 778.3, 922.5 | 144 Da |
e_2684106197423007927 |
1555.6, 1752.6 | 197 Da |
e_8119044117483804262 |
1305.7, 1108.5 | 197 Da |
e_14811341817612382122 |
1283.7, 1163.6 | 120 Da |
e_16907355690727166316 |
1420.7, 1420.7, 1511.8 | 91 Da |
e_12524258085768770586 |
1567.7, 1479.8 | 88 Da |
These are not scientifically plausible matches. The default max_distance=100 combined with auto mz_scale_factor allows far too many spurious groupings. Committing this as the expected reference output will mask future regressions. The QT linker reference on the same inputs keeps these features correctly separated.
The PR description acknowledges parameter tuning is outstanding — the reference output should be regenerated once defaults are fixed.
3. [IMPORTANT] Singleton features silently dropped
FeatureGroupingAlgorithmWNet.cpp:272-275 skips groups with members.size() < 2. Other linkers (QT) include unmatched features in the consensus map. Downstream tools expecting all features may produce incomplete results. Should either include singletons for consistency or document the behavior difference.
4. [MINOR] Pairwise alignment order affects results
The union-find processes pairs in order (0,1), (0,2), (1,2). Because unite() rejects merges on map conflicts, earlier accepted matches can block later ones. The algorithm is not symmetric with respect to input map ordering. Worth documenting.
5. [MINOR] pyOpenMS docstring says "globally optimal"
The binding docstring says "Produces globally optimal 1-to-1 feature matchings" — this is only true per pairwise comparison. The multi-map merge via union-find with conflict rejection is a heuristic, not globally optimal. Suggest clarifying.
OK, so vectors are absolutely possible, our Spectrum is basically a wrapper for two std::vectors, we can expose that. |
|
Hi, I think I'm ready for the merge. The failing checks are AFAICT (and correct me if I'm wrong) unrelated to this PR. The option to use a lambda distance function - I'd like to test that first on some actual data, and put that in a follow-up PR later (Timo: I'll get in touch later, do you have any specific MS2 datasets to test this use-case in mind?), but it makes no sense to keep this PR hanging until this happens. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Wasserstein optimal-transport feature grouping: new WNet matcher and FeatureGroupingAlgorithmWNet (implementation, tests, Python bindings), a TOPP tool (FeatureLinkerWNet), optional CMake FetchContent integration for external WNet libs, documentation/parameter registration, and related test fixtures. All changes are additive. Changes
Sequence Diagram(s)sequenceDiagram
participant TOPP as TOPP Tool
participant FGA as FeatureGroupingAlgorithmWNet
participant Matcher as WNetMatcher
participant Aligner as WNetAligner (external)
participant UF as Union-Find
participant Consensus as ConsensusMap Builder
TOPP->>FGA: group(FeatureMaps / ConsensusMaps)
FGA->>FGA: convert maps → Spectrum<2> (scale m/z, optional decharge, normalize)
loop for each map pair
FGA->>Matcher: match(points_a,intensities_a,points_b,intensities_b,metric,max_dist,trash_cost)
Matcher->>Aligner: run WNetAligner<2> (metric, params)
Aligner-->>Matcher: matched_pairs, cost
Matcher-->>FGA: MatchResult
FGA->>UF: union matched pairs (prevent same-map duplicates)
end
FGA->>UF: extract connected components
FGA->>Consensus: build ConsensusFeature per component
Consensus-->>FGA: aggregated ConsensusMap
FGA->>TOPP: return ConsensusMap
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 6
🧹 Nitpick comments (14)
cmake/cmake_findExternalLibs.cmake (1)
298-312: Pinning by tag (not commit SHA) is not fully reproducible.
GIT_TAG vX.Y.Zresolves a tag at fetch time; tags can be moved/re-pushed upstream, and CMake won't re-fetch on a moved tag once_depsis populated. For a third-party header dependency that gets baked into the OpenMS public library, consider pinning to the immutable commit SHA (or at least addingGIT_SHALLOW TRUEplus a comment recording the resolved SHA at the chosen tag) so contrib/CI builds remain bit-for-bit reproducible across rebases of upstream tags.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@cmake/cmake_findExternalLibs.cmake` around lines 298 - 312, The FetchContent_Declare blocks for pylmcf, wnet, and wnetalign currently pin by tag (GIT_TAG vX.Y.Z) which is not fully reproducible; update each FetchContent_Declare (pylmcf, wnet, wnetalign) to pin to the immutable commit SHA instead of the tag (set GIT_TAG to the resolved commit hash), or at minimum add GIT_SHALLOW TRUE and add a comment next to each declaration recording the exact resolved commit SHA for that tag so CI and contrib builds remain bit-for-bit reproducible.src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h (1)
41-57: Add@paramdirections to the publicgroup()overrides.Per the coding guidelines, public methods in
src/openms/include/OpenMS/...should include@paramtags with[in]/[out]/[in,out]directions for all parameters. The twogroup()overrides currently document only@preand@exception. A small addition would bring them in line with the rest of the project's headers.♻️ Proposed fix
/** `@brief` Applies the algorithm to feature maps + `@param`[in] maps input feature maps to be grouped + `@param`[out] out resulting consensus map containing the grouped features + `@pre` The data ranges of the input maps have to be up-to-date (use FeatureMap::updateRanges). `@exception` IllegalArgument is thrown if less than two input maps are given. */ void group(const std::vector<FeatureMap>& maps, ConsensusMap& out) override; /** `@brief` Applies the algorithm to consensus maps + `@param`[in] maps input consensus maps to be grouped + `@param`[out] out resulting consensus map containing the grouped features + `@pre` The data ranges of the input maps have to be up-to-date (use ConsensusMap::updateRanges). `@exception` IllegalArgument is thrown if less than two input maps are given. */ void group(const std::vector<ConsensusMap>& maps, ConsensusMap& out) override;As per coding guidelines: "Always use
@brieffor class and method documentation; include parameter directions[in],[out], or[in,out]for all parameters".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h` around lines 41 - 57, Add missing `@param` tags to both public overrides of group: for group(const std::vector<FeatureMap>& maps, ConsensusMap& out) override and group(const std::vector<ConsensusMap>& maps, ConsensusMap& out) override add a `@param` [in] maps describing the input maps and a `@param` [out] out describing the resulting ConsensusMap (or `@param` [in,out] if out is used as both input and output) so the method docs include parameter directions per the project's header guidelines.src/tests/class_tests/openms/source/WNetMatcher_test.cpp (1)
22-27: Document/test the silent fallback for unknown metric strings.
metricFromString("unknown") == LINFcodifies a silent fallback for any unrecognized string. TheFeatureGroupingAlgorithmWNetparameter restricts inputs to{L1, L2, LINF}, butWNetMatcher::metricFromStringis a public API that can be called directly (e.g., from pyOpenMS bindings). Consider either logging a warning on unknown input or making this stricter; at minimum, the header docstring should explicitly state this fallback so callers don't get silently coerced.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/WNetMatcher_test.cpp` around lines 22 - 27, WNetMatcher::metricFromString silently falls back to DistanceMetric::LINF for unknown strings; update the method to emit a warning when an unrecognized metric is passed and keep returning LINF, and also document this behavior in the WNetMatcher header docstring so callers (including pyOpenMS) are aware; specifically, modify WNetMatcher::metricFromString to detect unknown inputs, call the logger/warning facility used elsewhere in the codebase with a clear message, and add a sentence to the WNetMatcher class/method docstring describing the silent fallback to DistanceMetric::LINF for unrecognized strings (and update the test comment if needed).src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp (4)
161-177: Usestd::log1pfor ppm shift conversion.
log(1.0 + max_mz_shift * 1e-6)is a textbook case forstd::log1p, which preserves precision for smallx(e.g.max_mz_shift_ppm = 1⇒1e-6, wherelog(1+x)loses ~6 significant digits vs.log1p(x)). This affects the computedmz_scaleand indirectly all matching distances in ppm mode.♻️ Proposed fix
- mz_shift_native = log(1.0 + max_mz_shift * 1e-6); + mz_shift_native = std::log1p(max_mz_shift * 1e-6);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp` around lines 161 - 177, Replace the naive log(1.0 + max_mz_shift * 1e-6) used when computing mz_shift_native in FeatureGroupingAlgorithmWNet.cpp with std::log1p(max_mz_shift * 1e-6) to preserve precision for small ppm values (the branch where use_ppm is true and max_mz_shift comes from param_.getValue("max_mz_shift_ppm")); ensure <cmath> is available and use the std::log1p symbol so mz_scale and downstream distance calculations use the higher-precision conversion.
51-56: Confirm thetrash_cost == 0 ⇒ max_rt_shiftoverload is intentional.The parameter has
setMinFloat("trash_cost", 0.0)and "0 means use max_rt_shift" semantics, which means there is no way for a user to actually requesttrash_cost = 0. In practicetrash_cost = 0would mean "leaving signal unmatched is free" which is degenerate, so the overload is defensible — but the parameter description currently reads as if0is a normal numeric value. If you want to keep the auto-default behavior, consider documenting this more explicitly (e.g. "Set to 0 to auto-derive from max_rt_shift") and/or using a sentinel value like-1withsetMinFloat(-1)so the user-facing semantics are unambiguous.Also applies to: 156-159
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp` around lines 51 - 56, The description and constraints for the "trash_cost" parameter are misleading because 0 is currently overloaded to mean "auto-derive from max_rt_shift" while setMinFloat("trash_cost", 0.0) prevents users from explicitly choosing 0; update the parameter handling and docs to make this explicit: either (A) change the documentation string in defaults_.setValue(...) to state "Set to 0 to auto-derive from max_rt_shift" and keep the min as 0, or (B) switch to a sentinel value (e.g. use -1 as the sentinel) by changing setMinFloat("trash_cost", -1.0) and updating the docstring to "Set to -1 to auto-derive from max_rt_shift", and adjust any logic in FeatureGroupingAlgorithmWNet that interprets trash_cost accordingly; apply the same change to the other occurrence around lines 156-159 so both declarations and consumers use the same sentinel/documentation convention.
219-265: Group-map tracking is O(total_features) memory; consider keying by root only.
vector<set<Size>> group_maps(total_features)allocates astd::set<Size>per feature even though only group roots ever read non-empty contents after the first union. Eachsetcarries a non-trivial fixed overhead (sentinel + allocator state) so for datasets in the 10⁵–10⁶ feature range this adds up. Astd::unordered_map<Size, std::vector<bool>>(or a flatvector<vector<bool>>of sizen_mapsper root, since the number of input maps is small and known) keyed by root would also turn the conflict check (for (Size m : group_maps[b]) ... group_maps[a].count(m)) into O(n_maps) bitmap operations instead of two ordered-set walks.Not blocking — current logic is correct — but worth considering for scalability before this is exercised on real-world datasets.
179-182: Replaceendlwith'\n'.
OPENMS_LOG_INFO << ... << endlflushes the underlying stream on every record; for a hot logging path inside a pairwise alignment loop this adds avoidable overhead. As per coding guidelines: "Avoidstd::endlfor performance; prefer\n."♻️ Proposed fix
@@ -179,7 +179,7 @@ OPENMS_LOG_INFO << "FeatureGroupingAlgorithmWNet: max_mz_shift = " << max_mz_shift << (use_ppm ? " ppm" : " Da") << ", max_rt_shift = " << max_rt_shift << " s" - << ", mz_scale = " << mz_scale << endl; + << ", mz_scale = " << mz_scale << '\n'; @@ -294,7 +294,7 @@ OPENMS_LOG_INFO << "FeatureGroupingAlgorithmWNet: maps " << i << " vs " << j << ": " << emp_ids.size() << " pairs matched, " << accepted << " accepted (cost = " - << aligner.total_cost() << ")" << endl; + << aligner.total_cost() << ")" << '\n';Also applies to: 294-297
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp` around lines 179 - 182, Replace uses of std::endl in the logging statements with '\\n' to avoid unnecessary stream flushes; specifically update the OPENMS_LOG_INFO stream expressions in FeatureGroupingAlgorithmWNet (the line printing "FeatureGroupingAlgorithmWNet: max_mz_shift ..." and the similar logging block around the later occurrence at lines showing the same pattern) so they end with '\\n' instead of endl, ensuring no other formatting changes.src/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cpp (2)
117-120: Consider exercising the ConsensusMap overload directly.
group(const std::vector<ConsensusMap>&, ...)andgroup(const std::vector<FeatureMap>&, ...)both forward togroup_<MapType>but the templated path still differs at thecf.insert(map_idx, maps[map_idx][feat_idx])call (Feature vs ConsensusFeature insertion path). Marking itNOT_TESTABLEskips that branch; a small symmetric test on avector<ConsensusMap>would actually validate it.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cpp` around lines 117 - 120, Add a new test that calls FeatureGroupingAlgorithmWNet::group(const std::vector<ConsensusMap>&, ConsensusMap&) to exercise the ConsensusMap overload and the ConsensusFeature insertion path; create a small vector<ConsensusMap> with at least two ConsensusMap instances containing ConsensusFeature entries (with matching IDs/positions for grouping), call group(...) and assert the resulting ConsensusMap contains the expected grouped ConsensusFeatures (verifying counts/IDs), ensuring the code path through group_<MapType> and the cf.insert(map_idx, maps[map_idx][feat_idx]) ConsensusFeature branch is hit.
91-114: Optional: extend coverage to ppm mode anddecharge_mz.Current grouping test only covers
mz_unit="Da". Adding a small ppm-mode case (so thelog-transform path intransformMzis exercised) and adecharge_mz=truecase (sodechargeMzis exercised, including thedc_charge_adduct_massMetaValue branch) would meaningfully increase coverage of the new code paths inFeatureGroupingAlgorithmWNet.cpp.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cpp` around lines 91 - 114, Add tests exercising mz_unit="ppm" to hit the log-transform path in transformMz and add a test case with decharge_mz=true to exercise dechargeMz including the dc_charge_adduct_mass MetaValue branch: update FeatureGroupingAlgorithmWNet_test.cpp to duplicate the existing Da-mode scenario but set algo.getParameters().setValue("mz_unit","ppm") and verify same grouping behavior, and add another scenario where parameters include setValue("decharge_mz", "true") (and set appropriate dc_charge_adduct_mass meta on one feature) then call algo.group(maps, result) and assert expected consensus sizes so transformMz and dechargeMz code paths are covered.src/tests/topp/FeatureLinkerWNet_1_parameters.ini (1)
17-25: Optional: regenerate INI to includedecharge_mz.The algorithm registers a
decharge_mzparameter (seesrc/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpplines 63-71) that is missing from this test INI. Loading will fall back to the default (false), which appears to be the intent for this test, but if the INI is meant to be a complete dump of the tool's parameters it should be regenerated to stay consistent with the algorithm definition (and to avoid silent drift if the default ever changes).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/topp/FeatureLinkerWNet_1_parameters.ini` around lines 17 - 25, This INI is missing the algorithm parameter decharge_mz that FeatureGroupingAlgorithmWNet registers (see FeatureGroupingAlgorithmWNet.cpp around lines 63-71); update the INI so the algorithm parameter list includes an ITEM for decharge_mz (e.g., name="decharge_mz" value="false" type="string" restrictions="true,false" with a short description) or regenerate the INI from the tool so the decharge_mz parameter is present with its default (false).src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp (1)
60-66: Add a brief comment explaining whatset_point({1.0})configures.The
{1.0}parameter is a magic value with no inline explanation. Sincewnetalignis an external header-only library (https://github.com/michalsta/wnetalign) that lacks detailed C++ API documentation, a one-line comment clarifying what this value represents (e.g., a weight parameter for the alignment solver or consensus threshold) would help readers understand the intent. This call appears identically in bothWNetMatcher.cpp(line 62) andFeatureGroupingAlgorithmWNet.cpp(line 279).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp` around lines 60 - 66, Add a one-line inline comment next to the call to WNetAligner<2>::set_point({1.0}) explaining what the {1.0} configures (e.g., that it sets the point weight/score used by the WNet solver or the consensus weight for target alignment), so readers know the intent; update both occurrences where set_point({1.0}) is called (the one in the WNetAligner usage near aligner.set_point(...) and the similar call in FeatureGroupingAlgorithmWNet) with the same concise explanatory comment.src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h (2)
47-72: Document units (and meaning) ofmax_distance/trash_cost.The coding guidelines require parameters to document ranges/units.
max_distanceandtrash_costare defined in whatever space the chosenmetricoperates over the suppliedpositions_*(raw m/z vs. log-m/z for ppm, RT in seconds, etc.) — this is non-obvious to a caller usingWNetMatcherdirectly withoutFeatureGroupingAlgorithmWNet. Please clarify in the Doxygen which coordinate space distances are measured in, whattrash_costis measured against (same units as the metric output?), and whether the supplied defaults of100.0are meant as sensible defaults or just placeholders — given prior reviewer concerns about overly permissive defaults producing spurious matches, an explicit note here would help direct API users.As per coding guidelines: "Function parameters must use lower_case with underscores; document ranges/units".
74-75: Document the silent fallback behavior ofmetricFromString.The method silently returns
DistanceMetric::LINFfor any unrecognized input without raising an exception. Update the Doxygen comments to explicitly document this behavior (e.g., "ReturnsLINFif the input is not recognized"). This is important for callers and pyOpenMS bindings that may pass user-supplied strings. Consider whether this warrants throwingException::InvalidValuewith file/line/OPENMS_PRETTY_FUNCTIONinstead, which aligns with OpenMS exception-handling conventions.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h` around lines 74 - 75, Update the Doxygen for the static method metricFromString(const std::string& s) to explicitly state its current silent fallback behavior: document that it maps "L1", "L2", "LINF" to the corresponding DistanceMetric values and returns DistanceMetric::LINF if the input is not recognized. Also add a note suggesting the alternative: replace the silent fallback with throwing Exception::InvalidValue (using OPENMS_PRETTY_FUNCTION for context) if you prefer strict handling—if you choose that route, update callers/pyOpenMS accordingly. Ensure the comment references the DistanceMetric enum and LINF constant so callers know the exact behavior.src/pyOpenMS/bindings/bind_misc.cpp (1)
40-41: Place ANALYSIS bindings inbind_analysis.cppfor module consistency.These classes are from
OpenMS/ANALYSIS/MAPMATCHING/*but are added inbind_misc.cpp. Moving them tobind_analysis.cppkeeps domain boundaries consistent.As per coding guidelines:
Add#includeand class binding in the appropriate binding file based on C++ module location (KERNEL/ → bind_kernel.cpp, FORMAT/ → bind_format.cpp, ANALYSIS/ → bind_analysis.cpp, ...).Also applies to: 800-858
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/pyOpenMS/bindings/bind_misc.cpp` around lines 40 - 41, The included ANALYSIS headers and their Python bindings (FeatureGroupingAlgorithmWNet and WNetMatcher) are placed in bind_misc.cpp but belong in bind_analysis.cpp; move the `#include` lines for OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h and OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h and the corresponding class binding code (the binding blocks that define FeatureGroupingAlgorithmWNet and WNetMatcher) out of bind_misc.cpp and add them into bind_analysis.cpp so ANALYSIS module bindings are grouped consistently with the coding guideline; ensure you remove the duplicated includes/bindings from bind_misc.cpp and update any include ordering or module registration in bind_analysis.cpp to match existing patterns for other ANALYSIS bindings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmake/cmake_findExternalLibs.cmake`:
- Around line 291-335: Wrap the wnetalign FetchContent block behind a new
WITH_WNETALIGN option so the three FetchContent_Declare/Populate calls (pylmcf,
wnet, wnetalign) only run when WITH_WNETALIGN is ON; add an
option(WITH_WNETALIGN "Enable WNet alignment" OFF) and guard the existing
FetchContent_GetProperties/Populate block with if(WITH_WNETALIGN) ... endif(),
and provide a safe default for WNETALIGN_INCLUDE_DIRS (e.g. set to an empty
list) when the option is OFF so the variable is always defined. Also update
consumers: guard target_include_directories(... ${WNETALIGN_INCLUDE_DIRS}) and
any target_compile_definitions/OPENMS_HAS_WNETALIGN usage in
src/openms/CMakeLists.txt with the same WITH_WNETALIGN check, and conditionally
compile/register FeatureGroupingAlgorithmWNet and FeatureLinkerWNet behind
WITH_WNETALIGN.
- Around line 314-327: The current use of FetchContent_Populate(<name>) for
pylmcf, wnet and wnetalign is deprecated (CMP0169); instead, update the
FetchContent declarations for those targets to include SOURCE_SUBDIR set to a
nonexistent subdirectory and replace the
FetchContent_GetProperties/FetchContent_Populate blocks with a single
FetchContent_MakeAvailable(<name>) call for each; this will populate the source
dirs without executing their top-level CMakeLists (so nanobind modules won’t be
built) while still exposing ${pylmcf_SOURCE_DIR}, ${wnet_SOURCE_DIR}, and
${wnetalign_SOURCE_DIR} for includes.
In `@src/openms/CMakeLists.txt`:
- Around line 173-175: Add a new CMake option option(WITH_WNETALIGN "Enable
wnetalign integration" ON/OFF) in the top-level CMakeLists to control the
optional dependency, then wrap any FetchContent_Declare / FetchContent_Populate
calls that provision wnetalign (the blocks referencing wnetalign in
cmake_findExternalLibs.cmake) inside an if(WITH_WNETALIGN) ... endif() so
fetching only happens when enabled, and finally guard the lines that apply
WNETALIGN_INCLUDE_DIRS and set the LEMON_ONLY_TEMPLATES compile definition in
src/openms/CMakeLists.txt (the target_include_directories(OpenMS SYSTEM PRIVATE
${WNETALIGN_INCLUDE_DIRS}) and target_compile_definitions(OpenMS PRIVATE
LEMON_ONLY_TEMPLATES) lines) with the same if(WITH_WNETALIGN) condition so the
include dirs and compile defs are only added when the option is enabled.
In `@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h`:
- Around line 41-45: The MatchResult struct exposes a public POD member cost
that is not default-initialized and can be read as indeterminate; update the
MatchResult definition (struct MatchResult) to give cost a safe default (e.g.
initialize to 0.0) so any default-constructed MatchResult has a well-defined
cost while leaving matched_pairs as-is.
In `@src/pyOpenMS/bindings/bind_misc.cpp`:
- Around line 848-851: The docstring in src/pyOpenMS/bindings/bind_misc.cpp that
describes the multi-map grouping binding overstates optimality; update the
string literal for the multi-map grouping binding (the docstring associated with
the grouping/multi-map merge function in bind_misc.cpp) to remove "globally
optimal 1-to-1 feature matchings" and instead state that the algorithm finds
pairwise optimal 1-to-1 matches via minimum-cost flow and then merges maps using
a heuristic, e.g. "Finds pairwise optimal 1-to-1 feature matchings via
minimum-cost network flow on (m/z, RT) positions; the subsequent merge across
multiple maps is heuristic and not globally optimal." Ensure the revised wording
replaces the existing docstring text for the same binding.
- Around line 40-41: The bindings for WNetMatcher, FeatureGroupingAlgorithmWNet
and the MatchResult enum are in the wrong file; remove the `#include` lines for
OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h and
OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h from bind_misc.cpp
and relocate the corresponding binding code for the MatchResult enum, the
WNetMatcher class binding (WNetMatcher), and the FeatureGroupingAlgorithmWNet
class binding (FeatureGroupingAlgorithmWNet) into bind_analysis.cpp; in
bind_analysis.cpp add the two include directives, register the MatchResult enum
and the two class bindings inside the same pybind11 module/context used for
other ANALYSIS bindings, and ensure any constructor/method names and docstrings
are preserved when moving to avoid breaking imports.
---
Nitpick comments:
In `@cmake/cmake_findExternalLibs.cmake`:
- Around line 298-312: The FetchContent_Declare blocks for pylmcf, wnet, and
wnetalign currently pin by tag (GIT_TAG vX.Y.Z) which is not fully reproducible;
update each FetchContent_Declare (pylmcf, wnet, wnetalign) to pin to the
immutable commit SHA instead of the tag (set GIT_TAG to the resolved commit
hash), or at minimum add GIT_SHALLOW TRUE and add a comment next to each
declaration recording the exact resolved commit SHA for that tag so CI and
contrib builds remain bit-for-bit reproducible.
In
`@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h`:
- Around line 41-57: Add missing `@param` tags to both public overrides of group:
for group(const std::vector<FeatureMap>& maps, ConsensusMap& out) override and
group(const std::vector<ConsensusMap>& maps, ConsensusMap& out) override add a
`@param` [in] maps describing the input maps and a `@param` [out] out describing the
resulting ConsensusMap (or `@param` [in,out] if out is used as both input and
output) so the method docs include parameter directions per the project's header
guidelines.
In `@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h`:
- Around line 74-75: Update the Doxygen for the static method
metricFromString(const std::string& s) to explicitly state its current silent
fallback behavior: document that it maps "L1", "L2", "LINF" to the corresponding
DistanceMetric values and returns DistanceMetric::LINF if the input is not
recognized. Also add a note suggesting the alternative: replace the silent
fallback with throwing Exception::InvalidValue (using OPENMS_PRETTY_FUNCTION for
context) if you prefer strict handling—if you choose that route, update
callers/pyOpenMS accordingly. Ensure the comment references the DistanceMetric
enum and LINF constant so callers know the exact behavior.
In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp`:
- Around line 161-177: Replace the naive log(1.0 + max_mz_shift * 1e-6) used
when computing mz_shift_native in FeatureGroupingAlgorithmWNet.cpp with
std::log1p(max_mz_shift * 1e-6) to preserve precision for small ppm values (the
branch where use_ppm is true and max_mz_shift comes from
param_.getValue("max_mz_shift_ppm")); ensure <cmath> is available and use the
std::log1p symbol so mz_scale and downstream distance calculations use the
higher-precision conversion.
- Around line 51-56: The description and constraints for the "trash_cost"
parameter are misleading because 0 is currently overloaded to mean "auto-derive
from max_rt_shift" while setMinFloat("trash_cost", 0.0) prevents users from
explicitly choosing 0; update the parameter handling and docs to make this
explicit: either (A) change the documentation string in defaults_.setValue(...)
to state "Set to 0 to auto-derive from max_rt_shift" and keep the min as 0, or
(B) switch to a sentinel value (e.g. use -1 as the sentinel) by changing
setMinFloat("trash_cost", -1.0) and updating the docstring to "Set to -1 to
auto-derive from max_rt_shift", and adjust any logic in
FeatureGroupingAlgorithmWNet that interprets trash_cost accordingly; apply the
same change to the other occurrence around lines 156-159 so both declarations
and consumers use the same sentinel/documentation convention.
- Around line 179-182: Replace uses of std::endl in the logging statements with
'\\n' to avoid unnecessary stream flushes; specifically update the
OPENMS_LOG_INFO stream expressions in FeatureGroupingAlgorithmWNet (the line
printing "FeatureGroupingAlgorithmWNet: max_mz_shift ..." and the similar
logging block around the later occurrence at lines showing the same pattern) so
they end with '\\n' instead of endl, ensuring no other formatting changes.
In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp`:
- Around line 60-66: Add a one-line inline comment next to the call to
WNetAligner<2>::set_point({1.0}) explaining what the {1.0} configures (e.g.,
that it sets the point weight/score used by the WNet solver or the consensus
weight for target alignment), so readers know the intent; update both
occurrences where set_point({1.0}) is called (the one in the WNetAligner usage
near aligner.set_point(...) and the similar call in
FeatureGroupingAlgorithmWNet) with the same concise explanatory comment.
In `@src/pyOpenMS/bindings/bind_misc.cpp`:
- Around line 40-41: The included ANALYSIS headers and their Python bindings
(FeatureGroupingAlgorithmWNet and WNetMatcher) are placed in bind_misc.cpp but
belong in bind_analysis.cpp; move the `#include` lines for
OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h and
OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h and the corresponding class binding
code (the binding blocks that define FeatureGroupingAlgorithmWNet and
WNetMatcher) out of bind_misc.cpp and add them into bind_analysis.cpp so
ANALYSIS module bindings are grouped consistently with the coding guideline;
ensure you remove the duplicated includes/bindings from bind_misc.cpp and update
any include ordering or module registration in bind_analysis.cpp to match
existing patterns for other ANALYSIS bindings.
In `@src/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cpp`:
- Around line 117-120: Add a new test that calls
FeatureGroupingAlgorithmWNet::group(const std::vector<ConsensusMap>&,
ConsensusMap&) to exercise the ConsensusMap overload and the ConsensusFeature
insertion path; create a small vector<ConsensusMap> with at least two
ConsensusMap instances containing ConsensusFeature entries (with matching
IDs/positions for grouping), call group(...) and assert the resulting
ConsensusMap contains the expected grouped ConsensusFeatures (verifying
counts/IDs), ensuring the code path through group_<MapType> and the
cf.insert(map_idx, maps[map_idx][feat_idx]) ConsensusFeature branch is hit.
- Around line 91-114: Add tests exercising mz_unit="ppm" to hit the
log-transform path in transformMz and add a test case with decharge_mz=true to
exercise dechargeMz including the dc_charge_adduct_mass MetaValue branch: update
FeatureGroupingAlgorithmWNet_test.cpp to duplicate the existing Da-mode scenario
but set algo.getParameters().setValue("mz_unit","ppm") and verify same grouping
behavior, and add another scenario where parameters include
setValue("decharge_mz", "true") (and set appropriate dc_charge_adduct_mass meta
on one feature) then call algo.group(maps, result) and assert expected consensus
sizes so transformMz and dechargeMz code paths are covered.
In `@src/tests/class_tests/openms/source/WNetMatcher_test.cpp`:
- Around line 22-27: WNetMatcher::metricFromString silently falls back to
DistanceMetric::LINF for unknown strings; update the method to emit a warning
when an unrecognized metric is passed and keep returning LINF, and also document
this behavior in the WNetMatcher header docstring so callers (including
pyOpenMS) are aware; specifically, modify WNetMatcher::metricFromString to
detect unknown inputs, call the logger/warning facility used elsewhere in the
codebase with a clear message, and add a sentence to the WNetMatcher
class/method docstring describing the silent fallback to DistanceMetric::LINF
for unrecognized strings (and update the test comment if needed).
In `@src/tests/topp/FeatureLinkerWNet_1_parameters.ini`:
- Around line 17-25: This INI is missing the algorithm parameter decharge_mz
that FeatureGroupingAlgorithmWNet registers (see
FeatureGroupingAlgorithmWNet.cpp around lines 63-71); update the INI so the
algorithm parameter list includes an ITEM for decharge_mz (e.g.,
name="decharge_mz" value="false" type="string" restrictions="true,false" with a
short description) or regenerate the INI from the tool so the decharge_mz
parameter is present with its default (false).
🪄 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: f7dffee1-5665-4b6c-ba89-c67784d5a5e8
📒 Files selected for processing (21)
CHANGELOGcmake/cmake_findExternalLibs.cmakedoc/doxygen/parameters/DefaultParamHandlerDocumenter.cppdoc/doxygen/public/TOPP.doxygensrc/openms/CMakeLists.txtsrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.hsrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.hsrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/sources.cmakesrc/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cppsrc/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cppsrc/openms/source/ANALYSIS/MAPMATCHING/sources.cmakesrc/openms/source/APPLICATIONS/ToolHandler.cppsrc/pyOpenMS/bindings/bind_misc.cppsrc/tests/class_tests/openms/executables.cmakesrc/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cppsrc/tests/class_tests/openms/source/WNetMatcher_test.cppsrc/tests/topp/CMakeLists.txtsrc/tests/topp/FeatureLinkerWNet_1_output.consensusXMLsrc/tests/topp/FeatureLinkerWNet_1_parameters.inisrc/topp/FeatureLinkerWNet.cppsrc/topp/executables.cmake
| #------------------------------------------------------------------------------ | ||
| # wnetalign (Wasserstein network spectral alignment) | ||
| include(FetchContent) | ||
|
|
||
| # Header-only: use GIT_REPOSITORY for reproducible versioned fetch. | ||
| # To override with local checkouts, set FETCHCONTENT_SOURCE_DIR_PYLMCF, | ||
| # FETCHCONTENT_SOURCE_DIR_WNET, FETCHCONTENT_SOURCE_DIR_WNETALIGN. | ||
| FetchContent_Declare( | ||
| pylmcf | ||
| GIT_REPOSITORY https://github.com/michalsta/pylmcf.git | ||
| GIT_TAG v0.9.7 | ||
| ) | ||
| FetchContent_Declare( | ||
| wnet | ||
| GIT_REPOSITORY https://github.com/michalsta/wnet.git | ||
| GIT_TAG v0.9.11 | ||
| ) | ||
| FetchContent_Declare( | ||
| wnetalign | ||
| GIT_REPOSITORY https://github.com/michalsta/wnetalign.git | ||
| GIT_TAG v0.9.8 | ||
| ) | ||
|
|
||
| # Populate source dirs without running their CMakeLists.txt | ||
| # (they build nanobind Python modules, not needed for C++ header-only usage). | ||
| FetchContent_GetProperties(pylmcf) | ||
| if(NOT pylmcf_POPULATED) | ||
| FetchContent_Populate(pylmcf) | ||
| endif() | ||
| FetchContent_GetProperties(wnet) | ||
| if(NOT wnet_POPULATED) | ||
| FetchContent_Populate(wnet) | ||
| endif() | ||
| FetchContent_GetProperties(wnetalign) | ||
| if(NOT wnetalign_POPULATED) | ||
| FetchContent_Populate(wnetalign) | ||
| endif() | ||
|
|
||
| set(WNETALIGN_INCLUDE_DIRS | ||
| "${pylmcf_SOURCE_DIR}/src/pylmcf/cpp" | ||
| "${wnet_SOURCE_DIR}/src/wnet/cpp" | ||
| "${wnetalign_SOURCE_DIR}/src/wnetalign/cpp" | ||
| ) | ||
|
|
||
| message(STATUS "wnetalign include dirs: ${WNETALIGN_INCLUDE_DIRS}") |
There was a problem hiding this comment.
Wrap the wnetalign FetchContent block behind a WITH_WNETALIGN option.
This block currently runs on every configure, which forces all OpenMS builds (CI, packagers, downstream contrib mirrors) to clone three GitHub repositories at configure time even when the WNet feature linker is not wanted. Compare with the WITH_OPENTIMS guard at line 417 — same pattern should apply here. The corresponding target_include_directories(... ${WNETALIGN_INCLUDE_DIRS}) and any target_compile_definitions in src/openms/CMakeLists.txt should be guarded the same way (and a fallback definition for WNETALIGN_INCLUDE_DIRS may be needed so the variable is always defined).
🔧 Proposed fix
-#------------------------------------------------------------------------------
-# wnetalign (Wasserstein network spectral alignment)
-include(FetchContent)
-
-# Header-only: use GIT_REPOSITORY for reproducible versioned fetch.
-# To override with local checkouts, set FETCHCONTENT_SOURCE_DIR_PYLMCF,
-# FETCHCONTENT_SOURCE_DIR_WNET, FETCHCONTENT_SOURCE_DIR_WNETALIGN.
-FetchContent_Declare(
- pylmcf
- GIT_REPOSITORY https://github.com/michalsta/pylmcf.git
- GIT_TAG v0.9.7
-)
-FetchContent_Declare(
- wnet
- GIT_REPOSITORY https://github.com/michalsta/wnet.git
- GIT_TAG v0.9.11
-)
-FetchContent_Declare(
- wnetalign
- GIT_REPOSITORY https://github.com/michalsta/wnetalign.git
- GIT_TAG v0.9.8
-)
-
-# Populate source dirs without running their CMakeLists.txt
-# (they build nanobind Python modules, not needed for C++ header-only usage).
-FetchContent_GetProperties(pylmcf)
-if(NOT pylmcf_POPULATED)
- FetchContent_Populate(pylmcf)
-endif()
-FetchContent_GetProperties(wnet)
-if(NOT wnet_POPULATED)
- FetchContent_Populate(wnet)
-endif()
-FetchContent_GetProperties(wnetalign)
-if(NOT wnetalign_POPULATED)
- FetchContent_Populate(wnetalign)
-endif()
-
-set(WNETALIGN_INCLUDE_DIRS
- "${pylmcf_SOURCE_DIR}/src/pylmcf/cpp"
- "${wnet_SOURCE_DIR}/src/wnet/cpp"
- "${wnetalign_SOURCE_DIR}/src/wnetalign/cpp"
-)
-
-message(STATUS "wnetalign include dirs: ${WNETALIGN_INCLUDE_DIRS}")
+#------------------------------------------------------------------------------
+# wnetalign (Wasserstein network spectral alignment)
+option(WITH_WNETALIGN "Enable Wasserstein network feature linker (fetches pylmcf/wnet/wnetalign at configure time)" OFF)
+set(WNETALIGN_INCLUDE_DIRS "" CACHE INTERNAL "")
+if (WITH_WNETALIGN)
+ include(FetchContent)
+
+ # Header-only: use GIT_REPOSITORY for reproducible versioned fetch.
+ # To override with local checkouts, set FETCHCONTENT_SOURCE_DIR_PYLMCF,
+ # FETCHCONTENT_SOURCE_DIR_WNET, FETCHCONTENT_SOURCE_DIR_WNETALIGN.
+ FetchContent_Declare(pylmcf GIT_REPOSITORY https://github.com/michalsta/pylmcf.git GIT_TAG v0.9.7)
+ FetchContent_Declare(wnet GIT_REPOSITORY https://github.com/michalsta/wnet.git GIT_TAG v0.9.11)
+ FetchContent_Declare(wnetalign GIT_REPOSITORY https://github.com/michalsta/wnetalign.git GIT_TAG v0.9.8)
+
+ # ... populate ...
+
+ set(WNETALIGN_INCLUDE_DIRS
+ "${pylmcf_SOURCE_DIR}/src/pylmcf/cpp"
+ "${wnet_SOURCE_DIR}/src/wnet/cpp"
+ "${wnetalign_SOURCE_DIR}/src/wnetalign/cpp"
+ )
+ message(STATUS "wnetalign include dirs: ${WNETALIGN_INCLUDE_DIRS}")
+endif()Don't forget to also guard the consumer (target_include_directories(... ${WNETALIGN_INCLUDE_DIRS}) and any OPENMS_HAS_WNETALIGN / source-list additions) in src/openms/CMakeLists.txt, and to gate compilation/registration of FeatureGroupingAlgorithmWNet and FeatureLinkerWNet accordingly.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@cmake/cmake_findExternalLibs.cmake` around lines 291 - 335, Wrap the
wnetalign FetchContent block behind a new WITH_WNETALIGN option so the three
FetchContent_Declare/Populate calls (pylmcf, wnet, wnetalign) only run when
WITH_WNETALIGN is ON; add an option(WITH_WNETALIGN "Enable WNet alignment" OFF)
and guard the existing FetchContent_GetProperties/Populate block with
if(WITH_WNETALIGN) ... endif(), and provide a safe default for
WNETALIGN_INCLUDE_DIRS (e.g. set to an empty list) when the option is OFF so the
variable is always defined. Also update consumers: guard
target_include_directories(... ${WNETALIGN_INCLUDE_DIRS}) and any
target_compile_definitions/OPENMS_HAS_WNETALIGN usage in
src/openms/CMakeLists.txt with the same WITH_WNETALIGN check, and conditionally
compile/register FeatureGroupingAlgorithmWNet and FeatureLinkerWNet behind
WITH_WNETALIGN.
| # wnetalign: header-only Wasserstein network alignment (pylmcf, wnet, wnetalign) | ||
| target_include_directories(OpenMS SYSTEM PRIVATE ${WNETALIGN_INCLUDE_DIRS}) | ||
| target_compile_definitions(OpenMS PRIVATE LEMON_ONLY_TEMPLATES) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n --glob 'CMakeLists.txt' --glob 'cmake/*.cmake' \
'WITH_WNETALIGN|WNETALIGN_INCLUDE_DIRS|LEMON_ONLY_TEMPLATES|FetchContent_Declare\(\s*wnetalign'Repository: OpenMS/OpenMS
Length of output: 430
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect cmake/cmake_findExternalLibs.cmake around line 329 to see how WNETALIGN_INCLUDE_DIRS is set
echo "=== Checking WNETALIGN setup in cmake_findExternalLibs.cmake ==="
sed -n '320,345p' cmake/cmake_findExternalLibs.cmake
echo ""
echo "=== Search for WITH_WNETALIGN or any wnetalign option definition ==="
rg -n 'WITH_WNETALIGN|option.*wnetalign|set.*WNETALIGN' cmake/ --glob '*.cmake'
echo ""
echo "=== Search for wnetalign in root CMakeLists.txt ==="
rg -n -i 'wnetalign' CMakeLists.txtRepository: OpenMS/OpenMS
Length of output: 1063
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Search for FetchContent_Declare for wnet/wnetalign/pylmcf ==="
rg -n 'FetchContent_Declare' cmake/ --glob '*.cmake' -A 3 | head -60
echo ""
echo "=== Check if cmake_findExternalLibs.cmake is conditionally included ==="
rg -n 'cmake_findExternalLibs' CMakeLists.txt -B 2 -A 2
echo ""
echo "=== Check context around FetchContent_Populate in cmake_findExternalLibs.cmake ==="
sed -n '1,50p' cmake/cmake_findExternalLibs.cmake | head -40Repository: OpenMS/OpenMS
Length of output: 3620
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Check for optional dependency patterns in root CMakeLists.txt ==="
rg -n 'option\(|ENABLE_|BUILD_|WITH_' CMakeLists.txt | head -30
echo ""
echo "=== Check if other external libs (e.g., BOOST, XercesC) are conditional ==="
sed -n '50,150p' cmake/cmake_findExternalLibs.cmake | grep -E 'if\(|option\(|REQUIRED|OPTIONAL'
echo ""
echo "=== Look for conditional FetchContent patterns ==="
rg -n 'if.*FetchContent|if.*ENABLE|if.*BUILD' cmake/cmake_findExternalLibs.cmake -B 2 -A 2Repository: OpenMS/OpenMS
Length of output: 3064
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Search for wnetalign in comments/docs ==="
rg -n 'wnetalign|wnet|LEMON_ONLY_TEMPLATES' --glob '*.md' --glob '*.txt' | head -20
echo ""
echo "=== Check if LEMON_ONLY_TEMPLATES is used anywhere in source ==="
rg -n 'LEMON_ONLY_TEMPLATES' src/ --glob '*.cpp' --glob '*.h' --glob '*.hpp'
echo ""
echo "=== Check src/openms/CMakeLists.txt context around lines 173-175 ==="
sed -n '160,185p' src/openms/CMakeLists.txtRepository: OpenMS/OpenMS
Length of output: 374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Context around src/openms/CMakeLists.txt lines 160-185 ==="
wc -l src/openms/CMakeLists.txt
sed -n '165,180p' src/openms/CMakeLists.txt
echo ""
echo "=== Search for how optional features are gated (e.g., WITH_GUI, WITH_HDF5, WITH_OPENTIMS) ==="
rg -n 'if.*WITH_GUI|if.*WITH_HDF5|if.*WITH_OPENTIMS' src/openms/CMakeLists.txt -A 3 | head -30
echo ""
echo "=== Check if wnetalign is mentioned in any git or version control context ==="
git log --oneline --all -- '*wnetalign*' '*wnet*' 2>/dev/null | head -10Repository: OpenMS/OpenMS
Length of output: 1270
Wnetalign integration is unconditional but lacks a build option unlike other optional external dependencies.
Lines 173–175 apply ${WNETALIGN_INCLUDE_DIRS} and LEMON_ONLY_TEMPLATES unconditionally. This inconsistently excludes wnetalign from the optional dependency pattern used elsewhere (e.g., WITH_OPENTIMS, WITH_GUI).
However, a guard at lines 173–175 alone is insufficient: the FetchContent_Declare and FetchContent_Populate calls in cmake/cmake_findExternalLibs.cmake (lines 308–327) are also unconditional, and no WITH_WNETALIGN option exists. A complete fix requires:
- Add
option(WITH_WNETALIGN ...)in rootCMakeLists.txt - Gate the FetchContent calls in
cmake/cmake_findExternalLibs.cmake - Guard the include and compile definitions in
src/openms/CMakeLists.txt:173–175
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/openms/CMakeLists.txt` around lines 173 - 175, Add a new CMake option
option(WITH_WNETALIGN "Enable wnetalign integration" ON/OFF) in the top-level
CMakeLists to control the optional dependency, then wrap any
FetchContent_Declare / FetchContent_Populate calls that provision wnetalign (the
blocks referencing wnetalign in cmake_findExternalLibs.cmake) inside an
if(WITH_WNETALIGN) ... endif() so fetching only happens when enabled, and
finally guard the lines that apply WNETALIGN_INCLUDE_DIRS and set the
LEMON_ONLY_TEMPLATES compile definition in src/openms/CMakeLists.txt (the
target_include_directories(OpenMS SYSTEM PRIVATE ${WNETALIGN_INCLUDE_DIRS}) and
target_compile_definitions(OpenMS PRIVATE LEMON_ONLY_TEMPLATES) lines) with the
same if(WITH_WNETALIGN) condition so the include dirs and compile defs are only
added when the option is enabled.
| #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h> | ||
| #include <OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h> |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Search for WNet-related build options/macros =="
rg -n --hidden -S "WITH_WNETALIGN|WNETALIGN|HAVE_WNETALIGN|OPENMS_HAS_WNETALIGN|wnetalign"
echo
echo "== Inspect bind_misc.cpp around WNet for preprocessor guards =="
rg -n -C3 --type=cpp "FeatureGroupingAlgorithmWNet|WNetMatcher|#if|#ifdef|#endif" src/pyOpenMS/bindings/bind_misc.cppRepository: OpenMS/OpenMS
Length of output: 6050
🏁 Script executed:
# Check if bind_analysis.cpp exists and other ANALYSIS bindings
ls -la src/pyOpenMS/bindings/bind_analysis.cpp 2>/dev/null || echo "File not found"
# Check what ANALYSIS classes are already in bind_analysis vs bind_misc
rg -l "ANALYSIS/" src/pyOpenMS/bindings/bind_*.cpp | head -5
rg "class_.*ANALYSIS" src/pyOpenMS/bindings/bind_*.cpp | head -10Repository: OpenMS/OpenMS
Length of output: 300
Move WNetMatcher and FeatureGroupingAlgorithmWNet bindings to bind_analysis.cpp.
These ANALYSIS module classes belong in bind_analysis.cpp per coding guidelines, not bind_misc.cpp. Relocate lines 40-41 (includes), 803-808 (enum), 810-817 (MatchResult), 819-839 (WNetMatcher), and 844-858 (FeatureGroupingAlgorithmWNet) to the appropriate analysis bindings file.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/pyOpenMS/bindings/bind_misc.cpp` around lines 40 - 41, The bindings for
WNetMatcher, FeatureGroupingAlgorithmWNet and the MatchResult enum are in the
wrong file; remove the `#include` lines for
OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h and
OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h from bind_misc.cpp
and relocate the corresponding binding code for the MatchResult enum, the
WNetMatcher class binding (WNetMatcher), and the FeatureGroupingAlgorithmWNet
class binding (FeatureGroupingAlgorithmWNet) into bind_analysis.cpp; in
bind_analysis.cpp add the two include directives, register the MatchResult enum
and the two class bindings inside the same pybind11 module/context used for
other ANALYSIS bindings, and ensure any constructor/method names and docstrings
are preserved when moving to avoid breaking imports.
| Groups corresponding features across multiple maps by solving a minimum-cost | ||
| network flow problem on their (m/z, RT) positions. Produces globally optimal | ||
| 1-to-1 feature matchings. | ||
|
|
There was a problem hiding this comment.
Docstring overstates optimality for multi-map grouping.
The wording says globally optimal 1-to-1 grouping, but this binding represents a multi-map merge workflow where only pairwise matching is optimal; the merge step is heuristic.
💡 Proposed docstring correction
-Groups corresponding features across multiple maps by solving a minimum-cost
-network flow problem on their (m/z, RT) positions. Produces globally optimal
-1-to-1 feature matchings.
+Groups corresponding features across multiple maps by solving a minimum-cost
+network flow problem on their (m/z, RT) positions. Pairwise matches are
+optimal for each map pair; multi-map grouping is a heuristic merge step and
+may depend on pair-processing order.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| Groups corresponding features across multiple maps by solving a minimum-cost | |
| network flow problem on their (m/z, RT) positions. Produces globally optimal | |
| 1-to-1 feature matchings. | |
| Groups corresponding features across multiple maps by solving a minimum-cost | |
| network flow problem on their (m/z, RT) positions. Pairwise matches are | |
| optimal for each map pair; multi-map grouping is a heuristic merge step and | |
| may depend on pair-processing order. | |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/pyOpenMS/bindings/bind_misc.cpp` around lines 848 - 851, The docstring in
src/pyOpenMS/bindings/bind_misc.cpp that describes the multi-map grouping
binding overstates optimality; update the string literal for the multi-map
grouping binding (the docstring associated with the grouping/multi-map merge
function in bind_misc.cpp) to remove "globally optimal 1-to-1 feature matchings"
and instead state that the algorithm finds pairwise optimal 1-to-1 matches via
minimum-cost flow and then merges maps using a heuristic, e.g. "Finds pairwise
optimal 1-to-1 feature matchings via minimum-cost network flow on (m/z, RT)
positions; the subsequent merge across multiple maps is heuristic and not
globally optimal." Ensure the revised wording replaces the existing docstring
text for the same binding.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h (1)
66-67: Make special-member intent explicit (complete Rule-of-6 declaration).Copy operations are explicitly deleted, but move operations are currently implicit. Please declare move ctor/assignment explicitly (
= deleteor= default) to make object semantics unambiguous.♻️ Suggested fix
private: FeatureGroupingAlgorithmWNet(const FeatureGroupingAlgorithmWNet&) = delete; FeatureGroupingAlgorithmWNet& operator=(const FeatureGroupingAlgorithmWNet&) = delete; + FeatureGroupingAlgorithmWNet(FeatureGroupingAlgorithmWNet&&) = delete; + FeatureGroupingAlgorithmWNet& operator=(FeatureGroupingAlgorithmWNet&&) = delete;As per coding guidelines, “Follow Rule-of-0 (no custom special functions) or Rule-of-6 (define or delete all special member functions: default constructor, copy constructor, copy assignment, move constructor, move assignment, destructor)”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h` around lines 66 - 67, The class FeatureGroupingAlgorithmWNet currently deletes the copy ctor and copy assignment but leaves move operations implicit; explicitly declare the move constructor and move assignment (either = delete or = default to express intended semantics) and also ensure the default constructor and destructor are explicitly declared (defaulted) to complete the Rule-of-6 (i.e., add declarations for FeatureGroupingAlgorithmWNet(), FeatureGroupingAlgorithmWNet(const FeatureGroupingAlgorithmWNet&)=delete, FeatureGroupingAlgorithmWNet& operator=(const FeatureGroupingAlgorithmWNet&)=delete, FeatureGroupingAlgorithmWNet(FeatureGroupingAlgorithmWNet&&)=delete_or_default, FeatureGroupingAlgorithmWNet& operator=(FeatureGroupingAlgorithmWNet&&)=delete_or_default, ~FeatureGroupingAlgorithmWNet()=default).src/tests/class_tests/openms/source/WNetMatcher_test.cpp (1)
54-69: Strengthen the non-empty match assertions.These cases only check the number of returned pairs. A regression that returns the wrong pair identities or a non-zero cost would still pass. Please assert the expected
(index_a, index_b)pairs and the transport cost for the identical-input and filtered-match scenarios.Based on learnings: "Applies to src/tests/class_tests/**/*_test.cpp : Write unit tests for new functionality and ensure existing tests pass before suggesting changes."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/tests/class_tests/openms/source/WNetMatcher_test.cpp` around lines 54 - 69, Add precise assertions that verify the actual matched pair indices and the transport cost in both cases that call WNetMatcher::match: for the identical-input case (the first auto result = WNetMatcher::match(positions, intensities, positions, intensities)) assert that result.matched_pairs contains the expected pairs (e.g., (0,0),(1,1),(2,2)) and that result.cost (or the actual cost field name on the match result) is zero; for the filtered-match case (auto result = WNetMatcher::match(pos_a, int_a, pos_b, int_b, WNetMatcher::DistanceMetric::LINF, 5.0, 5.0)) assert the matched pair indices are the first two expected matches (e.g., (0,0),(1,1)) and check result.cost is the expected non-zero value (or within an epsilon if floating-point). Ensure you use result.matched_pairs and the match result's cost field to locate the values and adjust field name if different.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@cmake/cmake_findExternalLibs.cmake`:
- Around line 303-323: The FetchContent_Declare blocks for pylmcf, wnet, and
wnetalign currently set GIT_SHALLOW TRUE while pinning GIT_TAG to commit hashes,
which is unsupported; fix by either removing GIT_SHALLOW TRUE from those
FetchContent_Declare blocks or replacing the GIT_TAG commit hashes with matching
tag or branch names (e.g., the v0.9.x tag strings) so shallow clone is
allowed—update the pylmcf, wnet, and wnetalign declarations accordingly (adjust
the GIT_SHALLOW and GIT_TAG entries in each block).
In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp`:
- Around line 243-299: The current greedy union in unite() during the nested i/j
loop makes results input-order dependent; instead, collect all candidate merges
from each aligner.consensus_for_target(0) (recording the pair indices flat_i and
flat_j and a per-match score or cost—use per-pair confidence if available,
otherwise use aligner.total_cost() as a proxy) into a single list, then sort
that list by descending confidence (or ascending cost) and apply unite() to the
sorted candidates so conflicts are resolved globally rather than in nested i/j
order; update code around the pairwise alignment loop, referencing unite,
consensus_for_target, aligner and aligner.total_cost() when building and
consuming the global candidate list.
- Around line 156-177: The current code sets max_distance = max_rt_shift which
only preserves per-axis thresholds for LINF; update the logic in
FeatureGroupingAlgorithmWNet (around mz_scale and max_distance) to compute
max_distance based on the chosen distance_metric (e.g. distance_metric from
params or enum used in this file): for LINF keep max_distance = max_rt_shift;
for L1 set max_distance = 2.0 * max_rt_shift; for L2 set max_distance =
sqrt(2.0) * max_rt_shift (i.e. the norm of the vector [max_rt_shift,
max_rt_shift] after scaling), so that after computing mz_scale the global
threshold enforces the configured per-axis limits. Ensure this change uses the
same distance_metric symbol and leaves mz_scale computation (and
use_ppm/max_mz_shift/mz_shift_native) unchanged.
In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp`:
- Around line 56-62: Check that positions_a.size() == intensities_a.size() and
positions_b.size() == intensities_b.size() before constructing Spectrum<2>
(immediately before the Spectrum<2> spec_a/spec_b creation) and if either pair
mismatches throw Exception::IllegalArgument with file/line and
OPENMS_PRETTY_FUNCTION (e.g. throw Exception::IllegalArgument(..., __FILE__,
__LINE__, OPENMS_PRETTY_FUNCTION)); this rejects inconsistent input
deterministically and prevents forwarding bad data into Spectrum<2>.
In `@src/pyOpenMS/bindings/bind_analysis.cpp`:
- Around line 3264-3271: The new pyOpenMS bindings for WNetMatchResult and
FeatureGroupingAlgorithmWNet are missing the standard copy bindings; add a copy
constructor binding nb::init<const OpenMS::WNetMatcher::MatchResult &>() (and
analogous nb::init<const OpenMS::FeatureGroupingAlgorithmWNet &>() for the other
class), then add .def("__copy__", [](const ClassName &self){ return
ClassName(self); }) and .def("__deepcopy__", [](const ClassName &self, py::dict
/*memo*/){ return ClassName(self); }) for both WNetMatchResult and
FeatureGroupingAlgorithmWNet so they match pyOpenMS copy semantics and coding
guidelines.
---
Nitpick comments:
In
`@src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.h`:
- Around line 66-67: The class FeatureGroupingAlgorithmWNet currently deletes
the copy ctor and copy assignment but leaves move operations implicit;
explicitly declare the move constructor and move assignment (either = delete or
= default to express intended semantics) and also ensure the default constructor
and destructor are explicitly declared (defaulted) to complete the Rule-of-6
(i.e., add declarations for FeatureGroupingAlgorithmWNet(),
FeatureGroupingAlgorithmWNet(const FeatureGroupingAlgorithmWNet&)=delete,
FeatureGroupingAlgorithmWNet& operator=(const
FeatureGroupingAlgorithmWNet&)=delete,
FeatureGroupingAlgorithmWNet(FeatureGroupingAlgorithmWNet&&)=delete_or_default,
FeatureGroupingAlgorithmWNet&
operator=(FeatureGroupingAlgorithmWNet&&)=delete_or_default,
~FeatureGroupingAlgorithmWNet()=default).
In `@src/tests/class_tests/openms/source/WNetMatcher_test.cpp`:
- Around line 54-69: Add precise assertions that verify the actual matched pair
indices and the transport cost in both cases that call WNetMatcher::match: for
the identical-input case (the first auto result = WNetMatcher::match(positions,
intensities, positions, intensities)) assert that result.matched_pairs contains
the expected pairs (e.g., (0,0),(1,1),(2,2)) and that result.cost (or the actual
cost field name on the match result) is zero; for the filtered-match case (auto
result = WNetMatcher::match(pos_a, int_a, pos_b, int_b,
WNetMatcher::DistanceMetric::LINF, 5.0, 5.0)) assert the matched pair indices
are the first two expected matches (e.g., (0,0),(1,1)) and check result.cost is
the expected non-zero value (or within an epsilon if floating-point). Ensure you
use result.matched_pairs and the match result's cost field to locate the values
and adjust field name if different.
🪄 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: c3d95a64-abfc-4cf6-ab96-579bcfcb66b0
📒 Files selected for processing (13)
cmake/cmake_findExternalLibs.cmakesrc/openms/CMakeLists.txtsrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.hsrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.hsrc/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cppsrc/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cppsrc/openms/source/ANALYSIS/MAPMATCHING/sources.cmakesrc/pyOpenMS/bindings/bind_analysis.cppsrc/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cppsrc/tests/class_tests/openms/source/WNetMatcher_test.cppsrc/tests/topp/CMakeLists.txtsrc/tests/topp/FeatureLinkerWNet_1_parameters.inisrc/topp/executables.cmake
✅ Files skipped from review due to trivial changes (2)
- src/tests/topp/FeatureLinkerWNet_1_parameters.ini
- src/openms/CMakeLists.txt
🚧 Files skipped from review as they are similar to previous changes (4)
- src/topp/executables.cmake
- src/openms/source/ANALYSIS/MAPMATCHING/sources.cmake
- src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/WNetMatcher.h
- src/tests/class_tests/openms/source/FeatureGroupingAlgorithmWNet_test.cpp
| nb::class_<OpenMS::WNetMatcher::MatchResult>(m, "WNetMatchResult", | ||
| "Result of a pairwise WNetMatcher matching") | ||
| .def(nb::init<>()) | ||
| .def_rw("matched_pairs", &OpenMS::WNetMatcher::MatchResult::matched_pairs, | ||
| "List of (index_a, index_b) matched point pairs") | ||
| .def_rw("cost", &OpenMS::WNetMatcher::MatchResult::cost, | ||
| "Total transport cost") | ||
| ; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Add the standard pyOpenMS copy bindings to the new classes.
WNetMatchResult and FeatureGroupingAlgorithmWNet are missing the usual copy constructor binding plus __copy__ / __deepcopy__. That makes the new types inconsistent with the rest of pyOpenMS and drops expected Python copy semantics.
♻️ Proposed fix
nb::class_<OpenMS::WNetMatcher::MatchResult>(m, "WNetMatchResult",
"Result of a pairwise WNetMatcher matching")
.def(nb::init<>())
+ .def(nb::init<const OpenMS::WNetMatcher::MatchResult &>())
+ .def("__copy__", [](const OpenMS::WNetMatcher::MatchResult& self) { return OpenMS::WNetMatcher::MatchResult(self); })
+ .def("__deepcopy__", [](const OpenMS::WNetMatcher::MatchResult& self, nb::dict) { return OpenMS::WNetMatcher::MatchResult(self); }, "memo"_a)
.def_rw("matched_pairs", &OpenMS::WNetMatcher::MatchResult::matched_pairs,
"List of (index_a, index_b) matched point pairs")
.def_rw("cost", &OpenMS::WNetMatcher::MatchResult::cost,
"Total transport cost")
;
@@
nb::class_<OpenMS::FeatureGroupingAlgorithmWNet, OpenMS::FeatureGroupingAlgorithm>(m, "FeatureGroupingAlgorithmWNet",
R"doc(
A feature grouping algorithm using Wasserstein optimal transport.
@@
FeatureGroupingAlgorithm
)doc")
.def(nb::init<>())
+ .def(nb::init<const OpenMS::FeatureGroupingAlgorithmWNet &>())
+ .def("__copy__", [](const OpenMS::FeatureGroupingAlgorithmWNet& self) { return OpenMS::FeatureGroupingAlgorithmWNet(self); })
+ .def("__deepcopy__", [](const OpenMS::FeatureGroupingAlgorithmWNet& self, nb::dict) { return OpenMS::FeatureGroupingAlgorithmWNet(self); }, "memo"_a)
.def("group", [](OpenMS::FeatureGroupingAlgorithmWNet& self, const std::vector<OpenMS::FeatureMap>& maps, OpenMS::ConsensusMap& out) { return self.group(maps, out); }, "maps"_a, "out"_a)
.def("group", [](OpenMS::FeatureGroupingAlgorithmWNet& self, const std::vector<OpenMS::ConsensusMap>& maps, OpenMS::ConsensusMap& out) { return self.group(maps, out); }, "maps"_a, "out"_a)
.def("transferSubelements", [](const OpenMS::FeatureGroupingAlgorithmWNet& self, const std::vector<OpenMS::ConsensusMap>& maps, OpenMS::ConsensusMap& out) { return self.transferSubelements(maps, out); }, "maps"_a, "out"_a, "Transfers subelements (grouped features) from input consensus maps to the result consensus map")
;As per coding guidelines: "Class bindings must include default constructor nb::init<>(), copy constructor nb::init<const ClassName &>(), __copy__ method, and __deepcopy__ method with memo parameter."
Also applies to: 3298-3312
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/pyOpenMS/bindings/bind_analysis.cpp` around lines 3264 - 3271, The new
pyOpenMS bindings for WNetMatchResult and FeatureGroupingAlgorithmWNet are
missing the standard copy bindings; add a copy constructor binding
nb::init<const OpenMS::WNetMatcher::MatchResult &>() (and analogous
nb::init<const OpenMS::FeatureGroupingAlgorithmWNet &>() for the other class),
then add .def("__copy__", [](const ClassName &self){ return ClassName(self); })
and .def("__deepcopy__", [](const ClassName &self, py::dict /*memo*/){ return
ClassName(self); }) for both WNetMatchResult and FeatureGroupingAlgorithmWNet so
they match pyOpenMS copy semantics and coding guidelines.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp (2)
308-308: UseSizeinstead ofsize_tfor index iteration.Line 308 should use OpenMS primitive types for consistency with surrounding code and interfaces.
♻️ Proposed refactor
- for (size_t k = 0; k < emp_ids.size(); ++k) + for (Size k = 0; k < emp_ids.size(); ++k)As per coding guidelines: "Use OpenMS primitive types from
OpenMS/CONCEPT/Types.h(e.g.,Size,SignedSize) instead of rawstd::size_torint."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp` at line 308, Replace the raw std::size_t loop index with the OpenMS primitive Size in the for-loop that iterates over emp_ids inside FeatureGroupingAlgorithmWNet (currently written as "for (size_t k = 0; k < emp_ids.size(); ++k)"); change the type to Size, ensure OpenMS/CONCEPT/Types.h is included if not already, and update any related signed/unsigned comparisons (e.g., emp_ids.size()) to avoid warnings.
139-356: Consider splittinggroup_into smaller phases for maintainability.The method currently handles parameter parsing, normalization/scaling, pairwise matching, union-find conflict resolution, and output assembly in one block; extracting these into helpers would reduce cognitive load and make targeted unit tests easier.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp` around lines 139 - 356, The group_ function is too large and mixes parameter parsing, spectrum conversion, pairwise alignment, union‑find logic, candidate sorting/merging, and output assembly; split it into smaller helpers: extract parameter parsing (use parseDistanceMetric, mz_scale/max_distance calculation) into a buildParams or parseParams helper, move map conversion/normalization using mapToSpectrum into a convertAndNormalizeSpectra function, move the per-pair alignment loop that produces Candidate entries into a collectCandidates(spectra, max_distance, trash_cost, metric) function (uses WNetAligner and aligner.consensus_for_target), extract the union‑find logic into a UnionFind class or functions (find, unite, group_maps management), and extract the final ConsensusMap assembly into buildConsensusMap(groups, maps) before calling postprocess_; update group_ to orchestrate these helpers so each piece (params, conversion, candidate collection, merging, assembly) is testable and small.src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp (1)
84-84: UseSizefor loop indexing here.Line 84 uses
size_t; prefer OpenMS integral types for consistency with the rest of the API surface.♻️ Proposed refactor
- for (size_t i = 0; i < emp_ids.size(); ++i) + for (Size i = 0; i < emp_ids.size(); ++i)As per coding guidelines: "Use OpenMS primitive types from
OpenMS/CONCEPT/Types.h(e.g.,Size,SignedSize) instead of rawstd::size_torint."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp` at line 84, The for-loop indexing variable uses std::size_t; change it to OpenMS's Size type (from OpenMS/CONCEPT/Types.h) to follow project conventions: replace "for (size_t i = 0; i < emp_ids.size(); ++i)" with "for (Size i = 0; i < emp_ids.size(); ++i)" in WNetMatcher (where emp_ids is iterated), and add the Types.h include if it's not already present so Size is defined.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp`:
- Around line 165-178: The code computes mz_scale using mz_shift_native but
treats zero m/z tolerance by falling back to 1.0, which relaxes the constraint;
change the logic in FeatureGroupingAlgorithmWNet around variables max_mz_shift,
mz_shift_native and mz_scale so that when the configured max_mz_shift (from
param_.getValue("max_mz_shift_da") or "max_mz_shift_ppm") is exactly zero you
set mz_scale to a very large value or handle it as an infinite/strict m/z
constraint (e.g., set mz_scale = std::numeric_limits<double>::infinity() or
guard comparisons to enforce zero tolerance) instead of 1.0, and preserve the
existing ppm conversion (mz_shift_native = std::log1p(...)) and the existing
non-zero branch behavior when use_ppm is true/false.
- Around line 321-323: Sorting by only Candidate::cost is non-deterministic for
equal costs; update the sort comparator used on candidates so it first compares
cost and then deterministically tie-breaks by stable unique fields (for example
the two feature indices/IDs in Candidate, using an ordered pair so (min,max) for
symmetry). Modify the lambda used in sort(candidates.begin(), candidates.end(),
...) to compare std::tie(cost, ordered_endpoint1, ordered_endpoint2) (or
equivalent) so equal-cost candidates are ordered consistently across runs.
---
Nitpick comments:
In `@src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp`:
- Line 308: Replace the raw std::size_t loop index with the OpenMS primitive
Size in the for-loop that iterates over emp_ids inside
FeatureGroupingAlgorithmWNet (currently written as "for (size_t k = 0; k <
emp_ids.size(); ++k)"); change the type to Size, ensure OpenMS/CONCEPT/Types.h
is included if not already, and update any related signed/unsigned comparisons
(e.g., emp_ids.size()) to avoid warnings.
- Around line 139-356: The group_ function is too large and mixes parameter
parsing, spectrum conversion, pairwise alignment, union‑find logic, candidate
sorting/merging, and output assembly; split it into smaller helpers: extract
parameter parsing (use parseDistanceMetric, mz_scale/max_distance calculation)
into a buildParams or parseParams helper, move map conversion/normalization
using mapToSpectrum into a convertAndNormalizeSpectra function, move the
per-pair alignment loop that produces Candidate entries into a
collectCandidates(spectra, max_distance, trash_cost, metric) function (uses
WNetAligner and aligner.consensus_for_target), extract the union‑find logic into
a UnionFind class or functions (find, unite, group_maps management), and extract
the final ConsensusMap assembly into buildConsensusMap(groups, maps) before
calling postprocess_; update group_ to orchestrate these helpers so each piece
(params, conversion, candidate collection, merging, assembly) is testable and
small.
In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp`:
- Line 84: The for-loop indexing variable uses std::size_t; change it to
OpenMS's Size type (from OpenMS/CONCEPT/Types.h) to follow project conventions:
replace "for (size_t i = 0; i < emp_ids.size(); ++i)" with "for (Size i = 0; i <
emp_ids.size(); ++i)" in WNetMatcher (where emp_ids is iterated), and add the
Types.h include if it's not already present so Size is defined.
🪄 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: 7dfd7617-4c70-428c-a4b4-2b5fd2d4cbf0
📒 Files selected for processing (6)
cmake/cmake_findExternalLibs.cmakesrc/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.hsrc/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cppsrc/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cppsrc/pyOpenMS/bindings/bind_analysis.cppsrc/tests/class_tests/openms/source/WNetMatcher_test.cpp
✅ Files skipped from review due to trivial changes (1)
- src/pyOpenMS/bindings/bind_analysis.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
- cmake/cmake_findExternalLibs.cmake
- src/tests/class_tests/openms/source/WNetMatcher_test.cpp
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp (2)
33-42: Consider adding adefaultcase or removing the unreachable return.The
switchexhaustively covers allDistanceMetricenum values, making line 41 unreachable. Some compilers may warn about this. You could either add adefault: return ::DistanceMetric::LINF;case inside the switch, or rely on the existing post-switch return and suppress any warnings.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp` around lines 33 - 42, The switch in toWNetMetric(WNetMatcher::DistanceMetric m) already handles all WNetMatcher::DistanceMetric cases but leaves an unreachable return after the switch which can trigger compiler warnings; fix by adding a default: return ::DistanceMetric::LINF; branch inside the switch (or alternatively remove the trailing return and keep a default that returns ::DistanceMetric::LINF) so that all control paths explicitly return a ::DistanceMetric value.
73-89: Consider adding brief comments for clarity.The code logic is straightforward, but the coding guidelines recommend ~5% comments. A brief comment before the core matching logic (e.g., explaining what
aligner.set_point({1.0})does or whatconsensus_for_target(0)returns) would help future maintainers.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp` around lines 73 - 89, Add brief explanatory comments above the core matching block to clarify intent and return values: note that WNetAligner<2> aligner(spec_a, theoretical, ...) constructs the aligner for empirical vs. theoretical spectra, that aligner.set_point({1.0}) fixes a single unit-weight consensus (i.e., solving for a single consensus target), and that auto [emp_ids, theo_ids] = aligner.consensus_for_target(0) returns paired index lists for empirical and theoretical peaks; also add a short note that result.cost = aligner.total_cost() reads the alignment cost and that matched_pairs is populated from those index vectors.src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cpp (1)
96-112: Consider validating thedc_charge_adduct_massMetaValue type.Line 105 casts the MetaValue directly to
double. If the MetaValue exists but contains a non-numeric type (e.g., a string), this could produce unexpected results or throw. Consider validating the type or wrapping in a try-catch if robustness against malformed metadata is desired.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp`:
- Around line 33-42: The switch in toWNetMetric(WNetMatcher::DistanceMetric m)
already handles all WNetMatcher::DistanceMetric cases but leaves an unreachable
return after the switch which can trigger compiler warnings; fix by adding a
default: return ::DistanceMetric::LINF; branch inside the switch (or
alternatively remove the trailing return and keep a default that returns
::DistanceMetric::LINF) so that all control paths explicitly return a
::DistanceMetric value.
- Around line 73-89: Add brief explanatory comments above the core matching
block to clarify intent and return values: note that WNetAligner<2>
aligner(spec_a, theoretical, ...) constructs the aligner for empirical vs.
theoretical spectra, that aligner.set_point({1.0}) fixes a single unit-weight
consensus (i.e., solving for a single consensus target), and that auto [emp_ids,
theo_ids] = aligner.consensus_for_target(0) returns paired index lists for
empirical and theoretical peaks; also add a short note that result.cost =
aligner.total_cost() reads the alignment cost and that matched_pairs is
populated from those index vectors.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: bfa66d7c-998c-49c5-824d-587b7bff4e14
📒 Files selected for processing (2)
src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmWNet.cppsrc/openms/source/ANALYSIS/MAPMATCHING/WNetMatcher.cpp
Add FetchContent declarations for the three header-only libraries (pylmcf v0.9.5, wnet v0.9.9, wnetalign v0.9.6) and wire their include directories + LEMON_ONLY_TEMPLATES into the OpenMS target. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Header + stub implementation with parameter registration (distance_metric, max_distance, trash_cost, mz_scale_factor, normalize_intensities). The group_() body is a TODO placeholder. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Wrapper that delegates to FeatureGroupingAlgorithmWNet, following the same pattern as FeatureLinkerUnlabeledQT. Registered in ToolHandler and executables.cmake. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Use FetchContent_Populate instead of FetchContent_MakeAvailable to skip running the upstream CMakeLists.txt (which require nanobind for Python bindings). We only need the header include paths. Also switch to SSH URLs and document FETCHCONTENT_SOURCE_DIR_* overrides for local development. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Core logic: - Convert FeatureMap/ConsensusMap to Spectrum<2> (scaled m/z, RT) - Auto-compute mz_scale_factor as RT_range / MZ_range if not set - Pairwise alignment: for each pair (i,j), run WNetAligner<2> and extract consensus matches - Union-find to merge pairwise matches into transitive groups - Build ConsensusFeature per group with FeatureHandles, using computeConsensus() for position/intensity averaging Co-Authored-By: Claude Opus 4.6 <[email protected]>
Tests constructor, destructor, exception on too few maps, and functional grouping of two synthetic FeatureMaps with known overlapping features. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Runs FeatureLinkerWNet on the same 3-map featureXML input used by FeatureLinkerUnlabeledQT/KD tests, with reference output diffed against the expected consensusXML. Co-Authored-By: Claude Opus 4.6 <[email protected]>
The naive union-find was creating transitive chains across pairwise matches that merged features from the same map into one group (e.g. a group of size 15 from 3 maps). Now each unite() checks whether merging would introduce a duplicate map entry and skips if so. This produces results comparable to QT/KD linkers: max group size equals the number of input maps. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Change defaults from max_distance=800/trash_cost=800 to 100/100. After auto m/z scaling, both dimensions are in RT-like units (seconds), so these thresholds are comparable to the QT default distance_RT:max_difference of 100s. Improve parameter descriptions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Exposes the class with group() (both FeatureMap and ConsensusMap overloads) and transferSubelements(), following the same pattern as the other FeatureGroupingAlgorithm variants. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Use HTTPS URLs instead of SSH for FetchContent (fixes CI/contributor builds) - Guard FetchContent_Populate with _POPULATED check (avoids deprecated pattern) - Add $Maintainer tags to all new source files - Use = delete for copy ctor/assignment instead of private declarations - Replace std::function with auto lambda for union-find find() performance - Strengthen unit test assertion from >= 2 to exact equality Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…dly m/z and RT tolerances Replace max_distance/mz_scale_factor with max_rt_shift (seconds), max_mz_shift_da (Da), and max_mz_shift_ppm (ppm). The mz_unit parameter selects which m/z tolerance is active. In ppm mode the m/z axis is log-transformed so distances are mass-independent. Mark distance_metric and trash_cost as advanced parameters. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Exposes a FeatureMap-independent matching API that takes raw position vectors and intensities, addressing reviewer request for a simpler entry point to the algorithm. Co-Authored-By: Claude Opus 4.6 <[email protected]>
v0.9.7 adds the C++ headers (aligner.hpp, spectrum.hpp) required for header-only integration into OpenMS. v0.9.6 was Python-only. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ework The reference consensusXML was last generated with the old parameter scheme (max_distance / mz_scale_factor). Commit 7768d2d replaced those with max_rt_shift / mz_unit / max_mz_shift_ppm and updated the INI, but did not regenerate the expected output. Update the golden file to match the current ppm-based m/z scaling. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Mismatched lengths were silently forwarded into Spectrum<2> where they cause undefined behaviour. Throw Exception::IllegalArgument immediately so callers get a deterministic error with file/line context. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
With mz_scale applied, both axes are in "RT-equivalent seconds". The global distance threshold must match the chosen norm so that a feature exactly at [max_rt_shift, max_rt_shift] lies on the boundary: LINF → max_rt_shift (unchanged) L1 → 2 * max_rt_shift L2 → sqrt(2) * max_rt_shift Previously max_distance was always max_rt_shift, which was too tight for L1/L2 and would prematurely cut off valid matches. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…inistically Previously unite() was called in nested i/j loop order, so whether a conflicting pair was accepted depended on which map pair was processed first. Now: 1. All pairwise alignments run first and candidates are collected with an average per-pair cost (total_cost / n_pairs) as a confidence proxy. 2. Candidates are sorted by ascending cost before any merges are applied. This ensures that cheaper (more confident) matches win conflicts regardless of map index ordering. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
WNetMatchResult is a plain copyable struct; add the standard pyOpenMS copy-constructor binding, __copy__, and __deepcopy__ so it behaves consistently with other value types in the module. FeatureGroupingAlgorithmWNet has a deleted copy constructor and is intentionally non-copyable, so no copy bindings are added for it. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Copy is already deleted. Leaving move ops implicit means the compiler suppresses them silently, which is correct but opaque. Explicitly deleting them documents the intent and satisfies the Rule-of-5. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Identical-input case: verify each point matches itself ((0,0),(1,1),(2,2)) and that the total transport cost is exactly 0.0. Filtered case: verify the two close-pair indices are exactly (0,0) and (1,1), and that cost > 0 (non-trivial transport happened). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ance Previously mz_scale fell back to 1.0 when the configured m/z tolerance was zero, leaving the m/z axis unscaled and allowing matches across arbitrary m/z differences. Setting mz_scale to infinity maps any non-zero m/z difference to an infinite scaled distance so such pairs are always rejected. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… tie-break Sorting only by cost left equal-cost candidates in unspecified order, making conflict resolution input-order dependent. Tie-break by (min, max) of the two flat feature indices so equal-cost candidates are always resolved identically across runs. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…Net loop Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Extract the 217-line monolithic group_() into four self-contained units: - AlignParams struct + buildAlignParams(): consolidates all parameter parsing, mz_scale/max_distance/trash_cost derivation in one place. - convertAndNormalizeSpectra(): converts each map to Spectrum<2> and optionally normalises intensities; templated to handle both FeatureMap and ConsensusMap. - Candidate struct + collectCandidates(): runs all pairwise WNetAligner alignments and returns the flat candidate list; non-const spectra reference required by the WNetAligner pointer API. - UnionFind class: encapsulates parent/rank/group_maps state with path-halving find() and map-conflict-aware unite(). group_() is now an orchestrator: parse params, convert spectra, collect and sort candidates, merge via UnionFind, assemble ConsensusMap. All previously fixed logic (mz_scale=∞ for zero tolerance, sorted merge with tuple tie-breaking, Size loop indices) is preserved unchanged. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ts to match() Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Okay, so I did the changes suggested by CodeRabbit, and as far as I can tell, the test failures are unrelated (and one test seems stuck) - can we merge? |
CI failure analysisThe 6 red checks ( Failure mode (identical on all 6): SIGABRT during Root cause: cross-module nanobind base-class registered out of order
nb::class_<OpenMS::FeatureGroupingAlgorithmWNet,
OpenMS::FeatureGroupingAlgorithm>(m, "FeatureGroupingAlgorithmWNet", ...)but
The pre-existing cross-module bases in FixCleanest fix: move the new |
…rder abort FeatureGroupingAlgorithmWNet derives from FeatureGroupingAlgorithm, which is registered in bind_misc.cpp (_pyopenms_misc). Registering the derived class in bind_analysis.cpp (_pyopenms_analysis) caused a nanobind abort on import because _pyopenms_analysis is loaded before _pyopenms_misc, so the base type was not yet in the registry. Move WNetMatcherDistanceMetric, WNetMatchResult, WNetMatcher and FeatureGroupingAlgorithmWNet into bind_misc.cpp next to the other FeatureGroupingAlgorithm* subclasses. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
cool tests pass now. |
Added entries for: - IDRipper .idparquet input/output support (#9237) - FEATUREPARQUET and CONSENSUSPARQUET file types (#9242) - BrukerTimsFile FrameAggregator perf improvement with boost::unordered_flat_map (#9243) - PercolatorAdapter: fix post-filters on in-process backend (#9240) - IDMerger: fix input file order preservation (#9240) - ProteomicsLFQ: .idparquet/.mzId input support (#9236) - IsobaricWorkflow: .idparquet/.mzId input support (#9241) - wnetalign/wnet/pylmcf FetchContent dependencies (#8992) - OpenMS Library: FileTypes::FEATUREPARQUET/CONSENSUSPARQUET (#9242) - OpenMS Library: FeatureGroupingAlgorithmWNet and WNetMatcher (#8992) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: timosachsenberg <[email protected]>
…ference (#9265) The LP_SOLVER option (AUTO/COIN/GLPK/HIGHS) was introduced with HiGHS support (#9246) and the WITH_WNETALIGN option was added with the WNet feature alignment feature (#8992). Both are user-configurable CMake cache variables but were missing from the common-cmake-parameters.doxygen reference table included in all platform install guides. Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
The WNetAlign/WNet/PyLMCF header-only libraries were added in #8992 as FetchContent dependencies controlled by the WITH_WNETALIGN CMake option (ON by default). The common-cmake-parameters.doxygen reference was updated in #9265, but AGENTS.md was not updated. Add a note in the 'Build and Install' section so agents know about this ON-by-default option that requires network access (or FETCHCONTENT_SOURCE_DIR_* overrides for offline builds). Co-authored-by: GitHub Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
Description
Add the WNetAlign algorithm to OpenMS.
This is a draft / request for comments, I still need to review (and hopefully improve/replace) the union-find logic Claude came up for doing multi-spectral alignment, fine-tune the defaults for parameters, and actually check it on a non-toy dataset.
Summary by CodeRabbit
New Features
Documentation
Tests
Chore
Changelog