File: optimizers.i

package info (click to toggle)
quantlib-swig 1.40-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,276 kB
  • sloc: python: 6,024; java: 1,552; cs: 774; makefile: 309; sh: 22
file content (411 lines) | stat: -rw-r--r-- 11,332 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2003, 2004, 2005, 2006 StatPro Italia srl
 Copyright (C) 2005 Dominic Thuillier
 Copyright (C) 2015 Klaus Spanderen
 Copyright (C) 2018, 2019 Matthias Lungwitz

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <https://www.quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_optimizers_i
#define quantlib_optimizers_i

%include functions.i
%include linearalgebra.i
%include stl.i

// 1D Solvers

%{
using QuantLib::Bisection;
using QuantLib::Brent;
using QuantLib::FalsePosition;
using QuantLib::Newton;
using QuantLib::NewtonSafe;
using QuantLib::Ridder;
using QuantLib::Secant;
%}

%define DeclareSolver(SolverName)
class SolverName {
  public:
    void setMaxEvaluations(Size evaluations);
    void setLowerBound(Real lowerBound);
    void setUpperBound(Real upperBound);
    %extend {
        #if defined(SWIGPYTHON)
        Real solve(PyObject* function, Real xAccuracy,
                   Real guess, Real step) {
            UnaryFunction f(function);
            return self->solve(f, xAccuracy, guess, step);
        }
        Real solve(PyObject* function, Real xAccuracy,
                   Real guess, Real xMin, Real xMax) {
            UnaryFunction f(function);
            return self->solve(f, xAccuracy, guess, xMin, xMax);
        }
        #elif defined(SWIGJAVA) || defined(SWIGCSHARP)
        Real solve(UnaryFunctionDelegate* function, Real xAccuracy,
                   Real guess, Real step) {
            UnaryFunction f(function);
            return self->solve(f, xAccuracy, guess, step);
        }
        Real solve(UnaryFunctionDelegate* function, Real xAccuracy,
                   Real guess, Real xMin, Real xMax) {
            UnaryFunction f(function);
            return self->solve(f, xAccuracy, guess, xMin, xMax);
        }
        #endif
    }
};
%enddef


// Keep this list in sync with bondfunctions.i yield solvers.
// Actual solvers
DeclareSolver(Brent);
DeclareSolver(Bisection);
DeclareSolver(FalsePosition);
DeclareSolver(Ridder);
DeclareSolver(Secant);

#if defined(SWIGPYTHON)
// these two need f.derivative()
DeclareSolver(Newton);
DeclareSolver(NewtonSafe);
#elif defined(SWIGJAVA) || defined(SWIGCSHARP)
%{
class NFunctAndDer {
  public:
    NFunctAndDer(const UnaryFunction& function,
                 const UnaryFunction& derivative)
    : f_(function), d_(derivative) {}
           
    Real operator()(Real x) const { return f_(x); }
    Real derivative(Real x) const { return d_(x); }
  private:          
    UnaryFunction f_, d_;
};
%}
%ignore NFunctAndDer;

%define DeclareJavaNewtonSolver(SolverName)
class SolverName {
  public:
    void setMaxEvaluations(Size evaluations);
    void setLowerBound(Real lowerBound);
    void setUpperBound(Real upperBound);
    %extend {
        Real solve(UnaryFunctionDelegate* function,
                   UnaryFunctionDelegate* derivative,
                   Real xAccuracy, Real guess, Real step) {
            UnaryFunction f(function), d(derivative);            
            return self->solve(NFunctAndDer(f, d), xAccuracy, guess, step);
        }
        Real solve(UnaryFunctionDelegate* function,
                   UnaryFunctionDelegate* derivative,         
                   Real xAccuracy, Real guess, Real xMin, Real xMax) {
            UnaryFunction f(function), d(derivative);            
            return self->solve(NFunctAndDer(f, d), xAccuracy, guess, xMin, xMax);
        }
    }
};
%enddef

DeclareJavaNewtonSolver(Newton);
DeclareJavaNewtonSolver(NewtonSafe);
#endif


// Optimizers

%{
using QuantLib::Constraint;
using QuantLib::BoundaryConstraint;
using QuantLib::NoConstraint;
using QuantLib::PositiveConstraint;
using QuantLib::CompositeConstraint;
using QuantLib::NonhomogeneousBoundaryConstraint;
%}

%shared_ptr(Constraint)
class Constraint {
    // prevent direct instantiation
  private:
    Constraint();
};

%shared_ptr(BoundaryConstraint)
class BoundaryConstraint : public Constraint {
  public:
    BoundaryConstraint(Real lower, Real upper);
};

%shared_ptr(NoConstraint)
class NoConstraint : public Constraint {
  public:
    NoConstraint();
};

%shared_ptr(PositiveConstraint)
class PositiveConstraint : public Constraint {
  public:
    PositiveConstraint();
};

%shared_ptr(CompositeConstraint)
class CompositeConstraint : public Constraint {
  public:
    CompositeConstraint(const Constraint& c1, const Constraint& c2);
};

%shared_ptr(NonhomogeneousBoundaryConstraint)
class NonhomogeneousBoundaryConstraint : public Constraint {
  public:
    NonhomogeneousBoundaryConstraint(const Array& l, const Array& u);
};

%{
using QuantLib::EndCriteria;
%}

%shared_ptr(EndCriteria)
class EndCriteria {
    #if defined(SWIGCSHARP)
    %rename(call) operator();
    #elif defined(SWIGPYTHON)
    %rename(NoCriteria) None;
    #endif
  public:
    enum Type {
        None,
        MaxIterations,
        StationaryPoint,
        StationaryFunctionValue,
        StationaryFunctionAccuracy,
        ZeroGradientNorm,
        FunctionEpsilonTooSmall,
        Unknown
    };
    EndCriteria(Size maxIteration,
                Size maxStationaryStateIterations,
                Real rootEpsilon,
                Real functionEpsilon,
                Real gradientNormEpsilon);

    static bool succeeded(EndCriteria::Type ecType);
};


%{
using QuantLib::OptimizationMethod;
using QuantLib::ConjugateGradient;
using QuantLib::Simplex;
using QuantLib::SteepestDescent;
using QuantLib::BFGS;
using QuantLib::LevenbergMarquardt;
using QuantLib::DifferentialEvolution;
using QuantLib::SamplerGaussian;
using QuantLib::SamplerLogNormal;
using QuantLib::SamplerMirrorGaussian;
using QuantLib::ProbabilityBoltzmannDownhill;
using QuantLib::TemperatureExponential;
using QuantLib::ReannealingTrivial;
using QuantLib::GaussianSimulatedAnnealing;
using QuantLib::MirrorGaussianSimulatedAnnealing;
using QuantLib::LogNormalSimulatedAnnealing;

%}

%shared_ptr(OptimizationMethod)
class OptimizationMethod {
  private:
    // prevent direct instantiation
    OptimizationMethod();
};

%shared_ptr(ConjugateGradient)
class ConjugateGradient : public OptimizationMethod {
  public:
    ConjugateGradient();
};

%shared_ptr(Simplex)
class Simplex : public OptimizationMethod {
  public:
    Simplex(Real lambda);
    #if defined(SWIGPYTHON)
    %rename(getLambda) lambda;
    #endif
    Real lambda();
};

%shared_ptr(SteepestDescent)
class SteepestDescent : public OptimizationMethod {
  public:
    SteepestDescent();
};

%shared_ptr(BFGS)
class BFGS : public OptimizationMethod {
  public:
    BFGS();
};

%shared_ptr(LevenbergMarquardt)
class LevenbergMarquardt : public OptimizationMethod {
  public:
    LevenbergMarquardt(Real epsfcn = 1.0e-8,
                       Real xtol = 1.0e-8,
                       Real gtol = 1.0e-8,
                       bool useCostFunctionsJacobian = false);
};

%shared_ptr(DifferentialEvolution)
class DifferentialEvolution : public OptimizationMethod {
  public:
    DifferentialEvolution();
};

class SamplerGaussian{
  public:
    SamplerGaussian(unsigned long seed = 0);
};

class SamplerLogNormal{
  public:
    SamplerLogNormal(unsigned long seed = 0);
};

class SamplerMirrorGaussian{
  public:
    SamplerMirrorGaussian(const Array& lower, const Array& upper, unsigned long seed = 0);
};

class ProbabilityBoltzmannDownhill{
  public:
    ProbabilityBoltzmannDownhill(unsigned long seed = 0);
};

class TemperatureExponential {
  public:
    TemperatureExponential(Real initialTemp, Size dimension, Real power = 0.95);
};

class ReannealingTrivial {
  public:
    ReannealingTrivial();
};

%shared_ptr(GaussianSimulatedAnnealing)
class GaussianSimulatedAnnealing : public OptimizationMethod {
  public:
    enum ResetScheme{
        NoResetScheme,
        ResetToBestPoint,
        ResetToOrigin
    };
    GaussianSimulatedAnnealing(const SamplerGaussian &sampler,
            const ProbabilityBoltzmannDownhill &probability,
            const TemperatureExponential &temperature,
            const ReannealingTrivial &reannealing = ReannealingTrivial(),
            Real startTemperature = 200.0,
            Real endTemperature = 0.01,
            Size reAnnealSteps = 50,
            ResetScheme resetScheme = ResetToBestPoint,
            Size resetSteps = 150);
};

%shared_ptr(MirrorGaussianSimulatedAnnealing)
class MirrorGaussianSimulatedAnnealing : public OptimizationMethod {
  public:
    enum ResetScheme{
        NoResetScheme,
        ResetToBestPoint,
        ResetToOrigin
    };
    MirrorGaussianSimulatedAnnealing(const SamplerMirrorGaussian &sampler,
            const ProbabilityBoltzmannDownhill &probability,
            const TemperatureExponential &temperature,
            const ReannealingTrivial &reannealing = ReannealingTrivial(),
            Real startTemperature = 200.0,
            Real endTemperature = 0.01,
            Size reAnnealSteps = 50,
            ResetScheme resetScheme = ResetToBestPoint,
            Size resetSteps = 150);
};

%shared_ptr(LogNormalSimulatedAnnealing)
class LogNormalSimulatedAnnealing : public OptimizationMethod {
  public:
   enum ResetScheme{
        NoResetScheme,
        ResetToBestPoint,
        ResetToOrigin
    };
    LogNormalSimulatedAnnealing(const SamplerLogNormal &sampler,
            const ProbabilityBoltzmannDownhill &probability,
            const TemperatureExponential &temperature,
            const ReannealingTrivial &reannealing = ReannealingTrivial(),
            Real startTemperature = 10.0,
            Real endTemperature = 0.01,
            Size reAnnealSteps = 50,
            ResetScheme resetScheme = ResetToBestPoint,
            Size resetSteps = 150);
};

%{
using QuantLib::Problem;
%}

%inline %{
    class Optimizer {};
%}

#if defined(SWIGPYTHON)
%extend Optimizer {
    Array solve(PyObject* function, Constraint& c,
                OptimizationMethod& m, EndCriteria &e,
                Array &iv) {
        PyCostFunction f(function);
        Problem p(f,c,iv);
        m.minimize(p, e);
        return p.currentValue();
    }
}
#elif defined(SWIGJAVA)
%extend Optimizer {
    Array solve(CostFunctionDelegate* function,
                Constraint& c, OptimizationMethod& m,
                EndCriteria &e, Array &iv) {
        JavaCostFunction f(function);
        Problem p(f,c,iv);
        m.minimize(p, e);
        return p.currentValue();
    }
}
#elif defined(SWIGCSHARP)
%extend Optimizer {
    Array solve(CostFunctionDelegate* function,
                Constraint& c, OptimizationMethod& m,
                EndCriteria &e, Array &iv) {
        DotNetCostFunction f(function);
        Problem p(f,c,iv);
        m.minimize(p, e);
        return p.currentValue();
    }
}
#endif
#endif