Logo ROOT   6.08/07
Reference Guide
DataSetFactory.cxx
Go to the documentation of this file.
1 // @(#)root/tmva $Id$
2 // Author: Andreas Hoecker, Peter Speckmayer, Joerg Stelzer, Eckhard von Toerne, Helge Voss
3 
4 /*****************************************************************************
5  * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
6  * Package: TMVA *
7  * Class : DataSetFactory *
8  * Web : http://tmva.sourceforge.net *
9  * *
10  * Description: *
11  * Implementation (see header for description) *
12  * *
13  * Authors (alphabetical): *
14  * Andreas Hoecker <Andreas.Hocker@cern.ch> - CERN, Switzerland *
15  * Peter Speckmayer <Peter.Speckmayer@cern.ch> - CERN, Switzerland *
16  * Joerg Stelzer <Joerg.Stelzer@cern.ch> - MSU, USA *
17  * Eckhard von Toerne <evt@physik.uni-bonn.de> - U. of Bonn, Germany *
18  * Helge Voss <Helge.Voss@cern.ch> - MPI-K Heidelberg, Germany *
19  * *
20  * Copyright (c) 2009: *
21  * CERN, Switzerland *
22  * MPI-K Heidelberg, Germany *
23  * U. of Bonn, Germany *
24  * Redistribution and use in source and binary forms, with or without *
25  * modification, are permitted according to the terms listed in LICENSE *
26  * (http://tmva.sourceforge.net/LICENSE) *
27  *****************************************************************************/
28 
29 #include <assert.h>
30 
31 #include <map>
32 #include <vector>
33 #include <iomanip>
34 #include <iostream>
35 
36 #include <algorithm>
37 #include <functional>
38 #include <numeric>
39 
40 #include "TMVA/DataSetFactory.h"
41 
42 #include "TEventList.h"
43 #include "TFile.h"
44 #include "TH1.h"
45 #include "TH2.h"
46 #include "TProfile.h"
47 #include "TRandom3.h"
48 #include "TMatrixF.h"
49 #include "TVectorF.h"
50 #include "TMath.h"
51 #include "TROOT.h"
52 
53 #ifndef ROOT_TMVA_MsgLogger
54 #include "TMVA/MsgLogger.h"
55 #endif
56 #ifndef ROOT_TMVA_Configurable
57 #include "TMVA/Configurable.h"
58 #endif
59 #ifndef ROOT_TMVA_VariableIdentityTransform
61 #endif
62 #ifndef ROOT_TMVA_VariableDecorrTransform
64 #endif
65 #ifndef ROOT_TMVA_VariablePCATransform
67 #endif
68 #ifndef ROOT_TMVA_DataSet
69 #include "TMVA/DataSet.h"
70 #endif
71 #ifndef ROOT_TMVA_DataSetInfo
72 #include "TMVA/DataSetInfo.h"
73 #endif
74 #ifndef ROOT_TMVA_DataInputHandler
75 #include "TMVA/DataInputHandler.h"
76 #endif
77 #ifndef ROOT_TMVA_Event
78 #include "TMVA/Event.h"
79 #endif
80 
81 #include "TMVA/Types.h"
82 #include "TMVA/VariableInfo.h"
83 
84 using namespace std;
85 
86 //TMVA::DataSetFactory* TMVA::DataSetFactory::fgInstance = 0;
87 
88 namespace TMVA {
89  // calculate the largest common divider
90  // this function is not happy if numbers are negative!
92  {
93  if (a<b) {Int_t tmp = a; a=b; b=tmp; } // achieve a>=b
94  if (b==0) return a;
95  Int_t fullFits = a/b;
96  return LargestCommonDivider(b,a-b*fullFits);
97  }
98 }
99 
100 
101 ////////////////////////////////////////////////////////////////////////////////
102 /// constructor
103 
105  fVerbose(kFALSE),
106  fVerboseLevel(TString("Info")),
107  fScaleWithPreselEff(0),
108  fCurrentTree(0),
109  fCurrentEvtIdx(0),
110  fInputFormulas(0),
111  fLogger( new MsgLogger("DataSetFactory", kINFO) )
112 {
113 }
114 
115 ////////////////////////////////////////////////////////////////////////////////
116 /// destructor
117 
119 {
120  std::vector<TTreeFormula*>::const_iterator formIt;
121 
122  for (formIt = fInputFormulas.begin() ; formIt!=fInputFormulas.end() ; formIt++) if (*formIt) delete *formIt;
123  for (formIt = fTargetFormulas.begin() ; formIt!=fTargetFormulas.end() ; formIt++) if (*formIt) delete *formIt;
124  for (formIt = fCutFormulas.begin() ; formIt!=fCutFormulas.end() ; formIt++) if (*formIt) delete *formIt;
125  for (formIt = fWeightFormula.begin() ; formIt!=fWeightFormula.end() ; formIt++) if (*formIt) delete *formIt;
126  for (formIt = fSpectatorFormulas.begin(); formIt!=fSpectatorFormulas.end(); formIt++) if (*formIt) delete *formIt;
127 
128  delete fLogger;
129 }
130 
131 ////////////////////////////////////////////////////////////////////////////////
132 /// steering the creation of a new dataset
133 
135  TMVA::DataInputHandler& dataInput )
136 {
137  // build the first dataset from the data input
138  DataSet * ds = BuildInitialDataSet( dsi, dataInput );
139 
140  if (ds->GetNEvents() > 1) {
141  CalcMinMax(ds,dsi);
142 
143  // from the the final dataset build the correlation matrix
144  for (UInt_t cl = 0; cl< dsi.GetNClasses(); cl++) {
145  const TString className = dsi.GetClassInfo(cl)->GetName();
146  dsi.SetCorrelationMatrix( className, CalcCorrelationMatrix( ds, cl ) );
147  dsi.PrintCorrelationMatrix( className );
148  }
149  //Log() << kHEADER << Endl;
150  Log() << kHEADER << Form("[%s] : ",dsi.GetName()) << " " << Endl << Endl;
151  }
152 
153  return ds;
154 }
155 
156 ////////////////////////////////////////////////////////////////////////////////
157 
159 {
160  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "Build DataSet consisting of one Event with dynamically changing variables" << Endl;
161  DataSet* ds = new DataSet(dsi);
162 
163  // create a DataSet with one Event which uses dynamic variables
164  // (pointers to variables)
165  if(dsi.GetNClasses()==0){
166  dsi.AddClass( "data" );
167  dsi.GetClassInfo( "data" )->SetNumber(0);
168  }
169 
170  std::vector<Float_t*>* evdyn = new std::vector<Float_t*>(0);
171 
172  std::vector<VariableInfo>& varinfos = dsi.GetVariableInfos();
173 
174  if (varinfos.empty())
175  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName()) << "Dynamic data set cannot be built, since no variable informations are present. Apparently no variables have been set. This should not happen, please contact the TMVA authors." << Endl;
176 
177  std::vector<VariableInfo>::iterator it = varinfos.begin(), itEnd=varinfos.end();
178  for (;it!=itEnd;++it) {
179  Float_t* external=(Float_t*)(*it).GetExternalLink();
180  if (external==0)
181  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "The link to the external variable is NULL while I am trying to build a dynamic data set. In this case fTmpEvent from MethodBase HAS TO BE USED in the method to get useful values in variables." << Endl;
182  else evdyn->push_back (external);
183  }
184 
185  std::vector<VariableInfo>& spectatorinfos = dsi.GetSpectatorInfos();
186  it = spectatorinfos.begin();
187  for (;it!=spectatorinfos.end();it++) evdyn->push_back( (Float_t*)(*it).GetExternalLink() );
188 
189  TMVA::Event * ev = new Event((const std::vector<Float_t*>*&)evdyn, varinfos.size());
190  std::vector<Event*>* newEventVector = new std::vector<Event*>;
191  newEventVector->push_back(ev);
192 
193  ds->SetEventCollection(newEventVector, Types::kTraining);
194  ds->SetCurrentType( Types::kTraining );
195  ds->SetCurrentEvent( 0 );
196 
197  return ds;
198 }
199 
200 ////////////////////////////////////////////////////////////////////////////////
201 /// if no entries, than create a DataSet with one Event which uses
202 /// dynamic variables (pointers to variables)
203 
206  DataInputHandler& dataInput )
207 {
208  if (dataInput.GetEntries()==0) return BuildDynamicDataSet( dsi );
209  // -------------------------------------------------------------------------
210 
211  // register the classes in the datasetinfo-object
212  // information comes from the trees in the dataInputHandler-object
213  std::vector< TString >* classList = dataInput.GetClassList();
214  for (std::vector<TString>::iterator it = classList->begin(); it< classList->end(); it++) {
215  dsi.AddClass( (*it) );
216  }
217  delete classList;
218 
219  EvtStatsPerClass eventCounts(dsi.GetNClasses());
220  TString normMode;
221  TString splitMode;
222  TString mixMode;
223  UInt_t splitSeed;
224 
225  InitOptions( dsi, eventCounts, normMode, splitSeed, splitMode , mixMode );
226  // ======= build event-vector from input, apply preselection ===============
227  EventVectorOfClassesOfTreeType tmpEventVector;
228  BuildEventVector( dsi, dataInput, tmpEventVector, eventCounts );
229 
230  DataSet* ds = MixEvents( dsi, tmpEventVector, eventCounts,
231  splitMode, mixMode, normMode, splitSeed );
232 
233  const Bool_t showCollectedOutput = kFALSE;
234  if (showCollectedOutput) {
235  Int_t maxL = dsi.GetClassNameMaxLength();
236  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Collected:" << Endl;
237  for (UInt_t cl = 0; cl < dsi.GetNClasses(); cl++) {
238  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " "
239  << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
240  << " training entries: " << ds->GetNClassEvents( 0, cl ) << Endl;
241  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " "
242  << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
243  << " testing entries: " << ds->GetNClassEvents( 1, cl ) << Endl;
244  }
245  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " " << Endl;
246  }
247 
248  return ds;
249 }
250 
251 ////////////////////////////////////////////////////////////////////////////////
252 /// checks a TTreeFormula for problems
253 
255  const TString& expression,
256  Bool_t& hasDollar )
257 {
258  Bool_t worked = kTRUE;
259 
260  if( ttf->GetNdim() <= 0 )
261  Log() << kFATAL << "Expression " << expression.Data()
262  << " could not be resolved to a valid formula. " << Endl;
263  if( ttf->GetNdata() == 0 ){
264  Log() << kWARNING << "Expression: " << expression.Data()
265  << " does not provide data for this event. "
266  << "This event is not taken into account. --> please check if you use as a variable "
267  << "an entry of an array which is not filled for some events "
268  << "(e.g. arr[4] when arr has only 3 elements)." << Endl;
269  Log() << kWARNING << "If you want to take the event into account you can do something like: "
270  << "\"Alt$(arr[4],0)\" where in cases where arr doesn't have a 4th element, "
271  << " 0 is taken as an alternative." << Endl;
272  worked = kFALSE;
273  }
274  if( expression.Contains("$") )
275  hasDollar = kTRUE;
276  else
277  {
278  for (int i = 0, iEnd = ttf->GetNcodes (); i < iEnd; ++i)
279  {
280  TLeaf* leaf = ttf->GetLeaf (i);
281  if (!leaf->IsOnTerminalBranch())
282  hasDollar = kTRUE;
283  }
284  }
285  return worked;
286 }
287 
288 
289 ////////////////////////////////////////////////////////////////////////////////
290 /// While the data gets copied into the local training and testing
291 /// trees, the input tree can change (for intance when changing from
292 /// signal to background tree, or using TChains as input) The
293 /// TTreeFormulas, that hold the input expressions need to be
294 /// reassociated with the new tree, which is done here
295 
297 {
298  TTree *tr = tinfo.GetTree()->GetTree();
299 
300  tr->SetBranchStatus("*",1);
301 
302  Bool_t hasDollar = kFALSE;
303 
304  // 1) the input variable formulas
305  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "transform input variables" << Endl;
306  std::vector<TTreeFormula*>::const_iterator formIt, formItEnd;
307  for (formIt = fInputFormulas.begin(), formItEnd=fInputFormulas.end(); formIt!=formItEnd; formIt++) if (*formIt) delete *formIt;
308  fInputFormulas.clear();
309  TTreeFormula* ttf = 0;
310 
311  for (UInt_t i=0; i<dsi.GetNVariables(); i++) {
312  ttf = new TTreeFormula( Form( "Formula%s", dsi.GetVariableInfo(i).GetInternalName().Data() ),
313  dsi.GetVariableInfo(i).GetExpression().Data(), tr );
314  CheckTTreeFormula( ttf, dsi.GetVariableInfo(i).GetExpression(), hasDollar );
315  fInputFormulas.push_back( ttf );
316  }
317 
318  //
319  // targets
320  //
321  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "transform regression targets" << Endl;
322  for (formIt = fTargetFormulas.begin(), formItEnd = fTargetFormulas.end(); formIt!=formItEnd; formIt++) if (*formIt) delete *formIt;
323  fTargetFormulas.clear();
324  for (UInt_t i=0; i<dsi.GetNTargets(); i++) {
325  ttf = new TTreeFormula( Form( "Formula%s", dsi.GetTargetInfo(i).GetInternalName().Data() ),
326  dsi.GetTargetInfo(i).GetExpression().Data(), tr );
327  CheckTTreeFormula( ttf, dsi.GetTargetInfo(i).GetExpression(), hasDollar );
328  fTargetFormulas.push_back( ttf );
329  }
330 
331  //
332  // spectators
333  //
334  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "transform spectator variables" << Endl;
335  for (formIt = fSpectatorFormulas.begin(), formItEnd = fSpectatorFormulas.end(); formIt!=formItEnd; formIt++) if (*formIt) delete *formIt;
336  fSpectatorFormulas.clear();
337  for (UInt_t i=0; i<dsi.GetNSpectators(); i++) {
338  ttf = new TTreeFormula( Form( "Formula%s", dsi.GetSpectatorInfo(i).GetInternalName().Data() ),
339  dsi.GetSpectatorInfo(i).GetExpression().Data(), tr );
340  CheckTTreeFormula( ttf, dsi.GetSpectatorInfo(i).GetExpression(), hasDollar );
341  fSpectatorFormulas.push_back( ttf );
342  }
343 
344  //
345  // the cuts (one per class, if non-existent: formula pointer = 0)
346  //
347  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "transform cuts" << Endl;
348  for (formIt = fCutFormulas.begin(), formItEnd = fCutFormulas.end(); formIt!=formItEnd; formIt++) if (*formIt) delete *formIt;
349  fCutFormulas.clear();
350  for (UInt_t clIdx=0; clIdx<dsi.GetNClasses(); clIdx++) {
351  const TCut& tmpCut = dsi.GetClassInfo(clIdx)->GetCut();
352  const TString tmpCutExp(tmpCut.GetTitle());
353  ttf = 0;
354  if (tmpCutExp!="") {
355  ttf = new TTreeFormula( Form("CutClass%i",clIdx), tmpCutExp, tr );
356  Bool_t worked = CheckTTreeFormula( ttf, tmpCutExp, hasDollar );
357  if( !worked ){
358  Log() << kWARNING << "Please check class \"" << dsi.GetClassInfo(clIdx)->GetName()
359  << "\" cut \"" << dsi.GetClassInfo(clIdx)->GetCut() << Endl;
360  }
361  }
362  fCutFormulas.push_back( ttf );
363  }
364 
365  //
366  // the weights (one per class, if non-existent: formula pointer = 0)
367  //
368  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "transform weights" << Endl;
369  for (formIt = fWeightFormula.begin(), formItEnd = fWeightFormula.end(); formIt!=formItEnd; formIt++) if (*formIt) delete *formIt;
370  fWeightFormula.clear();
371  for (UInt_t clIdx=0; clIdx<dsi.GetNClasses(); clIdx++) {
372  const TString tmpWeight = dsi.GetClassInfo(clIdx)->GetWeight();
373 
374  if (dsi.GetClassInfo(clIdx)->GetName() != tinfo.GetClassName() ) { // if the tree is of another class
375  fWeightFormula.push_back( 0 );
376  continue;
377  }
378 
379  ttf = 0;
380  if (tmpWeight!="") {
381  ttf = new TTreeFormula( "FormulaWeight", tmpWeight, tr );
382  Bool_t worked = CheckTTreeFormula( ttf, tmpWeight, hasDollar );
383  if( !worked ){
384  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName()) << "Please check class \"" << dsi.GetClassInfo(clIdx)->GetName()
385  << "\" weight \"" << dsi.GetClassInfo(clIdx)->GetWeight() << Endl;
386  }
387  }
388  else {
389  ttf = 0;
390  }
391  fWeightFormula.push_back( ttf );
392  }
393  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches" << Endl;
394  // now enable only branches that are needed in any input formula, target, cut, weight
395 
396  if (!hasDollar) {
397  tr->SetBranchStatus("*",0);
398  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches: input variables" << Endl;
399  // input vars
400  for (formIt = fInputFormulas.begin(); formIt!=fInputFormulas.end(); formIt++) {
401  ttf = *formIt;
402  for (Int_t bi = 0; bi<ttf->GetNcodes(); bi++) {
403  tr->SetBranchStatus( ttf->GetLeaf(bi)->GetBranch()->GetName(), 1 );
404  }
405  }
406  // targets
407  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches: targets" << Endl;
408  for (formIt = fTargetFormulas.begin(); formIt!=fTargetFormulas.end(); formIt++) {
409  ttf = *formIt;
410  for (Int_t bi = 0; bi<ttf->GetNcodes(); bi++)
411  tr->SetBranchStatus( ttf->GetLeaf(bi)->GetBranch()->GetName(), 1 );
412  }
413  // spectators
414  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches: spectators" << Endl;
415  for (formIt = fSpectatorFormulas.begin(); formIt!=fSpectatorFormulas.end(); formIt++) {
416  ttf = *formIt;
417  for (Int_t bi = 0; bi<ttf->GetNcodes(); bi++)
418  tr->SetBranchStatus( ttf->GetLeaf(bi)->GetBranch()->GetName(), 1 );
419  }
420  // cuts
421  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches: cuts" << Endl;
422  for (formIt = fCutFormulas.begin(); formIt!=fCutFormulas.end(); formIt++) {
423  ttf = *formIt;
424  if (!ttf) continue;
425  for (Int_t bi = 0; bi<ttf->GetNcodes(); bi++)
426  tr->SetBranchStatus( ttf->GetLeaf(bi)->GetBranch()->GetName(), 1 );
427  }
428  // weights
429  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "enable branches: weights" << Endl;
430  for (formIt = fWeightFormula.begin(); formIt!=fWeightFormula.end(); formIt++) {
431  ttf = *formIt;
432  if (!ttf) continue;
433  for (Int_t bi = 0; bi<ttf->GetNcodes(); bi++)
434  tr->SetBranchStatus( ttf->GetLeaf(bi)->GetBranch()->GetName(), 1 );
435  }
436  }
437  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName()) << "tree initialized" << Endl;
438  return;
439 }
440 
441 ////////////////////////////////////////////////////////////////////////////////
442 /// compute covariance matrix
443 
445 {
446  const UInt_t nvar = ds->GetNVariables();
447  const UInt_t ntgts = ds->GetNTargets();
448  const UInt_t nvis = ds->GetNSpectators();
449 
450  Float_t *min = new Float_t[nvar];
451  Float_t *max = new Float_t[nvar];
452  Float_t *tgmin = new Float_t[ntgts];
453  Float_t *tgmax = new Float_t[ntgts];
454  Float_t *vmin = new Float_t[nvis];
455  Float_t *vmax = new Float_t[nvis];
456 
457  for (UInt_t ivar=0; ivar<nvar ; ivar++) { min[ivar] = FLT_MAX; max[ivar] = -FLT_MAX; }
458  for (UInt_t ivar=0; ivar<ntgts; ivar++) { tgmin[ivar] = FLT_MAX; tgmax[ivar] = -FLT_MAX; }
459  for (UInt_t ivar=0; ivar<nvis; ivar++) { vmin[ivar] = FLT_MAX; vmax[ivar] = -FLT_MAX; }
460 
461  // perform event loop
462 
463  for (Int_t i=0; i<ds->GetNEvents(); i++) {
464  const Event * ev = ds->GetEvent(i);
465  for (UInt_t ivar=0; ivar<nvar; ivar++) {
466  Double_t v = ev->GetValue(ivar);
467  if (v<min[ivar]) min[ivar] = v;
468  if (v>max[ivar]) max[ivar] = v;
469  }
470  for (UInt_t itgt=0; itgt<ntgts; itgt++) {
471  Double_t v = ev->GetTarget(itgt);
472  if (v<tgmin[itgt]) tgmin[itgt] = v;
473  if (v>tgmax[itgt]) tgmax[itgt] = v;
474  }
475  for (UInt_t ivis=0; ivis<nvis; ivis++) {
476  Double_t v = ev->GetSpectator(ivis);
477  if (v<vmin[ivis]) vmin[ivis] = v;
478  if (v>vmax[ivis]) vmax[ivis] = v;
479  }
480  }
481 
482  for (UInt_t ivar=0; ivar<nvar; ivar++) {
483  dsi.GetVariableInfo(ivar).SetMin(min[ivar]);
484  dsi.GetVariableInfo(ivar).SetMax(max[ivar]);
485  if( TMath::Abs(max[ivar]-min[ivar]) <= FLT_MIN )
486  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName()) << "Variable " << dsi.GetVariableInfo(ivar).GetExpression().Data() << " is constant. Please remove the variable." << Endl;
487  }
488  for (UInt_t ivar=0; ivar<ntgts; ivar++) {
489  dsi.GetTargetInfo(ivar).SetMin(tgmin[ivar]);
490  dsi.GetTargetInfo(ivar).SetMax(tgmax[ivar]);
491  if( TMath::Abs(tgmax[ivar]-tgmin[ivar]) <= FLT_MIN )
492  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName()) << "Target " << dsi.GetTargetInfo(ivar).GetExpression().Data() << " is constant. Please remove the variable." << Endl;
493  }
494  for (UInt_t ivar=0; ivar<nvis; ivar++) {
495  dsi.GetSpectatorInfo(ivar).SetMin(vmin[ivar]);
496  dsi.GetSpectatorInfo(ivar).SetMax(vmax[ivar]);
497  // if( TMath::Abs(vmax[ivar]-vmin[ivar]) <= FLT_MIN )
498  // Log() << kWARNING << "Spectator variable " << dsi.GetSpectatorInfo(ivar).GetExpression().Data() << " is constant." << Endl;
499  }
500  delete [] min;
501  delete [] max;
502  delete [] tgmin;
503  delete [] tgmax;
504  delete [] vmin;
505  delete [] vmax;
506 }
507 
508 ////////////////////////////////////////////////////////////////////////////////
509 /// computes correlation matrix for variables "theVars" in tree;
510 /// "theType" defines the required event "type"
511 /// ("type" variable must be present in tree)
512 
514 {
515  // first compute variance-covariance
516  TMatrixD* mat = CalcCovarianceMatrix( ds, classNumber );
517 
518  // now the correlation
519  UInt_t nvar = ds->GetNVariables(), ivar, jvar;
520 
521  for (ivar=0; ivar<nvar; ivar++) {
522  for (jvar=0; jvar<nvar; jvar++) {
523  if (ivar != jvar) {
524  Double_t d = (*mat)(ivar, ivar)*(*mat)(jvar, jvar);
525  if (d > 0) (*mat)(ivar, jvar) /= sqrt(d);
526  else {
527  Log() << kWARNING << Form("Dataset[%s] : ",DataSetInfo().GetName())<< "<GetCorrelationMatrix> Zero variances for variables "
528  << "(" << ivar << ", " << jvar << ") = " << d
529  << Endl;
530  (*mat)(ivar, jvar) = 0;
531  }
532  }
533  }
534  }
535 
536  for (ivar=0; ivar<nvar; ivar++) (*mat)(ivar, ivar) = 1.0;
537 
538  return mat;
539 }
540 
541 ////////////////////////////////////////////////////////////////////////////////
542 /// compute covariance matrix
543 
545 {
546  UInt_t nvar = ds->GetNVariables();
547  UInt_t ivar = 0, jvar = 0;
548 
549  TMatrixD* mat = new TMatrixD( nvar, nvar );
550 
551  // init matrices
552  TVectorD vec(nvar);
553  TMatrixD mat2(nvar, nvar);
554  for (ivar=0; ivar<nvar; ivar++) {
555  vec(ivar) = 0;
556  for (jvar=0; jvar<nvar; jvar++) mat2(ivar, jvar) = 0;
557  }
558 
559  // perform event loop
560  Double_t ic = 0;
561  for (Int_t i=0; i<ds->GetNEvents(); i++) {
562 
563  const Event * ev = ds->GetEvent(i);
564  if (ev->GetClass() != classNumber ) continue;
565 
566  Double_t weight = ev->GetWeight();
567  ic += weight; // count used events
568 
569  for (ivar=0; ivar<nvar; ivar++) {
570 
571  Double_t xi = ev->GetValue(ivar);
572  vec(ivar) += xi*weight;
573  mat2(ivar, ivar) += (xi*xi*weight);
574 
575  for (jvar=ivar+1; jvar<nvar; jvar++) {
576  Double_t xj = ev->GetValue(jvar);
577  mat2(ivar, jvar) += (xi*xj*weight);
578  }
579  }
580  }
581 
582  for (ivar=0; ivar<nvar; ivar++)
583  for (jvar=ivar+1; jvar<nvar; jvar++)
584  mat2(jvar, ivar) = mat2(ivar, jvar); // symmetric matrix
585 
586 
587  // variance-covariance
588  for (ivar=0; ivar<nvar; ivar++) {
589  for (jvar=0; jvar<nvar; jvar++) {
590  (*mat)(ivar, jvar) = mat2(ivar, jvar)/ic - vec(ivar)*vec(jvar)/(ic*ic);
591  }
592  }
593 
594  return mat;
595 }
596 
597 // --------------------------------------- new versions
598 
599 ////////////////////////////////////////////////////////////////////////////////
600 /// the dataset splitting
601 
602 void
604  EvtStatsPerClass& nEventRequests,
605  TString& normMode,
606  UInt_t& splitSeed,
607  TString& splitMode,
608  TString& mixMode)
609 {
610  Configurable splitSpecs( dsi.GetSplitOptions() );
611  splitSpecs.SetConfigName("DataSetFactory");
612  splitSpecs.SetConfigDescription( "Configuration options given in the \"PrepareForTrainingAndTesting\" call; these options define the creation of the data sets used for training and expert validation by TMVA" );
613 
614  splitMode = "Random"; // the splitting mode
615  splitSpecs.DeclareOptionRef( splitMode, "SplitMode",
616  "Method of picking training and testing events (default: random)" );
617  splitSpecs.AddPreDefVal(TString("Random"));
618  splitSpecs.AddPreDefVal(TString("Alternate"));
619  splitSpecs.AddPreDefVal(TString("Block"));
620 
621  mixMode = "SameAsSplitMode"; // the splitting mode
622  splitSpecs.DeclareOptionRef( mixMode, "MixMode",
623  "Method of mixing events of differnt classes into one dataset (default: SameAsSplitMode)" );
624  splitSpecs.AddPreDefVal(TString("SameAsSplitMode"));
625  splitSpecs.AddPreDefVal(TString("Random"));
626  splitSpecs.AddPreDefVal(TString("Alternate"));
627  splitSpecs.AddPreDefVal(TString("Block"));
628 
629  splitSeed = 100;
630  splitSpecs.DeclareOptionRef( splitSeed, "SplitSeed",
631  "Seed for random event shuffling" );
632 
633  normMode = "EqualNumEvents"; // the weight normalisation modes
634  splitSpecs.DeclareOptionRef( normMode, "NormMode",
635  "Overall renormalisation of event-by-event weights used in the training (NumEvents: average weight of 1 per event, independently for signal and background; EqualNumEvents: average weight of 1 per event for signal, and sum of weights for background equal to sum of weights for signal)" );
636  splitSpecs.AddPreDefVal(TString("None"));
637  splitSpecs.AddPreDefVal(TString("NumEvents"));
638  splitSpecs.AddPreDefVal(TString("EqualNumEvents"));
639 
640  splitSpecs.DeclareOptionRef(fScaleWithPreselEff=kFALSE,"ScaleWithPreselEff","Scale the number of requested events by the eff. of the preselection cuts (or not)" );
641 
642  // the number of events
643 
644  // fill in the numbers
645  for (UInt_t cl = 0; cl < dsi.GetNClasses(); cl++) {
646  TString clName = dsi.GetClassInfo(cl)->GetName();
647  TString titleTrain = TString().Format("Number of training events of class %s (default: 0 = all)",clName.Data()).Data();
648  TString titleTest = TString().Format("Number of test events of class %s (default: 0 = all)",clName.Data()).Data();
649  TString titleSplit = TString().Format("Split in training and test events of class %s (default: 0 = deactivated)",clName.Data()).Data();
650 
651  splitSpecs.DeclareOptionRef( nEventRequests.at(cl).nTrainingEventsRequested, TString("nTrain_")+clName, titleTrain );
652  splitSpecs.DeclareOptionRef( nEventRequests.at(cl).nTestingEventsRequested , TString("nTest_")+clName , titleTest );
653  splitSpecs.DeclareOptionRef( nEventRequests.at(cl).TrainTestSplitRequested , TString("TrainTestSplit_")+clName , titleTest );
654  }
655 
656  splitSpecs.DeclareOptionRef( fVerbose, "V", "Verbosity (default: true)" );
657 
658  splitSpecs.DeclareOptionRef( fVerboseLevel=TString("Info"), "VerboseLevel", "VerboseLevel (Debug/Verbose/Info)" );
659  splitSpecs.AddPreDefVal(TString("Debug"));
660  splitSpecs.AddPreDefVal(TString("Verbose"));
661  splitSpecs.AddPreDefVal(TString("Info"));
662 
663  splitSpecs.ParseOptions();
664  splitSpecs.CheckForUnusedOptions();
665 
666  // output logging verbosity
667  if (Verbose()) fLogger->SetMinType( kVERBOSE );
668  if (fVerboseLevel.CompareTo("Debug") ==0) fLogger->SetMinType( kDEBUG );
669  if (fVerboseLevel.CompareTo("Verbose") ==0) fLogger->SetMinType( kVERBOSE );
670  if (fVerboseLevel.CompareTo("Info") ==0) fLogger->SetMinType( kINFO );
671 
672  // put all to upper case
673  splitMode.ToUpper(); mixMode.ToUpper(); normMode.ToUpper();
674  // adjust mixmode if same as splitmode option has been set
675  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
676  << "\tSplitmode is: \"" << splitMode << "\" the mixmode is: \"" << mixMode << "\"" << Endl;
677  if (mixMode=="SAMEASSPLITMODE") mixMode = splitMode;
678  else if (mixMode!=splitMode)
679  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "DataSet splitmode="<<splitMode
680  <<" differs from mixmode="<<mixMode<<Endl;
681 }
682 
683 
684 ////////////////////////////////////////////////////////////////////////////////
685 /// build empty event vectors
686 /// distributes events between kTraining/kTesting/kMaxTreeType
687 
688 void
690  TMVA::DataInputHandler& dataInput,
692  EvtStatsPerClass& eventCounts)
693 {
694  const UInt_t nclasses = dsi.GetNClasses();
695 
696  eventsmap[ Types::kTraining ] = EventVectorOfClasses(nclasses);
697  eventsmap[ Types::kTesting ] = EventVectorOfClasses(nclasses);
698  eventsmap[ Types::kMaxTreeType ] = EventVectorOfClasses(nclasses);
699 
700  // create the type, weight and boostweight branches
701  const UInt_t nvars = dsi.GetNVariables();
702  const UInt_t ntgts = dsi.GetNTargets();
703  const UInt_t nvis = dsi.GetNSpectators();
704 
705  for (size_t i=0; i<nclasses; i++) {
706  eventCounts[i].varAvLength = new Float_t[nvars];
707  for (UInt_t ivar=0; ivar<nvars; ivar++)
708  eventCounts[i].varAvLength[ivar] = 0;
709  }
710 
711  // Bool_t haveArrayVariable = kFALSE;
712  Bool_t *varIsArray = new Bool_t[nvars];
713 
714  // if we work with chains we need to remember the current tree if
715  // the chain jumps to a new tree we have to reset the formulas
716  for (UInt_t cl=0; cl<nclasses; cl++) {
717 
718  //Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Create training and testing trees -- looping over class \"" << dsi.GetClassInfo(cl)->GetName() << "\" ..." << Endl;
719 
720  EventStats& classEventCounts = eventCounts[cl];
721 
722  // info output for weights
723  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
724  << "\tWeight expression for class \'" << dsi.GetClassInfo(cl)->GetName() << "\': \""
725  << dsi.GetClassInfo(cl)->GetWeight() << "\"" << Endl;
726 
727  // used for chains only
728  TString currentFileName("");
729 
730  std::vector<TreeInfo>::const_iterator treeIt(dataInput.begin(dsi.GetClassInfo(cl)->GetName()));
731  for (;treeIt!=dataInput.end(dsi.GetClassInfo(cl)->GetName()); treeIt++) {
732 
733  // read first the variables
734  std::vector<Float_t> vars(nvars);
735  std::vector<Float_t> tgts(ntgts);
736  std::vector<Float_t> vis(nvis);
737  TreeInfo currentInfo = *treeIt;
738 
739  Log() << kDEBUG << "Building event vectors " << currentInfo.GetTreeType() << Endl;
740 
741  EventVector& event_v = eventsmap[currentInfo.GetTreeType()].at(cl);
742 
743  Bool_t isChain = (TString("TChain") == currentInfo.GetTree()->ClassName());
744  currentInfo.GetTree()->LoadTree(0);
745  ChangeToNewTree( currentInfo, dsi );
746 
747  // count number of events in tree before cut
748  classEventCounts.nInitialEvents += currentInfo.GetTree()->GetEntries();
749 
750  // loop over events in ntuple
751  const UInt_t nEvts = currentInfo.GetTree()->GetEntries();
752  for (Long64_t evtIdx = 0; evtIdx < nEvts; evtIdx++) {
753  currentInfo.GetTree()->LoadTree(evtIdx);
754 
755  // may need to reload tree in case of chains
756  if (isChain) {
757  if (currentInfo.GetTree()->GetTree()->GetDirectory()->GetFile()->GetName() != currentFileName) {
758  currentFileName = currentInfo.GetTree()->GetTree()->GetDirectory()->GetFile()->GetName();
759  ChangeToNewTree( currentInfo, dsi );
760  }
761  }
762  currentInfo.GetTree()->GetEntry(evtIdx);
763  Int_t sizeOfArrays = 1;
764  Int_t prevArrExpr = 0;
765 
766  // ======= evaluate all formulas =================
767 
768  // first we check if some of the formulas are arrays
769  for (UInt_t ivar=0; ivar<nvars; ivar++) {
770  Int_t ndata = fInputFormulas[ivar]->GetNdata();
771  classEventCounts.varAvLength[ivar] += ndata;
772  if (ndata == 1) continue;
773  // haveArrayVariable = kTRUE;
774  varIsArray[ivar] = kTRUE;
775  if (sizeOfArrays == 1) {
776  sizeOfArrays = ndata;
777  prevArrExpr = ivar;
778  }
779  else if (sizeOfArrays!=ndata) {
780  Log() << kERROR << Form("Dataset[%s] : ",dsi.GetName())<< "ERROR while preparing training and testing trees:" << Endl;
781  Log() << Form("Dataset[%s] : ",dsi.GetName())<< " multiple array-type expressions of different length were encountered" << Endl;
782  Log() << Form("Dataset[%s] : ",dsi.GetName())<< " location of error: event " << evtIdx
783  << " in tree " << currentInfo.GetTree()->GetName()
784  << " of file " << currentInfo.GetTree()->GetCurrentFile()->GetName() << Endl;
785  Log() << Form("Dataset[%s] : ",dsi.GetName())<< " expression " << fInputFormulas[ivar]->GetTitle() << " has "
786  << Form("Dataset[%s] : ",dsi.GetName()) << ndata << " entries, while" << Endl;
787  Log() << Form("Dataset[%s] : ",dsi.GetName())<< " expression " << fInputFormulas[prevArrExpr]->GetTitle() << " has "
788  << Form("Dataset[%s] : ",dsi.GetName())<< fInputFormulas[prevArrExpr]->GetNdata() << " entries" << Endl;
789  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName())<< "Need to abort" << Endl;
790  }
791  }
792 
793  // now we read the information
794  for (Int_t idata = 0; idata<sizeOfArrays; idata++) {
795  Bool_t containsNaN = kFALSE;
796 
797  TTreeFormula* formula = 0;
798 
799  // the cut expression
800  Float_t cutVal = 1;
801  formula = fCutFormulas[cl];
802  if (formula) {
803  Int_t ndata = formula->GetNdata();
804  cutVal = (ndata==1 ?
805  formula->EvalInstance(0) :
806  formula->EvalInstance(idata));
807  if (TMath::IsNaN(cutVal)) {
808  containsNaN = kTRUE;
809  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Cut expression resolves to infinite value (NaN): "
810  << formula->GetTitle() << Endl;
811  }
812  }
813 
814  // the input variable
815  for (UInt_t ivar=0; ivar<nvars; ivar++) {
816  formula = fInputFormulas[ivar];
817  Int_t ndata = formula->GetNdata();
818  vars[ivar] = (ndata == 1 ?
819  formula->EvalInstance(0) :
820  formula->EvalInstance(idata));
821  if (TMath::IsNaN(vars[ivar])) {
822  containsNaN = kTRUE;
823  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Input expression resolves to infinite value (NaN): "
824  << formula->GetTitle() << Endl;
825  }
826  }
827 
828  // the targets
829  for (UInt_t itrgt=0; itrgt<ntgts; itrgt++) {
830  formula = fTargetFormulas[itrgt];
831  Int_t ndata = formula->GetNdata();
832  tgts[itrgt] = (ndata == 1 ?
833  formula->EvalInstance(0) :
834  formula->EvalInstance(idata));
835  if (TMath::IsNaN(tgts[itrgt])) {
836  containsNaN = kTRUE;
837  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Target expression resolves to infinite value (NaN): "
838  << formula->GetTitle() << Endl;
839  }
840  }
841 
842  // the spectators
843  for (UInt_t itVis=0; itVis<nvis; itVis++) {
844  formula = fSpectatorFormulas[itVis];
845  Int_t ndata = formula->GetNdata();
846  vis[itVis] = (ndata == 1 ?
847  formula->EvalInstance(0) :
848  formula->EvalInstance(idata));
849  if (TMath::IsNaN(vis[itVis])) {
850  containsNaN = kTRUE;
851  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Spectator expression resolves to infinite value (NaN): "
852  << formula->GetTitle() << Endl;
853  }
854  }
855 
856 
857  // the weight
858  Float_t weight = currentInfo.GetWeight(); // multiply by tree weight
859  formula = fWeightFormula[cl];
860  if (formula!=0) {
861  Int_t ndata = formula->GetNdata();
862  weight *= (ndata == 1 ?
863  formula->EvalInstance() :
864  formula->EvalInstance(idata));
865  if (TMath::IsNaN(weight)) {
866  containsNaN = kTRUE;
867  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Weight expression resolves to infinite value (NaN): "
868  << formula->GetTitle() << Endl;
869  }
870  }
871 
872  // Count the events before rejection due to cut or NaN
873  // value (weighted and unweighted)
874  classEventCounts.nEvBeforeCut++;
875  if (!TMath::IsNaN(weight))
876  classEventCounts.nWeEvBeforeCut += weight;
877 
878  // apply the cut, skip rest if cut is not fulfilled
879  if (cutVal<0.5) continue;
880 
881  // global flag if negative weights exist -> can be used
882  // by classifiers who may require special data
883  // treatment (also print warning)
884  if (weight < 0) classEventCounts.nNegWeights++;
885 
886  // now read the event-values (variables and regression targets)
887 
888  if (containsNaN) {
889  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "Event " << evtIdx;
890  if (sizeOfArrays>1) Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< " rejected" << Endl;
891  continue;
892  }
893 
894  // Count the events after rejection due to cut or NaN value
895  // (weighted and unweighted)
896  classEventCounts.nEvAfterCut++;
897  classEventCounts.nWeEvAfterCut += weight;
898 
899  // event accepted, fill temporary ntuple
900  event_v.push_back(new Event(vars, tgts , vis, cl , weight));
901  }
902  }
903  currentInfo.GetTree()->ResetBranchAddresses();
904  }
905  }
906 
907  // for output format, get the maximum class name length
908  Int_t maxL = dsi.GetClassNameMaxLength();
909 
910  Log() << kHEADER << Form("[%s] : ",dsi.GetName()) << "Number of events in input trees" << Endl;
911  Log() << kDEBUG << "(after possible flattening of arrays):" << Endl;
912 
913 
914  for (UInt_t cl = 0; cl < dsi.GetNClasses(); cl++) {
915  Log() << kDEBUG //<< Form("[%s] : ",dsi.GetName())
916  << " "
917  << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
918  << " -- number of events : "
919  << std::setw(5) << eventCounts[cl].nEvBeforeCut
920  << " / sum of weights: " << std::setw(5) << eventCounts[cl].nWeEvBeforeCut << Endl;
921  }
922 
923  for (UInt_t cl = 0; cl < dsi.GetNClasses(); cl++) {
924  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
925  << " " << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
926  <<" tree -- total number of entries: "
927  << std::setw(5) << dataInput.GetEntries(dsi.GetClassInfo(cl)->GetName()) << Endl;
928  }
929 
930  if (fScaleWithPreselEff)
931  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
932  << "\tPreselection: (will affect number of requested training and testing events)" << Endl;
933  else
934  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
935  << "\tPreselection: (will NOT affect number of requested training and testing events)" << Endl;
936 
937  if (dsi.HasCuts()) {
938  for (UInt_t cl = 0; cl< dsi.GetNClasses(); cl++) {
939  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " " << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
940  << " requirement: \"" << dsi.GetClassInfo(cl)->GetCut() << "\"" << Endl;
941  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " "
942  << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
943  << " -- number of events passed: "
944  << std::setw(5) << eventCounts[cl].nEvAfterCut
945  << " / sum of weights: " << std::setw(5) << eventCounts[cl].nWeEvAfterCut << Endl;
946  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " "
947  << setiosflags(ios::left) << std::setw(maxL) << dsi.GetClassInfo(cl)->GetName()
948  << " -- efficiency : "
949  << std::setw(6) << eventCounts[cl].nWeEvAfterCut/eventCounts[cl].nWeEvBeforeCut << Endl;
950  }
951  }
952  else Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
953  << " No preselection cuts applied on event classes" << Endl;
954 
955  delete[] varIsArray;
956 
957 }
958 
959 ////////////////////////////////////////////////////////////////////////////////
960 /// Select and distribute unassigned events to kTraining and kTesting
961 ///Bool_t emptyUndefined = kTRUE;
962 
965  EventVectorOfClassesOfTreeType& tmpEventVector,
966  EvtStatsPerClass& eventCounts,
967  const TString& splitMode,
968  const TString& mixMode,
969  const TString& normMode,
970  UInt_t splitSeed)
971 {
972  // check if the vectors of all classes are empty
973  //for( Int_t cls = 0, clsEnd = dsi.GetNClasses(); cls < clsEnd; ++cls ){
974  // emptyUndefined &= tmpEventVector[Types::kMaxTreeType].at(cls).empty();
975  //}
976 
977  TMVA::RandomGenerator rndm( splitSeed );
978 
979  // ==== splitting of undefined events to kTraining and kTesting
980 
981  // if splitMode contains "RANDOM", then shuffle the undefined events
982  if (splitMode.Contains( "RANDOM" ) /*&& !emptyUndefined*/ ) {
983  // random shuffle the undefined events of each class
984  for( UInt_t cls = 0; cls < dsi.GetNClasses(); ++cls ){
985  EventVector& unspecifiedEvents = tmpEventVector[Types::kMaxTreeType].at(cls);
986  if( ! unspecifiedEvents.empty() ) {
987  Log() << kDEBUG << "randomly shuffling "
988  << unspecifiedEvents.size()
989  << " events of class " << cls
990  << " which are not yet associated to testing or training" << Endl;
991  std::random_shuffle( unspecifiedEvents.begin(),
992  unspecifiedEvents.end(),
993  rndm );
994  }
995  }
996  }
997 
998  // check for each class the number of training and testing events, the requested number and the available number
999  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "SPLITTING ========" << Endl;
1000  for( UInt_t cls = 0; cls < dsi.GetNClasses(); ++cls ){
1001  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "---- class " << cls << Endl;
1002  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "check number of training/testing events, requested and available number of events and for class " << cls << Endl;
1003 
1004  // check if enough or too many events are already in the training/testing eventvectors of the class cls
1005  EventVector& eventVectorTraining = tmpEventVector[ Types::kTraining ].at(cls);
1006  EventVector& eventVectorTesting = tmpEventVector[ Types::kTesting ].at(cls);
1007  EventVector& eventVectorUndefined = tmpEventVector[ Types::kMaxTreeType ].at(cls);
1008 
1009  Int_t availableTraining = eventVectorTraining.size();
1010  Int_t availableTesting = eventVectorTesting.size();
1011  Int_t availableUndefined = eventVectorUndefined.size();
1012 
1013  Float_t presel_scale;
1014  if (fScaleWithPreselEff) {
1015  presel_scale = eventCounts[cls].cutScaling();
1016  if (presel_scale < 1)
1017  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " you have opted for scaling the number of requested training/testing events\n to be scaled by the preselection efficiency"<< Endl;
1018  }else{
1019  presel_scale = 1.; // this scaling was tooo confusing to most people, including me! Sorry... (Helge)
1020  if (eventCounts[cls].cutScaling() < 1)
1021  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " you have opted for interpreting the requested number of training/testing events\n to be the number of events AFTER your preselection cuts" << Endl;
1022 
1023  }
1024 
1025  // If TrainTestSplit_<class> is set, set number of requested training events to split*num_all_events
1026  // Requested number of testing events is set to zero and therefore takes all other events
1027  // The option TrainTestSplit_<class> overrides nTrain_<class> or nTest_<class>
1028  if(eventCounts[cls].TrainTestSplitRequested < 1.0 && eventCounts[cls].TrainTestSplitRequested > 0.0){
1029  eventCounts[cls].nTrainingEventsRequested = Int_t(eventCounts[cls].TrainTestSplitRequested*(availableTraining+availableTesting+availableUndefined));
1030  eventCounts[cls].nTestingEventsRequested = Int_t(0);
1031  }
1032  else if(eventCounts[cls].TrainTestSplitRequested != 0.0) Log() << kFATAL << Form("The option TrainTestSplit_<class> has to be in range (0, 1] but is set to %f.",eventCounts[cls].TrainTestSplitRequested) << Endl;
1033  Int_t requestedTraining = Int_t(eventCounts[cls].nTrainingEventsRequested * presel_scale);
1034  Int_t requestedTesting = Int_t(eventCounts[cls].nTestingEventsRequested * presel_scale);
1035 
1036  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "events in training trees : " << availableTraining << Endl;
1037  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "events in testing trees : " << availableTesting << Endl;
1038  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "events in unspecified trees : " << availableUndefined << Endl;
1039  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "requested for training : " << requestedTraining << Endl;;
1040 
1041  if(presel_scale<1)
1042  Log() << " ( " << eventCounts[cls].nTrainingEventsRequested
1043  << " * " << presel_scale << " preselection efficiency)" << Endl;
1044  else
1045  Log() << Endl;
1046  Log() << kDEBUG << "requested for testing : " << requestedTesting;
1047  if(presel_scale<1)
1048  Log() << " ( " << eventCounts[cls].nTestingEventsRequested
1049  << " * " << presel_scale << " preselection efficiency)" << Endl;
1050  else
1051  Log() << Endl;
1052 
1053  // nomenclature r = available training
1054  // s = available testing
1055  // u = available undefined
1056  // R = requested training
1057  // S = requested testing
1058  // nR = to be used to select training events
1059  // nS = to be used to select test events
1060  // we have the constraint: nR + nS < r+s+u,
1061  // since we can not use more events than we have
1062  // free events: Nfree = u-Thet(R-r)-Thet(S-s)
1063  // nomenclature: Thet(x) = x, if x>0 else 0
1064  // nR = max(R,r) + 0.5 * Nfree
1065  // nS = max(S,s) + 0.5 * Nfree
1066  // nR +nS = R+S + u-R+r-S+s = u+r+s= ok! for R>r
1067  // nR +nS = r+S + u-S+s = u+r+s= ok! for r>R
1068 
1069  // three different cases might occur here
1070  //
1071  // Case a
1072  // requestedTraining and requestedTesting >0
1073  // free events: Nfree = u-Thet(R-r)-Thet(S-s)
1074  // nR = Max(R,r) + 0.5 * Nfree
1075  // nS = Max(S,s) + 0.5 * Nfree
1076  //
1077  // Case b
1078  // exactly one of requestedTraining or requestedTesting >0
1079  // assume training R >0
1080  // nR = max(R,r)
1081  // nS = s+u+r-nR
1082  // and s=nS
1083  //
1084  // Case c
1085  // requestedTraining=0, requestedTesting=0
1086  // Nfree = u-|r-s|
1087  // if NFree >=0
1088  // R = Max(r,s) + 0.5 * Nfree = S
1089  // else if r>s
1090  // R = r; S=s+u
1091  // else
1092  // R = r+u; S=s
1093  //
1094  // Next steps:
1095  // Determination of Event numbers R,S, nR, nS
1096  // distribute undefined events according to nR, nS
1097  // finally determine actual sub samples from nR and nS to be used in training / testing
1098  //
1099 
1100  Int_t useForTesting(0),useForTraining(0);
1101  Int_t allAvailable(availableUndefined + availableTraining + availableTesting);
1102 
1103  if( (requestedTraining == 0) && (requestedTesting == 0)){
1104 
1105  // Case C: balance the number of training and testing events
1106 
1107  if ( availableUndefined >= TMath::Abs(availableTraining - availableTesting) ) {
1108  // enough unspecified are available to equal training and testing
1109  useForTraining = useForTesting = allAvailable/2;
1110  } else {
1111  // all unspecified are assigned to the smaller of training / testing
1112  useForTraining = availableTraining;
1113  useForTesting = availableTesting;
1114  if (availableTraining < availableTesting)
1115  useForTraining += availableUndefined;
1116  else
1117  useForTesting += availableUndefined;
1118  }
1119  requestedTraining = useForTraining;
1120  requestedTesting = useForTesting;
1121  }
1122 
1123  else if (requestedTesting == 0){
1124  // case B
1125  useForTraining = TMath::Max(requestedTraining,availableTraining);
1126  if (allAvailable < useForTraining) {
1127  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName())<< "More events requested for training ("
1128  << requestedTraining << ") than available ("
1129  << allAvailable << ")!" << Endl;
1130  }
1131  useForTesting = allAvailable - useForTraining; // the rest
1132  requestedTesting = useForTesting;
1133  }
1134 
1135  else if (requestedTraining == 0){ // case B)
1136  useForTesting = TMath::Max(requestedTesting,availableTesting);
1137  if (allAvailable < useForTesting) {
1138  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName())<< "More events requested for testing ("
1139  << requestedTesting << ") than available ("
1140  << allAvailable << ")!" << Endl;
1141  }
1142  useForTraining= allAvailable - useForTesting; // the rest
1143  requestedTraining = useForTraining;
1144  }
1145 
1146  else {
1147  // Case A
1148  // requestedTraining R and requestedTesting S >0
1149  // free events: Nfree = u-Thet(R-r)-Thet(S-s)
1150  // nR = Max(R,r) + 0.5 * Nfree
1151  // nS = Max(S,s) + 0.5 * Nfree
1152  Int_t stillNeedForTraining = TMath::Max(requestedTraining-availableTraining,0);
1153  Int_t stillNeedForTesting = TMath::Max(requestedTesting-availableTesting,0);
1154 
1155  int NFree = availableUndefined - stillNeedForTraining - stillNeedForTesting;
1156  if (NFree <0) NFree = 0;
1157  useForTraining = TMath::Max(requestedTraining,availableTraining) + NFree/2;
1158  useForTesting= allAvailable - useForTraining; // the rest
1159  }
1160 
1161  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "determined event sample size to select training sample from="<<useForTraining<<Endl;
1162  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "determined event sample size to select test sample from="<<useForTesting<<Endl;
1163 
1164 
1165 
1166  // associate undefined events
1167  if( splitMode == "ALTERNATE" ){
1168  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "split 'ALTERNATE'" << Endl;
1169  Int_t nTraining = availableTraining;
1170  Int_t nTesting = availableTesting;
1171  for( EventVector::iterator it = eventVectorUndefined.begin(), itEnd = eventVectorUndefined.end(); it != itEnd; ){
1172  ++nTraining;
1173  if( nTraining <= requestedTraining ){
1174  eventVectorTraining.insert( eventVectorTraining.end(), (*it) );
1175  ++it;
1176  }
1177  if( it != itEnd ){
1178  ++nTesting;
1179  eventVectorTesting.insert( eventVectorTesting.end(), (*it) );
1180  ++it;
1181  }
1182  }
1183  } else {
1184  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "split '" << splitMode << "'" << Endl;
1185 
1186  // test if enough events are available
1187  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "availableundefined : " << availableUndefined << Endl;
1188  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "useForTraining : " << useForTraining << Endl;
1189  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "useForTesting : " << useForTesting << Endl;
1190  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "availableTraining : " << availableTraining << Endl;
1191  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "availableTesting : " << availableTesting << Endl;
1192 
1193  if( availableUndefined<(useForTraining-availableTraining) ||
1194  availableUndefined<(useForTesting -availableTesting ) ||
1195  availableUndefined<(useForTraining+useForTesting-availableTraining-availableTesting ) ){
1196  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName())<< "More events requested than available!" << Endl;
1197  }
1198 
1199  // select the events
1200  if (useForTraining>availableTraining){
1201  eventVectorTraining.insert( eventVectorTraining.end() , eventVectorUndefined.begin(), eventVectorUndefined.begin()+ useForTraining- availableTraining );
1202  eventVectorUndefined.erase( eventVectorUndefined.begin(), eventVectorUndefined.begin() + useForTraining- availableTraining);
1203  }
1204  if (useForTesting>availableTesting){
1205  eventVectorTesting.insert( eventVectorTesting.end() , eventVectorUndefined.begin(), eventVectorUndefined.begin()+ useForTesting- availableTesting );
1206  }
1207  }
1208  eventVectorUndefined.clear();
1209 
1210  // finally shorten the event vectors to the requested size by removing random events
1211  if (splitMode.Contains( "RANDOM" )){
1212  UInt_t sizeTraining = eventVectorTraining.size();
1213  if( sizeTraining > UInt_t(requestedTraining) ){
1214  std::vector<UInt_t> indicesTraining( sizeTraining );
1215  // make indices
1216  std::generate( indicesTraining.begin(), indicesTraining.end(), TMVA::Increment<UInt_t>(0) );
1217  // shuffle indices
1218  std::random_shuffle( indicesTraining.begin(), indicesTraining.end(), rndm );
1219  // erase indices of not needed events
1220  indicesTraining.erase( indicesTraining.begin()+sizeTraining-UInt_t(requestedTraining), indicesTraining.end() );
1221  // delete all events with the given indices
1222  for( std::vector<UInt_t>::iterator it = indicesTraining.begin(), itEnd = indicesTraining.end(); it != itEnd; ++it ){
1223  delete eventVectorTraining.at( (*it) ); // delete event
1224  eventVectorTraining.at( (*it) ) = NULL; // set pointer to NULL
1225  }
1226  // now remove and erase all events with pointer==NULL
1227  eventVectorTraining.erase( std::remove( eventVectorTraining.begin(), eventVectorTraining.end(), (void*)NULL ), eventVectorTraining.end() );
1228  }
1229 
1230  UInt_t sizeTesting = eventVectorTesting.size();
1231  if( sizeTesting > UInt_t(requestedTesting) ){
1232  std::vector<UInt_t> indicesTesting( sizeTesting );
1233  // make indices
1234  std::generate( indicesTesting.begin(), indicesTesting.end(), TMVA::Increment<UInt_t>(0) );
1235  // shuffle indices
1236  std::random_shuffle( indicesTesting.begin(), indicesTesting.end(), rndm );
1237  // erase indices of not needed events
1238  indicesTesting.erase( indicesTesting.begin()+sizeTesting-UInt_t(requestedTesting), indicesTesting.end() );
1239  // delete all events with the given indices
1240  for( std::vector<UInt_t>::iterator it = indicesTesting.begin(), itEnd = indicesTesting.end(); it != itEnd; ++it ){
1241  delete eventVectorTesting.at( (*it) ); // delete event
1242  eventVectorTesting.at( (*it) ) = NULL; // set pointer to NULL
1243  }
1244  // now remove and erase all events with pointer==NULL
1245  eventVectorTesting.erase( std::remove( eventVectorTesting.begin(), eventVectorTesting.end(), (void*)NULL ), eventVectorTesting.end() );
1246  }
1247  }
1248  else { // erase at end
1249  if( eventVectorTraining.size() < UInt_t(requestedTraining) )
1250  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "DataSetFactory/requested number of training samples larger than size of eventVectorTraining.\n"
1251  << "There is probably an issue. Please contact the TMVA developers." << Endl;
1252  std::for_each( eventVectorTraining.begin()+requestedTraining, eventVectorTraining.end(), DeleteFunctor<Event>() );
1253  eventVectorTraining.erase(eventVectorTraining.begin()+requestedTraining,eventVectorTraining.end());
1254 
1255  if( eventVectorTesting.size() < UInt_t(requestedTesting) )
1256  Log() << kWARNING << Form("Dataset[%s] : ",dsi.GetName())<< "DataSetFactory/requested number of testing samples larger than size of eventVectorTesting.\n"
1257  << "There is probably an issue. Please contact the TMVA developers." << Endl;
1258  std::for_each( eventVectorTesting.begin()+requestedTesting, eventVectorTesting.end(), DeleteFunctor<Event>() );
1259  eventVectorTesting.erase(eventVectorTesting.begin()+requestedTesting,eventVectorTesting.end());
1260  }
1261  }
1262 
1263  TMVA::DataSetFactory::RenormEvents( dsi, tmpEventVector, eventCounts, normMode );
1264 
1265  Int_t trainingSize = 0;
1266  Int_t testingSize = 0;
1267 
1268  // sum up number of training and testing events
1269  for( UInt_t cls = 0; cls < dsi.GetNClasses(); ++cls ){
1270  trainingSize += tmpEventVector[Types::kTraining].at(cls).size();
1271  testingSize += tmpEventVector[Types::kTesting].at(cls).size();
1272  }
1273 
1274  // --- collect all training (testing) events into the training (testing) eventvector
1275 
1276  // create event vectors reserve enough space
1277  EventVector* trainingEventVector = new EventVector();
1278  EventVector* testingEventVector = new EventVector();
1279 
1280  trainingEventVector->reserve( trainingSize );
1281  testingEventVector->reserve( testingSize );
1282 
1283 
1284  // collect the events
1285 
1286  // mixing of kTraining and kTesting data sets
1287  Log() << kDEBUG << " MIXING ============= " << Endl;
1288 
1289  if( mixMode == "ALTERNATE" ){
1290  // Inform user if he tries to use alternate mixmode for
1291  // event classes with different number of events, this works but the alternation stops at the last event of the smaller class
1292  for( UInt_t cls = 1; cls < dsi.GetNClasses(); ++cls ){
1293  if (tmpEventVector[Types::kTraining].at(cls).size() != tmpEventVector[Types::kTraining].at(0).size()){
1294  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Training sample: You are trying to mix events in alternate mode although the classes have different event numbers. This works but the alternation stops at the last event of the smaller class."<<Endl;
1295  }
1296  if (tmpEventVector[Types::kTesting].at(cls).size() != tmpEventVector[Types::kTesting].at(0).size()){
1297  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Testing sample: You are trying to mix events in alternate mode although the classes have different event numbers. This works but the alternation stops at the last event of the smaller class."<<Endl;
1298  }
1299  }
1300  typedef EventVector::iterator EvtVecIt;
1301  EvtVecIt itEvent, itEventEnd;
1302 
1303  // insert first class
1304  Log() << kDEBUG << "insert class 0 into training and test vector" << Endl;
1305  trainingEventVector->insert( trainingEventVector->end(), tmpEventVector[Types::kTraining].at(0).begin(), tmpEventVector[Types::kTraining].at(0).end() );
1306  testingEventVector->insert( testingEventVector->end(), tmpEventVector[Types::kTesting].at(0).begin(), tmpEventVector[Types::kTesting].at(0).end() );
1307 
1308  // insert other classes
1309  EvtVecIt itTarget;
1310  for( UInt_t cls = 1; cls < dsi.GetNClasses(); ++cls ){
1311  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "insert class " << cls << Endl;
1312  // training vector
1313  itTarget = trainingEventVector->begin() - 1; // start one before begin
1314  // loop over source
1315  for( itEvent = tmpEventVector[Types::kTraining].at(cls).begin(), itEventEnd = tmpEventVector[Types::kTraining].at(cls).end(); itEvent != itEventEnd; ++itEvent ){
1316  // if( std::distance( itTarget, trainingEventVector->end()) < Int_t(cls+1) ) {
1317  if( (trainingEventVector->end() - itTarget) < Int_t(cls+1) ) {
1318  itTarget = trainingEventVector->end();
1319  trainingEventVector->insert( itTarget, itEvent, itEventEnd ); // fill in the rest without mixing
1320  break;
1321  }else{
1322  itTarget += cls+1;
1323  trainingEventVector->insert( itTarget, (*itEvent) ); // fill event
1324  }
1325  }
1326  // testing vector
1327  itTarget = testingEventVector->begin() - 1;
1328  // loop over source
1329  for( itEvent = tmpEventVector[Types::kTesting].at(cls).begin(), itEventEnd = tmpEventVector[Types::kTesting].at(cls).end(); itEvent != itEventEnd; ++itEvent ){
1330  // if( std::distance( itTarget, testingEventVector->end()) < Int_t(cls+1) ) {
1331  if( ( testingEventVector->end() - itTarget ) < Int_t(cls+1) ) {
1332  itTarget = testingEventVector->end();
1333  testingEventVector->insert( itTarget, itEvent, itEventEnd ); // fill in the rest without mixing
1334  break;
1335  }else{
1336  itTarget += cls+1;
1337  testingEventVector->insert( itTarget, (*itEvent) ); // fill event
1338  }
1339  }
1340  }
1341 
1342  // debugging output: classnumbers of all events in training and testing vectors
1343  // std::cout << std::endl;
1344  // std::cout << "TRAINING VECTOR" << std::endl;
1345  // std::transform( trainingEventVector->begin(), trainingEventVector->end(), ostream_iterator<Int_t>(std::cout, "|"), std::mem_fun(&TMVA::Event::GetClass) );
1346 
1347  // std::cout << std::endl;
1348  // std::cout << "TESTING VECTOR" << std::endl;
1349  // std::transform( testingEventVector->begin(), testingEventVector->end(), ostream_iterator<Int_t>(std::cout, "|"), std::mem_fun(&TMVA::Event::GetClass) );
1350  // std::cout << std::endl;
1351 
1352  }else{
1353  for( UInt_t cls = 0; cls < dsi.GetNClasses(); ++cls ){
1354  trainingEventVector->insert( trainingEventVector->end(), tmpEventVector[Types::kTraining].at(cls).begin(), tmpEventVector[Types::kTraining].at(cls).end() );
1355  testingEventVector->insert ( testingEventVector->end(), tmpEventVector[Types::kTesting].at(cls).begin(), tmpEventVector[Types::kTesting].at(cls).end() );
1356  }
1357  }
1358 
1359  // std::cout << "trainingEventVector " << trainingEventVector->size() << std::endl;
1360  // std::cout << "testingEventVector " << testingEventVector->size() << std::endl;
1361 
1362  // std::transform( trainingEventVector->begin(), trainingEventVector->end(), ostream_iterator<Int_t>(std::cout, "> \n"), std::mem_fun(&TMVA::Event::GetNVariables) );
1363  // std::transform( testingEventVector->begin(), testingEventVector->end(), ostream_iterator<Int_t>(std::cout, "> \n"), std::mem_fun(&TMVA::Event::GetNVariables) );
1364 
1365  // delete the tmpEventVector (but not the events therein)
1366  tmpEventVector[Types::kTraining].clear();
1367  tmpEventVector[Types::kTesting].clear();
1368 
1369  tmpEventVector[Types::kMaxTreeType].clear();
1370 
1371  if (mixMode == "RANDOM") {
1372  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "shuffling events"<<Endl;
1373 
1374  std::random_shuffle( trainingEventVector->begin(), trainingEventVector->end(), rndm );
1375  std::random_shuffle( testingEventVector->begin(), testingEventVector->end(), rndm );
1376  }
1377 
1378  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "trainingEventVector " << trainingEventVector->size() << Endl;
1379  Log() << kDEBUG << Form("Dataset[%s] : ",dsi.GetName())<< "testingEventVector " << testingEventVector->size() << Endl;
1380 
1381  // create dataset
1382  DataSet* ds = new DataSet(dsi);
1383 
1384  // Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Create internal training tree" << Endl;
1385  ds->SetEventCollection(trainingEventVector, Types::kTraining );
1386  // Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Create internal testing tree" << Endl;
1387  ds->SetEventCollection(testingEventVector, Types::kTesting );
1388 
1389 
1390  if (ds->GetNTrainingEvents() < 1){
1391  Log() << kFATAL << "Dataset " << std::string(dsi.GetName()) << " does not have any training events, I better stop here and let you fix that one first " << Endl;
1392  }
1393 
1394  if (ds->GetNTestEvents() < 1) {
1395  Log() << kERROR << "Dataset " << std::string(dsi.GetName()) << " does not have any testing events, guess that will cause problems later..but for now, I continue " << Endl;
1396  }
1397 
1398 
1399  return ds;
1400 
1401 }
1402 
1403 ////////////////////////////////////////////////////////////////////////////////
1404 /// =============================================================================
1405 /// renormalisation of the TRAINING event weights
1406 /// -none (kind of obvious) .. use the weights as supplied by the
1407 /// user.. (we store however the relative weight for later use)
1408 /// -numEvents
1409 /// -equalNumEvents reweight the training events such that the sum of all
1410 /// backgr. (class > 0) weights equal that of the signal (class 0)
1411 /// =============================================================================
1412 
1413 void
1415  EventVectorOfClassesOfTreeType& tmpEventVector,
1416  const EvtStatsPerClass& eventCounts,
1417  const TString& normMode )
1418 {
1419 
1420 
1421  // print rescaling info
1422  // ---------------------------------
1423  // compute sizes and sums of weights
1424  Int_t trainingSize = 0;
1425  Int_t testingSize = 0;
1426 
1427  ValuePerClass trainingSumWeightsPerClass( dsi.GetNClasses() );
1428  ValuePerClass testingSumWeightsPerClass( dsi.GetNClasses() );
1429 
1430  NumberPerClass trainingSizePerClass( dsi.GetNClasses() );
1431  NumberPerClass testingSizePerClass( dsi.GetNClasses() );
1432 
1433  Double_t trainingSumSignalWeights = 0;
1434  Double_t trainingSumBackgrWeights = 0; // Backgr. includes all clasess that are not signal
1435  Double_t testingSumSignalWeights = 0;
1436  Double_t testingSumBackgrWeights = 0; // Backgr. includes all clasess that are not signal
1437 
1438 
1439 
1440  for( UInt_t cls = 0, clsEnd = dsi.GetNClasses(); cls < clsEnd; ++cls ){
1441  trainingSizePerClass.at(cls) = tmpEventVector[Types::kTraining].at(cls).size();
1442  testingSizePerClass.at(cls) = tmpEventVector[Types::kTesting].at(cls).size();
1443 
1444  trainingSize += trainingSizePerClass.back();
1445  testingSize += testingSizePerClass.back();
1446 
1447  // the functional solution
1448  // sum up the weights in Double_t although the individual weights are Float_t to prevent rounding issues in addition of floating points
1449  //
1450  // accumulate --> does what the name says
1451  // begin() and end() denote the range of the vector to be accumulated
1452  // Double_t(0) tells accumulate the type and the starting value
1453  // compose_binary creates a BinaryFunction of ...
1454  // std::plus<Double_t>() knows how to sum up two doubles
1455  // null<Double_t>() leaves the first argument (the running sum) unchanged and returns it
1456  // std::mem_fun knows how to call a member function (type and member-function given as argument) and return the result
1457  //
1458  // all together sums up all the event-weights of the events in the vector and returns it
1459  trainingSumWeightsPerClass.at(cls) = std::accumulate( tmpEventVector[Types::kTraining].at(cls).begin(),
1460  tmpEventVector[Types::kTraining].at(cls).end(),
1461  Double_t(0),
1462  compose_binary( std::plus<Double_t>(),
1463  null<Double_t>(),
1464  std::mem_fun(&TMVA::Event::GetOriginalWeight) ) );
1465 
1466  testingSumWeightsPerClass.at(cls) = std::accumulate( tmpEventVector[Types::kTesting].at(cls).begin(),
1467  tmpEventVector[Types::kTesting].at(cls).end(),
1468  Double_t(0),
1469  compose_binary( std::plus<Double_t>(),
1470  null<Double_t>(),
1471  std::mem_fun(&TMVA::Event::GetOriginalWeight) ) );
1472 
1473  if ( cls == dsi.GetSignalClassIndex()){
1474  trainingSumSignalWeights += trainingSumWeightsPerClass.at(cls);
1475  testingSumSignalWeights += testingSumWeightsPerClass.at(cls);
1476  }else{
1477  trainingSumBackgrWeights += trainingSumWeightsPerClass.at(cls);
1478  testingSumBackgrWeights += testingSumWeightsPerClass.at(cls);
1479  }
1480  }
1481 
1482  // ---------------------------------
1483  // compute renormalization factors
1484 
1485  ValuePerClass renormFactor( dsi.GetNClasses() );
1486 
1487 
1488  // for information purposes
1489  dsi.SetNormalization( normMode );
1490  // !! these will be overwritten later by the 'rescaled' ones if
1491  // NormMode != None !!!
1492  dsi.SetTrainingSumSignalWeights(trainingSumSignalWeights);
1493  dsi.SetTrainingSumBackgrWeights(trainingSumBackgrWeights);
1494  dsi.SetTestingSumSignalWeights(testingSumSignalWeights);
1495  dsi.SetTestingSumBackgrWeights(testingSumBackgrWeights);
1496 
1497 
1498  if (normMode == "NONE") {
1499  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "No weight renormalisation applied: use original global and event weights" << Endl;
1500  return;
1501  }
1502  //changed by Helge 27.5.2013 What on earth was done here before? I still remember the idea behind this which apparently was
1503  //NOT understood by the 'programmer' :) .. the idea was to have SAME amount of effective TRAINING data for signal and background.
1504  // Testing events are totally irrelevant for this and might actually skew the whole normalisation!!
1505  else if (normMode == "NUMEVENTS") {
1506  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1507  << "\tWeight renormalisation mode: \"NumEvents\": renormalises all event classes " << Endl;
1508  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1509  << " such that the effective (weighted) number of events in each class equals the respective " << Endl;
1510  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1511  << " number of events (entries) that you demanded in PrepareTrainingAndTestTree(\"\",\"nTrain_Signal=.. )" << Endl;
1512  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1513  << " ... i.e. such that Sum[i=1..N_j]{w_i} = N_j, j=0,1,2..." << Endl;
1514  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1515  << " ... (note that N_j is the sum of TRAINING events (nTrain_j...with j=Signal,Background.." << Endl;
1516  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1517  << " ..... Testing events are not renormalised nor included in the renormalisation factor! )"<< Endl;
1518 
1519  for( UInt_t cls = 0, clsEnd = dsi.GetNClasses(); cls < clsEnd; ++cls ){
1520  // renormFactor.at(cls) = ( (trainingSizePerClass.at(cls) + testingSizePerClass.at(cls))/
1521  // (trainingSumWeightsPerClass.at(cls) + testingSumWeightsPerClass.at(cls)) );
1522  //changed by Helge 27.5.2013
1523  renormFactor.at(cls) = ((Float_t)trainingSizePerClass.at(cls) )/
1524  (trainingSumWeightsPerClass.at(cls)) ;
1525  }
1526  }
1527  else if (normMode == "EQUALNUMEVENTS") {
1528  //changed by Helge 27.5.2013 What on earth was done here before? I still remember the idea behind this which apparently was
1529  //NOT understood by the 'programmer' :) .. the idea was to have SAME amount of effective TRAINING data for signal and background.
1530  //done here was something like having each data source normalized to its number of entries and this even for trainig+testing together.
1531  // what should this have been good for ???
1532 
1533  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "Weight renormalisation mode: \"EqualNumEvents\": renormalises all event classes ..." << Endl;
1534  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " such that the effective (weighted) number of events in each class is the same " << Endl;
1535  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " (and equals the number of events (entries) given for class=0 )" << Endl;
1536  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "... i.e. such that Sum[i=1..N_j]{w_i} = N_classA, j=classA, classB, ..." << Endl;
1537  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << "... (note that N_j is the sum of TRAINING events" << Endl;
1538  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << " ..... Testing events are not renormalised nor included in the renormalisation factor!)" << Endl;
1539 
1540  // normalize to size of first class
1541  UInt_t referenceClass = 0;
1542  for (UInt_t cls = 0, clsEnd = dsi.GetNClasses(); cls < clsEnd; ++cls ) {
1543  renormFactor.at(cls) = Float_t(trainingSizePerClass.at(referenceClass))/
1544  (trainingSumWeightsPerClass.at(cls));
1545  }
1546  }
1547  else {
1548  Log() << kFATAL << Form("Dataset[%s] : ",dsi.GetName())<< "<PrepareForTrainingAndTesting> Unknown NormMode: " << normMode << Endl;
1549  }
1550 
1551  // ---------------------------------
1552  // now apply the normalization factors
1553  Int_t maxL = dsi.GetClassNameMaxLength();
1554  for (UInt_t cls = 0, clsEnd = dsi.GetNClasses(); cls<clsEnd; ++cls) {
1555  Log() << kDEBUG //<< Form("Dataset[%s] : ",dsi.GetName())
1556  << "--> Rescale " << setiosflags(ios::left) << std::setw(maxL)
1557  << dsi.GetClassInfo(cls)->GetName() << " event weights by factor: " << renormFactor.at(cls) << Endl;
1558  for (EventVector::iterator it = tmpEventVector[Types::kTraining].at(cls).begin(),
1559  itEnd = tmpEventVector[Types::kTraining].at(cls).end(); it != itEnd; ++it){
1560  (*it)->SetWeight ((*it)->GetWeight() * renormFactor.at(cls));
1561  }
1562 
1563  }
1564 
1565 
1566  // print out the result
1567  // (same code as before --> this can be done nicer )
1568  //
1569 
1570  Log() << kINFO //<< Form("Dataset[%s] : ",dsi.GetName())
1571  << "Number of training and testing events" << Endl;
1572  Log() << kDEBUG << "\tafter rescaling:" << Endl;
1573  Log() << kINFO //<< Form("Dataset[%s] : ",dsi.GetName())
1574  << "---------------------------------------------------------------------------" << Endl;
1575 
1576  trainingSumSignalWeights = 0;
1577  trainingSumBackgrWeights = 0; // Backgr. includes all clasess that are not signal
1578  testingSumSignalWeights = 0;
1579  testingSumBackgrWeights = 0; // Backgr. includes all clasess that are not signal
1580 
1581  for( UInt_t cls = 0, clsEnd = dsi.GetNClasses(); cls < clsEnd; ++cls ){
1582 
1583  trainingSumWeightsPerClass.at(cls) = (std::accumulate( tmpEventVector[Types::kTraining].at(cls).begin(), // accumulate --> start at begin
1584  tmpEventVector[Types::kTraining].at(cls).end(), // until end()
1585  Double_t(0), // values are of type double
1586  compose_binary( std::plus<Double_t>(), // define addition for doubles
1587  null<Double_t>(), // take the argument, don't do anything and return it
1588  std::mem_fun(&TMVA::Event::GetOriginalWeight) ) )); // take the value from GetOriginalWeight
1589 
1590  testingSumWeightsPerClass.at(cls) = std::accumulate( tmpEventVector[Types::kTesting].at(cls).begin(),
1591  tmpEventVector[Types::kTesting].at(cls).end(),
1592  Double_t(0),
1593  compose_binary( std::plus<Double_t>(),
1594  null<Double_t>(),
1595  std::mem_fun(&TMVA::Event::GetOriginalWeight) ) );
1596 
1597 
1598  if ( cls == dsi.GetSignalClassIndex()){
1599  trainingSumSignalWeights += trainingSumWeightsPerClass.at(cls);
1600  testingSumSignalWeights += testingSumWeightsPerClass.at(cls);
1601  }else{
1602  trainingSumBackgrWeights += trainingSumWeightsPerClass.at(cls);
1603  testingSumBackgrWeights += testingSumWeightsPerClass.at(cls);
1604  }
1605 
1606  // output statistics
1607 
1608  Log() << kINFO //<< Form("Dataset[%s] : ",dsi.GetName())
1609  << setiosflags(ios::left) << std::setw(maxL)
1610  << dsi.GetClassInfo(cls)->GetName() << " -- "
1611  << "training events : " << trainingSizePerClass.at(cls) << Endl;
1612  Log() << kDEBUG << "\t(sum of weights: " << trainingSumWeightsPerClass.at(cls) << ")"
1613  << " - requested were " << eventCounts[cls].nTrainingEventsRequested << " events" << Endl;
1614  Log() << kINFO //<< Form("Dataset[%s] : ",dsi.GetName())
1615  << setiosflags(ios::left) << std::setw(maxL)
1616  << dsi.GetClassInfo(cls)->GetName() << " -- "
1617  << "testing events : " << testingSizePerClass.at(cls) << Endl;
1618  Log() << kDEBUG << "\t(sum of weights: " << testingSumWeightsPerClass.at(cls) << ")"
1619  << " - requested were " << eventCounts[cls].nTestingEventsRequested << " events" << Endl;
1620  Log() << kINFO //<< Form("Dataset[%s] : ",dsi.GetName())
1621  << setiosflags(ios::left) << std::setw(maxL)
1622  << dsi.GetClassInfo(cls)->GetName() << " -- "
1623  << "training and testing events: "
1624  << (trainingSizePerClass.at(cls)+testingSizePerClass.at(cls)) << Endl;
1625  Log() << kDEBUG << "\t(sum of weights: "
1626  << (trainingSumWeightsPerClass.at(cls)+testingSumWeightsPerClass.at(cls)) << ")" << Endl;
1627  if(eventCounts[cls].nEvAfterCut<eventCounts[cls].nEvBeforeCut) {
1628  Log() << kINFO << Form("Dataset[%s] : ",dsi.GetName()) << setiosflags(ios::left) << std::setw(maxL)
1629  << dsi.GetClassInfo(cls)->GetName() << " -- "
1630  << "due to the preselection a scaling factor has been applied to the numbers of requested events: "
1631  << eventCounts[cls].cutScaling() << Endl;
1632  }
1633  }
1634  Log() << kINFO << Endl;
1635 
1636  // for information purposes
1637  dsi.SetTrainingSumSignalWeights(trainingSumSignalWeights);
1638  dsi.SetTrainingSumBackgrWeights(trainingSumBackgrWeights);
1639  dsi.SetTestingSumSignalWeights(testingSumSignalWeights);
1640  dsi.SetTestingSumBackgrWeights(testingSumBackgrWeights);
1641 
1642 
1643 }
1644 
const int ndata
TTree * GetTree() const
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition: TLeaf.h:37
UInt_t GetNVariables() const
Definition: DataSetInfo.h:128
std::vector< EventVector > EventVectorOfClasses
void SetTrainingSumBackgrWeights(Double_t trainingSumBackgrWeights)
Definition: DataSetInfo.h:136
MsgLogger & Endl(MsgLogger &ml)
Definition: MsgLogger.h:162
long long Long64_t
Definition: RtypesCore.h:69
const TString & GetInternalName() const
Definition: VariableInfo.h:66
std::vector< VariableInfo > & GetSpectatorInfos()
Definition: DataSetInfo.h:122
std::vector< TTreeFormula * > fInputFormulas
float Float_t
Definition: RtypesCore.h:53
std::vector< TTreeFormula * > fCutFormulas
std::vector< Double_t > ValuePerClass
UInt_t GetNVariables() const
access the number of variables through the datasetinfo
Definition: DataSet.cxx:225
void SetTrainingSumSignalWeights(Double_t trainingSumSignalWeights)
Definition: DataSetInfo.h:135
void SetTestingSumBackgrWeights(Double_t testingSumBackgrWeights)
Definition: DataSetInfo.h:138
void BuildEventVector(DataSetInfo &dsi, DataInputHandler &dataInput, EventVectorOfClassesOfTreeType &eventsmap, EvtStatsPerClass &eventCounts)
build empty event vectors distributes events between kTraining/kTesting/kMaxTreeType ...
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
TArc * a
Definition: textangle.C:12
const Bool_t kFALSE
Definition: Rtypes.h:92
void generate(R &r, TH1D *h)
Definition: piRandom.C:28
UInt_t GetNClasses() const
Definition: DataSetInfo.h:154
STL namespace.
std::vector< TreeInfo >::const_iterator end(const TString &className) const
void CalcMinMax(DataSet *, DataSetInfo &dsi)
compute covariance matrix
Short_t Abs(Short_t d)
Definition: TMathBase.h:110
virtual Int_t GetNdim() const
Definition: TFormula.h:243
const TString & GetExpression() const
Definition: VariableInfo.h:65
std::vector< int > NumberPerClass
std::map< Types::ETreeType, EventVectorOfClasses > EventVectorOfClassesOfTreeType
double sqrt(double)
void InitOptions(DataSetInfo &dsi, EvtStatsPerClass &eventsmap, TString &normMode, UInt_t &splitSeed, TString &splitMode, TString &mixMode)
the dataset splitting
DataSet * BuildDynamicDataSet(DataSetInfo &)
UInt_t GetNSpectators() const
access the number of targets through the datasetinfo
Definition: DataSet.cxx:241
MsgLogger & Log() const
message logger
std::vector< TTreeFormula * > fWeightFormula
UInt_t GetClass() const
Definition: Event.h:89
void SetTestingSumSignalWeights(Double_t testingSumSignalWeights)
Definition: DataSetInfo.h:137
std::vector< std::vector< double > > Data
void PrintCorrelationMatrix(const TString &className)
calculates the correlation matrices for signal and background, prints them to standard output...
void SetMin(Double_t v)
Definition: VariableInfo.h:77
void SetMinType(EMsgType minType)
Definition: MsgLogger.h:76
void RenormEvents(DataSetInfo &dsi, EventVectorOfClassesOfTreeType &eventsmap, const EvtStatsPerClass &eventCounts, const TString &normMode)
renormalisation of the TRAINING event weights -none (kind of obvious) .
virtual Int_t GetNcodes() const
Definition: TTreeFormula.h:199
Double_t GetWeight() const
return the event weight - depending on whether the flag IgnoreNegWeightsInTraining is or not...
Definition: Event.cxx:378
Long64_t GetNTrainingEvents() const
Definition: DataSet.h:93
Used to pass a selection expression to the Tree drawing routine.
Definition: TTreeFormula.h:64
void ChangeToNewTree(TreeInfo &, const DataSetInfo &)
While the data gets copied into the local training and testing trees, the input tree can change (for ...
TMatrixT< Double_t > TMatrixD
Definition: TMatrixDfwd.h:24
void SetCorrelationMatrix(const TString &className, TMatrixD *matrix)
DataSetFactory()
constructor
TMatrixD * CalcCorrelationMatrix(DataSet *, const UInt_t classNumber)
computes correlation matrix for variables "theVars" in tree; "theType" defines the required event "ty...
Float_t GetTarget(UInt_t itgt) const
Definition: Event.h:104
Int_t LargestCommonDivider(Int_t a, Int_t b)
UInt_t GetNTargets() const
Definition: DataSetInfo.h:129
Types::ETreeType GetTreeType() const
SVector< double, 2 > v
Definition: Dict.h:5
ClassInfo * GetClassInfo(Int_t clNum) const
std::vector< TTreeFormula * > fSpectatorFormulas
DataSet * CreateDataSet(DataSetInfo &, DataInputHandler &)
steering the creation of a new dataset
VariableInfo & GetTargetInfo(Int_t i)
Definition: DataSetInfo.h:119
std::vector< TreeInfo >::const_iterator begin(const TString &className) const
unsigned int UInt_t
Definition: RtypesCore.h:42
char * Form(const char *fmt,...)
UInt_t GetNSpectators(bool all=kTRUE) const
UInt_t GetSignalClassIndex()
Definition: DataSetInfo.h:157
std::vector< TTreeFormula * > fTargetFormulas
std::vector< Event *> EventVector
Long64_t GetNTestEvents() const
Definition: DataSet.h:94
void SetMax(Double_t v)
Definition: VariableInfo.h:78
Float_t GetValue(UInt_t ivar) const
return value of i&#39;th variable
Definition: Event.cxx:233
DataSet * BuildInitialDataSet(DataSetInfo &, TMVA::DataInputHandler &)
if no entries, than create a DataSet with one Event which uses dynamic variables (pointers to variabl...
~DataSetFactory()
destructor
virtual Int_t GetNdata()
Return number of available instances in the formula.
virtual TLeaf * GetLeaf(Int_t n) const
Return leaf corresponding to serial number n.
double Double_t
Definition: RtypesCore.h:55
const TString & GetClassName() const
VariableInfo & GetSpectatorInfo(Int_t i)
Definition: DataSetInfo.h:124
compose_binary_t< F, G, H > compose_binary(const F &_f, const G &_g, const H &_h)
UInt_t GetEntries(const TString &name) const
void SetEventCollection(std::vector< Event *> *, Types::ETreeType, Bool_t deleteEvents=true)
Sets the event collection (by DataSetFactory)
Definition: DataSet.cxx:259
VariableInfo & GetVariableInfo(Int_t i)
Definition: DataSetInfo.h:114
T EvalInstance(Int_t i=0, const char *stringStack[]=0)
Evaluate this treeformula.
ClassInfo * AddClass(const TString &className)
Int_t GetClassNameMaxLength() const
virtual const char * GetName() const
Returns name of object.
Definition: DataSetInfo.h:85
Long64_t GetNClassEvents(Int_t type, UInt_t classNumber)
Definition: DataSet.cxx:177
void SetConfigName(const char *n)
Definition: Configurable.h:69
virtual const char * GetTitle() const
Returns title of object.
Definition: TObject.cxx:460
Abstract ClassifierFactory template that handles arbitrary types.
const TCut & GetCut() const
Definition: ClassInfo.h:72
std::vector< EventStats > EvtStatsPerClass
const TString & GetSplitOptions() const
Definition: DataSetInfo.h:185
Bool_t HasCuts() const
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
Int_t IsNaN(Double_t x)
Definition: TMath.h:613
Double_t GetOriginalWeight() const
Definition: Event.h:87
Bool_t CheckTTreeFormula(TTreeFormula *ttf, const TString &expression, Bool_t &hasDollar)
checks a TTreeFormula for problems
void SetNumber(const UInt_t index)
Definition: ClassInfo.h:67
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
#define NULL
Definition: Rtypes.h:82
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
Definition: DataSet.h:229
const TString & GetWeight() const
Definition: ClassInfo.h:71
DataSet * MixEvents(DataSetInfo &dsi, EventVectorOfClassesOfTreeType &eventsmap, EvtStatsPerClass &eventCounts, const TString &splitMode, const TString &mixMode, const TString &normMode, UInt_t splitSeed)
Select and distribute unassigned events to kTraining and kTesting Bool_t emptyUndefined = kTRUE;...
TBranch * GetBranch() const
Definition: TLeaf.h:70
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:416
virtual Bool_t IsOnTerminalBranch() const
Definition: TLeaf.h:89
const Bool_t kTRUE
Definition: Rtypes.h:91
Double_t GetWeight() const
UInt_t GetNTargets() const
access the number of targets through the datasetinfo
Definition: DataSet.cxx:233
Float_t GetSpectator(UInt_t ivar) const
return spectator content
Definition: Event.cxx:258
void SetNormalization(const TString &norm)
Definition: DataSetInfo.h:133
TMatrixD * CalcCovarianceMatrix(DataSet *, const UInt_t classNumber)
compute covariance matrix
const Event * GetEvent() const
Definition: DataSet.cxx:211
std::vector< VariableInfo > & GetVariableInfos()
Definition: DataSetInfo.h:112
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
std::vector< TString > * GetClassList() const