Skip to content

[SimpleSVM] Implement Pimpl idiom and remove direct libSVM dependencies - #7892

Merged
timosachsenberg merged 2 commits into
OpenMS:developfrom
moabo3li:Use_PIMPL_for_SimpleSVM
Mar 10, 2025
Merged

timosachsenberg merged 2 commits into
OpenMS:developfrom
moabo3li:Use_PIMPL_for_SimpleSVM

Conversation

@moabo3li

@moabo3li moabo3li commented Mar 8, 2025 •

Copy link
Copy Markdown
Contributor

Implement Pimpl idiom and remove direct libSVM dependencies

Fixes #6378

Description

Removed the direct inclusion of <svm.h> header
Added header for std::unique_ptr
Added deleted copy constructor and assignment operator
Removed all implementation details (member variables and private methods) from the header file
Added a forward declaration for an Impl class
Added a std::unique_ptr member called pimpl_ to manage the implementation

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).


PR Type

Enhancement


Description

  • Refactored SimpleSVM class to use the PIMPL idiom for encapsulation.

  • Removed direct dependencies on libSVM from the header file.

  • Introduced a new implementation class SimpleSVM::Impl to handle internal logic.

  • Improved modularity and maintainability by delegating functionality to the implementation class.


Changes walkthrough 📝

Relevant files
Enhancement
SimpleSVM.cpp
Refactor `SimpleSVM` implementation using PIMPL idiom       

src/openms/source/ML/SVM/SimpleSVM.cpp

  • Introduced SimpleSVM::Impl class to encapsulate internal logic.
  • Moved libSVM-specific code and data structures to the implementation
    file.
  • Added methods in Impl for scaling, data conversion, and parameter
    optimization.
  • Updated SimpleSVM methods to delegate functionality to the Impl class.
  • +369/-296
    SimpleSVM.h
    Update `SimpleSVM` header for PIMPL pattern                           

    src/openms/include/OpenMS/ML/SVM/SimpleSVM.h

  • Removed direct inclusion of libSVM header.
  • Added forward declaration of SimpleSVM::Impl class.
  • Introduced a std::unique_ptr to Impl for encapsulation.
  • Deleted internal data structures and methods, delegating them to Impl.
  • +12/-47 

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    Summary by CodeRabbit

    • New Features

      • Enhanced SVM performance through improved parameter optimization and data scaling.
      • Introduced a new method for determining optimal SVM parameters based on cross-validation results.
    • Refactor

      • Restructured the underlying SVM implementation for better resource management and maintainability, ensuring a more robust predictive experience for users.
      • Simplified the public interface of the SVM class by encapsulating core functionality within a private implementation class.

    @coderabbitai

    coderabbitai Bot commented Mar 8, 2025 •

    Copy link
    Copy Markdown
    Contributor

    Walkthrough

    The changes refactor the SimpleSVM class by removing the direct dependency on the libSVM library and adopting the Pimpl idiom. In the header, the libSVM includes, member variables, and functions are removed, and a forward-declared Impl class with a std::unique_ptr<Impl> is introduced along with deleted copy operations. In the source file, the implementation details are moved to the new Impl class with added methods to handle data conversion, scaling, parameter optimization, and prediction tasks. The constructors and method signatures are updated to delegate functionality to Impl.

    Changes

    Files Change Summary
    src/openms/.../ML/SVM/SimpleSVM.h Removed libSVM includes and associated members; introduced a forward declaration of Impl and a std::unique_ptr<Impl> pimpl_; deleted copy constructor and copy assignment operator.
    src/openms/.../ML/SVM/SimpleSVM.cpp Added the Impl class encapsulating methods (clear_, scaleData_, convertData_, chooseBestParameters_, optimizeParameters_); updated constructor/destructor and method signatures to delegate to Impl.

    Suggested labels

    OpenSwathAlgo, Bug fix

    Suggested reviewers

    • jcharkow
    • timosachsenberg

    Poem

    I’m a rabbit coding in the light,
    Hopping to a refactor, oh so bright!
    With a hidden Impl to guard each core,
    Old bugs scurry away, forgotten lore.
    A joyful hop for changes in our code! 🐇

    ✨ Finishing Touches
    • 📝 Generate Docstrings

    🪧 Tips

    Chat

    There are 3 ways to chat with CodeRabbit:

    • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
      • I pushed a fix in commit <commit_id>, please review it.
      • Generate unit testing code for this file.
      • Open a follow-up GitHub issue for this discussion.
    • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
      • @coderabbitai generate unit testing code for this file.
      • @coderabbitai modularize this function.
    • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
      • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
      • @coderabbitai read src/utils.ts and generate unit testing code.
      • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
      • @coderabbitai help me debug CodeRabbit configuration file.

    Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

    CodeRabbit Commands (Invoked using PR comments)

    • @coderabbitai pause to pause the reviews on a PR.
    • @coderabbitai resume to resume the paused reviews.
    • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai full review to do a full review from scratch and review all the files again.
    • @coderabbitai summary to regenerate the summary of the PR.
    • @coderabbitai generate docstrings to generate docstrings for this PR.
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Other keywords and placeholders

    • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
    • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
    • Add @coderabbitai anywhere in the PR title to generate the title automatically.

    CodeRabbit Configuration File (.coderabbit.yaml)

    • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
    • Please see the configuration documentation for more information.
    • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

    Documentation and Community

    • Visit our Documentation for detailed information on how to use CodeRabbit.
    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.

    @qodo-code-review

    Copy link
    Copy Markdown
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    🎫 Ticket compliance analysis ✅

    6378 - Fully compliant

    Compliant requirements:

    • Create a SimpleSVM implementation class
    • Store only a pointer in the class that is exposed via headers
    • Make libSVM a private link
    • Remove the need for end-users/devs to include svm.h
    • Make the code cleaner by hiding implementation details

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Memory Management

    The implementation of the destructor for SimpleSVM is using the default destructor, but it should ensure proper cleanup of resources, especially when the Impl class is handling memory allocation.

    SimpleSVM::~SimpleSVM() = default;
    Move Semantics

    The class lacks move constructor and move assignment operator which could be beneficial for performance when transferring ownership of the implementation pointer.

    SimpleSVM::SimpleSVM() :
      DefaultParamHandler("SimpleSVM")
    {
      pimpl_ = make_unique<Impl>(param_);
      defaults_.setValue("kernel", "RBF", "SVM kernel");
      defaults_.setValidStrings("kernel", {"RBF","linear"});
    
      defaults_.setValue("xval", 5, "Number of partitions for cross-validation (parameter optimization)");
      defaults_.setMinInt("xval", 1);
    
      String values = "-5,-3,-1,1,3,5,7,9,11,13,15";
      defaults_.setValue("log2_C", ListUtils::create<double>(values), "Values to try for the SVM parameter 'C' during parameter optimization. A value 'x' is used as 'C = 2^x'.");
    
      values = "-15,-13,-11,-9,-7,-5,-3,-1,1,3";
      defaults_.setValue("log2_gamma", ListUtils::create<double>(values), "Values to try for the SVM parameter 'gamma' during parameter optimization (RBF kernel only). A value 'x' is used as 'gamma = 2^x'.");
    
      values = "-15,-12,-9,-6,-3.32192809489,0,3.32192809489,6,9,12,15";
      defaults_.setValue("log2_p", ListUtils::create<double>(values), "Values to try for the SVM parameter 'epsilon' during parameter optimization (epsilon-SVR only). A value 'x' is used as 'epsilon = 2^x'.");
    
      vector<std::string> advanced(1, "advanced");
      defaults_.setValue("epsilon", 0.001, "Stopping criterion", advanced);
      defaults_.setMinFloat("epsilon", 0.0);
    
      defaults_.setValue("cache_size", 100.0, "Size of the kernel cache (in MB)", 
                         advanced);
      defaults_.setMinFloat("cache_size", 1.0);
    
      defaults_.setValue("no_shrinking", "false",
                         "Disable the shrinking heuristics", advanced);
      defaults_.setValidStrings("no_shrinking",
                                {"true","false"});
    
      defaultsToParam_();
    }

    @qodo-code-review

    qodo-code-review Bot commented Mar 8, 2025 •

    Copy link
    Copy Markdown
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Explicit implementation destruction

    The destructor should explicitly destroy the implementation object before the
    unique_ptr is destroyed. With just '= default', the compiler-generated
    destructor might not properly handle the forward-declared Impl class.

    src/openms/source/ML/SVM/SimpleSVM.cpp [397]

    -SimpleSVM::~SimpleSVM() = default;
    +SimpleSVM::~SimpleSVM() 
    +{
    +  pimpl_.reset();
    +}
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    __

    Why: The suggestion correctly identifies a potential issue with the default destructor when using the Pimpl pattern with forward declarations. Explicitly resetting the unique_ptr ensures proper cleanup of the implementation object, preventing potential memory leaks or undefined behavior.

    Medium
    General
    Fix spacing in condition

    There's a spacing issue in the for loop condition that could lead to readability
    problems. The space between 'i <' and 'n_obs' should be consistent with the
    coding style.

    src/openms/source/ML/SVM/SimpleSVM.cpp [513]

     void SimpleSVM::predict(vector<Prediction>& predictions, vector<Size> indexes) const
     {
       if (pimpl_->model_ == nullptr)
       {
         throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
                                       "SVM model has not been trained (use the "
                                       "'setup' method)");
       }
     
       Size n_obs = pimpl_->nodes_.size();
       if (indexes.empty())
       {
         indexes.reserve(n_obs);
    -    for (Size i = 0; i <n_obs; indexes.push_back(i++)){};
    +    for (Size i = 0; i < n_obs; indexes.push_back(i++)){};
       }

    [To ensure code accuracy, apply this suggestion manually]

    Suggestion importance[1-10]: 2

    __

    Why: The suggestion correctly identifies a minor spacing inconsistency in the for loop condition. While this is a valid style improvement for code readability and consistency, it has minimal impact on functionality and is purely cosmetic.

    Low
    • Update

    @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: 0

    🧹 Nitpick comments (8)
    src/openms/include/OpenMS/ML/SVM/SimpleSVM.h (1)

    78-81: Preventing copying is a good move
    Deleting the copy constructor and assignment operator aligns with the Pimpl idiom. If move semantics are needed later, consider adding a move constructor and move assignment operator.

    src/openms/source/ML/SVM/SimpleSVM.cpp (7)

    27-83: Implementation class effectively encapsulates internal details
    Grouping the necessary data structures and parameters into Impl helps keep SimpleSVM's public interface lean. Consider adding brief doc comments for each member to ensure clarity.


    106-131: Handles feature scaling well
    Predictors are scaled to [0,1], and uninformative predictors are cleared. This approach is valid, but consider explicitly removing these predictors from the map to avoid potential confusion later.


    133-162: Converts predictors to LIBSVM format
    This logic is sound. If the commented-out condition at lines 149–151 is no longer needed, consider removing it to keep the codebase clean.


    164-249: Potential method complexity
    The nested loops and tie-breaking logic are correct but somewhat complex. Consider extracting the tie-breaking steps into a helper method or adding more inline comments for clarity.

    🧰 Tools
    🪛 GitHub Check: CodeFactor

    [notice] 164-249: src/openms/source/ML/SVM/SimpleSVM.cpp#L164-L249
    Complex Method

    🪛 Cppcheck (2.10-2)

    [error] 243-243: Out of bounds access in expression 'best_indexes[tiebreaker.rbegin()->second]' because 'best_indexes' is empty and 'tiebreaker.rbegin()->second' may be non-zero.

    (containerOutOfBounds)


    [error] 243-243: Out of bounds access in expression 'tiebreaker.rbegin()' because 'tiebreaker' is empty.

    (containerOutOfBounds)


    250-359: Efficient parameter optimization
    The implementation thoroughly covers cross-validation. Although it is somewhat lengthy, it is logically structured. If reusability is desired, extracting smaller helper functions could improve readability.


    541-563: Scaling logic for new data
    This function reuses training ranges to scale new predictor data. Consider adding a sanity check to handle values that fall outside the original min-max range, to prevent undesired negative or >1 scaled values.


    566-611: Predict method for novel data
    Allocating a temporary array x works with LIBSVM. Using a smart pointer or std::vector could simplify memory management but is optional.

    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between 5d0705e and d12741e.

    📒 Files selected for processing (2)
    • src/openms/include/OpenMS/ML/SVM/SimpleSVM.h (3 hunks)
    • src/openms/source/ML/SVM/SimpleSVM.cpp (5 hunks)
    🧰 Additional context used
    🪛 GitHub Check: CodeFactor
    src/openms/source/ML/SVM/SimpleSVM.cpp

    [notice] 164-249: src/openms/source/ML/SVM/SimpleSVM.cpp#L164-L249
    Complex Method

    🔇 Additional comments (12)
    src/openms/include/OpenMS/ML/SVM/SimpleSVM.h (3)

    13-14: Good removal of direct libSVM dependency
    Removing the libSVM header from the public interface reduces compile-time dependencies and fosters better encapsulation.


    20-20: Necessary include for std::unique_ptr
    Importing <memory> is essential for using std::unique_ptr in this header.


    135-139: Solid Pimpl usage
    Forward declaring Impl and storing it as a std::unique_ptr effectively hides implementation details.

    src/openms/source/ML/SVM/SimpleSVM.cpp (9)

    18-21: Implementation-only inclusion
    Shifting #include "svm.h" from the header to the source file adheres to the Pimpl principle by limiting exposure of third-party details.


    85-95: Clean constructor and destructor
    Using clear_() in the destructor ensures resources are properly freed. This approach is consistent with RAII principles.


    97-104: Properly frees allocated resources
    clear_() ensures the SVM model memory and allocated arrays are freed to prevent memory leaks.


    361-395: Comprehensive constructor initialization
    Initializing pimpl_ early and carefully setting default parameters is a good practice, ensuring consistent usage of DefaultParamHandler.


    397-498: Robust SVM setup
    Properly differentiates classification vs. regression, validates input shapes, and ensures cross-validation feasibility. The error messages are descriptive and helpful.


    499-539: Predict method for trained data
    The boundary checks and probability-based predictions are prudent. The straightforward approach to populate 'predictions' is clear.


    613-644: Feature weights for 2-class classification
    Correctly accumulates coefficients for a 2-class SVM. For multi-class scenarios, this function raises an exception, which is an appropriate safeguard.


    646-649: Provides direct access to scaling
    Returning the ScaleMap reference is straightforward.


    652-668: Exports cross-validation results
    Writing results to CSV with column headers is helpful for analysis.

    @moabo3li
    moabo3li force-pushed the Use_PIMPL_for_SimpleSVM branch from d12741e to 4f5d524 Compare March 9, 2025 02:06

    @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: 0

    🔭 Outside diff range comments (1)
    src/openms/source/ML/SVM/SimpleSVM.cpp (1)

    243-243: 🛠️ Refactor suggestion

    Investigate the TODO about using begin vs rbegin

    The current code uses rbegin() with a commented TODO suggesting using begin() if higher_better is false. This conditional logic should be implemented rather than left as a TODO.

    - const auto& indexes = best_indexes[tiebreaker.rbegin()->second]; // TODO: use begin if higher_better == false
    + // Use rbegin() for higher values (when higher_better is true) and begin() for lower values
    + const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];
    🧰 Tools
    🪛 Cppcheck (2.10-2)

    [error] 243-243: Out of bounds access in expression 'best_indexes[tiebreaker.rbegin()->second]' because 'best_indexes' is empty and 'tiebreaker.rbegin()->second' may be non-zero.

    (containerOutOfBounds)


    [error] 243-243: Out of bounds access in expression 'tiebreaker.rbegin()' because 'tiebreaker' is empty.

    (containerOutOfBounds)

    🧹 Nitpick comments (2)
    src/openms/source/ML/SVM/SimpleSVM.cpp (2)

    164-248: Consider simplifying the chooseBestParameters_ method

    This method has been flagged by static analysis as complex. While it accurately handles parameter selection, it could benefit from being broken down into smaller, more focused functions.

    Consider decomposing this method into separate functions:

    1. One for finding the best value
    2. One for resolving ties
    - tuple<double, double, double> SimpleSVM::Impl::chooseBestParameters_(bool higher_better) const
    + // Find the best parameter set based on performance
    + vector<tuple<Size, Size, Size>> SimpleSVM::Impl::findBestParameterIndexes_(bool higher_better, double& best_value) const
    {
      auto is_better = [&higher_better](double l, double r)->bool { return higher_better ? (l > r) : (l < r); };
    
      // which parameter set(s) achieved best cross-validation performance?
      double best_value_local = higher_better ? std::numeric_limits<double>::lowest() : std::numeric_limits<double>::max();
      vector<tuple<Size, Size, Size>> best_indexes;
      for (Size g_index = 0; g_index < log2_gamma_.size(); ++g_index)
      {
        for (Size c_index = 0; c_index < log2_C_.size(); ++c_index)
        {
          for (Size p_index = 0; p_index < log2_p_.size(); ++p_index)
          {
            double value = performance_[g_index][c_index][p_index];
            if (value == best_value_local)
            {
              best_indexes.emplace_back(g_index, c_index, p_index); // tie
            }
            else if (is_better(value, best_value_local))
            {
              best_value_local = value;
              best_indexes.clear();
              best_indexes.emplace_back(g_index, c_index, p_index);
            }
          }
        }
      }
      OPENMS_LOG_INFO << "Best cross-validation performance: " 
               << best_value_local << " (ties: " << best_indexes.size() << ")" << endl;
    +  best_value = best_value_local;
    +  return best_indexes;
    }
    
    + // Resolve ties by looking at neighboring parameter performance
    + tuple<Size, Size, Size> SimpleSVM::Impl::resolveTiesByNeighbors_(const vector<tuple<Size, Size, Size>>& best_indexes) const
    + {
      if (best_indexes.size() == 1)
      {
        return best_indexes[0];
      }
    
      // break ties between parameter sets - look at "neighboring" parameters:
      multimap<pair<double, Size>, Size> tiebreaker;
      for (Size i = 0; i < best_indexes.size(); ++i)
      {
        const auto& indexes = best_indexes[i];
        Size n_neighbors = 0;
        double neighbor_value = 0.0;
        if (std::get<0>(indexes) > 0)
        {
          neighbor_value += performance_[std::get<0>(indexes) - 1][std::get<1>(indexes)][std::get<2>(indexes)];
          ++n_neighbors;
        }
        if (std::get<0>(indexes) + 1 < log2_gamma_.size())
        {
          neighbor_value += performance_[std::get<0>(indexes) + 1][std::get<1>(indexes)][std::get<2>(indexes)];
          ++n_neighbors;
        }
        if (std::get<1>(indexes) > 0)
        {
          neighbor_value += performance_[std::get<0>(indexes)][std::get<1>(indexes) - 1][std::get<2>(indexes)];
          ++n_neighbors;
        }
        if (std::get<1>(indexes) + 1 < log2_C_.size())
        {
          neighbor_value += performance_[std::get<0>(indexes)][std::get<1>(indexes) + 1][std::get<2>(indexes)];
          ++n_neighbors;
        }
        if (std::get<2>(indexes) > 0)
        {
          neighbor_value += performance_[std::get<0>(indexes)][std::get<1>(indexes)][std::get<2>(indexes) - 1];
          ++n_neighbors;
        }
        if (std::get<2>(indexes) + 1 < log2_p_.size())
        {
          neighbor_value += performance_[std::get<0>(indexes)][std::get<1>(indexes)][std::get<2>(indexes) + 1];
          ++n_neighbors;
        }
        neighbor_value /= n_neighbors; // avg. performance of neighbors
        tiebreaker.insert(make_pair(make_pair(neighbor_value, n_neighbors), i));
      }
      return best_indexes[tiebreaker.rbegin()->second]; // use begin if higher_better == false
    + }
    
    + tuple<double, double, double> SimpleSVM::Impl::chooseBestParameters_(bool higher_better) const
    + {
    +  double best_value;
    +  auto best_indexes = findBestParameterIndexes_(higher_better, best_value);
    +  auto best_index = resolveTiesByNeighbors_(best_indexes);
    +  
    +  return make_tuple(log2_C_[std::get<1>(best_index)],
    +      log2_gamma_[std::get<0>(best_index)], 
    +      log2_p_[std::get<2>(best_index)]);
    }
    🧰 Tools
    🪛 GitHub Check: CodeFactor

    [notice] 164-249: src/openms/source/ML/SVM/SimpleSVM.cpp#L164-L249
    Complex Method

    🪛 Cppcheck (2.10-2)

    [error] 243-243: Out of bounds access in expression 'best_indexes[tiebreaker.rbegin()->second]' because 'best_indexes' is empty and 'tiebreaker.rbegin()->second' may be non-zero.

    (containerOutOfBounds)


    [error] 243-243: Out of bounds access in expression 'tiebreaker.rbegin()' because 'tiebreaker' is empty.

    (containerOutOfBounds)


    544-566: Consider moving the utility function into the Impl class

    The free function scaleDataUsingTrainingRanges seems like it should be a method of the Impl class since it's closely related to the implementation details.

    - void scaleDataUsingTrainingRanges(SimpleSVM::PredictorMap& predictors, const map<String, pair<double, double>>& scaling)
    + void SimpleSVM::Impl::scaleDataUsingTrainingRanges(SimpleSVM::PredictorMap& predictors) const
    {
      // scale each feature dimension to the min-max-range
      for (auto pred_it = predictors.begin();
           pred_it != predictors.end(); ++pred_it)
      {
        if (pred_it->second.empty()) continue; // uninformative predictor
        auto val_begin = pred_it->second.begin();
        auto val_end = pred_it->second.end();
        for (; val_begin != val_end; ++val_begin)
        {
          if (scaling.count(pred_it->first) == 0)
    -     if (scaling_.count(pred_it->first) == 0)
          {
            //std::cout << "Predictor: '" << pred_it->first << "' not found in scale map because it was uninformative during training." << std::endl;
            continue;
          }      
    -     auto [min, max] = scaling.at(pred_it->first);
    +     auto [min, max] = scaling_.at(pred_it->first);
          double range = max - min;
           *val_begin = (*val_begin - min) / range;
        }
      }
    }

    Then update the predict method to use this method:

    - scaleDataUsingTrainingRanges(predictors, pimpl_->scaling_);
    + pimpl_->scaleDataUsingTrainingRanges(predictors);
    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between d12741e and 4f5d524.

    📒 Files selected for processing (2)
    • src/openms/include/OpenMS/ML/SVM/SimpleSVM.h (3 hunks)
    • src/openms/source/ML/SVM/SimpleSVM.cpp (5 hunks)
    🧰 Additional context used
    🪛 GitHub Check: CodeFactor
    src/openms/source/ML/SVM/SimpleSVM.cpp

    [notice] 164-249: src/openms/source/ML/SVM/SimpleSVM.cpp#L164-L249
    Complex Method

    🔇 Additional comments (15)
    src/openms/include/OpenMS/ML/SVM/SimpleSVM.h (4)

    13-14: Good removal of direct libSVM dependency from the header

    This change reduces coupling and compilation dependencies by removing the direct inclusion of the libSVM header from the public interface. This aligns with the PR's objective of implementing the Pimpl idiom.


    20-20: Good addition of memory header for std::unique_ptr

    Adding the memory header is necessary to support the std::unique_ptr which is a key component of the Pimpl idiom implementation.


    78-80: Good prevention of copying

    Correctly deleting the copy constructor and copy assignment operator prevents shallow copying of the unique_ptr which would lead to double deletion. This is a necessary part of implementing the Pimpl idiom with a unique_ptr.


    135-139: Good Pimpl idiom implementation

    The forward declaration of the Impl class and the use of std::unique_ptr as a member variable correctly implements the Pimpl idiom. This effectively hides the implementation details from clients of this header.

    src/openms/source/ML/SVM/SimpleSVM.cpp (11)

    18-20: Good isolation of libSVM dependency to implementation file

    Moving the libSVM include to the implementation file is a key part of the Pimpl idiom implementation, ensuring that clients of the SimpleSVM class don't need to have libSVM headers available.


    27-83: Good implementation of the private implementation class

    The Impl class correctly encapsulates all the libSVM-specific data structures and functionality that was previously directly in the SimpleSVM class. The class definition is well-structured with clear member variables and methods.


    361-395: Good implementation of the SimpleSVM constructor

    The constructor correctly initializes the implementation object and sets up all the parameters with appropriate documentation and validation.


    396-400: Good implementation of the SimpleSVM destructor

    The destructor explicitly resets the unique_ptr to the implementation object, which ensures proper cleanup.


    402-500: Good delegation of setup method to implementation

    The setup method properly delegates to the Impl object's methods while maintaining the original error checking and validation logic.


    503-542: Good delegation of prediction on training data

    The predict method correctly delegates to the implementation while maintaining the same interface and error checking.


    569-614: Good implementation of prediction on new data

    The prediction method for new data correctly handles scaling and prediction while maintaining the same interface.


    617-647: Good delegation of feature weight retrieval

    The getFeatureWeights method correctly delegates to the implementation while maintaining the same interface and error checking.


    649-652: Good delegation of scaling retrieval

    The getScaling method properly delegates to the implementation's scaling data.


    655-671: Good delegation of cross-validation results

    The writeXvalResults method correctly delegates to the implementation while maintaining the same interface.


    199-200:

    Details

    ✅ Verification successful

    Investigate the commented TODO about parameter order

    There's a TODO comment questioning why the order of parameters was changed. This should be investigated and either fixed or the comment should be removed if the current order is correct.


    🏁 Script executed:

    #!/bin/bash
    # Check if there's any specific reason for the parameter order documented elsewhere
    rg -A 2 "parameter.*order" --no-ignore-vcs

    Length of output: 24991


    Parameter Order in SimpleSVM Is Confirmed as Intended – Remove the Superfluous TODO Comment

    After exploring the repository for additional documentation on parameter order (including related patterns elsewhere), there isn’t any evidence that the current order in SimpleSVM.cpp deviates from the intended design. Similar modules that enforce a specific ordering explain their choices (or note historical accidents), but nothing indicates a required change for the SVM parameters in this case.

    • The investigation did not uncover supporting documentation or usage examples that justify altering the current order.
    • In light of this, the TODO comment questioning the parameter order appears outdated and can be removed.

    @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 (3)
    src/openms/source/ML/SVM/SimpleSVM.cpp (3)

    149-153: Remove or clarify commented code

    There's commented code that suggests filtering values > 0.0 was previously implemented. Since this is now commented out, either remove it completely or add a clear comment explaining why it was removed but kept as a comment.

    -//      if (value > 0.0) // TODO: why > 0.0?
    -//      {
            svm_node node = {pred_index, value};
            nodes_[obs_index].push_back(node);
    -//      }

    545-567: Consider moving helper function into the Impl class

    The scaleDataUsingTrainingRanges function appears to be a helper function for the SimpleSVM class, but it's defined at global scope. For better encapsulation, consider moving this function inside the SimpleSVM::Impl class, which will make the relationship clearer and prevent potential name conflicts.

    -void scaleDataUsingTrainingRanges(SimpleSVM::PredictorMap& predictors, const map<String, pair<double, double>>& scaling)
    +void SimpleSVM::Impl::scaleDataUsingTrainingRanges(SimpleSVM::PredictorMap& predictors, const map<String, pair<double, double>>& scaling)

    Then update the call in the predict method:

    -  scaleDataUsingTrainingRanges(predictors, pimpl_->scaling_);
    +  pimpl_->scaleDataUsingTrainingRanges(predictors, pimpl_->scaling_);

    197-200: Clarify the order of parameters in returned tuple

    There's a TODO comment questioning why the order of parameters changed. Please address this comment by either correcting the order if it's inconsistent or clarifying why it's intentionally different.

    -    return make_tuple(
    -      log2_C_[std::get<1>(best_indexes[0])], // TODO: check why order changed
    -      log2_gamma_[std::get<0>(best_indexes[0])], 
    -      log2_p_[std::get<2>(best_indexes[0])]);
    +    // Order is C, gamma, p to match the function's return signature
    +    return make_tuple(
    +      log2_C_[std::get<1>(best_indexes[0])],
    +      log2_gamma_[std::get<0>(best_indexes[0])], 
    +      log2_p_[std::get<2>(best_indexes[0])]);
    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between 4f5d524 and 8719083.

    📒 Files selected for processing (1)
    • src/openms/source/ML/SVM/SimpleSVM.cpp (5 hunks)
    🧰 Additional context used
    🪛 Cppcheck (2.10-2)
    src/openms/source/ML/SVM/SimpleSVM.cpp

    [error] 244-244: Out of bounds access in expression 'best_indexes[higher_better?tiebreaker.rbegin()->second

    (containerOutOfBounds)

    🔇 Additional comments (3)
    src/openms/source/ML/SVM/SimpleSVM.cpp (3)

    18-20: Good implementation of the Pimpl pattern

    The code now properly includes the libSVM header only in the implementation file, which successfully removes the direct dependency from the header file. This is exactly what the Pimpl idiom is designed for - hiding implementation details and reducing dependencies.


    27-83: Well-structured implementation class

    The SimpleSVM::Impl class encapsulates all the libSVM-related implementation details effectively. The class is organized with clear member variables and methods to handle SVM operations while keeping the public API clean. Particularly good use of private utilities like printNull_, scaleData_, and other helper methods to modularize the implementation.


    362-401: Good implementation of Pimpl constructor/destructor

    The constructor correctly initializes the Impl object with a std::unique_ptr, and the destructor explicitly resets the pointer, which follows best practices for the Pimpl idiom. The initialization of defaults is well-structured and clear.

    Size n_obs = predictors.begin()->second.size();
    pimpl_->n_parts_ = param_.getValue("xval");

    // clear old models

    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

    Address potential out-of-bounds access

    The static analyzer flagged a potential out-of-bounds access here. While this is likely a false positive because tiebreaker should never be empty when this code is reached (as you return early at line 195 if best_indexes.size() == 1), it's better to add a safeguard to prevent any possibility of undefined behavior.

    -  const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];
    +  // Ensure tiebreaker is not empty before accessing its elements
    +  if (tiebreaker.empty()) {
    +    // This should never happen based on code logic, but handle it anyway
    +    return make_tuple(log2_C_[std::get<1>(best_indexes[0])],
    +                     log2_gamma_[std::get<0>(best_indexes[0])], 
    +                     log2_p_[std::get<2>(best_indexes[0])]);
    +  }
    +  const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];

    Let's verify that our understanding of the code flow is correct:


    🏁 Script executed:

    #!/bin/bash
    # Verify that tiebreaker is always populated when we reach line 244
    # and that we never reach line 244 with an empty tiebreaker
    
    # Check if the function ever returns early without populating tiebreaker
    echo "Checking control flow in chooseBestParameters_:"
    rg -A 10 -B 5 "chooseBestParameters_" src/openms/source/ML/SVM/SimpleSVM.cpp

    Length of output: 2059


    Fix potential out-of-bounds access in SimpleSVM::chooseBestParameters_

    While the control flow (with an early return when only one candidate is present) should normally ensure that the tiebreaker container is populated, the static analyzer correctly flags a potential risk if, against expectations, tiebreaker were empty. To guard against any unexpected behavior, please add an explicit check before accessing its elements. This change will protect against undefined behavior even in scenarios not originally anticipated by the design.

    Please update the code in src/openms/source/ML/SVM/SimpleSVM.cpp (around line 244) as follows:

    -  const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];
    +  // Ensure tiebreaker is not empty before accessing its elements
    +  if (tiebreaker.empty()) {
    +    // This should never happen based on code logic, but handle it safely
    +    return make_tuple(log2_C_[std::get<1>(best_indexes[0])],
    +                      log2_gamma_[std::get<0>(best_indexes[0])], 
    +                      log2_p_[std::get<2>(best_indexes[0])]);
    +  }
    +  const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];

    This safeguard addresses potential false positives and ensures robustness against any unforeseen control flow issues.

    📝 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
    const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];
    // Ensure tiebreaker is not empty before accessing its elements
    if (tiebreaker.empty()) {
    // This should never happen based on code logic, but handle it safely
    return make_tuple(log2_C_[std::get<1>(best_indexes[0])],
    log2_gamma_[std::get<0>(best_indexes[0])],
    log2_p_[std::get<2>(best_indexes[0])]);
    }
    const auto& indexes = best_indexes[higher_better ? tiebreaker.rbegin()->second : tiebreaker.begin()->second];
    🧰 Tools
    🪛 Cppcheck (2.10-2)

    [error] 244-244: Out of bounds access in expression 'best_indexes[higher_better?tiebreaker.rbegin()->second

    (containerOutOfBounds)

    @timosachsenberg

    Copy link
    Copy Markdown
    Contributor

    thanks! looks good to me :)

    @timosachsenberg
    timosachsenberg merged commit 9492629 into OpenMS:develop Mar 10, 2025
    @moabo3li
    moabo3li deleted the Use_PIMPL_for_SimpleSVM branch March 10, 2025 08:34
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    Use PIMPL for SimpleSVM

    2 participants