Coverage Report

Created: 2026-01-25 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/quantlib/ql/math/optimization/leastsquare.hpp
Line
Count
Source
1
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3
/*
4
 Copyright (C) 2001, 2002, 2003 Nicolas Di Césaré
5
 Copyright (C) 2005, 2007 StatPro Italia srl
6
7
 This file is part of QuantLib, a free-software/open-source library
8
 for financial quantitative analysts and developers - http://quantlib.org/
9
10
 QuantLib is free software: you can redistribute it and/or modify it
11
 under the terms of the QuantLib license.  You should have received a
12
 copy of the license along with this program; if not, please email
13
 <quantlib-dev@lists.sf.net>. The license is also available online at
14
 <https://www.quantlib.org/license.shtml>.
15
16
 This program is distributed in the hope that it will be useful, but WITHOUT
17
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18
 FOR A PARTICULAR PURPOSE.  See the license for more details.
19
*/
20
21
/*! \file leastsquare.hpp
22
    \brief Least square cost function
23
*/
24
25
#ifndef quantlib_least_square_hpp
26
#define quantlib_least_square_hpp
27
28
#include <ql/math/optimization/problem.hpp>
29
#include <ql/math/optimization/conjugategradient.hpp>
30
#include <ql/math/matrix.hpp>
31
32
namespace QuantLib {
33
34
    class Constraint;
35
    class OptimizationMethod;
36
37
    //! Base class for least square problem
38
    class LeastSquareProblem {
39
      public:
40
0
        virtual ~LeastSquareProblem() = default;
41
        //! size of the problem ie size of target vector
42
        virtual Size size() = 0;
43
        //! compute the target vector and the values of the function to fit
44
        virtual void targetAndValue(const Array& x,
45
                                    Array& target,
46
                                    Array& fct2fit) = 0;
47
        /*! compute the target vector, the values of the function to fit
48
            and the matrix of derivatives
49
        */
50
        virtual void targetValueAndGradient(const Array& x,
51
                                            Matrix& grad_fct2fit,
52
                                            Array& target,
53
                                            Array& fct2fit) = 0;
54
    };
55
56
    //! Cost function for least-square problems
57
    /*! Implements a cost function using the interface provided by
58
        the LeastSquareProblem class.
59
    */
60
    class LeastSquareFunction : public CostFunction {
61
      public:
62
        //! Default constructor
63
0
        LeastSquareFunction(LeastSquareProblem& lsp) : lsp_(lsp) {}
64
        //! Destructor
65
        ~LeastSquareFunction() override = default;
66
67
        //! compute value of the least square function
68
        Real value(const Array& x) const override;
69
        Array values(const Array&) const override;
70
        //! compute vector of derivatives of the least square function
71
        void gradient(Array& grad_f, const Array& x) const override;
72
        //! compute value and gradient of the least square function
73
        Real valueAndGradient(Array& grad_f, const Array& x) const override;
74
75
      protected:
76
        //! least square problem
77
        LeastSquareProblem &lsp_;
78
    };
79
80
    //! Non-linear least-square method.
81
    /*! Using a given optimization algorithm (default is conjugate
82
        gradient),
83
84
        \f[ min \{ r(x) : x in R^n \} \f]
85
86
        where \f$ r(x) = |f(x)|^2 \f$ is the Euclidean norm of \f$
87
        f(x) \f$ for some vector-valued function \f$ f \f$ from
88
        \f$ R^n \f$ to \f$ R^m \f$,
89
        \f[ f = (f_1, ..., f_m) \f]
90
        with \f$ f_i(x) = b_i - \phi(x,t_i) \f$ where \f$ b \f$ is the
91
        vector of target data and \f$ phi \f$ is a scalar function.
92
93
        Assuming the differentiability of \f$ f \f$, the gradient of
94
        \f$ r \f$ is defined by
95
        \f[ grad r(x) = f'(x)^t.f(x) \f]
96
    */
97
    class NonLinearLeastSquare {
98
      public:
99
        //! Default constructor
100
        NonLinearLeastSquare(Constraint& c,
101
                             Real accuracy = 1e-4,
102
                             Size maxiter = 100);
103
        //! Default constructor
104
        NonLinearLeastSquare(Constraint& c,
105
                             Real accuracy,
106
                             Size maxiter,
107
                             ext::shared_ptr<OptimizationMethod> om);
108
        //! Destructor
109
0
        ~NonLinearLeastSquare() = default;
110
111
        //! Solve least square problem using numerix solver
112
        Array& perform(LeastSquareProblem& lsProblem);
113
114
0
        void setInitialValue(const Array& initialValue) {
115
0
            initialValue_ = initialValue;
116
0
        }
117
118
        //! return the results
119
0
        Array& results() { return results_; }
120
121
        //! return the least square residual norm
122
0
        Real residualNorm() const { return resnorm_; }
123
124
        //! return last function value
125
0
        Real lastValue() const { return bestAccuracy_; }
126
127
        //! return exit flag
128
0
        Integer exitFlag() const { return exitFlag_; }
129
130
        //! return the performed number of iterations
131
0
        Integer iterationsNumber() const { return nbIterations_; }
132
133
      private:
134
        //! solution vector
135
        Array results_, initialValue_;
136
        //! least square residual norm
137
        Real resnorm_;
138
        //! Exit flag of the optimization process
139
        Integer exitFlag_;
140
        //! required accuracy of the solver
141
        Real accuracy_, bestAccuracy_;
142
        //! maximum and real number of iterations
143
        Size maxIterations_, nbIterations_;
144
        //! Optimization method
145
        ext::shared_ptr<OptimizationMethod> om_;
146
        //constraint
147
        Constraint& c_;
148
149
    };
150
151
}
152
153
#endif