Skip to content

Feature/tm lowess cv span - #8166

Merged
timosachsenberg merged 28 commits into
OpenMS:developfrom
singjc:feature/tm_lowess_cv_span
Sep 8, 2025
Merged

timosachsenberg merged 28 commits into
OpenMS:developfrom
singjc:feature/tm_lowess_cv_span

Conversation

@singjc

@singjc singjc commented Aug 13, 2025 •

Copy link
Copy Markdown
Contributor

Description

This pull request introduces automatic LOWESS span selection via cross-validation to the TransformationModelLowess class, along with supporting utilities and statistical functions. The main goal was to add an option to automatically tune the smoothing span parameter using cross-validation for the lowess model. The changes also add a reusable cross-validation utility and extend statistical functions for error calculation and quantile computation. This is used for automating some other params in another separate incoming PR for OpenSwathWorkflow.

Automatic LOWESS span selection and cross-validation:

  • Added logic to TransformationModelLowess to optionally select the LOWESS span parameter automatically using cross-validation, including new parameters for controlling grid search, metrics, and fold selection. [1] [2]
  • Introduced helper functions to parse candidate span grids, build span grids with clamping and deduplication, and score residuals using different error metrics (rmse, mae, quantiles). These helpers are hidden from the public API. [1] [2]

Cross-validation and grid search utilities:

  • Added a new header-only utility CrossValidation.h providing deterministic K-fold/LOO split and a generic 1-D grid search function with flexible tie-breaking and scoring.
  • Integrated the new cross-validation utility into the build system. [1] [2] [3]

Statistical function enhancements:

  • Added meanAbsoluteError, quantile (with linear interpolation), and rootMeanSquareError functions to OpenMS::Math::StatisticFunctions to support new error metrics for model selection. [1] [2] [3]
  • Included necessary headers and dependencies for new statistical and string operations. [1] [2]

Parameter and documentation improvements:

  • Extended TransformationModelLowess::getDefaultParameters to include new auto-span tuning parameters, with validation and documentation for each.

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

How can I get additional information on failed tests during CI

Click to expand If your PR is failing you can check out

Advanced commands (admins / reviewer only)

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

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

Summary by CodeRabbit

  • New Features

    • Auto span selection for Lowess smoothing via cross-validation (LOO/K‑fold), configurable metrics (RMSE, MAE, p90/p95/p99), candidate grids and persistence of chosen span.
    • Cross‑validation utilities: deterministic K‑fold/LOO folding and a 1‑D grid search with tie‑breaking/tolerance policies.
    • Statistical helpers: quantile (sorted/unsorted) and root‑mean‑square‑error utilities.
  • Tests

    • Unit tests covering auto‑span selection, tie‑breaking/tolerance, cross‑validation, and statistical helpers.
  • Chores

    • Build updated to include the new cross‑validation module.

@coderabbitai

coderabbitai Bot commented Aug 13, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.

Walkthrough

Adds cross‑validated automatic span selection to TransformationModelLowess, a new CrossValidation utility (k‑fold/LOO and 1‑D grid search), templated quantile/RMSE helpers in StatisticFunctions, CMake integration for the CROSSVALIDATION module, and unit tests for CV, tie‑breaking, and quantile/RMSE behavior.

Changes

Cohort / File(s) Summary
Lowess auto‑span selection
src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h, src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp, src/tests/class_tests/openms/source/TransformationModelLowess_test.cpp
Adds CV‑driven auto‑span tuning (LOO vs K‑fold), private/internal helpers (buildSpanGrid, scoreResiduals, CVMetric enum, kTieTol), new auto‑span params (auto_span, auto_span_min/max, auto_min_neighbors, auto_k_folds, auto_metric, auto_span_grid), logging, persistence of chosen span, and a unit test for selection and tie behavior.
Statistic functions (Math)
src/openms/include/OpenMS/MATH/StatisticFunctions.h, src/tests/class_tests/openms/source/StatisticFunctions_test.cpp
Adds templated helpers: quantile (Type‑7 interpolation for sorted input), quantileUnsortedInput (sorts then quantile), and rootMeanSquareError (RMSE wrapper). Includes validation and tests for quantile and RMSE behaviors.
CrossValidation module & tests
src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h, src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp, src/tests/class_tests/openms/source/CrossValidation_test.cpp
Introduces CrossValidation with makeKFolds and templated gridSearch1D (candidate tie‑breaking and tie_tol), adds a source TU (placeholder), and unit tests covering folds, grid search, tie policies/tolerances, and error cases.
CMake integration (ML/CROSSVALIDATION)
src/openms/include/OpenMS/ML/CROSSVALIDATION/sources.cmake, src/openms/source/ML/CROSSVALIDATION/sources.cmake, src/openms/includes.cmake, src/tests/class_tests/openms/executables.cmake
Registers CROSSVALIDATION headers/sources via new CMake fragments, integrates them into project includes, and adds CrossValidation_test to test executables.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TML as TransformationModelLowess
  participant CV as CrossValidation
  participant Stats as StatisticFunctions

  Client->>TML: fit(data, params{auto_span=true,...})
  TML->>TML: build candidate span grid
  TML->>CV: makeKFolds(n_pts, K)
  CV-->>TML: folds
  loop per candidate span
    TML->>TML: train on training folds (lowess)
    TML->>TML: collect validation residuals
    TML->>Stats: scoreResiduals / RMSE/MAE/quantile
    Stats-->>TML: score
  end
  TML->>CV: gridSearch1D(candidates, folds, train_eval, score)
  CV-->>TML: best_span, best_score
  TML->>TML: persist best_span (update params, auto_span=false)
  TML-->>Client: fitted model using best_span
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

Review effort 2/5

Suggested reviewers

  • jpfeuffer

Poem

A rabbit counts the folds with care,
Hops through spans both short and fair,
Quantiles, RMSE held tight,
Picks the span that fits just right.
Then thumps a tune — CV done, huzzah! 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

❤️ Share

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

@singjc

singjc commented Aug 13, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 13, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
CHANGELOG (1)

57-57: Fix PR link formatting (double hash).

Use a single hash for GitHub PR references to be consistent with the rest of the changelog.

-    - TransformationModelLowess: Add option to automate span selection via cross-validation (##8166)
+    - TransformationModelLowess: Add option to automate span selection via cross-validation (#8166)
src/openms/source/ML/CROSSVALIDATION/sources.cmake (1)

5-7: Consider removing CrossValidation.cpp from build if the API is header-only.

Given CrossValidation.cpp is currently an empty translation unit (see CrossValidation.cpp), keeping it in the build adds unnecessary compilation overhead. If all functionality is defined inline in the header, drop the .cpp from the build.

Apply this diff to stop compiling the empty TU:

 set(sources_list
-CrossValidation.cpp
 )

Follow-up: delete src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp from the repository.

src/openms/include/OpenMS/MATH/StatisticFunctions.h (1)

200-226: Consider simplifying the empty range check

The function already calls checkIteratorsNotNULL which verifies begin != end. The additional check for n == 0 on line 215-218 appears redundant since if begin != end, then n = std::distance(begin, end) cannot be 0.

 template <typename IteratorType>
 static double meanAbsoluteError(IteratorType begin, IteratorType end)
 {
     checkIteratorsNotNULL(begin, end);
     const Size n = std::distance(begin, end);
-    if (n == 0)
-    {
-      throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
-    }

     double acc = 0.0;
     for (IteratorType it = begin; it != end; ++it)
     {
       acc += std::fabs(static_cast<double>(*it));
     }
     return acc / static_cast<double>(n);
 }
src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1)

60-77: Consider adding parameter validation for fold distribution

The function validates that n and K are non-zero, but doesn't check if the resulting fold distribution would be meaningful. For example, when K > n, the function silently clamps K to n. Consider documenting this behavior more explicitly or logging a warning.

Add a note in the documentation:

   /**
     @brief Build @p K folds for indices [0, n).
 
     Deterministic round-robin assignment: fold(i) = i % K.
     For leave-one-out (LOO), use K = n.
+    Note: If K > n, it will be automatically adjusted to n (LOO).
 
     @param n Number of samples
     @param K Requested number of folds (clamped to [1, n])
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (1)

229-239: Consider adding validation for malformed input

The parsing function handles comma/space separation well but doesn't validate for potential edge cases like consecutive delimiters or invalid characters. While the current implementation is functional, consider adding input validation.

Consider trimming whitespace and handling edge cases:

 std::vector<double> TransformationModelLowess::parseSpanGridString(const String& s)
 {
   std::vector<double> out;
   if (s.empty()) return out;
   std::string cpp = s;
+  // Remove leading/trailing whitespace
+  cpp.erase(0, cpp.find_first_not_of(" \t\n\r"));
+  cpp.erase(cpp.find_last_not_of(" \t\n\r") + 1);
   for (char& c : cpp) if (c == ',') c = ' ';
   std::istringstream iss(cpp);
   double v;
   while (iss >> v) if (v > 0.0 && v < 1.0) out.push_back(v);
   return out;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e43c17d and 7c9be87.

📒 Files selected for processing (10)
  • CHANGELOG (1 hunks)
  • src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h (1 hunks)
  • src/openms/include/OpenMS/MATH/StatisticFunctions.h (4 hunks)
  • src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1 hunks)
  • src/openms/include/OpenMS/ML/CROSSVALIDATION/sources.cmake (1 hunks)
  • src/openms/includes.cmake (2 hunks)
  • src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (4 hunks)
  • src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp (1 hunks)
  • src/openms/source/ML/CROSSVALIDATION/sources.cmake (1 hunks)
  • src/tests/class_tests/openms/source/TransformationModelLowess_test.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp
  • src/tests/class_tests/openms/source/TransformationModelLowess_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms

Applied to files:

  • src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp
  • src/openms/includes.cmake
  • src/openms/include/OpenMS/MATH/StatisticFunctions.h
🧬 Code Graph Analysis (4)
src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1)
src/openms/source/CONCEPT/Exception.cpp (1)
  • InvalidValue (224-228)
src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h (1)
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (6)
  • parseSpanGridString (229-239)
  • parseSpanGridString (229-229)
  • buildSpanGrid (241-276)
  • buildSpanGrid (241-245)
  • scoreResiduals (278-304)
  • scoreResiduals (278-278)
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (2)
src/openms/include/OpenMS/MATH/StatisticFunctions.h (1)
  • meanAbsoluteError (211-226)
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (1)
  • quantile (398-398)
src/openms/include/OpenMS/MATH/StatisticFunctions.h (2)
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (2)
  • quantile (398-398)
  • meanSquareError (121-121)
src/openms/source/CONCEPT/Exception.cpp (1)
  • InvalidValue (224-228)
🔇 Additional comments (14)
src/openms/source/ML/CROSSVALIDATION/sources.cmake (1)

1-19: CMake registration looks correct and consistent.

The source file is correctly added to OpenMS_sources and grouped for IDEs. No issues found.

src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp (1)

12-14: Remove src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp — implementations are header-only

The header src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h provides in-header implementations for makeKFolds (inline in-class) and gridSearch1D (template with body). The .cpp contains only an include and an empty namespace and is redundant.

Files/actions:

  • Delete: src/openms/source/ML/CROSSVALIDATION/CrossValidation.cpp
  • Remove from build: update src/openms/source/ML/CROSSVALIDATION/sources.cmake (or the appropriate CMake list) to drop CrossValidation.cpp

No further changes required.

src/openms/include/OpenMS/ML/CROSSVALIDATION/sources.cmake (1)

1-19: Header registration LGTM.

Headers are grouped and appended to OpenMS_sources_h in line with project conventions.

src/openms/includes.cmake (2)

15-15: Good placement of CROSSVALIDATION sources in inclusion order.

Including CROSSVALIDATION right after GRIDSEARCH aligns with the stated inclusion hierarchy.


113-113: Header include integration looks correct.

CROSSVALIDATION headers are included alongside other ML modules; ordering is consistent with sources.

src/tests/class_tests/openms/source/TransformationModelLowess_test.cpp (1)

144-184: Well-structured test covering the auto-span feature!

The test effectively validates the auto-span cross-validation behavior with:

  • Perfectly linear data that creates a tie scenario (MAE = 0 for all spans)
  • Proper verification of tie-breaking (larger span preferred)
  • Validation that auto_span is disabled after selection
  • Confirmation that the model accurately reproduces the linear mapping
src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h (1)

48-109: Well-designed private API for auto-span support!

The helper functions are properly encapsulated in the private section and documented within an @cond INTERNAL block to hide them from the public API documentation. The interface is clean and follows good practices:

  • Clear separation between parsing, grid building, and scoring
  • Comprehensive documentation of parameters and behavior
  • Appropriate use of const-correctness
  • Sensible tie tolerance constant
src/openms/include/OpenMS/MATH/StatisticFunctions.h (2)

287-351: Robust implementation of quantile function!

The quantile implementation follows the standard Type 7 linear interpolation method and includes:

  • Proper validation of input ranges and quantile values
  • Efficient handling of edge cases (q=0, q=1)
  • Clear documentation of the algorithm
  • In-place sorting when needed

488-505: LGTM! Clean RMSE implementation

The function correctly delegates to meanSquareError and returns the square root, following the mathematical definition of RMSE.

src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1)

107-150: Well-designed grid search with thoughtful tie-breaking!

The implementation provides:

  • Clear separation of concerns with template callbacks
  • Thoughtful tie-breaking logic that supports both preferring larger (for regularization) or smaller values
  • Proper exception handling for empty candidate ranges
  • Good performance optimization with pre-allocated error buffer
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (4)

80-153: Excellent implementation of auto-span cross-validation!

The cross-validation logic is well-structured with:

  • Adaptive folding strategy (LOO for small datasets, K-fold for larger)
  • Comprehensive parameter handling and validation
  • Clear logging of the selection process
  • Proper persistence of the selected span to prevent re-computation

241-276: Robust span grid construction with good boundary handling!

The function provides:

  • Sensible default grid when none specified
  • Proper clamping to valid ranges
  • Minimum neighbor enforcement to avoid degenerate fits
  • De-duplication with appropriate tolerance
  • Fallback to ensure non-empty result

278-304: Clean metric implementation with proper error handling!

The scoring function:

  • Returns infinity for empty input (appropriate for optimization)
  • Supports multiple useful metrics
  • Properly preserves the input by copying when sorting is needed
  • Has a sensible default (p95)

182-227: Comprehensive parameter documentation for auto-span feature!

The default parameters are well-documented with:

  • Clear descriptions of each parameter's purpose
  • Appropriate min/max bounds
  • Valid string options specified
  • Sensible defaults that balance performance and accuracy

Comment on lines 106 to +135
@@ -101,6 +185,35 @@ namespace OpenMS
params.setMinFloat("span", 0.0);
params.setMaxFloat("span", 1.0);

// --- Auto-span tuning (optional) ---
params.setValue("auto_span", "false",
"If true, or if 'span' is 0, automatically select LOWESS span by cross-validation.");
params.setValidStrings("auto_span", {"true","false"});

params.setValue("auto_span_min", 0.15,
"Lower bound for auto-selected span.");
params.setMinFloat("auto_span_min", 0.001);

params.setValue("auto_span_max", 0.80,
"Upper bound for auto-selected span.");
params.setMaxFloat("auto_span_max", 0.99);

params.setValue("auto_min_neighbors", 5,
"Minimum number of neighbors (span*n) enforced in auto mode.");
params.setMinInt("auto_min_neighbors", 3);

params.setValue("auto_k_folds", 5,
"K-folds for CV when n>50 (else LOO is used).");
params.setMinInt("auto_k_folds", 2);

params.setValue("auto_metric", "mae",

@coderabbitai coderabbitai Bot Aug 13, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider edge case handling in cross-validation callback

The train_eval lambda correctly skips folds when there's insufficient data, but silently continues without logging. This could lead to situations where some folds contribute no errors to the scoring, potentially biasing the results.

Let me verify if there are any edge cases where all folds might be skipped:


🏁 Script executed:

#!/bin/bash
# Check if there are any tests or usage patterns where min_neighbors might be too large
rg -A 5 -B 5 "auto_min_neighbors" --type cpp

Length of output: 2736


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp"
echo "=== File exists ==="
[ -f "$FILE" ] && echo "yes: $FILE" || { echo "file not found: $FILE"; exit 1; }

echo
echo "=== Showing function / region around auto-span CV logic ==="
rg -n "^\\s*// Determine optimal span using CV|auto_span|train_eval|auto_min_neighbors|auto_k_folds" "$FILE" -n -n -S || true
echo
nl -ba "$FILE" | sed -n '1,240p'

Length of output: 2196


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp"
[ -f "$FILE" ] || { echo "file not found: $FILE"; exit 1; }

echo "=== show lines 1..260 with numbers ==="
awk '{printf("%4d: %s\n", NR, $0)}' "$FILE" | sed -n '1,260p'

echo
echo "=== show lines 100..200 for focused view ==="
awk '{printf("%4d: %s\n", NR, $0)}' "$FILE" | sed -n '100,200p'

echo
echo "=== Search for where train_eval is called and how score is computed ==="
rg -n "train_eval|auto_span_grid|score" "$FILE" -n -S || true
rg -n "std::accumulate|mean|median|abs_errs|abs_err" "$FILE" -S || true

Length of output: 18817


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp"
[ -f "$FILE" ] || { echo "file not found: $FILE"; exit 1; }

echo "=== lines 240..360 ==="
awk '{printf("%4d: %s\n", NR, $0)}' "$FILE" | sed -n '240,360p'

Length of output: 3117


Consider logging/fallback when CV folds/spans are silently skipped

The train_eval lambda (lines ~105–135) early-returns when s * n < min_neighbors and skips folds whose train.size() < max(3,min_neighbors) without any log. If abs_errs remains empty for a candidate span, scoreResiduals returns +infinity (lines ~278–281) so gridSearch1D may get only infinite scores or pick a span non-deterministically — this can lead to surprising/biased span selection.

Files/locations to address

  • src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp
    • train_eval lambda: ~lines 105–135 (early return / per-fold continue)
    • gridSearch1D call: ~lines 141–144 (use of train_eval/score)
    • scoreResiduals empty check: ~lines 278–281 (returns infinity for empty errs)

Suggested fixes (concise)

  • Log when skipping a span or an individual fold (OPENMS_LOG_WARN/INFO) so users can see why CV produced few/no errors.
  • Treat candidate spans that produce zero errors explicitly: either skip them in gridSearch1D (filter before search) or provide a deterministic fallback after gridSearch1D (e.g., fall back to configured span or to span_min), and log that decision.
  • Optionally, make scoreResiduals' behavior explicit in docs/comments (that empty errs => inf) so callers know the implication.
🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp around
lines 106–135, the train_eval lambda silently early-returns when s * n <
min_neighbors and silently continues when a fold's train.size() is too small;
add OPENMS_LOG_WARN (or INFO) messages in both places that include the candidate
span value s, n, min_neighbors and which fold index or counts were skipped so
users can see why no CV errors were produced. At the gridSearch1D call site
around lines 141–144, ensure spans that produced zero errors are either filtered
out before passing scores into gridSearch1D or detect after the search and apply
a deterministic fallback (e.g., configured span or span_min) with a clear
OPENMS_LOG_WARN explaining the fallback choice. Finally, near scoreResiduals
behavior around lines 278–281 add a short comment and/or log when it returns
+infinity due to empty errs so callers/readers know empty error sets map to
infinite score.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this a valid concern? "gridSearch1D may get only infinite scores or pick a span non-deterministically"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

@timosachsenberg Yes, this is a valid concern, but not necessarily about non-determinism. Here's the analysis:

The Issue:

  1. Empty error vectors → infinite scores: When train_eval skips all folds for a span (due to insufficient neighbors), abs_errs remains empty, causing scoreResiduals() to return +infinity
  2. gridSearch1D handles infinites deterministically: Looking at the implementation, it maintains best_score and only updates when score < best_score - tie_tol. Infinite scores will never beat finite ones
  3. Real problem: If all spans produce infinite scores (e.g., dataset too small, min_neighbors too restrictive), gridSearch1D returns the first span with infinite score, which may not be meaningful

Current behavior:

  • If some spans work: gridSearch1D correctly picks the best finite score
  • If no spans work: gridSearch1D returns the first span with infinite score (deterministic, but suboptimal)

The concern is valid because:

  • Users get no warning when CV fails to evaluate spans
  • Fallback to first span with infinite score isn't documented
  • Silent failures make debugging difficult

Recommendation: The suggested logging and fallback handling would indeed improve robustness and user experience, especially for edge cases with small datasets or restrictive parameters.


🏁 Script executed:

#!/bin/bash
# Let's examine the gridSearch1D implementation to see how it handles infinite scores
echo "=== CrossValidation gridSearch1D implementation ==="
cat src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h

Length of output: 5932


🏁 Script executed:

#!/bin/bash
# Let's also check if there are any tests that show how infinite scores are handled
echo "=== Looking for tests with infinite scores ==="
rg -n "infinity|infinite|inf" src/tests/class_tests/openms/source/CrossValidation_test.cpp -A 3 -B 3

echo -e "\n=== Check StatisticFunctions scoreResiduals behavior ==="
rg -n "infinity|infinite|inf" src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp -A 2 -B 2

Length of output: 1119


🏁 Script executed:

#!/bin/bash
# Let's examine the exact gridSearch1D logic for handling scores
echo "=== Extract gridSearch1D template implementation ==="
sed -n '/template.*gridSearch1D/,/^[[:space:]]*}/p' src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h

Length of output: 231


@timosachsenberg After examining the gridSearch1D implementation, the concern is partially valid but not about non-determinism. Here's the precise analysis:

Deterministic Behavior:

// gridSearch1D starts with:
double best_score = std::numeric_limits<double>::infinity();

// Updates only when: s < best_score - tie_tol
// If all scores are infinite, it keeps the first candidate

What actually happens:

  1. Some spans work: gridSearch1D correctly picks the span with the best finite score ✅
  2. All spans fail: gridSearch1D deterministically returns the first span (with infinite score) - this is predictable but potentially suboptimal ⚠️

The real issue:

  • Silent failures: Users get no warning when CV evaluation fails for spans
  • Suboptimal fallback: First span with infinite score may not be the best choice
  • Poor debugging: Hard to diagnose why span selection didn't work as expected

Evidence from tests: The CrossValidation tests explicitly handle infinite scores for empty error vectors (lines 80, 195), confirming this is expected behavior.

Verdict: The behavior is deterministic, not random. However, CodeRabbit's suggestion for logging and explicit fallback handling is still valuable for:

  • User awareness of CV failures
  • Better fallback strategy (e.g., use configured span or span_min instead of first candidate)
  • Improved debugging experience

So yes, it's a valid concern worth addressing for robustness and user experience.

@cbielow cbielow left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

certainly useful changes.
Some comments for streamlining

Comment thread CHANGELOG Resolved
TransformationModelLowess::getDefaultParameters(p);
p.setValue("span", 0.0); // trigger auto when auto_span=true
p.setValue("auto_span", "true");
p.setValue("auto_span_grid", "0.3,0.8"); // two candidates

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

you can directly set {0.3, 0.8} (DoubeList) as values. No need to convert from string.

@singjc

singjc commented Aug 29, 2025

Copy link
Copy Markdown
Contributor Author

certainly useful changes. Some comments for streamlining

Thanks for all the comments and suggestions! I addressed mostly all of them I think.

@singjc
singjc requested a review from cbielow August 29, 2025 22:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (1)

112-141: Log/guard candidates that yield no errors across all folds

Early return when s*n < min_neighbors and per-fold skips can leave abs_errs empty; scoring then returns +inf, potentially picking spans “by tie-break” without user visibility. Add a warning when a span contributes zero CV errors.

       auto train_eval = [&](double s,
                             const std::vector<std::vector<Size>>& folds_in,
                             std::vector<double>& abs_errs)
       {
-        if (s * static_cast<double>(n) < static_cast<double>(min_neighbors)) return;
+        if (s * static_cast<double>(n) < static_cast<double>(min_neighbors))
+        {
+          OPENMS_LOG_INFO << "CV: skip span " << s << " (insufficient neighbors: "
+                          << (s * n) << " < " << min_neighbors << ")" << std::endl;
+          return;
+        }
@@
-          if (train.size() < static_cast<Size>(std::max(3, min_neighbors))) continue;
+          if (train.size() < static_cast<Size>(std::max(3, min_neighbors)))
+          {
+            OPENMS_LOG_DEBUG << "CV: skip fold " << f << " for span " << s
+                             << " (train size " << train.size()
+                             << " < " << std::max(3, min_neighbors) << ")" << std::endl;
+            continue;
+          }
@@
-        }
+        }
+        if (abs_errs.empty())
+        {
+          OPENMS_LOG_WARN << "CV: span " << s << " produced no validation errors across folds; "
+                          << "its score will be treated as +inf (worst)." << std::endl;
+        }
       };
🧹 Nitpick comments (5)
src/openms/include/OpenMS/MATH/StatisticFunctions.h (1)

259-309: Type‑7 quantile implementation is correct; minor nits

  • Redundant empty-range check after checkIteratorsNotNULL (n == 0) can be removed.
  • The exact compare (frac == 0.0) is unnecessary; interpolation also returns the same value. Consider dropping the branch to avoid fragile equality checks.

Apply this minimal cleanup:

-      const Size n = std::distance(begin, end);
-      if (n == 0)
-      {
-        throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
-      }
+      const Size n = std::distance(begin, end);

@@
-      if (frac == 0.0) return static_cast<double>(*it_i);
-
       const auto it_ip1 = it_i + 1;
       return (1.0 - frac) * static_cast<double>(*it_i) + frac * static_cast<double>(*it_ip1);
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (4)

239-279: Span grid: allow 1.0 upper bound and ensure feasible neighbor count

Restricting to 0.99 can make all candidates invalid for tiny n and large min_neighbors. Include 1.0 and avoid the hard 0.9 clamp in the lower bound.

-    static const double cand[] = {0.01, 0.05, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90};
+    static const double cand[] = {0.01, 0.05, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00};
@@
-    double span_max = std::min(0.99, span_max_param);
+    double span_max = std::min(1.00, span_max_param);
@@
-    const double min_span_neighbors = (n_pts > 0) ? static_cast<double>(min_neighbors) / static_cast<double>(n_pts) : 1.0;
-    const double lower = std::max(span_min, std::min(0.9, min_span_neighbors)); // avoid 1–2 neighbor fits
+    const double min_span_neighbors = (n_pts > 0) ? static_cast<double>(min_neighbors) / static_cast<double>(n_pts) : 1.0;
+    const double lower = std::max(span_min, std::min(1.0, min_span_neighbors));
@@
-      grid.push_back(std::min(0.95, std::max(0.01, lower)));
+      grid.push_back(std::min(1.0, std::max(0.01, lower)));

If you want to keep avoiding extremely small neighbor counts, document the policy and make it parameterized rather than hard-coded.


203-225: Parameter bounds: consider permitting auto_span_max up to 1.0

A max of 0.99 can preclude feasible spans for small n. Bumping to 1.0 aligns with the grid change and avoids pathological “no valid folds” spans.

-    params.setMaxFloat("auto_span_max", 0.99);
+    params.setMaxFloat("auto_span_max", 1.0);

11-23: Remove unused headers

, , and appear unused; drop them to speed builds and reduce noise.

-#include <iostream>
-#include <iterator>
-#include <sstream>

150-150: Remove unused variable

prefer_larger is never used.

-      const bool prefer_larger = true;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 046e8c7 and 53abb5f.

📒 Files selected for processing (7)
  • src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h (1 hunks)
  • src/openms/include/OpenMS/MATH/StatisticFunctions.h (3 hunks)
  • src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1 hunks)
  • src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (4 hunks)
  • src/tests/class_tests/openms/executables.cmake (1 hunks)
  • src/tests/class_tests/openms/source/CrossValidation_test.cpp (1 hunks)
  • src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h
  • src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h
🧰 Additional context used
📓 Path-based instructions (3)
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/CrossValidation_test.cpp
  • src/tests/class_tests/openms/source/StatisticFunctions_test.cpp
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/include/OpenMS/MATH/StatisticFunctions.h
  • src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/MATH/StatisticFunctions.h
🧠 Learnings (3)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/CrossValidation_test.cpp
  • src/tests/class_tests/openms/source/StatisticFunctions_test.cpp
  • src/openms/include/OpenMS/MATH/StatisticFunctions.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/source/CrossValidation_test.cpp
  • src/tests/class_tests/openms/source/StatisticFunctions_test.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
PR: OpenMS/OpenMS#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use appropriate OpenMS containers and algorithms

Applied to files:

  • src/openms/include/OpenMS/MATH/StatisticFunctions.h
🧬 Code graph analysis (4)
src/tests/class_tests/openms/source/CrossValidation_test.cpp (2)
src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h (1)
  • CrossValidation (44-178)
src/openms/source/CONCEPT/Exception.cpp (1)
  • InvalidValue (224-228)
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (1)
src/openms/source/CONCEPT/Exception.cpp (1)
  • InvalidValue (224-228)
src/openms/include/OpenMS/MATH/StatisticFunctions.h (2)
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (4)
  • quantile (398-398)
  • quantileUnsortedInput (429-429)
  • rootMeanSquareError (438-438)
  • meanSquareError (121-121)
src/openms/source/CONCEPT/Exception.cpp (1)
  • InvalidValue (224-228)
src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (1)
src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (3)
  • rootMeanSquareError (438-438)
  • MeanAbsoluteDeviation (97-97)
  • quantileUnsortedInput (429-429)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: build-and-test (ubuntu-22.04, clang++, 15)
  • GitHub Check: build-and-test (ubuntu-22.04, g++, 11)
  • GitHub Check: build-and-test (macos-13, xcode, 14.2)
  • GitHub Check: build-and-test (macos-14, xcode, 15.0.1)
  • GitHub Check: build-and-test (windows-2022, cl.exe, 14.36)
🔇 Additional comments (9)
src/tests/class_tests/openms/executables.cmake (1)

291-291: Add CrossValidation_test to math_executables_list — looks good

Registration is correct and consistent with the new unit test. No further changes needed.

src/tests/class_tests/openms/source/CrossValidation_test.cpp (1)

21-52: Solid coverage of folds, grid search, tie-breaking, and errors

Tests are deterministic, exercise key branches (K>n clamping, tie policies, tie tolerance, empty candidates), and use OpenMS exceptions properly. LGTM.

Also applies to: 55-91, 93-141, 143-183, 185-203

src/tests/class_tests/openms/source/StatisticFunctions_test.cpp (3)

412-428: Quantile (sorted) tests are precise and include edge cases

Endpoints, median (even-length), and typical quartiles covered; invalid q and empty range verified. LGTM.


429-437: Quantile (unsorted) tests validate in-place sort path

Covers endpoints and median; good complement to sorted tests.


438-469: RMSE tests validate both MSE linkage and residuals vs zero

Mismatched/empty range exceptions also covered. LGTM.

src/openms/include/OpenMS/MATH/StatisticFunctions.h (2)

310-330: quantileUnsortedInput: clear contract and safe delegation

In-place sort + delegate to quantile is straightforward and matches docs. LGTM.


466-484: rootMeanSquareError correctly composes meanSquareError

Simple and efficient; leverages existing validation in MSE. LGTM.

src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp (2)

283-315: scoreResiduals: MAE via MeanAbsoluteDeviation(errs, 0.0) is acceptable

Mapping MAE to MeanAbsoluteDeviation with mean 0 is correct since errs are absolute errors. RMSE/quantiles paths also look good. LGTM.


219-225: Metric names and validation are consistent

names_of_cvmetric and getDefaultParameters valid string set are aligned. Good.

Comment on lines +81 to +88
if (train.size() < static_cast<Size>(std::max(3, min_neighbors))) continue;

TransformationModelLowess cv_model(train, p_cv);

for (Size j : folds_in[f])
{
const double yhat = cv_model.evaluate(x[j]);
const double e = std::fabs(yhat - y[j]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Honor “span == 0 triggers auto-selection” as documented

Docs state auto runs when auto_span is true or span==0, but code only checks auto_span. Ensure span==0 also enables CV to prevent invalid smoothing with span 0.

-    double span = params_.getValue("span");
+    double span = params_.getValue("span");
@@
-    const bool auto_span_flag = params_.getValue("auto_span").toBool();
+    const bool auto_span_flag = params_.getValue("auto_span").toBool() || (span == 0.0);

Also consider documenting this in getDefaultParameters description (already implied).

Also applies to: 191-202

🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp around
lines 81 to 88, the code only enables auto-selection when auto_span parameter is
true but the documented behavior also requires triggering auto-selection when
span == 0; update the condition so that CV-based span selection is activated
when either auto_span is true OR the provided span parameter equals 0.0 (handle
floating comparison safely), and mirror the same change in the other location
noted (around lines 191-202); also add/update the brief comment in
getDefaultParameters to mention that span==0 triggers auto-selection.

Comment on lines 149 to 156
@@ -113,4 +236,82 @@ namespace OpenMS
params.setValidStrings("extrapolation_type", {"two-point-linear","four-point-linear","global-linear"});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix enum qualifier and undefined tie tolerance — compilation blocker

  • The enum is OpenMS::CrossValidation::CandidateTieBreak, not OpenMS::CrossValidation::CrossValidation::CandidateTieBreak.
  • kTieTol is used but not defined in this TU.

Apply:

-      const bool prefer_larger = true;
-      const auto [best_span, best_score] =
-        OpenMS::CrossValidation::gridSearch1D(spans.begin(), spans.end(),
-                                              folds, train_eval, score,
-                                              kTieTol, OpenMS::CrossValidation::CrossValidation::CandidateTieBreak::PreferLarger);
+      // Numerical tie tolerance aligned with CrossValidation default
+      constexpr double kTieTol = 1e-12;
+      const auto [best_span, best_score] =
+        OpenMS::CrossValidation::gridSearch1D(spans.begin(), spans.end(),
+                                              folds, train_eval, score,
+                                              kTieTol, OpenMS::CrossValidation::CandidateTieBreak::PreferLarger);
📝 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.

Suggested change
// Run 1-D grid search
const bool prefer_larger = true;
const auto [best_span, best_score] =
OpenMS::CrossValidation::gridSearch1D(spans.begin(), spans.end(),
folds, train_eval, score,
kTieTol, OpenMS::CrossValidation::CrossValidation::CandidateTieBreak::PreferLarger);
span = best_span;
// Run 1-D grid search
// Numerical tie tolerance aligned with CrossValidation default
constexpr double kTieTol = 1e-12;
const auto [best_span, best_score] =
OpenMS::CrossValidation::gridSearch1D(spans.begin(), spans.end(),
folds, train_eval, score,
kTieTol, OpenMS::CrossValidation::CandidateTieBreak::PreferLarger);
span = best_span;
🤖 Prompt for AI Agents
In src/openms/source/ANALYSIS/MAPMATCHING/TransformationModelLowess.cpp around
lines 149-156, the code uses the wrong enum qualifier and an undefined kTieTol;
change the enum qualifier to OpenMS::CrossValidation::CandidateTieBreak (remove
the extra CrossValidation:: prefix) and define a tie tolerance constant (for
example add a constexpr double kTieTol = 1e-9; in the enclosing function or at
the top of the TU) or replace kTieTol with an explicit numeric literal; ensure
the constant is in the same namespace/scope so the compilation error is
resolved.

@timosachsenberg

Copy link
Copy Markdown
Contributor

@timosachsenberg timosachsenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nice. only some minor comments

@jpfeuffer

jpfeuffer commented Sep 3, 2025 •

Copy link
Copy Markdown
Contributor

Phew. Yes it would make sense but I think it might be quite some work.
It was kind of hard getting it to work for basic multidimensional cases (checking which simple score of one param set is better than the others).
Adding train/test splits and custom comparators might be a different beast in such a general template recursive (i.e. multidimensional) implementation.

@timosachsenberg

Copy link
Copy Markdown
Contributor

Phew. Yes it would make sense but I think it might be quite some work. It was kind of hard getting it to work for basic multidimensional cases (checking which simple score of one param set is better than the others). Adding train/test splits and custom comparators might be a different beast in such a general template recursive (i.e. multidimensional) implementation.

Ok then maybe not worth it.

@singjc

singjc commented Sep 7, 2025

Copy link
Copy Markdown
Contributor Author

Phew. Yes it would make sense but I think it might be quite some work. It was kind of hard getting it to work for basic multidimensional cases (checking which simple score of one param set is better than the others). Adding train/test splits and custom comparators might be a different beast in such a general template recursive (i.e. multidimensional) implementation.

Ok then maybe not worth it.

I agree that it would make more sense and would be nicer to integrate the gridSearch1D with the current GridSearch module, but it does seem like it would require a bit more thought and work. Maybe for another PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants