Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
GeneticPopulation.cxx
Go to the documentation of this file.
1// @(#)root/tmva $Id$
2// Author: Peter Speckmayer
3
4/**********************************************************************************
5 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
6 * Package: TMVA *
7 * Class : TMVA::GeneticPopulation *
8 * *
9 * *
10 * Description: *
11 * Implementation (see header for description) *
12 * *
13 * Authors (alphabetical): *
14 * Peter Speckmayer <speckmay@mail.cern.ch> - CERN, Switzerland *
15 * *
16 * Copyright (c) 2005: *
17 * CERN, Switzerland *
18 * MPI-K Heidelberg, Germany *
19 * *
20 * Redistribution and use in source and binary forms, with or without *
21 * modification, are permitted according to the terms listed in LICENSE *
22 * (see tmva/doc/LICENSE) *
23 **********************************************************************************/
24
25/*! \class TMVA::GeneticPopulation
26\ingroup TMVA
27
28Population definition for genetic algorithm.
29
30*/
31
32#include "TRandom3.h"
33#include "TH1.h"
34
36#include "TMVA/GeneticGenes.h"
37#include "TMVA/MsgLogger.h"
38
39#include <sstream>
40
41using std::vector, std::ostream;
42
43////////////////////////////////////////////////////////////////////////////////
44/// Constructor
45
46TMVA::GeneticPopulation::GeneticPopulation(const std::vector<Interval*>& ranges, Int_t size, UInt_t seed)
47 : fGenePool(size),
48 fRanges(ranges.size()),
49 fLogger( new MsgLogger("GeneticPopulation") )
50{
51 // create a randomGenerator for this population and set a seed
52 // create the genePools
53 //
54 fRandomGenerator = new TRandom3( 100 ); //please check
57
58 for ( unsigned int i = 0; i < ranges.size(); ++i )
59 fRanges[i] = new TMVA::GeneticRange( fRandomGenerator, ranges[i] );
60
62 for ( int i = 0; i < size; ++i )
63 {
64 for ( unsigned int rIt = 0; rIt < fRanges.size(); ++rIt )
65 newEntry[rIt] = fRanges[rIt]->Random();
67 }
68
70}
71
72////////////////////////////////////////////////////////////////////////////////
73/// destructor
74
76{
77 if (fRandomGenerator != NULL) delete fRandomGenerator;
78
79 std::vector<GeneticRange*>::iterator it = fRanges.begin();
80 for (;it!=fRanges.end(); ++it) delete *it;
81
82 delete fLogger;
83}
84
85
86
87////////////////////////////////////////////////////////////////////////////////
88/// the random seed of the random generator
89
91{
92 fRandomGenerator->SetSeed( seed );
93}
94
95////////////////////////////////////////////////////////////////////////////////
96/// Produces offspring which is are copies of their parents.
97///
98/// Parameters:
99/// - int number : the number of the last individual to be copied
100
102{
103 int i=0;
104 for (std::vector<TMVA::GeneticGenes>::iterator it = fGenePool.begin();
105 it != fGenePool.end() && i < number;
106 ++it, ++i ) {
107 GiveHint( it->GetFactors(), it->GetFitness() );
108 }
109}
110
111////////////////////////////////////////////////////////////////////////////////
112/// Creates children out of members of the current generation.
113///
114/// Children have a combination of the coefficients of their parents
115
117{
118#ifdef _GLIBCXX_PARALLEL
119#pragma omp parallel
120#pragma omp for
121#endif
122 for ( int it = 0; it < (int) (fGenePool.size() / 2); ++it )
123 {
124 Int_t pos = (Int_t)fRandomGenerator->Integer( fGenePool.size()/2 );
125 fGenePool[(fGenePool.size() / 2) + it] = MakeSex( fGenePool[it], fGenePool[pos] );
126 }
127}
128
129////////////////////////////////////////////////////////////////////////////////
130/// this function takes two individuals and produces offspring by mixing
131/// (recombining) their coefficients.
132
135{
136 vector< Double_t > child(fRanges.size());
137 for (unsigned int i = 0; i < fRanges.size(); ++i) {
138 if (fRandomGenerator->Integer( 2 ) == 0) {
139 child[i] = male.GetFactors()[i];
140 }else{
141 child[i] = female.GetFactors()[i];
142 }
143 }
144 return TMVA::GeneticGenes( child );
145}
146
147////////////////////////////////////////////////////////////////////////////////
148/// Mutates the individuals in the genePool.
149///
150/// Parameters:
151///
152/// - double probability : gives the probability (in percent) of a mutation of a coefficient
153/// - int startIndex : leaves unchanged (without mutation) the individuals which are better ranked
154/// than indicated by "startIndex". This means: if "startIndex==3", the first (and best)
155/// three individuals are not mutated. This allows to preserve the best result of the
156/// current Generation for the next generation.
157/// - Bool_t near : if true, the mutation will produce a new coefficient which is "near" the old one
158/// (gaussian around the current value)
159/// - double spread : if near==true, spread gives the sigma of the gaussian
160/// - Bool_t mirror : if the new value obtained would be outside of the given constraints
161/// the value is mapped between the constraints again. This can be done either
162/// by a kind of periodic boundary conditions or mirrored at the boundary.
163/// (mirror = true seems more "natural")
164
167{
168 vector< Double_t>::iterator vec;
169 vector< TMVA::GeneticRange* >::iterator vecRange;
170
171 //#ifdef _GLIBCXX_PARALLEL
172 // #pragma omp parallel
173 // #pragma omp for
174 //#endif
175 // The range methods are not thread safe!
176 for (int it = startIndex; it < (int) fGenePool.size(); ++it) {
177 vecRange = fRanges.begin();
178 for (vec = (fGenePool[it].GetFactors()).begin(); vec < (fGenePool[it].GetFactors()).end(); ++vec) {
179 if (fRandomGenerator->Uniform( 100 ) <= probability) {
180 (*vec) = (*vecRange)->Random( near, (*vec), spread, mirror );
181 }
182 ++vecRange;
183 }
184 }
185}
186
187
188////////////////////////////////////////////////////////////////////////////////
189/// gives back the "Genes" of the population with the given index.
190
195
196////////////////////////////////////////////////////////////////////////////////
197/// make a little printout of the individuals up to index "untilIndex"
198/// this means, .. write out the best "untilIndex" individuals.
199
201{
202 for ( unsigned int it = 0; it < fGenePool.size(); ++it )
203 {
204 Int_t n=0;
205 if (untilIndex >= -1 ) {
206 if (untilIndex == -1 ) return;
207 untilIndex--;
208 }
209 Log() << "fitness: " << fGenePool[it].GetFitness() << " ";
210 for (vector< Double_t >::iterator vec = fGenePool[it].GetFactors().begin();
211 vec < fGenePool[it].GetFactors().end(); ++vec ) {
212 Log() << "f_" << n++ << ": " << (*vec) << " ";
213 }
214 Log() << Endl;
215 }
216}
217
218////////////////////////////////////////////////////////////////////////////////
219/// make a little printout to the stream "out" of the individuals up to index "untilIndex"
220/// this means, .. write out the best "untilIndex" individuals.
221
223{
224 for ( unsigned int it = 0; it < fGenePool.size(); ++it ) {
225 Int_t n=0;
226 if (untilIndex >= -1 ) {
227 if (untilIndex == -1 ) return;
228 untilIndex--;
229 }
230 out << "fitness: " << fGenePool[it].GetFitness() << " ";
231 for (vector< Double_t >::iterator vec = fGenePool[it].GetFactors().begin();
232 vec < fGenePool[it].GetFactors().end(); ++vec ) {
233 out << "f_" << n++ << ": " << (*vec) << " ";
234 }
235 out << std::endl;
236 }
237}
238
239////////////////////////////////////////////////////////////////////////////////
240/// give back a histogram with the distribution of the coefficients.
241///
242/// Parameters:
243///
244/// - int bins : number of bins of the histogram
245/// - int min : histogram minimum
246/// - int max : maximum value of the histogram
247
249 Int_t min, Int_t max )
250{
251 std::cout << "FAILED! TMVA::GeneticPopulation::VariableDistribution" << std::endl;
252
253 std::stringstream histName;
254 histName.clear();
255 histName.str("v");
256 histName << varNumber;
257 TH1F *hist = new TH1F( histName.str().c_str(),histName.str().c_str(), bins,min,max );
258
259 return hist;
260}
261
262////////////////////////////////////////////////////////////////////////////////
263/// gives back all the values of coefficient "varNumber" of the current generation
264
266{
267 std::cout << "FAILED! TMVA::GeneticPopulation::VariableDistribution" << std::endl;
268
269 vector< Double_t > varDist;
270
271 return varDist;
272}
273
274////////////////////////////////////////////////////////////////////////////////
275/// add another population (strangers) to the one of this GeneticPopulation
276
278{
279 for (std::vector<TMVA::GeneticGenes>::iterator it = strangers->fGenePool.begin();
280 it != strangers->fGenePool.end(); ++it ) {
281 GiveHint( it->GetFactors(), it->GetFitness() );
282 }
283}
284
285////////////////////////////////////////////////////////////////////////////////
286/// add another population (strangers) to the one of this GeneticPopulation
287
292
293////////////////////////////////////////////////////////////////////////////////
294/// trim the population to the predefined size
295
297{
298 std::sort(fGenePool.begin(), fGenePool.end());
299 while ( fGenePool.size() > (unsigned int) fPopulationSizeLimit )
300 fGenePool.pop_back();
301}
302
303////////////////////////////////////////////////////////////////////////////////
304/// add an individual (a set of variables) to the population
305/// if there is a set of variables which is known to perform good, they can be given as a hint to the population
306
308{
310 g.SetFitness(fitness);
311
312 fGenePool.push_back( g );
313}
314
315////////////////////////////////////////////////////////////////////////////////
316/// sort the genepool according to the fitness of the individuals
317
319{
320 std::sort(fGenePool.begin(), fGenePool.end());
321}
322
#define g(i)
Definition RSha256.hxx:105
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t child
const_iterator begin() const
const_iterator end() const
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:878
Cut optimisation interface class for genetic algorithm.
Population definition for genetic algorithm.
void Mutate(Double_t probability=20, Int_t startIndex=0, Bool_t near=kFALSE, Double_t spread=0.1, Bool_t mirror=kFALSE)
Mutates the individuals in the genePool.
virtual ~GeneticPopulation()
destructor
std::vector< TMVA::GeneticRange * > fRanges
contains the ranges in between the values of the coefficients have to be
TRandom3 * fRandomGenerator
random Generator for this population
void Sort()
sort the genepool according to the fitness of the individuals
void MakeCopies(int number)
Produces offspring which is are copies of their parents.
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.
GeneticPopulation(const std::vector< TMVA::Interval * > &ranges, Int_t size, UInt_t seed=0)
Constructor.
void Print(Int_t untilIndex=-1)
make a little printout of the individuals up to index "untilIndex" this means, .
void MakeChildren()
Creates children out of members of the current generation.
void GiveHint(std::vector< Double_t > &hint, Double_t fitness=0)
add an individual (a set of variables) to the population if there is a set of variables which is know...
std::vector< TMVA::GeneticGenes > fGenePool
the "genePool" where the individuals of the current generation are stored
void AddPopulation(GeneticPopulation *strangers)
add another population (strangers) to the one of this GeneticPopulation
void SetRandomSeed(UInt_t seed=0)
the random seed of the random generator
GeneticGenes MakeSex(GeneticGenes male, GeneticGenes female)
this function takes two individuals and produces offspring by mixing (recombining) their coefficients...
TH1F * VariableDistribution(Int_t varNumber, Int_t bins, Int_t min, Int_t max)
give back a histogram with the distribution of the coefficients.
Range definition for genetic algorithm.
ostringstream derivative to redirect and format output
Definition MsgLogger.h:57
Random number generator class based on M.
Definition TRandom3.h:27
void SetSeed(ULong_t seed=0) override
Set the random generator sequence.
Definition TRandom3.cxx:229
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
Definition TRandom.cxx:681
const Int_t n
Definition legend1.C:16
MsgLogger & Endl(MsgLogger &ml)
Definition MsgLogger.h:148