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