laura is hosted by Hepforge, IPPP Durham
Laura++  v3r0p1
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  outputTableName_(""),
78  fitToyMCFileName_("fitToyMC.root"),
79  fitToyMCTableName_("fitToyMCTable"),
80  fitToyMCScale_(10),
81  fitToyMCPoissonSmear_(kFALSE),
82  sPlotFileName_(""),
83  sPlotTreeName_(""),
84  sPlotVerbosity_("")
85 {
86 }
87 
88 
90 {
91  delete inputFitData_; inputFitData_ = 0;
92  delete fitNtuple_; fitNtuple_ = 0;
93  delete genNtuple_; genNtuple_ = 0;
94  delete sPlotNtuple_; sPlotNtuple_ = 0;
95 
96  // Remove the components created to apply constraints to fit parameters
97  for (std::vector<LauAbsRValue*>::iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter){
98  if ( !(*iter)->isLValue() ){
99  delete (*iter);
100  (*iter) = 0;
101  }
102  }
103 }
104 
105 void LauAbsFitModel::run(const TString& applicationCode, const TString& dataFileName, const TString& dataTreeName,
106  const TString& histFileName, const TString& tableFileName)
107 {
108  // Chose whether you want to generate or fit events in the Dalitz plot.
109  // To generate events choose applicationCode = "gen", to fit events choose
110  // applicationCode = "fit".
111 
112  TString runCode(applicationCode);
113  runCode.ToLower();
114 
115  TString histFileNameCopy(histFileName);
116  TString tableFileNameCopy(tableFileName);
117  TString dataFileNameCopy(dataFileName);
118  TString dataTreeNameCopy(dataTreeName);
119 
120  // Initialise the fit par vectors. Each class that inherits from this one
121  // must implement this sensibly for all vectors specified in clearFitParVectors,
122  // i.e. specify parameter names, initial, min, max and fixed values
123  this->initialise();
124 
125  // Add variables to Gaussian constrain to a list
126  this->addConParameters();
127 
128  if (dataFileNameCopy == "") {dataFileNameCopy = "data.root";}
129  if (dataTreeNameCopy == "") {dataTreeNameCopy = "genResults";}
130 
131  if (runCode.Contains("gen")) {
132 
133  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
134  if (tableFileNameCopy == "") {tableFileNameCopy = "genResults";}
135 
136  this->setGenValues();
137  this->generate(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
138 
139  } else if (runCode.Contains("fit")) {
140 
141  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
142  if (tableFileNameCopy == "") {tableFileNameCopy = "fitResults";}
143 
144  this->fit(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
145 
146  } else if (runCode.Contains("reweight")) {
147 
148  this->weightEvents(dataFileNameCopy, dataTreeNameCopy);
149  }
150 }
151 
152 void LauAbsFitModel::runSlave(const TString& dataFileName, const TString& dataTreeName,
153  const TString& histFileName, const TString& tableFileName,
154  const TString& addressMaster, const UInt_t portMaster)
155 {
156  // Establish the connection to the master process
157  this->connectToMaster( addressMaster, portMaster );
158 
159  // Initialise the fit par vectors. Each class that inherits from this one
160  // must implement this sensibly for all vectors specified in clearFitParVectors,
161  // i.e. specify parameter names, initial, min, max and fixed values
162  this->initialise();
163 
164  // NB call to addConParameters() is intentionally not included here cf.
165  // run() since this has to be dealt with by the master to avoid
166  // multiple inclusions of each penalty term
167 
168  TString dataFileNameCopy(dataFileName);
169  TString dataTreeNameCopy(dataTreeName);
170  TString histFileNameCopy(histFileName);
171  TString tableFileNameCopy(tableFileName);
172 
173  if (dataFileNameCopy == "") {dataFileNameCopy = "data.root";}
174  if (dataTreeNameCopy == "") {dataTreeNameCopy = "genResults";}
175  if (histFileNameCopy == "") {histFileNameCopy = "parInfo.root";}
176  if (tableFileNameCopy == "") {tableFileNameCopy = "fitResults";}
177 
178  this->fitSlave(dataFileNameCopy, dataTreeNameCopy, histFileNameCopy, tableFileNameCopy);
179 
180  std::cout << "INFO in LauAbsFitModel::runSlave : Fit slave " << this->slaveId() << " has finished successfully" << std::endl;
181 }
182 
183 void LauAbsFitModel::doSFit( const TString& sWeightBranchName, Double_t scaleFactor )
184 {
185  if ( sWeightBranchName == "" ) {
186  std::cerr << "WARNING in LauAbsFitModel::doSFit : sWeight branch name is empty string, not setting-up sFit." << std::endl;
187  return;
188  }
189 
190  doSFit_ = kTRUE;
191  sWeightBranchName_ = sWeightBranchName;
192  sWeightScaleFactor_ = scaleFactor;
193 }
194 
195 void LauAbsFitModel::setBkgndClassNames( const std::vector<TString>& names )
196 {
197  if ( !bkgndClassNames_.empty() ) {
198  std::cerr << "WARNING in LauAbsFitModel::setBkgndClassNames : Names already stored, not changing them." << std::endl;
199  return;
200  }
201 
202  UInt_t nBkgnds = names.size();
203  for ( UInt_t i(0); i < nBkgnds; ++i ) {
204  bkgndClassNames_.insert( std::make_pair( i, names[i] ) );
205  }
206 
207  this->setupBkgndVectors();
208 }
209 
210 Bool_t LauAbsFitModel::validBkgndClass( const TString& className ) const
211 {
212  if ( bkgndClassNames_.empty() ) {
213  return kFALSE;
214  }
215 
216  Bool_t found(kFALSE);
217  for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) {
218  if ( iter->second == className ) {
219  found = kTRUE;
220  break;
221  }
222  }
223 
224  return found;
225 }
226 
227 UInt_t LauAbsFitModel::bkgndClassID( const TString& className ) const
228 {
229  if ( ! this->validBkgndClass( className ) ) {
230  std::cerr << "ERROR in LauAbsFitModel::bkgndClassID : Request for ID for invalid background class \"" << className << "\"." << std::endl;
231  return (bkgndClassNames_.size() + 1);
232  }
233 
234  UInt_t bgID(0);
235  for ( LauBkgndClassMap::const_iterator iter = bkgndClassNames_.begin(); iter != bkgndClassNames_.end(); ++iter ) {
236  if ( iter->second == className ) {
237  bgID = iter->first;
238  break;
239  }
240  }
241 
242  return bgID;
243 }
244 
245 const TString& LauAbsFitModel::bkgndClassName( UInt_t classID ) const
246 {
247  LauBkgndClassMap::const_iterator iter = bkgndClassNames_.find( classID );
248 
249  if ( iter == bkgndClassNames_.end() ) {
250  std::cerr << "ERROR in LauAbsFitModel::bkgndClassName : Request for name of invalid background class ID " << classID << "." << std::endl;
251  return nullString_;
252  }
253 
254  return iter->second;
255 }
256 
258 {
259  std::cout << "INFO in LauAbsFitModel::clearFitParVectors : Clearing fit variable vectors" << std::endl;
260 
261  // Remove the components created to apply constraints to fit parameters
262  for (std::vector<LauAbsRValue*>::iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter){
263  if ( !(*iter)->isLValue() ){
264  delete (*iter);
265  (*iter) = 0;
266  }
267  }
268  conVars_.clear();
269  fitVars_.clear();
270 }
271 
273 {
274  std::cout << "INFO in LauAbsFitModel::clearExtraVarVectors : Clearing extra ntuple variable vectors" << std::endl;
275  extraVars_.clear();
276 }
277 
279 {
280  // makes sure each parameter holds its genValue as its current value
281  for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) {
282  (*iter)->value((*iter)->genValue());
283  }
284  this->propagateParUpdates();
285 }
286 
287 void LauAbsFitModel::writeSPlotData(const TString& fileName, const TString& treeName, Bool_t storeDPEfficiency, const TString& verbosity)
288 {
289  if (this->writeSPlotData()) {
290  std::cerr << "ERROR in LauAbsFitModel::writeSPlotData : Already have an sPlot ntuple setup, not doing it again." << std::endl;
291  return;
292  }
293  writeSPlotData_ = kTRUE;
294  sPlotFileName_ = fileName;
295  sPlotTreeName_ = treeName;
296  sPlotVerbosity_ = verbosity;
297  storeDPEff_ = storeDPEfficiency;
298 }
299 
300 // TODO : histFileName isn't used here at the moment but could be used for
301 // storing the values of the parameters used in the generation.
302 // These could then be read and used for setting the "true" values
303 // in a subsequent fit.
304 void LauAbsFitModel::generate(const TString& dataFileName, const TString& dataTreeName, const TString& /*histFileName*/, const TString& tableFileNameBase)
305 {
306  // Create the ntuple for storing the results
307  std::cout << "INFO in LauAbsFitModel::generate : Creating generation ntuple." << std::endl;
308  if (genNtuple_ != 0) {delete genNtuple_; genNtuple_ = 0;}
309  genNtuple_ = new LauGenNtuple(dataFileName,dataTreeName);
310 
311  // add branches for storing the experiment number and the number of
312  // the event within the current experiment
313  this->addGenNtupleIntegerBranch("iExpt");
314  this->addGenNtupleIntegerBranch("iEvtWithinExpt");
315  this->setupGenNtupleBranches();
316 
317  // Start the cumulative timer
318  cumulTimer_.Start();
319 
320  Bool_t genOK(kTRUE);
321  do {
322  // Loop over the number of experiments
323  for (iExpt_ = firstExpt_; iExpt_ < (firstExpt_+nExpt_); ++iExpt_) {
324 
325  // Start the timer to see how long each experiment takes to generate
326  timer_.Start();
327 
328  // Store the experiment number in the ntuple
329  this->setGenNtupleIntegerBranchValue("iExpt",iExpt_);
330 
331  // Do the generation for this experiment
332  std::cout << "INFO in LauAbsFitModel::generate : Generating experiment number " << iExpt_ << std::endl;
333  genOK = this->genExpt();
334 
335  // Stop the timer and see how long the program took so far
336  timer_.Stop();
337  timer_.Print();
338 
339  if (!genOK) {
340  // delete and recreate an empty tree
342 
343  // then break out of the experiment loop
344  std::cerr << "WARNING in LauAbsFitModel::generate : Problem in toy MC generation. Starting again with updated parameters..." << std::endl;
345  break;
346  }
347 
348  if (this->writeLatexTable()) {
349  TString tableFileName(tableFileNameBase);
350  tableFileName += "_";
351  tableFileName += iExpt_;
352  tableFileName += ".tex";
353  this->writeOutTable(tableFileName);
354  }
355 
356  } // Loop over number of experiments
357  } while (!genOK);
358 
359  // Print out total timing info.
360  cumulTimer_.Stop();
361  std::cout << "INFO in LauAbsFitModel::generate : Finished generating all experiments." << std::endl;
362  std::cout << "INFO in LauAbsFitModel::generate : Cumulative timing:" << std::endl;
363  cumulTimer_.Print();
364 
365  // Build the event index
366  std::cout << "INFO in LauAbsFitModel::generate : Building experiment:event index." << std::endl;
367  // TODO - can test this return value?
368  //Int_t nIndexEntries =
369  genNtuple_->buildIndex("iExpt","iEvtWithinExpt");
370 
371  // Write out toy MC ntuple
372  std::cout << "INFO in LauAbsFitModel::generate : Writing data to file " << dataFileName << "." << std::endl;
374 }
375 
377 {
379 }
380 
382 {
384 }
385 
387 {
388  genNtuple_->setIntegerBranchValue(name,value);
389 }
390 
392 {
393  genNtuple_->setDoubleBranchValue(name,value);
394 }
395 
397 {
398  return genNtuple_->getIntegerBranchValue(name);
399 }
400 
402 {
403  return genNtuple_->getDoubleBranchValue(name);
404 }
405 
407 {
409 }
410 
412 {
414 }
415 
417 {
419 }
420 
422 {
423  sPlotNtuple_->setIntegerBranchValue(name,value);
424 }
425 
427 {
428  sPlotNtuple_->setDoubleBranchValue(name,value);
429 }
430 
432 {
434 }
435 
436 void LauAbsFitModel::fit(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase)
437 {
438  // Routine to perform the total fit.
439 
440  std::cout << "INFO in LauAbsFitModel::fit : First experiment = " << firstExpt_ << std::endl;
441  std::cout << "INFO in LauAbsFitModel::fit : Number of experiments = " << nExpt_ << std::endl;
442 
443  // Start the cumulative timer
444  cumulTimer_.Start();
445 
446  numberOKFits_ = 0, numberBadFits_ = 0;
447  fitStatus_ = -1;
448 
449  // Create and setup the fit results ntuple
450  std::cout << "INFO in LauAbsFitModel::fit : Creating fit ntuple." << std::endl;
451  if (fitNtuple_ != 0) {delete fitNtuple_; fitNtuple_ = 0;}
452  fitNtuple_ = new LauFitNtuple(histFileName, this->useAsymmFitErrors());
453 
454  // Create and setup the sPlot ntuple
455  if (this->writeSPlotData()) {
456  std::cout << "INFO in LauAbsFitModel::fit : Creating sPlot ntuple." << std::endl;
457  if (sPlotNtuple_ != 0) {delete sPlotNtuple_; sPlotNtuple_ = 0;}
459  this->setupSPlotNtupleBranches();
460  }
461 
462  // This reads in the given dataFile and creates an input
463  // fit data tree that stores them for all events and experiments.
464  Bool_t dataOK = this->cacheFitData(dataFileName,dataTreeName);
465  if (!dataOK) {
466  std::cerr << "ERROR in LauAbsFitModel::fit : Problem caching the fit data." << std::endl;
467  gSystem->Exit(EXIT_FAILURE);
468  }
469 
470  // Loop over the number of experiments
471  for (iExpt_ = firstExpt_; iExpt_ < (firstExpt_+nExpt_); ++iExpt_) {
472 
473  // Start the timer to see how long each fit takes
474  timer_.Start();
475 
476  UInt_t nEvents = this->readExperimentData( iExpt_ );
477  if (nEvents < 1) {
478  std::cerr << "WARNING in LauAbsFitModel::fit : Zero events in experiment " << iExpt_ << ", skipping..." << std::endl;
479  timer_.Stop();
480  continue;
481  }
482 
483  // Now the sub-classes must implement whatever they need to do
484  // to cache any more input fit data they need in order to
485  // calculate the likelihoods during the fit.
486  // They need to use the inputFitData_ tree as input. For example,
487  // inputFitData_ contains m13Sq and m23Sq. The appropriate fit model
488  // then caches the resonance dynamics for the signal model, as
489  // well as the background likelihood values in the Dalitz plot
490  this->cacheInputFitVars();
491  if ( this->doSFit() ) {
492  this->cacheInputSWeights();
493  }
494 
495  // Do the fit for this experiment
496  this->fitExpt();
497 
498  // Write the results into the ntuple
499  this->finaliseFitResults(tableFileNameBase);
500 
501  // Stop the timer and see how long the program took so far
502  timer_.Stop();
503  timer_.Print();
504 
505  // Store the per-event likelihood values
506  if ( this->writeSPlotData() ) {
507  this->storePerEvtLlhds();
508  }
509 
510  // Create a toy MC sample using the fitted parameters so that
511  // the user can compare the fit to the data.
512  if (compareFitData_ == kTRUE && fitStatus_ == 3) {
514  }
515 
516  // Keep track of how many fits worked or failed
517  // NB values of fitStatus_ now indicate the status of the error matrix:
518  // 0= not calculated at all
519  // 1= approximation only, not accurate
520  // 2= full matrix, but forced positive-definite
521  // 3= full accurate covariance matrix
522  if (fitStatus_ == 3) {
523  numberOKFits_++;
524  } else {
525  numberBadFits_++;
526  }
527 
528  } // Loop over number of experiments
529 
530  // Print out total timing info.
531  cumulTimer_.Stop();
532  std::cout << "INFO in LauAbsFitModel::fit : Cumulative timing:" << std::endl;
533  cumulTimer_.Print();
534 
535  // Print out stats on OK fits.
536  std::cout << "INFO in LauAbsFitModel::fit : Number of OK Fits = " << numberOKFits_ << std::endl;
537  std::cout << "INFO in LauAbsFitModel::fit : Number of Failed Fits = " << numberBadFits_ << std::endl;
538  Double_t fitEff(0.0);
539  if (nExpt_ != 0) {fitEff = numberOKFits_/(1.0*nExpt_);}
540  std::cout << "INFO in LauAbsFitModel::fit : Fit efficiency = " << fitEff*100.0 << "%." << std::endl;
541 
542  // Write out any fit results (ntuples etc...).
543  this->writeOutAllFitResults();
544  if ( this->writeSPlotData() ) {
545  this->calculateSPlotData();
546  }
547 }
548 
549 void LauAbsFitModel::fitSlave(const TString& dataFileName, const TString& dataTreeName, const TString& histFileName, const TString& tableFileNameBase)
550 {
551  outputTableName_ = tableFileNameBase;
552 
553  // Create and setup the fit results ntuple
554  std::cout << "INFO in LauAbsFitModel::fitSlave : Creating fit ntuple." << std::endl;
555  if (fitNtuple_ != 0) {delete fitNtuple_; fitNtuple_ = 0;}
556  fitNtuple_ = new LauFitNtuple(histFileName, this->useAsymmFitErrors());
557 
558  // This reads in the given dataFile and creates an input
559  // fit data tree that stores them for all events and experiments.
560  Bool_t dataOK = this->cacheFitData(dataFileName,dataTreeName);
561  if (!dataOK) {
562  std::cerr << "ERROR in LauAbsFitModel::fitSlave : Problem caching the fit data." << std::endl;
563  gSystem->Exit(EXIT_FAILURE);
564  }
565 
566  // Now process the various requests from the master
567  this->processMasterRequests();
568 }
569 
570 Bool_t LauAbsFitModel::cacheFitData(const TString& dataFileName, const TString& dataTreeName)
571 {
572  // From the input data stream, store the variables into the
573  // internal tree inputFitData_ that can be used by the sub-classes
574  // in calculating their likelihood functions for the fit
575  delete inputFitData_;
576  inputFitData_ = new LauFitDataTree(dataFileName,dataTreeName);
577  Bool_t dataOK = inputFitData_->findBranches();
578 
579  if (!dataOK) {
580  delete inputFitData_; inputFitData_ = 0;
581  }
582 
583  return dataOK;
584 }
585 
587 {
588  Bool_t hasBranch = inputFitData_->haveBranch( sWeightBranchName_ );
589  if ( ! hasBranch ) {
590  std::cerr << "ERROR in LauAbsFitModel::cacheInputSWeights : Input data does not contain variable \"" << sWeightBranchName_ << "\".\n";
591  std::cerr << " : Turning off sFit!" << std::endl;
592  doSFit_ = kFALSE;
593  return;
594  }
595 
596  UInt_t nEvents = this->eventsPerExpt();
597  sWeights_.clear();
598  sWeights_.reserve( nEvents );
599 
600  for (UInt_t iEvt = 0; iEvt < nEvents; ++iEvt) {
601 
602  const LauFitData& dataValues = inputFitData_->getData(iEvt);
603 
604  LauFitData::const_iterator iter = dataValues.find( sWeightBranchName_ );
605 
606  sWeights_.push_back( iter->second * sWeightScaleFactor_ );
607  }
608 }
609 
611 {
612  // Routine to perform the actual fit for the given experiment
613 
614  // Reset the worst likelihood found to its catch-all value
615  worstLogLike_ = std::numeric_limits<Double_t>::max();
616 
617  // Update initial fit parameters if required (e.g. if using random numbers).
618  this->checkInitFitParams();
619 
620  // Initialise the fitter
624 
627 
628  // Now ready for minimisation step
629  std::cout << "\nINFO in LauAbsFitModel::fitExpt : Start minimisation...\n";
630  std::pair<Int_t,Double_t> fitResult = LauFitter::fitter()->minimise();
631 
632  fitStatus_ = fitResult.first;
633  NLL_ = fitResult.second;
634 
635  // If we're doing a two stage fit we can now release (i.e. float)
636  // the 2nd stage parameters and re-fit
637  if (this->twoStageFit()) {
638 
639  if ( fitStatus_ != 3 ) {
640  std::cerr << "WARNING in LauAbsFitModel:fitExpt : Not running second stage fit since first stage failed." << std::endl;
642  } else {
647  fitResult = LauFitter::fitter()->minimise();
648  }
649  }
650 
651  fitStatus_ = fitResult.first;
652  NLL_ = fitResult.second;
653  const TMatrixD& covMat = LauFitter::fitter()->covarianceMatrix();
654  covMatrix_.Clear();
655  covMatrix_.ResizeTo( covMat.GetNrows(), covMat.GetNcols() );
656  covMatrix_.SetMatrixArray( covMat.GetMatrixArray() );
657 
658  // Store the final fit results and errors into protected internal vectors that
659  // all sub-classes can use within their own finalFitResults implementation
660  // used below (e.g. putting them into an ntuple in a root file)
663 }
664 
666 {
667  // Write out histograms at end
668  if (fitNtuple_ != 0) {
670  }
671 }
672 
674 {
675  if (sPlotNtuple_ != 0) {
678  LauSPlot splot(sPlotNtuple_->fileName(), sPlotNtuple_->treeName(), this->firstExpt(), this->nExpt(),
679  this->variableNames(), this->freeSpeciesNames(), this->fixdSpeciesNames(), this->twodimPDFs(),
680  this->splitSignal(), this->scfDPSmear());
682  splot.writeOutResults();
683  }
684 }
685 
686 void LauAbsFitModel::compareFitData(UInt_t toyMCScale, const TString& mcFileName, const TString& tableFileName, Bool_t poissonSmearing)
687 {
688  compareFitData_ = kTRUE;
689  fitToyMCScale_ = toyMCScale;
690  fitToyMCFileName_ = mcFileName;
691  fitToyMCTableName_ = tableFileName;
692  fitToyMCPoissonSmear_ = poissonSmearing;
693 }
694 
695 void LauAbsFitModel::createFitToyMC(const TString& mcFileName, const TString& tableFileName)
696 {
697  // Create a toy MC sample so that the user can compare the fitted
698  // result with the data.
699  // Generate more toy MC to reduce statistical fluctuations:
700  // - use the rescaling value fitToyMCScale_
701 
702  // Store the info on the number of experiments, first expt and current expt
703  const UInt_t oldNExpt(this->nExpt());
704  const UInt_t oldFirstExpt(this->firstExpt());
705  const UInt_t oldIExpt(iExpt_);
706 
707  // Turn off Poisson smearing if required
708  const Bool_t poissonSmearing(this->doPoissonSmearing());
710 
711  // Turn off embedding, since we need toy MC, not reco'ed events
712  const Bool_t enableEmbeddingOrig(this->enableEmbedding());
713  this->enableEmbedding(kFALSE);
714 
715  // Need to make sure that the generation of the DP co-ordinates is
716  // switched on if any of our PDFs depend on it
717  const Bool_t origUseDP = this->useDP();
718  if ( !origUseDP && this->pdfsDependOnDP() ) {
719  this->useDP( kTRUE );
720  this->initialiseDPModels();
721  }
722 
723  // Construct a unique filename for this experiment
724  TString exptString("_expt");
725  exptString += oldIExpt;
726  TString fileName( mcFileName );
727  fileName.Insert( fileName.Last('.'), exptString );
728 
729  // Generate the toy MC
730  std::cout << "INFO in LauAbsFitModel::createFitToyMC : Generating toy MC in " << fileName << " to compare fit with data..." << std::endl;
731  std::cout << " : Number of experiments to generate = " << fitToyMCScale_ << "." << std::endl;
732  std::cout << " : This is to allow the toy MC to be made with reduced statistical fluctuations." << std::endl;
733 
734  // Set the genValue of each parameter to its current (fitted) value
735  // but first store the original genValues for restoring later
736  std::vector<Double_t> origGenValues; origGenValues.reserve(nParams_);
737  for (LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter) {
738  origGenValues.push_back((*iter)->genValue());
739  (*iter)->genValue((*iter)->value());
740  }
741 
742  // If we're asked to generate more than 100 experiments then split it
743  // up into multiple files since otherwise can run into memory issues
744  // when building the index
745 
746  UInt_t totalExpts = fitToyMCScale_;
747  if ( totalExpts > 100 ) {
748  UInt_t nFiles = totalExpts/100;
749  if ( totalExpts%100 ) {
750  nFiles += 1;
751  }
752  for ( UInt_t iFile(0); iFile < nFiles; ++iFile ) {
753 
754  UInt_t firstExp( iFile*100 );
755 
756  // Set number of experiments and first experiment to generate
757  UInt_t nExp = ((firstExp + 100)>totalExpts) ? totalExpts-firstExp : 100;
758  this->setNExpts(nExp, firstExp);
759 
760  // Create a unique filename and generate the events
761  TString extraname = "_file";
762  extraname += iFile;
763  fileName.Insert( fileName.Last('.'), extraname );
764  this->generate(fileName, "genResults", "dummy.root", tableFileName);
765  }
766  } else {
767  // Set number of experiments to new value
768  this->setNExpts(fitToyMCScale_, 0);
769  // Generate the toy
770  this->generate(fileName, "genResults", "dummy.root", tableFileName);
771  }
772 
773  // Reset number of experiments to original value
774  iExpt_ = oldIExpt;
775  this->setNExpts(oldNExpt, oldFirstExpt);
776 
777  // Restore the Poisson smearing to its former value
778  this->doPoissonSmearing(poissonSmearing);
779 
780  // Restore the embedding status
781  this->enableEmbedding(enableEmbeddingOrig);
782 
783  // Restore "useDP" to its former status
784  this->useDP( origUseDP );
785 
786  // Restore the original genValue to each parameter
787  for (UInt_t i(0); i<nParams_; ++i) {
788  fitVars_[i]->genValue(origGenValues[i]);
789  }
790 
791  std::cout << "INFO in LauAbsFitModel::createFitToyMC : Finished in createFitToyMC." << std::endl;
792 }
793 
795 {
796  // Calculate the total negative log-likelihood over all events.
797  // This function assumes that the fit parameters and data tree have
798  // already been set-up correctly.
799 
800  // Loop over the data points to calculate the log likelihood
801  Double_t logLike = this->getLogLikelihood( 0, this->eventsPerExpt() );
802 
803  // Include the Poisson term in the extended likelihood if required
804  if (this->doEMLFit()) {
805  logLike -= this->getEventSum();
806  }
807 
808  // Calculate any penalty terms from Gaussian constrained variables
809  if ( ! conVars_.empty() ){
810  logLike -= this->getLogLikelihoodPenalty();
811  }
812 
813  Double_t totNegLogLike = -logLike;
814  return totNegLogLike;
815 }
816 
818 {
819  Double_t penalty(0.0);
820 
821  for ( LauAbsRValuePList::const_iterator iter = conVars_.begin(); iter != conVars_.end(); ++iter ) {
822  Double_t val = (*iter)->value();
823  Double_t mean = (*iter)->constraintMean();
824  Double_t width = (*iter)->constraintWidth();
825 
826  Double_t term = ( val - mean )*( val - mean );
827  penalty += term/( 2*width*width );
828  }
829 
830  return penalty;
831 }
832 
833 Double_t LauAbsFitModel::getLogLikelihood( UInt_t iStart, UInt_t iEnd )
834 {
835  // Calculate the total negative log-likelihood over all events.
836  // This function assumes that the fit parameters and data tree have
837  // already been set-up correctly.
838 
839  // Loop over the data points to calculate the log likelihood
840  Double_t logLike(0.0);
841 
842  // Loop over the number of events in this experiment
843  Bool_t ok(kTRUE);
844  for (UInt_t iEvt = iStart; iEvt < iEnd; ++iEvt) {
845 
846  Double_t likelihood = this->getTotEvtLikelihood(iEvt);
847 
848  if (likelihood > DBL_MIN) { // Is the likelihood zero?
849  Double_t evtLogLike = TMath::Log(likelihood);
850  if ( doSFit_ ) {
851  evtLogLike *= sWeights_[iEvt];
852  }
853  logLike += evtLogLike;
854  } else {
855  ok = kFALSE;
856  std::cerr << "WARNING in LauAbsFitModel::getLogLikelihood : Strange likelihood value for event " << iEvt << ": " << likelihood << "\n";
857  this->printEventInfo(iEvt);
858  this->printVarsInfo(); //Write the values of the floated variables for which the likelihood is zero
859  break;
860  }
861  }
862 
863  if (!ok) {
864  std::cerr << " : Returning worst NLL found so far to force MINUIT out of this region." << std::endl;
865  logLike = worstLogLike_;
866  } else if (logLike < worstLogLike_) {
867  worstLogLike_ = logLike;
868  }
869 
870  return logLike;
871 }
872 
873 void LauAbsFitModel::setParsFromMinuit(Double_t* par, Int_t npar)
874 {
875  // This function sets the internal parameters based on the values
876  // that Minuit is using when trying to minimise the total likelihood function.
877 
878  // MINOS reports different numbers of free parameters depending on the
879  // situation, so disable this check
880  if ( ! withinAsymErrorCalc_ ) {
881  if (static_cast<UInt_t>(npar) != nFreeParams_) {
882  std::cerr << "ERROR in LauAbsFitModel::setParsFromMinuit : Unexpected number of free parameters: " << npar << ".\n";
883  std::cerr << " Expected: " << nFreeParams_ << ".\n" << std::endl;
884  gSystem->Exit(EXIT_FAILURE);
885  }
886  }
887 
888  // Despite npar being the number of free parameters
889  // the par array actually contains all the parameters,
890  // free and floating...
891 
892  // Update all the floating ones with their new values
893  // Also check if we have any parameters on which the DP integrals depend
894  // and whether they have changed since the last iteration
895  Bool_t recalcNorm(kFALSE);
896  const LauParameterPSet::const_iterator resVarsEnd = resVars_.end();
897  for (UInt_t i(0); i<nParams_; ++i) {
898  if (!fitVars_[i]->fixed()) {
899  if ( resVars_.find( fitVars_[i] ) != resVarsEnd ) {
900  if ( fitVars_[i]->value() != par[i] ) {
901  recalcNorm = kTRUE;
902  }
903  }
904  fitVars_[i]->value(par[i]);
905  }
906  }
907 
908  // If so, then recalculate the normalisation
909  if (recalcNorm) {
910  this->recalculateNormalisation();
911  }
912 
913  this->propagateParUpdates();
914 }
915 
917 {
918  UInt_t nParsAdded(0);
919  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
920  LauAbsPdf* pdf = (*pdf_iter);
921  if ( pdf->isDPDependent() ) {
922  this->pdfsDependOnDP( kTRUE );
923  }
924  LauAbsRValuePList& pars = pdf->getParameters();
925  for (LauAbsRValuePList::iterator pars_iter = pars.begin(); pars_iter != pars.end(); ++pars_iter) {
926  LauParameterPList params = (*pars_iter)->getPars();
927  for (LauParameterPList::iterator params_iter = params.begin(); params_iter != params.end(); ++params_iter) {
928  if ( !(*params_iter)->clone() && ( !(*params_iter)->fixed() ||
929  (this->twoStageFit() && ( (*params_iter)->secondStage() || (*params_iter)->firstStage())) ) ) {
930  fitVars_.push_back(*params_iter);
931  ++nParsAdded;
932  }
933  }
934  }
935  }
936  return nParsAdded;
937 }
938 
939 void LauAbsFitModel::addConstraint(const TString& formula, const std::vector<TString>& pars, const Double_t mean, const Double_t width)
940 {
941  StoreConstraints newCon;
942  newCon.formula_ = formula;
943  newCon.conPars_ = pars;
944  newCon.mean_ = mean;
945  newCon.width_ = width;
946  storeCon_.push_back(newCon);
947 }
948 
950 {
951  for ( LauParameterPList::const_iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
952  if ( (*iter)->gaussConstraint() ) {
953  conVars_.push_back( *iter );
954  std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to parameter "<< (*iter)->name() << std::endl;
955  }
956  }
957 
958  // Add penalties from the constraints to fit parameters
959  for ( std::vector<StoreConstraints>::iterator iter = storeCon_.begin(); iter != storeCon_.end(); ++iter ) {
960  std::vector<TString> names = (*iter).conPars_;
961  std::vector<LauParameter*> params;
962  for ( std::vector<TString>::iterator iternames = names.begin(); iternames != names.end(); ++iternames ) {
963  for ( LauParameterPList::const_iterator iterfit = fitVars_.begin(); iterfit != fitVars_.end(); ++iterfit ) {
964  if ( (*iternames) == (*iterfit)->name() ){
965  params.push_back(*iterfit);
966  }
967  }
968  }
969 
970  // If the parameters are not found, skip it
971  if ( params.size() != (*iter).conPars_.size() ) {
972  std::cerr << "WARNING in LauAbsFitModel::addConParameters: Could not find parameters to constrain in the formula... skipping" << std::endl;
973  continue;
974  }
975 
976  LauFormulaPar* formPar = new LauFormulaPar( (*iter).formula_, (*iter).formula_, params );
977  formPar->addGaussianConstraint( (*iter).mean_, (*iter).width_ );
978  conVars_.push_back(formPar);
979 
980  std::cout << "INFO in LauAbsFitModel::addConParameters : Added Gaussian constraint to formula\n";
981  std::cout << " : Formula: " << (*iter).formula_ << std::endl;
982  for ( std::vector<LauParameter*>::iterator iterparam = params.begin(); iterparam != params.end(); ++iterparam ) {
983  std::cout << " : Parameter: " << (*iterparam)->name() << std::endl;
984  }
985  }
986 
987 }
988 
990 {
991  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
992  (*pdf_iter)->updatePulls();
993  }
994 }
995 
996 void LauAbsFitModel::printFitParameters(const LauPdfList& pdfList, std::ostream& fout) const
997 {
998  LauPrint print;
999  for (LauPdfList::const_iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1000  const LauAbsRValuePList& pars = (*pdf_iter)->getParameters();
1001  for (LauAbsRValuePList::const_iterator pars_iter = pars.begin(); pars_iter != pars.end(); ++pars_iter) {
1002  LauParameterPList params = (*pars_iter)->getPars();
1003  for (LauParameterPList::iterator params_iter = params.begin(); params_iter != params.end(); ++params_iter) {
1004  if (!(*params_iter)->clone()) {
1005  fout << (*params_iter)->name() << " & $";
1006  print.printFormat(fout, (*params_iter)->value());
1007  if ((*params_iter)->fixed() == kTRUE) {
1008  fout << "$ (fixed) \\\\";
1009  } else {
1010  fout << " \\pm ";
1011  print.printFormat(fout, (*params_iter)->error());
1012  fout << "$ \\\\" << std::endl;
1013  }
1014  }
1015  }
1016  }
1017  }
1018 }
1019 
1021 {
1022  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1023  (*pdf_iter)->cacheInfo(theData);
1024  }
1025 }
1026 
1027 Double_t LauAbsFitModel::prodPdfValue(LauPdfList& pdfList, UInt_t iEvt)
1028 {
1029  Double_t pdfVal = 1.0;
1030  for (LauPdfList::iterator pdf_iter = pdfList.begin(); pdf_iter != pdfList.end(); ++pdf_iter) {
1031  (*pdf_iter)->calcLikelihoodInfo(iEvt);
1032  pdfVal *= (*pdf_iter)->getLikelihood();
1033  }
1034  return pdfVal;
1035 }
1036 
1037 void LauAbsFitModel::printEventInfo(UInt_t iEvt) const
1038 {
1039  const LauFitData& data = inputFitData_->getData(iEvt);
1040  std::cerr << " : Input data values for this event:" << std::endl;
1041  for (LauFitData::const_iterator iter = data.begin(); iter != data.end(); ++iter) {
1042  std::cerr << " " << iter->first << " = " << iter->second << std::endl;
1043  }
1044 }
1045 
1047 {
1048  std::cerr << " : Current values of fit parameters:" << std::endl;
1049  for (UInt_t i(0); i<nParams_; ++i) {
1050  std::cerr << " " << (fitVars_[i]->name()).Data() << " = " << fitVars_[i]->value() << std::endl;
1051  }
1052 }
1053 
1055 {
1056  // Update initial fit parameters if required (e.g. if using random numbers).
1057  this->checkInitFitParams();
1058 
1059  // Store the total number of parameters and the number of free parameters
1060  nParams_ = fitVars_.size();
1061  nFreeParams_ = 0;
1062 
1063  // Send the fit parameters
1064  for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
1065  if ( ! (*iter)->fixed() ) {
1066  ++nFreeParams_;
1067  }
1068  array.Add( *iter );
1069  }
1070 }
1071 
1072 void LauAbsFitModel::finaliseResults( const Int_t fitStat, const Double_t NLL, const TObjArray* parsFromMaster, const TMatrixD* covMat, TObjArray& parsToMaster )
1073 {
1074  // Copy the fit status information
1075  fitStatus_ = fitStat;
1076  NLL_ = NLL;
1077 
1078  // Copy the contents of the covariance matrix
1079  covMatrix_.Clear();
1080  covMatrix_.ResizeTo( covMat->GetNrows(), covMat->GetNcols() );
1081  covMatrix_.SetMatrixArray( covMat->GetMatrixArray() );
1082 
1083  // Now process the parameters
1084  UInt_t nPars = parsFromMaster->GetEntries();
1085  if ( nPars != nParams_ ) {
1086  std::cerr << "ERROR in LauAbsFitModel::finaliseResults : Unexpected number of parameters received from master" << std::endl;
1087  std::cerr << " : Received " << nPars << " when expecting " << nParams_ << std::endl;
1088  gSystem->Exit( EXIT_FAILURE );
1089  }
1090 
1091  for ( UInt_t iPar(0); iPar < nPars; ++iPar ) {
1092  LauParameter* parameter = dynamic_cast<LauParameter*>( (*parsFromMaster)[iPar] );
1093  if ( ! parameter ) {
1094  std::cerr << "ERROR in LauAbsFitModel::finaliseResults : Error reading parameter from master" << std::endl;
1095  gSystem->Exit( EXIT_FAILURE );
1096  }
1097 
1098  if ( parameter->name() != fitVars_[iPar]->name() ) {
1099  std::cerr << "ERROR in LauAbsFitModel::finaliseResults : Error reading parameter from master" << std::endl;
1100  gSystem->Exit( EXIT_FAILURE );
1101  }
1102 
1103  *(fitVars_[iPar]) = *parameter;
1104  }
1105 
1106  // Write the results into the ntuple
1108 
1109  // Store the per-event likelihood values
1110  if ( this->writeSPlotData() ) {
1111  this->storePerEvtLlhds();
1112  }
1113 
1114  // Create a toy MC sample using the fitted parameters so that
1115  // the user can compare the fit to the data.
1116  if (compareFitData_ == kTRUE && fitStatus_ == 3) {
1118  }
1119 
1120  // Send the finalised fit parameters
1121  for ( LauParameterPList::iterator iter = fitVars_.begin(); iter != fitVars_.end(); ++iter ) {
1122  parsToMaster.Add( *iter );
1123  }
1124 }
1125 
1126 UInt_t LauAbsFitModel::readExperimentData( const UInt_t exptIndex )
1127 {
1128  // set our record of which experiment we're examining
1129  iExpt_ = exptIndex;
1130 
1131  // retrieve the data and find out how many events have been read
1133  UInt_t nEvent = inputFitData_->nEvents();
1134  this->eventsPerExpt( nEvent );
1135 
1136  return nEvent;
1137 }
1138 
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.
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.
virtual 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.
void processMasterRequests()
Listen for requests from the master and act accordingly.
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.
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.
virtual 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.
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.
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.
virtual UInt_t readExperimentData(const UInt_t exptIndex)
Read in the data for the specified experiment.
void addGaussianConstraint(Double_t newGaussMean, Double_t newGaussWidth)
Add a Gaussian constraint (or modify an existing one)
void connectToMaster(const TString &addressMaster, const UInt_t portMaster)
Establish the connection to the master process.
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.
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.
virtual void recalculateNormalisation()=0
Recalculate normalisation the signal DP model(s)
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.
virtual void prepareInitialParArray(TObjArray &array)
Package the initial fit parameters for transmission to the master.
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:34
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.
UInt_t slaveId() const
Obtain the ID number of this slave.
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 vector 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.
virtual void finaliseResults(const Int_t fitStat, const Double_t NLL, const TObjArray *parsFromMaster, const TMatrixD *covMat, TObjArray &parsToMaster)
Perform all finalisation actions.
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.
LauParameterPSet resVars_
Internal set of fit parameters upon which the DP normalisation depends.
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
TString outputTableName_
The output table name.
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.