Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
GeneticMinimizer.cxx
Go to the documentation of this file.
2
5
6#include "Math/IFunction.h"
8
9#include "TError.h"
10
11#include <cassert>
12
13namespace ROOT {
14namespace Math {
15
16
17// wrapper class for TMVA interface to evaluate objective function
19private:
20 unsigned int fNCalls;
21 unsigned int fNFree;
23 std::vector<int> fFixedParFlag;
24 mutable std::vector<double> fValues;
25
26public:
28 fFunc(function)
29 { fNFree = fFunc.NDim(); }
30
31 unsigned int NCalls() const { return fNCalls; }
32 unsigned int NDims() const { return fNFree; }
33
34 unsigned int NTotal() const { return fFunc.NDim(); }
35
36 void FixParameter(unsigned int ipar, double value, bool fix = true) {
37
38 if (fValues.size() != fFunc.NDim() ) {
39 fValues.resize(fFunc.NDim() );
40 fFixedParFlag.resize(fFunc.NDim());
41 }
42
43 if (ipar >= fValues.size() ) return;
44
45 // first find if it has been already fixed
46 fFixedParFlag[ipar] = fix;
47 fValues[ipar] = value;
48 // count number of fixed params
49 for (unsigned int i = 0; i < fFixedParFlag.size(); ++i)
50 if (!fFixedParFlag[i] ) fNFree++;
51
52 }
53
54 // transform from internal parameters (not fixed to external vector which include the fixed ones)
55 const std::vector<double> & Transform( const std::vector<double> & factors) const {
56 unsigned int n = fValues.size();
57 if (n == 0 || fNFree == n )
58 return factors;
59
60 // in case of fixed parameters
61 for (unsigned int i = 0, j = 0; i < n ; ++i) {
62 if (!fFixedParFlag[i] ) {
63 assert (j < fNFree);
64 fValues[i] = factors[j];
65 j++;
66 }
67 }
68 return fValues;
69 }
70
71 Double_t Evaluate(const std::vector<double> & factors ) const {
72 const std::vector<double> & x = Transform( factors);
73 return fFunc(&x[0]);
74 }
75
76 Double_t EstimatorFunction(std::vector<double> & factors ) override{
77 fNCalls += 1;
78 return Evaluate( factors);
79 }
80};
81
83{
84 // constructor of parameters with default values (use 100 is max iterations is not defined)
86 fNsteps = (defmaxiter > 0) ? defmaxiter : 100;
87 fPopSize =300;
88 fCycles = 3;
89 fSC_steps =10;
90 fSC_rate =5;
91 fSC_factor=0.95;
93 if (fConvCrit <=0 ) fConvCrit = 0.001;
94 fSeed=0; // random seed
95}
96
97// genetic minimizer class
98
100 fFitness(nullptr),
101 fMinValue(0)
102{
103
104 // check with default minimizer options
106 if (geneticOpt) {
107 ROOT::Math::MinimizerOptions opt; // create using default options
108 opt.SetExtraOptions(*geneticOpt);
109 this->SetOptions(opt);
110 }
111
112 // set the parameters
115 }
116
118{
119 if ( fFitness )
120 {
121 delete fFitness;
122 fFitness = nullptr;
123 }
124}
125
127{
128 fRanges.clear();
129 fResult.clear();
130 if ( fFitness )
131 {
132 delete fFitness;
133 fFitness = nullptr;
134 }
135}
136
138{
139 Clear();
140
142 fResult = std::vector<double>(func.NDim() );
143 assert(fResult.size() == NDim() );
144}
145
146bool GeneticMinimizer::SetLimitedVariable(unsigned int , const std::string & , double , double , double lower , double upper )
147{
148 fRanges.push_back( new TMVA::Interval(lower,upper) );
149
150 return true;
151}
152
153bool GeneticMinimizer::SetVariable(unsigned int, const std::string& name, double value, double step)
154{
155 //It does nothing! As there is no variable if it has no limits!
156 double lower = value - (50 * step);
157 double upper = value + (50 * step);
158 Info("GeneticMinimizer::SetVariable", "Variables should be limited - set automatic range to 50 times step size for %s : [%f, %f]",
159 name.c_str(),lower,upper);
160 fRanges.push_back( new TMVA::Interval(lower, upper ) );
161
162 return true;
163}
164
165bool GeneticMinimizer::SetFixedVariable(unsigned int par, const std::string& name, double value) {
166 // set a fixed variable
167 if (!fFitness) {
168 Error("GeneticMinimizer::SetFixedVariable", "Function has not been set - cannot set fixed variables %s",name.c_str());
169 return false;
170 }
171
172 static_cast<MultiGenFunctionFitness*>(fFitness)->FixParameter(par, value);
173 return true;
174}
175
176
178{
179 fParameters = params;
180 // set also the one defined in Minimizer
183}
184
188 return opt;
189}
190
192 // get the genetic options of the class and return them in the MinimizerOptions class
193 opt.SetTolerance(fParameters.fConvCrit/10); // use a factor of 10 to have default as Minuit
196 // use fixed or dammy value for the other options
197 opt.SetMinimizerType("Genetic");
198 opt.SetMaxFunctionCalls(0);
199 opt.SetStrategy(-1);
200 opt.SetErrorDef(0);
201 opt.SetPrecision(0);
202 opt.SetMinimizerAlgorithm("");
203
205 geneticOpt.SetValue("PopSize",fParameters.fPopSize);
206 geneticOpt.SetValue("Steps",fParameters.fNsteps);
207 geneticOpt.SetValue("Cycles",fParameters.fCycles);
208 geneticOpt.SetValue("SC_steps",fParameters.fSC_steps);
209 geneticOpt.SetValue("SC_rate",fParameters.fSC_rate);
210 geneticOpt.SetValue("SC_factor",fParameters.fSC_factor);
211 geneticOpt.SetValue("ConvCrit",fParameters.fConvCrit);
212 geneticOpt.SetValue("RandomSeed",fParameters.fSeed);
213
214 opt.SetExtraOptions(geneticOpt);
215}
216
218{
219 SetTolerance(opt.Tolerance() );
221 //SetMaxFunctionCalls(opt.MaxFunctionCalls() );
223
224 fParameters.fConvCrit = 10.*opt.Tolerance(); // use a factor of 10 to have default as Minuit
225
226 // set genetic parameter from minimizer options
227 const ROOT::Math::IOptions * geneticOpt = opt.ExtraOptions();
228 if (!geneticOpt) {
229 Warning("GeneticMinimizer::SetOptions", "No specific genetic minimizer options have been set");
230 return;
231 }
232
233 // if options are not existing values will not be set
234 geneticOpt->GetValue("PopSize",fParameters.fPopSize);
235 geneticOpt->GetValue("Steps",fParameters.fNsteps);
236 geneticOpt->GetValue("Cycles",fParameters.fCycles);
237 geneticOpt->GetValue("SC_steps",fParameters.fSC_steps);
238 geneticOpt->GetValue("SC_rate",fParameters.fSC_rate);
239 geneticOpt->GetValue("SC_factor",fParameters.fSC_factor);
240 geneticOpt->GetValue("ConvCrit",fParameters.fConvCrit);
241 geneticOpt->GetValue("RandomSeed",fParameters.fSeed);
242
243 // use same of options in base class
244 int maxiter = opt.MaxIterations();
245 if (maxiter > 0 && fParameters.fNsteps > 0 && maxiter != fParameters.fNsteps ) {
246 Warning("GeneticMinimizer::SetOptions", "max iterations value given different than than Steps - set equal to Steps %d",fParameters.fNsteps);
247 }
249
250}
251
253{
254
255 if (!fFitness) {
256 Error("GeneticMinimizer::Minimize","Fitness function has not been set");
257 return false;
258 }
259
260 // sync parameters
262 if (Tolerance() > 0) fParameters.fConvCrit = 10* Tolerance();
263
265
266 if (PrintLevel() > 0) {
267 std::cout << "GeneticMinimizer::Minimize - Start iterating - max iterations = " << MaxIterations()
268 << " conv criteria (tolerance) = " << fParameters.fConvCrit << std::endl;
269 }
270
271 fStatus = 0;
272 unsigned int niter = 0;
273 do {
274 mg.Init();
275
276 mg.CalculateFitness();
277
278 // Just for debugging options
279 //mg.GetGeneticPopulation().Print(0);
280
282
284
285 if (PrintLevel() > 2) {
286 std::cout << "New Iteration " << niter << " with parameter values :" << std::endl;
288 if (genes) {
289 std::vector<Double_t> gvec;
290 gvec = genes->GetFactors();
291 for (unsigned int i = 0; i < gvec.size(); ++i) {
292 std::cout << gvec[i] << " ";
293 }
294 std::cout << std::endl;
295 std::cout << "\tFitness function value = " << static_cast<MultiGenFunctionFitness*>(fFitness)->Evaluate(gvec) << std::endl;
296 }
297 }
298 niter++;
299 if ( niter > MaxIterations() && MaxIterations() > 0) {
300 if (PrintLevel() > 0) {
301 Info("GeneticMinimizer::Minimize","Max number of iterations %d reached - stop iterating",MaxIterations());
302 }
303 fStatus = 1;
304 break;
305 }
306
307 } while (!mg.HasConverged( fParameters.fNsteps, fParameters.fConvCrit )); // converged if: fitness-improvement < CONVCRIT within the last CONVSTEPS loops
308
310 std::vector<Double_t> gvec;
311 gvec = genes->GetFactors();
312
313
314 // transform correctly gvec on fresult in case there are fixed parameters
315 const std::vector<double> & transVec = static_cast<MultiGenFunctionFitness*>(fFitness)->Transform(gvec);
316 std::copy(transVec.begin(), transVec.end(), fResult.begin() );
317 fMinValue = static_cast<MultiGenFunctionFitness*>(fFitness)->Evaluate(gvec);
318
319
320 if (PrintLevel() > 0) {
321 if (PrintLevel() > 2) std::cout << std::endl;
322 std::cout << "Finished Iteration (niter = " << niter << " with fitness function value = " << MinValue() << std::endl;
323 for (unsigned int i = 0; i < fResult.size(); ++i) {
324 std::cout << " Parameter-" << i << "\t=\t" << fResult[i] << std::endl;
325 }
326 }
327
328 return true;
329}
330
332{
333 return (fFitness) ? fMinValue : 0;
334}
335
336const double * GeneticMinimizer::X() const {
337 return (fFitness) ? &fResult[0] : nullptr;
338}
339
340unsigned int GeneticMinimizer::NCalls() const
341{
342 if ( fFitness )
343 return static_cast<MultiGenFunctionFitness*>(fFitness)->NCalls();
344 else
345 return 0;
346}
347
348unsigned int GeneticMinimizer::NDim() const
349{
350 if ( fFitness )
351 return static_cast<MultiGenFunctionFitness*>(fFitness)->NTotal();
352 else
353 return 0;
354}
355unsigned int GeneticMinimizer::NFree() const
356{
357 if ( fFitness )
358 return static_cast<MultiGenFunctionFitness*>(fFitness)->NDims();
359 else
360 return 0;
361}
362
363// Functions we don't need...
364const double * GeneticMinimizer::MinGradient() const { return nullptr; }
365bool GeneticMinimizer::ProvidesError() const { return false; }
366const double * GeneticMinimizer::Errors() const { return nullptr; }
367double GeneticMinimizer::Edm() const { return 0; }
368double GeneticMinimizer::CovMatrix(unsigned int, unsigned int) const { return 0; }
369
370}
371}
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:218
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:229
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:110
class implementing generic options for a numerical algorithm Just store the options in a map of strin...
const double * X() const override
return pointer to X values at the minimum
unsigned int NDim() const override
this is <= Function().NDim() which is the total number of variables (free+ constrained ones)
double CovMatrix(unsigned int i, unsigned int j) const override
return covariance matrices element for variables ivar,jvar if the variable is fixed the return value ...
unsigned int NFree() const override
number of free variables (real dimension of the problem) this is <= Function().NDim() which is the to...
bool SetLimitedVariable(unsigned int, const std::string &, double, double, double, double) override
set a new upper/lower limited variable (override if minimizer supports them ) otherwise as default se...
virtual void SetOptions(const ROOT::Math::MinimizerOptions &opt)
double MinValue() const override
return minimum function value
const double * Errors() const override
return errors at the minimum
unsigned int NCalls() const override
number of function calls to reach the minimum
bool Minimize() override
method to perform the minimization
void GetGeneticOptions(ROOT::Math::MinimizerOptions &opt) const
bool ProvidesError() const override
minimizer provides error and error matrix
bool SetVariable(unsigned int ivar, const std::string &name, double val, double step) override
set a new free variable
std::vector< double > fResult
TMVA::IFitterTarget * fFitness
std::vector< TMVA::Interval * > fRanges
void SetParameters(const GeneticMinimizerParameters &params)
const double * MinGradient() const override
return pointer to gradient values at the minimum
double Edm() const override
return expected distance reached from the minimum (re-implement if minimizer provides it
void Clear() override
reset for consecutive minimization - implement if needed
ROOT::Math::MinimizerOptions Options() const override
retrieve the minimizer options (implement derived class if needed)
GeneticMinimizerParameters fParameters
void SetFunction(const ROOT::Math::IMultiGenFunction &func) override
set the function to minimize
bool SetFixedVariable(unsigned int ivar, const std::string &name, double val) override
set a new fixed variable (override if minimizer supports them )
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:61
virtual unsigned int NDim() const =0
Retrieve the dimension of the function.
Generic interface for defining configuration options of a numerical algorithm.
Definition IOptions.h:28
void SetValue(const char *name, double val)
generic methods for retrieving options
Definition IOptions.h:42
bool GetValue(const char *name, T &t) const
Definition IOptions.h:54
void SetMaxFunctionCalls(unsigned int maxfcn)
set maximum of function calls
void SetStrategy(int stra)
set the strategy
void SetMaxIterations(unsigned int maxiter)
set maximum iterations (one iteration can have many function calls)
const IOptions * ExtraOptions() const
return extra options (NULL pointer if they are not present)
static ROOT::Math::IOptions * FindDefault(const char *name)
Find an extra options and return a nullptr if it is not existing.
double Tolerance() const
absolute tolerance
void SetMinimizerType(const char *type)
set minimizer type
void SetExtraOptions(const IOptions &opt)
set extra options (in this case pointer is cloned)
unsigned int MaxIterations() const
max iterations
void SetPrecision(double prec)
set the precision
int PrintLevel() const
non-static methods for retrieving options
void SetErrorDef(double err)
set error def
void SetPrintLevel(int level)
set print level
void SetMinimizerAlgorithm(const char *type)
set minimizer algorithm
void SetTolerance(double tol)
set the tolerance
double Tolerance() const
absolute tolerance
Definition Minimizer.h:300
void SetMaxIterations(unsigned int maxiter)
set maximum iterations (one iteration can have many function calls)
Definition Minimizer.h:334
int fStatus
status of minimizer
Definition Minimizer.h:371
unsigned int MaxIterations() const
max iterations
Definition Minimizer.h:297
void SetTolerance(double tol)
set the tolerance
Definition Minimizer.h:337
void SetPrintLevel(int level)
set print level
Definition Minimizer.h:328
int PrintLevel() const
minimizer configuration parameters
Definition Minimizer.h:291
Double_t EstimatorFunction(std::vector< double > &factors) override
MultiGenFunctionFitness(const ROOT::Math::IMultiGenFunction &function)
void FixParameter(unsigned int ipar, double value, bool fix=true)
const ROOT::Math::IMultiGenFunction & fFunc
const std::vector< double > & Transform(const std::vector< double > &factors) const
Double_t Evaluate(const std::vector< double > &factors) const
Base definition for genetic algorithm.
virtual Double_t SpreadControl(Int_t steps, Int_t ofSteps, Double_t factor)
this function provides the ability to change the stepSize of a mutation according to the success of t...
virtual Bool_t HasConverged(Int_t steps=10, Double_t ratio=0.1)
gives back true if the last "steps" steps have lead to an improvement of the "fitness" of the "indivi...
GeneticPopulation & GetGeneticPopulation()
void Init()
calls evolution, but if it is not the first time.
virtual Double_t CalculateFitness()
starts the evaluation of the fitness of all different individuals of the population.
Cut optimisation interface class for genetic algorithm.
std::vector< Double_t > & GetFactors()
void TrimPopulation()
trim the population to the predefined size
GeneticGenes * GetGenes(Int_t index)
gives back the "Genes" of the population with the given index.
Interface for a fitter 'target'.
The TMVA::Interval Class.
Definition Interval.h:61
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
Namespace for new Math classes and functions.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...