laura is hosted by Hepforge, IPPP Durham
Laura++  v2r1
A maximum likelihood fitting package for performing Dalitz-plot analysis.
LauAbsFitModel.cc
Go to the documentation of this file.
1 
2 // Copyright University of Warwick 2004 - 2014.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5 
6 // Authors:
7 // Thomas Latham
8 // John Back
9 // Paul Harrison
10 
15 #include <iostream>
16 #include <limits>
17 #include <vector>
18 
19 #include "TMessage.h"
20 #include "TMonitor.h"
21 #include "TServerSocket.h"
22 #include "TSocket.h"
23 #include "TSystem.h"
24 #include "TVectorD.h"
25 #include "TVirtualFitter.h"
26 
27 #include "LauAbsFitModel.hh"
28 #include "LauAbsFitter.hh"
29 #include "LauAbsPdf.hh"
30 #include "LauComplex.hh"
31 #include "LauFitter.hh"
32 #include "LauFitDataTree.hh"
33 #include "LauFitNtuple.hh"
34 #include "LauGenNtuple.hh"
35 #include "LauParameter.hh"
36 #include "LauParamFixed.hh"
37 #include "LauPrint.hh"
38 #include "LauSPlot.hh"
39 
41 
42 
44  storeCon_(0),
45  twoStageFit_(kFALSE),
46  useAsymmFitErrors_(kFALSE),
47  compareFitData_(kFALSE),
48  writeLatexTable_(kFALSE),
49  writeSPlotData_(kFALSE),
50  storeDPEff_(kFALSE),
51  randomFit_(kFALSE),
52  emlFit_(kFALSE),
53  poissonSmear_(kFALSE),
54  enableEmbedding_(kFALSE),
55  usingDP_(kTRUE),
56  pdfsDependOnDP_(kFALSE),
57  firstExpt_(0),
58  nExpt_(0),
59  evtsPerExpt_(0),
60  iExpt_(0),
61  inputFitData_(0),
62  fitNtuple_(0),
63  genNtuple_(0),
64  sPlotNtuple_(0),
65  fitStatus_(0),
66  NLL_(0),
67  numberOKFits_(0),
68  numberBadFits_(0),
69  nParams_(0),
70  nFreeParams_(0),
71  worstLogLike_(std::numeric_limits<Double_t>::max()),
72  withinAsymErrorCalc_(kFALSE),
73  nullString_(""),
74  doSFit_(kFALSE),
75  sWeightBranchName_(""),
76  sWeightScaleFactor_(1.0),
77  fitToyMCFileName_("fitToyMC.root"),
78  fitToyMCTableName_("fitToyMCTable"),
79  fitToyMCScale_(10),
80  fitToyMCPoissonSmear_(kFALSE),
81  sPlotFileName_(""),
82  sPlotTreeName_(""),
83  sPlotVerbosity_(""),
84  sMaster_(0),
85  messageFromMaster_(0),
86  slaveId_(-1),
87  nSlaves_(0),
88  parValues_(0)
89 {
90 }
91 
92 
94 {
95  delete inputFitData_; inputFitData_ = 0;
96  delete fitNtuple_; fitNtuple_ = 0;
97  delete genNtuple_; genNtuple_ = 0;
98  delete sPlotNtuple_; sPlotNtuple_ = 0;
99  delete sMaster_; sMaster_ = 0;
100  delete[] parValues_; parValues_ = 0;
101 
102  // Remove the components created to apply constraints to fit parameters
103  for (std::vector<LauAbsRValue*>::iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter){
104  if ( !(*iter)->isLValue() ){
105  delete (*iter);
106  (*iter) = 0;
107  }
108  }
109 }
110 
111 void LauAbsFitModel::run(const TString& applicationCode, const TString& dataFileName, const TString& dataTreeName,
112  const TString& histFileName, const TString& tableFileName)
113 {
114  // Chose whether you want to generate or fit events in the Dalitz plot.
115  // To generate events choose applicationCode = "gen", to fit events choose
116  // applicationCode = "fit".
117 
118  TString runCode(applicationCode);
119  runCode.ToLower();
120 
121  TString histFileNameCopy(histFileName);
122  TString tableFileNameCopy(tableFileName);
123  TString dataFileNameCopy(dataFileName);
124  TString dataTreeNameCopy(dataTreeName);
125 
126  // Initialise the fit par vectors. Each class that inherits from this one
127  // must implement this sensibly for all vectors specified in clearFitParVectors,
128  // i.e. specify parameter names, initial, min, max and fixed values
129  this->initialise();
130 
131  // Add variables to Gaussian constrain to a list
132  this->addConParameters();
133 
134  // Add formula Gaussian constraints to the list
135 
136  if (dataFileNameCopy == "") {dataFileNameCopy = "data.root";}
137  if (dataTreeNameCopy == "") {dataTreeNameCopy = "genResults";}
138 
139  if (runCode.Contains("gen")) {
140 
141  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
142  if (tableFileNameCopy == "") {tableFileNameCopy = "genResults";}
143 
144  this->setGenValues();
145  this->generate(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
146 
147  } else if (runCode.Contains("fit")) {
148 
149  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
150  if (tableFileNameCopy == "") {tableFileNameCopy = "fitResults";}
151 
152  this->fit(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
153 
154  } else if (runCode.Contains("reweight")) {
155 
156  this->weightEvents(dataFileNameCopy, dataTreeNameCopy);
157  }
158 }
159 
160 void LauAbsFitModel::runSlave(const TString& dataFileName, const TString& dataTreeName,
161  const TString& histFileName, const TString& tableFileName,
162  const TString& addressMaster, const UInt_t portMaster)
163 {
164  if ( sMaster_ != 0 ) {
165  std::cerr << "ERROR in LauAbsFitModel::runSlave : master socket already present" << std::endl;
166  return;
167  }
168 
169  // Open connection to master
170  sMaster_ = new TSocket(addressMaster, portMaster);
171  sMaster_->Recv( messageFromMaster_ );
172  messageFromMaster_->ReadUInt( slaveId_ );
173  messageFromMaster_->ReadUInt( nSlaves_ );
174 
175  delete messageFromMaster_;
176  messageFromMaster_ = 0;
177 
178  std::cout << "INFO in LauAbsFitModel::runSlave : Established connection to master on port " << portMaster << std::endl;
179  std::cout << " : We are slave " << slaveId_ << " of " << nSlaves_ << std::endl;
180 
181  // Initialise the fit par vectors. Each class that inherits from this one
182  // must implement this sensibly for all vectors specified in clearFitParVectors,
183  // i.e. specify parameter names, initial, min, max and fixed values
184  this->initialise();
185 
186  nParams_ = fitVars_.size();
187  parValues_ = new Double_t[nParams_];
188  for ( UInt_t iPar(0); iPar < nParams_; ++iPar ) {
189  parValues_[iPar] = fitVars_[iPar]->initValue();
190  }
191 
192  TString dataFileNameCopy(dataFileName);
193  TString dataTreeNameCopy(dataTreeName);
194  TString histFileNameCopy(histFileName);
195  TString tableFileNameCopy(tableFileName);
196 
197  if (dataFileNameCopy == "") {dataFileNameCopy = "data.root";}
198  if (dataTreeNameCopy == "") {dataTreeNameCopy = "genResults";}
199  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
200  if (tableFileNameCopy == "") {tableFileNameCopy = "fitResults";}
201 
202  this->fitSlave(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
203 
204  std::cout << "INFO in LauAbsFitModel::runSlave : Fit slave " << slaveId_ << " has finished successfully" << std::endl;
205 }
206 
207 void LauAbsFitModel::doSFit( const TString& sWeightBranchName, Double_t scaleFactor )
208 {
209  if ( sWeightBranchName == "" ) {
210  std::cerr << "WARNING in LauAbsFitModel::doSFit : sWeight branch name is empty string, not setting-up sFit." << std::endl;
211  return;
212  }
213 
214  doSFit_ = kTRUE;
215  sWeightBranchName_ = sWeightBranchName;
216  sWeightScaleFactor_ = scaleFactor;
217 }
218 
219 void LauAbsFitModel::setBkgndClassNames( const std::vector<TString>& names )
220 {
221  if ( !bkgndClassNames_.empty() ) {
222  std::cerr << "WARNING in LauAbsFitModel::setBkgndClassNames : Names already stored, not changing them." << std::endl;
223  return;
224  }
225 
226  UInt_t nBkgnds = names.size();
227  for ( UInt_t i(0); i < nBkgnds; ++i ) {
228  bkgndClassNames_.insert( std::make_pair( i, names[i] ) );
229  }
230 
231  this->setupBkgndVectors();
232 }
233 
234 Bool_t LauAbsFitModel::validBkgndClass( const TString& className ) const
235 {
236  if ( bkgndClassNames_.empty() ) {
237  return kFALSE;
238  }
239 
240  Bool_t found(kFALSE);
241  for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) {
242  if ( iter->second == className ) {
243  found = kTRUE;
244  break;
245  }
246  }
247 
248  return found;
249 }
250 
251 UInt_t LauAbsFitModel::bkgndClassID( const TString& className ) const
252 {
253  if ( ! this->validBkgndClass( className ) ) {
254  std::cerr << "ERROR in LauAbsFitModel::bkgndClassID : Request for ID for invalid background class \"" << className << "\"." << std::endl;
255  return (bkgndClassNames_.size() + 1);
256  }
257 
258  UInt_t bgID(0);
259  for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) {
260  if ( iter->second == className ) {
261  bgID = iter->first;
262  break;
263  }
264  }
265 
266  return bgID;
267 }
268 
269 const TString& LauAbsFitModel::bkgndClassName( UInt_t classID ) const
270 {
271  LauBkgndClassMap::const_iterator iter = bkgndClassNames_.find( classID );
272 
273  if ( iter == bkgndClassNames_.end() ) {
274  std::cerr << "ERROR in LauAbsFitModel::bkgndClassName : Request for name of invalid background class ID " << classID << "." << std::endl;
275  return nullString_;
276  }
277 
278  return iter->second;
279 }
280 
282 {
283  std::cout << "INFO in LauAbsFitModel::clearFitParVectors : Clearing fit variable vectors" << std::endl;
284 
285  // Remove the components created to apply constraints to fit parameters
286  for (std::vector<LauAbsRValue*>::iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter){
287  if ( !(*iter)->isLValue() ){
288  delete (*iter);
289  (*iter) = 0;
290  }
291  }
292  conVars_.clear();
293  fitVars_.clear();
294 }
295 
297 {
298  std::cout << "INFO in LauAbsFitModel::clearExtraVarVectors : Clearing extra ntuple variable vectors" << std::endl;
299  extraVars_.clear();
300 }
301 
303 {
304  // makes sure each parameter holds its genValue as its current value
305  for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) {
306  (*iter)->value((*iter)->genValue());
307  }
308  this->propagateParUpdates();
309 }
310 
311 void LauAbsFitModel::writeSPlotData(const TString& fileName, const TString& treeName, Bool_t storeDPEfficiency, const TString& verbosity)
312 {
313  if (this->writeSPlotData()) {
314  std::cerr << "ERROR in LauAbsFitModel::writeSPlotData : Already have an sPlot ntuple setup, not doing it again." << std::endl;
315  return;
316  }
317  writeSPlotData_ = kTRUE;
318  sPlotFileName_ = fileName;
319  sPlotTreeName_ = treeName;
320  sPlotVerbosity_ = verbosity;
321  storeDPEff_ = storeDPEfficiency;
322 }
323 
324 // TODO : histFileName isn't used here at the moment but could be used for
325 // storing the values of the parameters used in the generation.
326 // These could then be read and used for setting the "true" values
327 // in a subsequent fit.
328 void LauAbsFitModel::generate(const TString& dataFileName, const TString& dataTreeName, const TString& /*histFileName*/, const TString& tableFileNameBase)
329 {
330  // Create the ntuple for storing the results
331  std::cout << "INFO in LauAbsFitModel::generate : Creating generation ntuple." << std::endl;
332  if (genNtuple_ != 0) {delete genNtuple_; genNtuple_ = 0;}
333  genNtuple_ = new LauGenNtuple(dataFileName,dataTreeName);
334 
335  // add branches for storing the experiment number and the number of
336  // the event within the current experiment
337  this->addGenNtupleIntegerBranch("iExpt");
338  this->addGenNtupleIntegerBranch("iEvtWithinExpt");
339  this->setupGenNtupleBranches();
340 
341  // Start the cumulative timer
342  cumulTimer_.Start();
343 
344  Bool_t genOK(kTRUE);
345  do {
346  // Loop over the number of experiments
347  for (iExpt_ = firstExpt_; iExpt_ < (firstExpt_+nExpt_); ++iExpt_) {
348 
349  // Start the timer to see how long each experiment takes to generate
350  timer_.Start();
351 
352  // Store the experiment number in the ntuple
353  this->setGenNtupleIntegerBranchValue("iExpt",iExpt_);
354 
355  // Do the generation for this experiment
356  std::cout << "INFO in LauAbsFitModel::generate : Generating experiment number " << iExpt_ << std::endl;
357  genOK = this->genExpt();
358 
359  // Stop the timer and see how long the program took so far
360  timer_.Stop();
361  timer_.Print();
362 
363  if (!genOK) {
364  // delete and recreate an empty tree
366 
367  // then break out of the experiment loop
368  std::cerr << "ERROR in LauAbsFitModel::generate : Problem in toy MC generation. Starting again with updated parameters..." << std::endl;
369  break;
370  }
371 
372  if (this->writeLatexTable()) {
373  TString tableFileName(tableFileNameBase);
374  tableFileName += "_";
375  tableFileName += iExpt_;
376  tableFileName += ".tex";
377  this->writeOutTable(tableFileName);
378  }
379 
380  } // Loop over number of experiments
381  } while (!genOK);
382 
383  // Print out total timing info.
384  cumulTimer_.Stop();
385  std::cout << "INFO in LauAbsFitModel::generate : Finished generating all experiments." << std::endl;
386  std::cout << "INFO in LauAbsFitModel::generate : Cumulative timing:" << std::endl;
387  cumulTimer_.Print();
388 
389  // Build the event index
390  std::cout << "INFO in LauAbsFitModel::generate : Building experiment:event index." << std::endl;
391  // TODO - can test this return value?
392  //Int_t nIndexEntries =
393  genNtuple_->buildIndex("iExpt","iEvtWithinExpt");
394 
395  // Write out toy MC ntuple
396  std::cout << "INFO in LauAbsFitModel::generate : Writing data to file " << dataFileName << "." << std::endl;
398 }
399 
401 {
403 }
404 
406 {
408 }
409 
411 {
412  genNtuple_->setIntegerBranchValue(name,value);
413 }
414 
416 {
417  genNtuple_->setDoubleBranchValue(name,value);
418 }
419 
421 {
422  return genNtuple_->getIntegerBranchValue(name);
423 }
424 
426 {
427  return genNtuple_->getDoubleBranchValue(name);
428 }
429 
431 {
433 }
434 
436 {
438 }
439 
441 {
443 }
444 
446 {
447  sPlotNtuple_->setIntegerBranchValue(name,value);
448 }
449 
451 {
452  sPlotNtuple_->setDoubleBranchValue(name,value);
453 }
454 
456 {
458 }
459 
460 void LauAbsFitModel::fit(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase)
461 {
462  // Routine to perform the total fit.
463 
464  std::cout << "INFO in LauAbsFitModel::fit : First experiment = " << firstExpt_ << std::endl;
465  std::cout << "INFO in LauAbsFitModel::fit : Number of experiments = " << nExpt_ << std::endl;
466 
467  // Start the cumulative timer
468  cumulTimer_.Start();
469 
470  numberOKFits_ = 0, numberBadFits_ = 0;
471  fitStatus_ = -1;
472 
473  // Create and setup the fit results ntuple
474  std::cout << "INFO in LauAbsFitModel::fit : Creating fit ntuple." << std::endl;
475  if (fitNtuple_ != 0) {delete fitNtuple_; fitNtuple_ = 0;}
476  fitNtuple_ = new LauFitNtuple(histFileName, this->useAsymmFitErrors());
477 
478  // Create and setup the sPlot ntuple
479  if (this->writeSPlotData()) {
480  std::cout << "INFO in LauAbsFitModel::fit : Creating sPlot ntuple." << std::endl;
481  if (sPlotNtuple_ != 0) {delete sPlotNtuple_; sPlotNtuple_ = 0;}
483  this->setupSPlotNtupleBranches();
484  }
485 
486  // This reads in the given dataFile and creates an input
487  // fit data tree that stores them for all events and experiments.
488  Bool_t dataOK = this->cacheFitData(dataFileName,dataTreeName);
489  if (!dataOK) {
490  std::cerr << "ERROR in LauAbsFitModel::fit : Problem caching the fit data." << std::endl;
491  gSystem->Exit(EXIT_FAILURE);
492  }
493 
494  // Loop over the number of experiments
495  for (iExpt_ = firstExpt_; iExpt_ < (firstExpt_+nExpt_); ++iExpt_) {
496 
497  // Start the timer to see how long each fit takes
498  timer_.Start();
499 
502 
503  if (this->eventsPerExpt() < 1) {
504  std::cerr << "ERROR in LauAbsFitModel::fit : Zero events in experiment " << iExpt_ << ", skipping..." << std::endl;
505  timer_.Stop();
506  continue;
507  }
508 
509  // Now the sub-classes must implement whatever they need to do
510  // to cache any more input fit data they need in order to
511  // calculate the likelihoods during the fit.
512  // They need to use the inputFitData_ tree as input. For example,
513  // inputFitData_ contains m13Sq and m23Sq. The appropriate fit model
514  // then caches the resonance dynamics for the signal model, as
515  // well as the background likelihood values in the Dalitz plot
516  this->cacheInputFitVars();
517  if ( this->doSFit() ) {
518  this->cacheInputSWeights();
519  }
520 
521  // Do the fit for this experiment
522  this->fitExpt();
523 
524  // Write the results into the ntuple
525  this->finaliseFitResults(tableFileNameBase);
526 
527  // Stop the timer and see how long the program took so far
528  timer_.Stop();
529  timer_.Print();
530 
531  // Store the per-event likelihood values
532  if ( this->writeSPlotData() ) {
533  this->storePerEvtLlhds();
534  }
535 
536  // Create a toy MC sample using the fitted parameters so that
537  // the user can compare the fit to the data.
538  if (compareFitData_ == kTRUE && fitStatus_ == 3) {
540  }
541 
542  // Keep track of how many fits worked or failed
543  // NB values of fitStatus_ now indicate the status of the error matrix:
544  // 0= not calculated at all
545  // 1= approximation only, not accurate
546  // 2= full matrix, but forced positive-definite
547  // 3= full accurate covariance matrix
548  if (fitStatus_ == 3) {
549  numberOKFits_++;
550  } else {
551  numberBadFits_++;
552  }
553 
554  } // Loop over number of experiments
555 
556  // Print out total timing info.
557  cumulTimer_.Stop();
558  std::cout << "INFO in LauAbsFitModel::fit : Cumulative timing:" << std::endl;
559  cumulTimer_.Print();
560 
561  // Print out stats on OK fits.
562  std::cout << "INFO in LauAbsFitModel::fit : Number of OK Fits = " << numberOKFits_ << std::endl;
563  std::cout << "INFO in LauAbsFitModel::fit : Number of Failed Fits = " << numberBadFits_ << std::endl;
564  Double_t fitEff(0.0);
565  if (nExpt_ != 0) {fitEff = numberOKFits_/(1.0*nExpt_);}
566  std::cout << "INFO in LauAbsFitModel::fit : Fit efficiency = " << fitEff*100.0 << "%." << std::endl;
567 
568  // Write out any fit results (ntuples etc...).
569  this->writeOutAllFitResults();
570  if ( this->writeSPlotData() ) {
571  this->calculateSPlotData();
572  }
573 }
574 
575 void LauAbsFitModel::fitSlave(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase)
576 {
577  // Create and setup the fit results ntuple
578  std::cout << "INFO in LauAbsFitModel::fitSlave : Creating fit ntuple." << std::endl;
579  if (fitNtuple_ != 0) {delete fitNtuple_; fitNtuple_ = 0;}
580  fitNtuple_ = new LauFitNtuple(histFileName, this->useAsymmFitErrors());
581 
582  // This reads in the given dataFile and creates an input
583  // fit data tree that stores them for all events and experiments.
584  Bool_t dataOK = this->cacheFitData(dataFileName,dataTreeName);
585  if (!dataOK) {
586  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Problem caching the fit data." << std::endl;
587  gSystem->Exit(EXIT_FAILURE);
588  }
589 
590  // Now process the various requests from the master
591 
592  TMessage messageToMaster(kMESS_ANY);
593 
594  while ( kTRUE ) {
595 
596  sMaster_->Recv( messageFromMaster_ );
597 
598  if ( messageFromMaster_->What() == kMESS_STRING ) {
599 
600  TString msgStr;
601  messageFromMaster_->ReadTString( msgStr );
602 
603  std::cout << "INFO in LauAbsFitModel::fitSlave : Received message from master: " << msgStr << std::endl;
604 
605  if ( msgStr == "Send Parameters" ) {
606 
607  // Update initial fit parameters if required (e.g. if using random numbers).
608  this->checkInitFitParams();
609 
610  // Send the fit parameters
611  TObjArray array;
612  for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
613  array.Add( *iter );
614  }
615 
616  messageToMaster.Reset( kMESS_OBJECT );
617  messageToMaster.WriteObject( &array );
618  sMaster_->Send( messageToMaster );
619 
620  } else if ( msgStr == "Read Expt" ) {
621 
622  // Read the data for this experiment
623  messageFromMaster_->ReadUInt( iExpt_ );
624 
626  UInt_t nEvent = inputFitData_->nEvents();
627  this->eventsPerExpt( nEvent );
628 
629  if ( nEvent < 1 ) {
630  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Zero events in experiment " << firstExpt_ << ", the master should skip this experiment..." << std::endl;
631  }
632 
633  messageToMaster.Reset( kMESS_ANY );
634  messageToMaster.WriteUInt( slaveId_ );
635  messageToMaster.WriteUInt( nEvent );
636  sMaster_->Send( messageToMaster );
637 
638  } else if ( msgStr == "Cache" ) {
639 
640  // Perform the caching
641 
642  this->cacheInputFitVars();
643 
644  messageToMaster.Reset( kMESS_ANY );
645  messageToMaster.WriteUInt( slaveId_ );
646  messageToMaster.WriteBool( kTRUE );
647  sMaster_->Send( messageToMaster );
648 
649  } else if ( msgStr == "Write Results" ) {
650 
651  this->writeOutAllFitResults();
652 
653  messageToMaster.Reset( kMESS_ANY );
654  messageToMaster.WriteUInt( slaveId_ );
655  messageToMaster.WriteBool( kTRUE );
656  sMaster_->Send( messageToMaster );
657 
658  } else if ( msgStr == "Finish" ) {
659 
660  std::cout << "INFO in LauAbsFitModel::fitSlave : Message from master to finish" << std::endl;
661  break;
662  } else {
663  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Unexpected message from master" << std::endl;
664  gSystem->Exit( EXIT_FAILURE );
665  }
666 
667  } else if ( messageFromMaster_->What() == kMESS_OBJECT ) {
668 
669  std::cout << "INFO in LauAbsFitModel::fitSlave : Received message from master: Finalise" << std::endl;
670 
671  messageFromMaster_->ReadInt( fitStatus_ );
672  messageFromMaster_->ReadDouble( NLL_ );
673 
674  TObjArray * objarray = dynamic_cast<TObjArray*>( messageFromMaster_->ReadObject( messageFromMaster_->GetClass() ) );
675  if ( ! objarray ) {
676  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Error reading parameters from master" << std::endl;
677  gSystem->Exit( EXIT_FAILURE );
678  }
679 
680  TMatrixD * covMat = dynamic_cast<TMatrixD*>( messageFromMaster_->ReadObject( messageFromMaster_->GetClass() ) );
681  if ( ! covMat ) {
682  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Error reading covariance matrix from master" << std::endl;
683  gSystem->Exit( EXIT_FAILURE );
684  }
685  covMatrix_.Clear();
686  covMatrix_.ResizeTo( covMat->GetNrows(), covMat->GetNcols() );
687  covMatrix_.SetMatrixArray( covMat->GetMatrixArray() );
688  delete covMat; covMat = 0;
689 
690 
691  UInt_t nPars = objarray->GetEntries();
692 
693  if ( nPars != nParams_ ) {
694  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Unexpected number of parameters received from master" << std::endl;
695  std::cerr << " ::fitSlave : Received " << nPars << " when expecting " << nParams_ << std::endl;
696  gSystem->Exit( EXIT_FAILURE );
697  }
698 
699  for ( UInt_t iPar(0); iPar < nPars; ++iPar ) {
700  LauParameter* parameter = dynamic_cast<LauParameter*>( (*objarray)[iPar] );
701  if ( ! parameter ) {
702  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Error reading parameter from master" << std::endl;
703  gSystem->Exit( EXIT_FAILURE );
704  }
705 
706  if ( parameter->name() != fitVars_[iPar]->name() ) {
707  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Error reading parameter from master" << std::endl;
708  gSystem->Exit( EXIT_FAILURE );
709  }
710 
711  *(fitVars_[iPar]) = *parameter;
712  }
713 
714  this->finaliseFitResults( tableFileNameBase );
715 
716  // Send the finalised parameters
717  TObjArray array;
718  for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
719  array.Add( *iter );
720  }
721 
722  messageToMaster.Reset( kMESS_ANY );
723  messageToMaster.WriteUInt( slaveId_ );
724  messageToMaster.WriteBool( kTRUE );
725  messageToMaster.WriteObject( &array );
726  sMaster_->Send( messageToMaster );
727 
728  } else if ( messageFromMaster_->What() == kMESS_ANY ) {
729 
730  UInt_t nPars(0);
731  messageFromMaster_->ReadUInt( nPars );
732 
733  if ( nPars != nParams_ ) {
734  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Unexpected number of parameters received from master" << std::endl;
735  std::cerr << " ::fitSlave : Received " << nPars << " when expecting " << nParams_ << std::endl;
736  gSystem->Exit( EXIT_FAILURE );
737  }
738 
739  messageFromMaster_->ReadFastArray( parValues_, nPars );
740 
741  for ( UInt_t iPar(0); iPar < nPars; ++iPar ) {
742  if ( ! fitVars_[iPar]->fixed() ) {
743  fitVars_[iPar]->value( parValues_[iPar] );
744  }
745  }
746  this->propagateParUpdates();
747 
748  Double_t negLogLike = this->getTotNegLogLikelihood();
749 
750  messageToMaster.Reset( kMESS_ANY );
751  messageToMaster.WriteDouble( negLogLike );
752  sMaster_->Send( messageToMaster );
753 
754  } else {
755  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Unexpected message type" << std::endl;
756  gSystem->Exit( EXIT_FAILURE );
757  }
758 
759  delete messageFromMaster_;
760  messageFromMaster_ = 0;
761  }
762 }
763 
764 Bool_t LauAbsFitModel::cacheFitData(const TString& dataFileName, const TString& dataTreeName)
765 {
766  // From the input data stream, store the variables into the
767  // internal tree inputFitData_ that can be used by the sub-classes
768  // in calculating their likelihood functions for the fit
769  delete inputFitData_;
770  inputFitData_ = new LauFitDataTree(dataFileName,dataTreeName);
771  Bool_t dataOK = inputFitData_->findBranches();
772 
773  if (!dataOK) {
774  delete inputFitData_; inputFitData_ = 0;
775  }
776 
777  return dataOK;
778 }
779 
781 {
782  Bool_t hasBranch = inputFitData_->haveBranch( sWeightBranchName_ );
783  if ( ! hasBranch ) {
784  std::cerr << "ERROR in LauAbsFitModel::cacheInputSWeights : Input data does not contain variable \"" << sWeightBranchName_ << "\".\n";
785  std::cerr << " : Turning off sFit!" << std::endl;
786  doSFit_ = kFALSE;
787  return;
788  }
789 
790  UInt_t nEvents = this->eventsPerExpt();
791  sWeights_.clear();
792  sWeights_.reserve( nEvents );
793 
794  for (UInt_t iEvt = 0; iEvt < nEvents; ++iEvt) {
795 
796  const LauFitData& dataValues = inputFitData_->getData(iEvt);
797 
798  LauFitData::const_iterator iter = dataValues.find( sWeightBranchName_ );
799 
800  sWeights_.push_back( iter->second * sWeightScaleFactor_ );
801  }
802 }
803 
805 {
806  // Routine to perform the actual fit for the given experiment
807 
808  // Reset the worst likelihood found to its catch-all value
809  worstLogLike_ = std::numeric_limits<Double_t>::max();
810 
811  // Update initial fit parameters if required (e.g. if using random numbers).
812  this->checkInitFitParams();
813 
814  // Initialise the fitter
818 
821 
822  // Now ready for minimisation step
823  std::cout << "\nINFO in LauAbsFitModel::fitExpt : Start minimisation...\n";
824  std::pair<Int_t,Double_t> fitResult = LauFitter::fitter()->minimise();
825 
826  fitStatus_ = fitResult.first;
827  NLL_ = fitResult.second;
828 
829  // If we're doing a two stage fit we can now release (i.e. float)
830  // the 2nd stage parameters and re-fit
831  if (this->twoStageFit()) {
832 
833  if ( fitStatus_ != 3 ) {
834  std::cerr << "ERROR in LauAbsFitModel:fitExpt : Not running second stage fit since first stage failed." << std::endl;
836  } else {
841  fitResult = LauFitter::fitter()->minimise();
842  }
843  }
844 
845  fitStatus_ = fitResult.first;
846  NLL_ = fitResult.second;
847  const TMatrixD& covMat = LauFitter::fitter()->covarianceMatrix();
848  covMatrix_.Clear();
849  covMatrix_.ResizeTo( covMat.GetNrows(), covMat.GetNcols() );
850  covMatrix_.SetMatrixArray( covMat.GetMatrixArray() );
851 
852  // Store the final fit results and errors into protected internal vectors that
853  // all sub-classes can use within their own finalFitResults implementation
854  // used below (e.g. putting them into an ntuple in a root file)
857 }
858 
860 {
861  // Write out histograms at end
862  if (fitNtuple_ != 0) {
864  }
865 }
866 
868 {
869  if (sPlotNtuple_ != 0) {
872  LauSPlot splot(sPlotNtuple_->fileName(), sPlotNtuple_->treeName(), this->firstExpt(), this->nExpt(),
873  this->variableNames(), this->freeSpeciesNames(), this->fixdSpeciesNames(), this->twodimPDFs(),
874  this->splitSignal(), this->scfDPSmear());
876  splot.writeOutResults();
877  }
878 }
879 
880 void LauAbsFitModel::compareFitData(UInt_t toyMCScale, const TString& mcFileName, const TString& tableFileName, Bool_t poissonSmearing)
881 {
882  compareFitData_ = kTRUE;
883  fitToyMCScale_ = toyMCScale;
884  fitToyMCFileName_ = mcFileName;
885  fitToyMCTableName_ = tableFileName;
886  fitToyMCPoissonSmear_ = poissonSmearing;
887 }
888 
889 void LauAbsFitModel::createFitToyMC(const TString& mcFileName, const TString& tableFileName)
890 {
891  // Create a toy MC sample so that the user can compare the fitted
892  // result with the data.
893  // Generate more toy MC to reduce statistical fluctuations:
894  // - use the rescaling value fitToyMCScale_
895 
896  // Store the info on the number of experiments, first expt and current expt
897  UInt_t oldNExpt(this->nExpt());
898  UInt_t oldFirstExpt(this->firstExpt());
899  UInt_t oldIExpt(iExpt_);
900 
901  // Turn off Poisson smearing if required
902  Bool_t poissonSmearing(this->doPoissonSmearing());
904 
905  // Turn off embedding, since we need toy MC, not reco'ed events
906  Bool_t enableEmbeddingOrig(this->enableEmbedding());
907  this->enableEmbedding(kFALSE);
908 
909  // Need to make sure that the generation of the DP co-ordinates is
910  // switched on if any of our PDFs depend on it
911  Bool_t origUseDP = this->useDP();
912  if ( this->pdfsDependOnDP() && !origUseDP ) {
913  this->useDP( kTRUE );
914  this->initialiseDPModels();
915  }
916 
917  // Construct a unique filename for this experiment
918  TString exptString("_expt");
919  exptString += oldIExpt;
920  TString fileName( mcFileName );
921  fileName.Insert( fileName.Last('.'), exptString );
922 
923  // Generate the toy MC
924  std::cout << "INFO in LauAbsFitModel::createFitToyMC : Generating toy MC in " << fileName << " to compare fit with data..." << std::endl;
925  std::cout << " : Number of experiments to generate = " << fitToyMCScale_ << "." << std::endl;
926  std::cout << " : This is to allow the toy MC to be made with reduced statistical fluctuations." << std::endl;
927 
928  // Set the genValue of each parameter to its current (fitted) value
929  // but first store the original genValues for restoring later
930  std::vector<Double_t> origGenValues; origGenValues.reserve(nParams_);
931  for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) {
932  origGenValues.push_back((*iter)->genValue());
933  (*iter)->genValue((*iter)->value());
934  }
935 
936  // If we're asked to generate more than 100 experiments then split it
937  // up into multiple files since otherwise can run into memory issues
938  // when building the index
939 
940  UInt_t totalExpts = fitToyMCScale_;
941  if ( totalExpts > 100 ) {
942  UInt_t nFiles = totalExpts/100;
943  if ( totalExpts%100 ) {
944  nFiles += 1;
945  }
946  for ( UInt_t iFile(0); iFile < nFiles; ++iFile ) {
947 
948  UInt_t firstExp( iFile*100 );
949 
950  // Set number of experiments and first experiment to generate
951  UInt_t nExp = ((firstExp + 100)>totalExpts) ? totalExpts-firstExp : 100;
952  this->setNExpts(nExp, firstExp);
953 
954  // Create a unique filename and generate the events
955  TString extraname = "_file";
956  extraname += iFile;
957  fileName.Insert( fileName.Last('.'), extraname );
958  this->generate(fileName, "genResults", "dummy.root", tableFileName);
959  }
960  } else {
961  // Set number of experiments to new value
962  this->setNExpts(fitToyMCScale_, 0);
963  // Generate the toy
964  this->generate(fileName, "genResults", "dummy.root", tableFileName);
965  }
966 
967  // Reset number of experiments to original value
968  iExpt_ = oldIExpt;
969  this->setNExpts(oldNExpt, oldFirstExpt);
970 
971  // Restore the Poisson smearing to its former value
972  this->doPoissonSmearing(poissonSmearing);
973 
974  // Restore the embedding status
975  this->enableEmbedding(enableEmbeddingOrig);
976 
977  // Restore "useDP" to its former status
978  this->useDP( origUseDP );
979 
980  // Restore the original genValue to each parameter
981  for (UInt_t i(0); i<nParams_; ++i) {
982  fitVars_[i]->genValue(origGenValues[i]);
983  }
984 
985  std::cout << "INFO in LauAbsFitModel::createFitToyMC : Finished in createFitToyMC." << std::endl;
986 }
987 
989 {
990  // Calculate the total negative log-likelihood over all events.
991  // This function assumes that the fit parameters and data tree have
992  // already been set-up correctly.
993 
994  // Loop over the data points to calculate the log likelihood
995  Double_t logLike = this->getLogLikelihood( 0, this->eventsPerExpt() );
996 
997  // Include the Poisson term in the extended likelihood if required
998  if (this->doEMLFit()) {
999  logLike -= this->getEventSum();
1000  }
1001 
1002  // Calculate any penalty terms from Gaussian constrained variables
1003  if ( ! conVars_.empty() ){
1004  logLike -= this->getLogLikelihoodPenalty();
1005  }
1006 
1007  Double_t totNegLogLike = -logLike;
1008  return totNegLogLike;
1009 }
1010 
1012 {
1013  Double_t penalty(0.0);
1014 
1015  for ( LauAbsRValuePList::const_iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter ) {
1016  Double_t val = (*iter)->value();
1017  Double_t mean = (*iter)->constraintMean();
1018  Double_t width = (*iter)->constraintWidth();
1019 
1020  Double_t term = ( val - mean ) / width;
1021  penalty += term*term;
1022  }
1023 
1024  return penalty;
1025 }
1026 
1027 Double_t LauAbsFitModel::getLogLikelihood( UInt_t iStart, UInt_t iEnd )
1028 {
1029  // Calculate the total negative log-likelihood over all events.
1030  // This function assumes that the fit parameters and data tree have
1031  // already been set-up correctly.
1032 
1033  // Loop over the data points to calculate the log likelihood
1034  Double_t logLike(0.0);
1035 
1036  // Loop over the number of events in this experiment
1037  Bool_t ok(kTRUE);
1038  for (UInt_t iEvt = iStart; iEvt < iEnd; ++iEvt) {
1039 
1040  Double_t likelihood = this->getTotEvtLikelihood(iEvt);
1041 
1042  if (likelihood > DBL_MIN) { // Is the likelihood zero?
1043  Double_t evtLogLike = TMath::Log(likelihood);
1044  if ( doSFit_ ) {
1045  evtLogLike *= sWeights_[iEvt];
1046  }
1047  logLike += evtLogLike;
1048  } else {
1049  ok = kFALSE;
1050  std::cerr << "WARNING in LauAbsFitModel::getLogLikelihood : Strange likelihood value for event " << iEvt << ": " << likelihood << "\n";
1051  this->printEventInfo(iEvt);
1052  this->printVarsInfo(); //Write the values of the floated variables for which the likelihood is zero
1053  break;
1054  }
1055  }
1056 
1057  if (!ok) {
1058  std::cerr << " : Returning worst NLL found so far to force MINUIT out of this region." << std::endl;
1059  logLike = worstLogLike_;
1060  } else if (logLike < worstLogLike_) {
1061  worstLogLike_ = logLike;
1062  }
1063 
1064  return logLike;
1065 }
1066 
1067 void LauAbsFitModel::setParsFromMinuit(Double_t* par, Int_t npar)
1068 {
1069  // This function sets the internal parameters based on the values
1070  // that Minuit is using when trying to minimise the total likelihood function.
1071 
1072  // MINOS reports different numbers of free parameters depending on the
1073  // situation, so disable this check
1074  if ( ! withinAsymErrorCalc_ ) {
1075  if (static_cast<UInt_t>(npar) != nFreeParams_) {
1076  std::cerr << "ERROR in LauAbsFitModel::setParsFromMinuit : Unexpected number of free parameters: " << npar << ".\n";
1077  std::cerr << " Expected: " << nFreeParams_ << ".\n" << std::endl;
1078  gSystem->Exit(EXIT_FAILURE);
1079  }
1080  }
1081 
1082  // Despite npar being the number of free parameters
1083  // the par array actually contains all the parameters,
1084  // free and floating...
1085  // Update all the floating ones with their new values.
1086  for (UInt_t i(0); i<nParams_; ++i) {
1087  if (!fitVars_[i]->fixed()) {
1088  fitVars_[i]->value(par[i]);
1089  }
1090  }
1091 
1092  this->propagateParUpdates();
1093 }
1094 
1096 {
1097  UInt_t nParsAdded(0);
1098  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1099  LauAbsPdf* pdf = (*pdf_iter);
1100  if ( pdf->isDPDependent() ) {
1101  this->pdfsDependOnDP( kTRUE );
1102  }
1103  LauAbsRValuePList& pars = pdf->getParameters();
1104  for (LauAbsRValuePList::iterator pars_iter = pars.begin(); pars_iter != pars.end(); ++pars_iter) {
1105  LauParameterPList params = (*pars_iter)->getPars();
1106  for (LauParameterPList::iterator params_iter = params.begin(); params_iter != params.end(); ++params_iter) {
1107  if ( !(*params_iter)->clone() && ( !(*params_iter)->fixed() ||
1108  (this->twoStageFit() && ( (*params_iter)->secondStage() || (*params_iter)->firstStage())) ) ) {
1109  fitVars_.push_back(*params_iter);
1110  ++nParsAdded;
1111  }
1112  }
1113  }
1114  }
1115  return nParsAdded;
1116 }
1117 
1118 void LauAbsFitModel::addConstraint(const TString& formula, const std::vector<TString>& pars, const Double_t mean, const Double_t width)
1119 {
1120  StoreConstraints newCon;
1121  newCon.formula_ = formula;
1122  newCon.conPars_ = pars;
1123  newCon.mean_ = mean;
1124  newCon.width_ = width;
1125  storeCon_.push_back(newCon);
1126 }
1127 
1129 {
1130  for ( LauParameterPList::const_iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
1131  if ( (*iter)->gaussConstraint() ) {
1132  conVars_.push_back( *iter );
1133  std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to parameter "<< (*iter)->name() << std::endl;
1134  }
1135  }
1136 
1137  // Add penalties from the constraints to fit parameters
1138  for ( std::vector<StoreConstraints>::iterator iter = storeCon_.begin(); iter != storeCon_.end(); ++iter ) {
1139  std::vector<TString> names = (*iter).conPars_;
1140  std::vector<LauParameter*> params;
1141  for ( std::vector<TString>::iterator iternames = names.begin(); iternames != names.end(); ++iternames ) {
1142  for ( LauParameterPList::const_iterator iterfit = fitVars_.begin(); iterfit != fitVars_.end(); ++iterfit ) {
1143  if ( (*iternames) == (*iterfit)->name() ){
1144  params.push_back(*iterfit);
1145  }
1146  }
1147  }
1148 
1149  // If the parameters are not found, skip it
1150  if ( params.size() != (*iter).conPars_.size() ) {
1151  std::cerr << "WARNING in LauAbsFitModel::addConParameters: Could not find parameters to constrain in the formula... skipping" << std::endl;
1152  continue;
1153  }
1154 
1155  LauFormulaPar* formPar = new LauFormulaPar( (*iter).formula_, (*iter).formula_, params );
1156  formPar->addGaussianConstraint( (*iter).mean_, (*iter).width_ );
1157  conVars_.push_back(formPar);
1158 
1159  std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to formula\n";
1160  std::cout << " : Formula: " << (*iter).formula_ << std::endl;
1161  for ( std::vector<LauParameter*>::iterator iterparam = params.begin(); iterparam != params.end(); ++iterparam ) {
1162  std::cout << "INFO in LauAbsFitModel::addConParameters : Parameter: " << (*iterparam)->name() << std::endl;
1163  }
1164  }
1165 
1166 }
1167 
1169 {
1170  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1171  (*pdf_iter)->updatePulls();
1172  }
1173 }
1174 
1175 void LauAbsFitModel::printFitParameters(const LauPdfList& pdfList, std::ostream& fout) const
1176 {
1177  LauPrint print;
1178  for (LauPdfList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1179  const LauAbsRValuePList& pars = (*pdf_iter)->getParameters();
1180  for (LauAbsRValuePList::const_iterator pars_iter = pars.begin(); pars_iter != pars.end(); ++pars_iter) {
1181  LauParameterPList params = (*pars_iter)->getPars();
1182  for (LauParameterPList::iterator params_iter = params.begin(); params_iter != params.end(); ++params_iter) {
1183  if (!(*params_iter)->clone()) {
1184  fout << (*params_iter)->name() << " & $";
1185  print.printFormat(fout, (*params_iter)->value());
1186  if ((*params_iter)->fixed() == kTRUE) {
1187  fout << "$ (fixed) \\\\";
1188  } else {
1189  fout << " \\pm ";
1190  print.printFormat(fout, (*params_iter)->error());
1191  fout << "$ \\\\" << std::endl;
1192  }
1193  }
1194  }
1195  }
1196  }
1197 }
1198 
1200 {
1201  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1202  (*pdf_iter)->cacheInfo(theData);
1203  }
1204 }
1205 
1206 Double_t LauAbsFitModel::prodPdfValue(LauPdfList& pdfList, UInt_t iEvt)
1207 {
1208  Double_t pdfVal = 1.0;
1209  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1210  (*pdf_iter)->calcLikelihoodInfo(iEvt);
1211  pdfVal *= (*pdf_iter)->getLikelihood();
1212  }
1213  return pdfVal;
1214 }
1215 
1216 void LauAbsFitModel::printEventInfo(UInt_t iEvt) const
1217 {
1218  const LauFitData& data = inputFitData_->getData(iEvt);
1219  std::cerr << " : Input data values for this event:" << std::endl;
1220  for (LauFitData::const_iterator iter = data.begin(); iter != data.end(); ++iter) {
1221  std::cerr << " " << iter->first << " = " << iter->second << std::endl;
1222  }
1223 }
1224 
1226 {
1227  std::cerr << " : Current values of fit parameters:" << std::endl;
1228  for (UInt_t i(0); i<nParams_; ++i) {
1229  std::cerr << " " << (fitVars_[i]->name()).Data() << " = " << fitVars_[i]->value() << std::endl;
1230  }
1231 }
1232 
Class for defining the SPlot technique.
Definition: LauSPlot.hh:55
TString fitToyMCTableName_
The output table name for Toy MC.
Double_t mean_
The mean value of the Gaussian constraint to be applied.
virtual void addSPlotNtupleIntegerBranch(const TString &name)
Add a branch to the sPlot tree for storing an integer.
Bool_t findBranches()
Find all of the branches in the tree.
virtual Bool_t twoStageFit() const
Determine whether the two-stage fit is enabled.
virtual Bool_t genExpt()=0
The method that actually generates the toy MC events for the given experiment.
void createFitToyMC(const TString &mcFileName, const TString &tableFileName)
Create a toy MC sample from the fitted parameters.
UInt_t firstExpt() const
Obtain the number of the first experiment.
File containing declaration of LauFitDataTree class.
virtual Double_t getEventSum() const =0
Returns the sum of the expected events over all hypotheses; used in the EML fit scenario.
Bool_t fixed() const
Check whether the parameter is fixed or floated.
virtual void updateParameters()=0
Update the values and errors of the parameters based on the fit minimum.
UInt_t eventsPerExpt() const
Obtain the total number of events in the current experiment.
void setGenValues()
Make sure all parameters hold their genValue as the current value.
TString sPlotFileName_
The name of the sPlot file.
Double_t * parValues_
Parameter values array (for reading from the master)
virtual void writeOutTable(const TString &outputFile)=0
Write the latex table.
Bool_t writeLatexTable() const
Determine whether writing out of the latex table is enabled.
Bool_t doSFit_
Option to perfom the sFit.
Bool_t writeSPlotData() const
Determine whether the sPlot data is to be written out.
TStopwatch timer_
The fit timer.
UInt_t nParams_
The number of fit parameters.
File containing declaration of LauParamFixed class.
Double_t getTotNegLogLikelihood()
Calculates the total negative log-likelihood.
LauAbsRValuePList conVars_
Internal vectors of Gaussian parameters.
Bool_t storeDPEff_
Option to store DP efficiencies in the sPlot ntuple.
void cacheInfo(LauPdfList &pdfList, const LauFitDataTree &theData)
Have all PDFs in the list cache the data.
void runCalculations(const TString &option="q")
Method to calculate the sWeights and cN coeffs.
Definition: LauSPlot.cc:626
virtual void setGenNtupleIntegerBranchValue(const TString &name, Int_t value)
Set the value of an integer branch in the gen tree.
ClassImp(LauAbsCoeffSet)
virtual void setupBkgndVectors()=0
Method to set up the storage for background-related quantities called by setBkgndClassNames.
LauGenNtuple * genNtuple_
The generated ntuple.
File containing declaration of LauAbsFitModel class.
Bool_t withinAsymErrorCalc_
Flag to indicate if the asymmetric error calculation (e.g. MINOS) is currently running.
TString formula_
The formula to be used in the LauFormulaPar.
Bool_t useAsymmFitErrors() const
Determine whether calculation of asymmetric errors is enabled.
const TString & name() const
The parameter name.
Class for defining combinations of fit parameter objects.
virtual void setupGenNtupleBranches()=0
Setup the generation ntuple branches.
UInt_t addFitParameters(LauPdfList &pdfList)
Add parameters of the PDFs in the list to the list of all fit parameters.
virtual void generate(const TString &dataFileName, const TString &dataTreeName, const TString &histFileName, const TString &tableFileNameBase)
Generate toy MC.
virtual void setBkgndClassNames(const std::vector< TString > &names)
Setup the background class names.
Bool_t useDP() const
Is the Dalitz plot term in the likelihood.
Int_t buildIndex(const TString &majorName, const TString &minorName="0")
Create an index table using leaves of the tree.
void compareFitData(UInt_t toyMCScale=10, const TString &mcFileName="fitToyMC.root", const TString &tableFileName="fitToyMCTable.tex", Bool_t poissonSmearing=kTRUE)
Specify that a toy MC sample should be created for a successful fit to an experiment.
const TString & treeName() const
Ntuple tree name.
Definition: LauGenNtuple.hh:56
std::vector< TString > conPars_
The list of LauParameter names to be used in the LauFormulaPar.
Int_t getIntegerBranchValue(const TString &name) const
Get value of an integer branch.
virtual void cacheInputSWeights()
Cache the value of the sWeights to be used in the sFit.
virtual Bool_t twoStageFit() const =0
Determine whether the two-stage fit is enabled.
virtual void setGenNtupleDoubleBranchValue(const TString &name, Double_t value)
Set the value of a double branch in the gen tree.
void deleteAndRecreateTree()
Delete and recreate tree.
File containing declaration of LauAbsFitter class.
TSocket * sMaster_
A socket to enable parallel setup.
void addFriendTree(const TString &rootFileName, const TString &rootTreeName)
Add a friend tree.
virtual void storePerEvtLlhds()=0
Store the per-event likelihood values.
virtual void printEventInfo(UInt_t iEvt) const
Prints the values of all the fit variables for the specified event - useful for diagnostics.
Bool_t pdfsDependOnDP() const
Do any of the PDFs have a dependence on the DP?
virtual ~LauAbsFitModel()
Destructor.
Bool_t compareFitData_
Option to make toy from 1st successful experiment.
File containing declaration of LauPrint class.
Double_t prodPdfValue(LauPdfList &pdfList, UInt_t iEvt)
Calculate the product of the per-event likelihoods of the PDFs in the list.
void addConstraint(const TString &formula, const std::vector< TString > &pars, const Double_t mean, const Double_t width)
Store constraint information for fit parameters.
Double_t getDoubleBranchValue(const TString &name) const
Get value of a double branch.
std::vector< LauAbsPdf * > LauPdfList
List of Pdfs.
std::map< TString, Double_t > LauFitData
Type for holding event data.
void fillBranches()
Fill branches in the ntuple.
virtual Int_t getGenNtupleIntegerBranchValue(const TString &name) const
Get the value of an integer branch in the gen tree.
UInt_t nSlaves_
The total number of slaves.
virtual LauSPlot::NumbMap fixdSpeciesNames() const =0
Returns the names and yields of species that are fixed in the fit.
LauBkgndClassMap bkgndClassNames_
The background class names.
TMessage * messageFromMaster_
Message from master to the slaves.
Class to define various output print commands.
Definition: LauPrint.hh:29
virtual void setupSPlotNtupleBranches()=0
Setup the branches of the sPlot tuple.
virtual void fillGenNtupleBranches()
Fill the gen tuple branches.
void fitSlave(const TString &dataFileName, const TString &dataTreeName, const TString &histFileName, const TString &tableFileNameBase)
Slaves required when performing a simultaneous fit.
virtual void setSPlotNtupleDoubleBranchValue(const TString &name, Double_t value)
Set the value of a double branch in the sPlot tree.
void printFitParameters(const LauPdfList &pdfList, std::ostream &fout) const
Print the fit parameters for all PDFs in the list.
void addGaussianConstraint(Double_t newGaussMean, Double_t newGaussWidth)
Add a Gaussian constraint (or modify an existing one)
virtual void initialise(LauFitObject *fitObj, const std::vector< LauParameter * > &parameters)=0
Initialise the fitter, setting the information on the parameters.
void readExperimentData(UInt_t iExpt)
Read events only for the given experiment.
virtual std::pair< Int_t, Double_t > minimise()=0
Perform the minimisation of the fit function.
std::vector< LauAbsRValue * > LauAbsRValuePList
List of parameter pointers.
UInt_t slaveId_
Slave id number.
virtual Double_t getTotEvtLikelihood(UInt_t iEvt)=0
Calculates the likelihood for a given event.
TStopwatch cumulTimer_
The total fit timer.
File containing LauFitter class.
virtual void propagateParUpdates()=0
This function (specific to each model) calculates anything that depends on the fit parameter values...
void addConParameters()
Add parameters to the list of Gaussian constrained parameters.
LauFitDataTree * inputFitData_
The input data.
Bool_t doSFit() const
Return the flag to store the status of using an sFit or not.
void run(const TString &applicationCode, const TString &dataFileName, const TString &dataTreeName, const TString &histFileName, const TString &tableFileName="")
Start the toy generation / fitting.
std::vector< LauParameter * > LauParameterPList
List of parameter pointers.
const TString & treeName() const
Retrieve the tree name.
LauParameterList extraVars_
Extra variables that aren&#39;t in the fit but are stored in the ntuple.
std::vector< StoreConstraints > storeCon_
Store the constraints for fit parameters until initialisation is complete.
TMatrixD covMatrix_
The fit covariance matrix.
void writeOutFitResults()
Write out fit results.
void addIntegerBranch(const TString &name)
Add integer branch to tree.
Definition: LauGenNtuple.cc:73
const TString & fileName() const
Ntuple file name.
Definition: LauGenNtuple.hh:50
Abstract interface to the fitting and toy MC model.
UInt_t numberBadFits_
The number of bad fits.
virtual void addGenNtupleIntegerBranch(const TString &name)
Add a branch to the gen tree for storing an integer.
UInt_t nExpt() const
Obtain the number of experiments.
File containing declaration of LauParameter class.
Bool_t doPoissonSmearing() const
Determine whether Poisson smearing is enabled for the toy MC generation.
virtual Double_t getGenNtupleDoubleBranchValue(const TString &name) const
Get the value of a double branch in the gen tree.
void setNExpts(UInt_t nExperiments, UInt_t firstExperiment=0)
Set the number of experiments and the first experiment.
virtual void weightEvents(const TString &dataFileName, const TString &dataTreeName)=0
Reweighting - allows e.g. MC events to be weighted by the DP model.
Bool_t doEMLFit() const
Determine whether an extended maximum likelihood fit it being performed.
virtual void fixFirstStageParameters()=0
Fix parameters marked as &quot;first stage&quot;.
File containing declaration of LauComplex class.
UInt_t numberOKFits_
The number of good fits.
const TString & fileName() const
Retrieve the file name.
virtual Bool_t isDPDependent() const
Specifies whether or not the PDF is DP dependent.
Definition: LauAbsPdf.hh:111
virtual UInt_t nParameters() const =0
Get the total number of fit parameters.
virtual LauSPlot::NumbMap freeSpeciesNames() const =0
Returns the names and yields of species that are free in the fit.
Class to store the results from the toy MC generation into an ntuple.
Definition: LauGenNtuple.hh:32
File containing declaration of LauSPlot class.
virtual Bool_t splitSignal() const =0
Check if the signal is split into well-reconstructed and mis-reconstructed types. ...
Double_t worstLogLike_
The worst LL value found so far.
virtual void releaseSecondStageParameters()=0
Release parameters marked as &quot;second stage&quot;.
TString sPlotTreeName_
The name of the sPlot tree.
virtual void initialiseDPModels()=0
Initialise the DP models.
LauGenNtuple * sPlotNtuple_
The sPlot ntuple.
TString sPlotVerbosity_
Control the verbosity of the sFit.
const TString nullString_
An empty string.
void clearFitParVectors()
Clear the vectors containing fit parameters.
Class for defining the fit parameter objects.
Definition: LauParameter.hh:33
virtual void addSPlotNtupleDoubleBranch(const TString &name)
Add a branch to the sPlot tree for storing a double.
void clearExtraVarVectors()
Clear the vectors containing extra ntuple variables.
Struct to store constraint information until the fit is run.
virtual void cacheInputFitVars()=0
Cache the input data values to calculate the likelihood during the fit.
void fitExpt()
Routine to perform the actual fit for a given experiment.
virtual const std::vector< LauAbsRValue * > & getParameters() const
Retrieve the parameters of the PDF, e.g. so that they can be loaded into a fit.
Definition: LauAbsPdf.hh:239
Double_t sWeightScaleFactor_
The sWeight scaling factor.
File containing declaration of LauAbsPdf class.
UInt_t bkgndClassID(const TString &className) const
The number assigned to a background class.
const LauFitData & getData(UInt_t iEvt) const
Retrieve the data for a given event.
virtual void writeOutAllFitResults()
Write out any fit results.
virtual void finaliseFitResults(const TString &tableFileName)=0
Write the results of the fit into the ntuple.
UInt_t firstExpt_
The number of the first experiment to consider.
static LauAbsFitter * fitter()
Method that provides access to the singleton fitter.
Definition: LauFitter.cc:34
void setIntegerBranchValue(const TString &name, Int_t value)
Set value of an integer branch.
Definition: LauGenNtuple.cc:91
virtual void checkInitFitParams()=0
Update initial fit parameters if required.
virtual void printVarsInfo() const
Same as printEventInfo, but printing out the values of the variables in the fit.
Bool_t writeSPlotData_
Option to write sPlot data.
Bool_t validBkgndClass(const TString &className) const
Check if the given background class is in the list.
Bool_t fitToyMCPoissonSmear_
Option to perform Poisson smearing.
TString sWeightBranchName_
The name of the sWeight branch.
virtual UInt_t nFreeParameters() const =0
Get the number of floating fit parameters.
UInt_t iExpt_
The number of the current experiment.
LauParameterPList fitVars_
Internal vectors of fit parameters.
virtual Bool_t scfDPSmear() const =0
Check if the mis-reconstructed signal is to be smeared in the DP.
Bool_t cacheFitData(const TString &dataFileName, const TString &dataTreeName)
Store variables from the input file into the internal data storage.
void fit(const TString &dataFileName, const TString &dataTreeName, const TString &histFileName, const TString &tableFileNameBase)
Perform the total fit.
virtual void setSPlotNtupleIntegerBranchValue(const TString &name, Int_t value)
Set the value of an integer branch in the sPlot tree.
UInt_t fitToyMCScale_
The scaling factor (toy vs data statistics)
virtual void fillSPlotNtupleBranches()
Fill the sPlot tuple.
TString fitToyMCFileName_
The output file name for Toy MC.
Double_t width_
The width of the Gaussian constraint to be applied.
void writeOutGenResults()
Write out the results from the generation.
void printFormat(std::ostream &stream, Double_t value) const
Method to choose the printing format to a specified level of precision.
Definition: LauPrint.cc:32
void runSlave(const TString &dataFileName, const TString &dataTreeName, const TString &histFileName, const TString &tableFileName="", const TString &addressMaster="localhost", const UInt_t portMaster=9090)
Start the slave process for simultaneous fitting.
virtual LauSPlot::TwoDMap twodimPDFs() const =0
Returns the species and variables for all 2D PDFs in the fit.
Double_t getLogLikelihoodPenalty()
Calculate the penalty terms to the log likelihood from Gaussian constraints.
Bool_t haveBranch(const TString &name) const
Check if the named branch is stored.
const TString & bkgndClassName(UInt_t classID) const
Get the name of a background class from the number.
virtual Bool_t useAsymmFitErrors() const =0
Determine whether calculation of asymmetric errors is enabled.
Bool_t enableEmbedding() const
Determine whether embedding of events is enabled in the generation.
Double_t NLL_
The negative log-likelihood.
Class for defining the abstract interface for PDF classes.
Definition: LauAbsPdf.hh:41
Double_t getLogLikelihood(UInt_t iStart, UInt_t iEnd)
Calculate the sum of the log-likelihood over the specified events.
UInt_t nExpt_
The number of experiments to consider.
LauFitNtuple * fitNtuple_
The fit ntuple.
virtual LauSPlot::NameSet variableNames() const =0
Returns the names of all variables in the fit.
Double_t value() const
The value of the parameter.
UInt_t nEvents() const
Retrieve the number of events.
virtual void addGenNtupleDoubleBranch(const TString &name)
Add a branch to the gen tree for storing a double.
friend class LauFitNtuple
LauFitNtuple is a friend class.
void updateFitParameters(LauPdfList &pdfList)
Update the fit parameters for all PDFs in the list.
void addDoubleBranch(const TString &name)
Add double branch to tree.
Definition: LauGenNtuple.cc:82
virtual void setParsFromMinuit(Double_t *par, Int_t npar)
This function sets the parameter values from Minuit.
virtual void releaseFirstStageParameters()=0
Release parameters marked as &quot;first stage&quot;.
Int_t fitStatus_
The status of the fit.
virtual void initialise()=0
Initialise the fit par vectors.
Class to store the input fit variables.
File containing declaration of LauFitNtuple class.
virtual const TMatrixD & covarianceMatrix() const =0
Retrieve the fit covariance matrix.
virtual void calculateSPlotData()
Calculate the sPlot data.
File containing declaration of LauGenNtuple class.
void setDoubleBranchValue(const TString &name, Double_t value)
Set value of a double branch.
Definition: LauGenNtuple.cc:96
std::vector< Double_t > sWeights_
The vector of sWeights.
UInt_t nFreeParams_
The number of free fit parameters.