Objective function to be fit using the MpFit library. An objective function has exactly one 'x' variable and any number of additional non-variable parameters whose values are unknown. The purpose of curve fitting is to find the best values for those parameters given an objective function and a series of x/y data points. This class contains the objective function as well as the data points because
| 41 | /// By convention, the first argument is the value of the 'x' variable and the second |
| 42 | /// argument is an array of function parameters which are determined during fitting. |
| 43 | class ObjectiveFunction { |
| 44 | public: |
| 45 | ObjectiveFunction(std::string name, int num_params, |
| 46 | std::function<double (double, const double*)> fn); |
| 47 | |
| 48 | /// Performs least mean squares (LMS) curve fitting using the MpFit library |
| 49 | /// against the provided x/y data points. |
| 50 | /// Returns true if fitting was successful, false otherwise. |
| 51 | bool LmsFit(const double* xs, const double* ys, int num_points) WARN_UNUSED_RESULT; |
| 52 | |
| 53 | /// Evaluates the objective function over the given 'x' value. |
| 54 | double GetY(int64_t x) const { |
| 55 | DCHECK(params_ != nullptr); |
| 56 | return fn_(x, params_.get()); |
| 57 | } |
| 58 | |
| 59 | /// Returns the difference between the y value of data point 'pidx' and the |
| 60 | /// y value of the objective function with the given parameters over the x value |
| 61 | /// of the same point. |
| 62 | double GetDeltaY(int pidx, const double* params) const { |
| 63 | DCHECK_LT(pidx, num_points_); |
| 64 | return ys_[pidx] - fn_(xs_[pidx], params); |
| 65 | } |
| 66 | |
| 67 | /// Returns the Chi-Square of fitting. This is an indication of how well the function |
| 68 | /// fits. Lower is better. Valid to call after LmsFit(). |
| 69 | double GetError() const { |
| 70 | DCHECK(params_ != nullptr); |
| 71 | return result_.bestnorm; |
| 72 | } |
| 73 | |
| 74 | private: |
| 75 | /// Human-readable name of this function. Used for debugging. |
| 76 | std::string name_; |
| 77 | |
| 78 | /// Function parameters to be determined by fitting. |
| 79 | const int num_params_; |
| 80 | std::unique_ptr<double[]> params_; |
| 81 | |
| 82 | /// MPFit result structure. Populated by in LmsFit(). All pointers in this structure |
| 83 | /// are optional and must be allocated and owned by the caller of mpfit(). Passing |
| 84 | /// nullptr indicates to MPFit that those fields should not be populated. |
| 85 | mp_result result_; |
| 86 | |
| 87 | /// Objective function whose parameters should be fit to the data points. |
| 88 | std::function<double (double, const double*)> fn_; |
| 89 | |
| 90 | /// Known x/y data points. Memory not owned. |
| 91 | int num_points_; |
| 92 | const double* xs_; |
| 93 | const double* ys_; |
| 94 | }; |
| 95 | |
| 96 | } |
| 97 |