Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
RooFitResult.cxx
Go to the documentation of this file.
1 /*****************************************************************************
2  * Project: RooFit *
3  * Package: RooFitCore *
4  * @(#)root/roofitcore:$Id$
5  * Authors: *
6  * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7  * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8  * *
9  * Copyright (c) 2000-2005, Regents of the University of California *
10  * and Stanford University. All rights reserved. *
11  * *
12  * Redistribution and use in source and binary forms, *
13  * with or without modification, are permitted according to the terms *
14  * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15  *****************************************************************************/
16 
17 //////////////////////////////////////////////////////////////////////////////
18 /// \class RooFitResult
19 /// RooFitResult is a container class to hold the input and output
20 /// of a PDF fit to a dataset. It contains:
21 ///
22 /// * Values of all constant parameters
23 /// * Initial and final values of floating parameters with error
24 /// * Correlation matrix and global correlation coefficients
25 /// * NLL and EDM at mininum
26 ///
27 /// No references to the fitted PDF and dataset are stored
28 ///
29 
30 #include "RooFit.h"
31 #include "Riostream.h"
32 
33 #include <iomanip>
34 #include "TMinuit.h"
35 #include "TMath.h"
36 #include "TMarker.h"
37 #include "TLine.h"
38 #include "TBox.h"
39 #include "TGaxis.h"
40 #include "TMatrix.h"
41 #include "TVector.h"
42 #include "TDirectory.h"
43 #include "TClass.h"
44 #include "RooFitResult.h"
45 #include "RooArgSet.h"
46 #include "RooArgList.h"
47 #include "RooRealVar.h"
48 #include "RooPlot.h"
49 #include "RooEllipse.h"
50 #include "RooRandom.h"
51 #include "RooMsgService.h"
52 #include "TH2D.h"
53 #include "TText.h"
54 #include "TMatrixDSym.h"
55 #include "RooMultiVarGaussian.h"
56 
57 
58 
59 using namespace std;
60 
61 ClassImp(RooFitResult);
62 ;
63 
64 
65 
66 ////////////////////////////////////////////////////////////////////////////////
67 /// Constructor with name and title
68 
69 RooFitResult::RooFitResult(const char* name, const char* title) :
70  TNamed(name,title), _constPars(0), _initPars(0), _finalPars(0), _globalCorr(0), _randomPars(0), _Lt(0),
71  _CM(0), _VM(0), _GC(0)
72 {
73  if (name) appendToDir(this,kTRUE) ;
74 }
75 
76 
77 ////////////////////////////////////////////////////////////////////////////////
78 /// Copy constructor
79 
80 RooFitResult::RooFitResult(const RooFitResult& other) :
81  TNamed(other),
82  RooPrintable(other),
83  RooDirItem(other),
84  _status(other._status),
85  _covQual(other._covQual),
86  _numBadNLL(other._numBadNLL),
87  _minNLL(other._minNLL),
88  _edm(other._edm),
89  _globalCorr(0),
90  _randomPars(0),
91  _Lt(0),
92  _CM(0),
93  _VM(0),
94  _GC(0),
95  _statusHistory(other._statusHistory)
96 {
97  _constPars = (RooArgList*) other._constPars->snapshot() ;
98  _initPars = (RooArgList*) other._initPars->snapshot() ;
99  _finalPars = (RooArgList*) other._finalPars->snapshot() ;
100  if (other._randomPars) _randomPars = (RooArgList*) other._randomPars->snapshot() ;
101  if (other._Lt) _Lt = new TMatrix(*other._Lt);
102  if (other._VM) _VM = new TMatrixDSym(*other._VM) ;
103  if (other._CM) _CM = new TMatrixDSym(*other._CM) ;
104  if (other._GC) _GC = new TVectorD(*other._GC) ;
105 
106  if (GetName())
107  appendToDir(this, kTRUE);
108 }
109 
110 
111 
112 ////////////////////////////////////////////////////////////////////////////////
113 /// Destructor
114 
115 RooFitResult::~RooFitResult()
116 {
117  if (_constPars) delete _constPars ;
118  if (_initPars) delete _initPars ;
119  if (_finalPars) delete _finalPars ;
120  if (_globalCorr) delete _globalCorr;
121  if (_randomPars) delete _randomPars;
122  if (_Lt) delete _Lt;
123  if (_CM) delete _CM ;
124  if (_VM) delete _VM ;
125  if (_GC) delete _GC ;
126 
127  _corrMatrix.RemoveAll();
128  _corrMatrix.Delete();
129 
130  removeFromDir(this) ;
131 }
132 
133 
134 ////////////////////////////////////////////////////////////////////////////////
135 /// Fill the list of constant parameters
136 
137 void RooFitResult::setConstParList(const RooArgList& list)
138 {
139  if (_constPars) delete _constPars ;
140  _constPars = (RooArgList*) list.snapshot() ;
141  TIterator* iter = _constPars->createIterator() ;
142  RooAbsArg* arg ;
143  while((arg=(RooAbsArg*)iter->Next())) {
144  RooRealVar* rrv = dynamic_cast<RooRealVar*>(arg) ;
145  if (rrv) {
146  rrv->deleteSharedProperties() ;
147  }
148  }
149  delete iter ;
150 }
151 
152 
153 
154 ////////////////////////////////////////////////////////////////////////////////
155 /// Fill the list of initial values of the floating parameters
156 
157 void RooFitResult::setInitParList(const RooArgList& list)
158 {
159  if (_initPars) delete _initPars ;
160  _initPars = (RooArgList*) list.snapshot() ;
161  TIterator* iter = _initPars->createIterator() ;
162  RooAbsArg* arg ;
163  while((arg=(RooAbsArg*)iter->Next())) {
164  RooRealVar* rrv = dynamic_cast<RooRealVar*>(arg) ;
165  if (rrv) {
166  rrv->deleteSharedProperties() ;
167  }
168  }
169  delete iter ;
170 }
171 
172 
173 
174 ////////////////////////////////////////////////////////////////////////////////
175 /// Fill the list of final values of the floating parameters
176 
177 void RooFitResult::setFinalParList(const RooArgList& list)
178 {
179  if (_finalPars) delete _finalPars ;
180  _finalPars = (RooArgList*) list.snapshot() ;
181 
182  TIterator* iter = _finalPars->createIterator() ;
183  RooAbsArg* arg ;
184  while((arg=(RooAbsArg*)iter->Next())) {
185  RooRealVar* rrv = dynamic_cast<RooRealVar*>(arg) ;
186  if (rrv) {
187  rrv->deleteSharedProperties() ;
188  }
189  }
190  delete iter ;
191 }
192 
193 
194 
195 ////////////////////////////////////////////////////////////////////////////////
196 
197 Int_t RooFitResult::statusCodeHistory(UInt_t icycle) const
198 {
199  if (icycle>=_statusHistory.size()) {
200  coutE(InputArguments) << "RooFitResult::statusCodeHistory(" << GetName()
201  << " ERROR request for status history slot "
202  << icycle << " exceeds history count of " << _statusHistory.size() << endl ;
203  }
204  return _statusHistory[icycle].second ;
205 }
206 
207 
208 
209 ////////////////////////////////////////////////////////////////////////////////
210 
211 const char* RooFitResult::statusLabelHistory(UInt_t icycle) const
212 {
213  if (icycle>=_statusHistory.size()) {
214  coutE(InputArguments) << "RooFitResult::statusLabelHistory(" << GetName()
215  << " ERROR request for status history slot "
216  << icycle << " exceeds history count of " << _statusHistory.size() << endl ;
217  }
218  return _statusHistory[icycle].first.c_str() ;
219 }
220 
221 
222 
223 ////////////////////////////////////////////////////////////////////////////////
224 /// Add objects to a 2D plot that represent the fit results for the
225 /// two named parameters. The input frame with the objects added is
226 /// returned, or zero in case of an error. Which objects are added
227 /// are determined by the options string which should be a concatenation
228 /// of the following (not case sensitive):
229 ///
230 /// * M - a marker at the best fit result
231 /// * E - an error ellipse calculated at 1-sigma using the error matrix at the minimum
232 /// * 1 - the 1-sigma error bar for parameter 1
233 /// * 2 - the 1-sigma error bar for parameter 2
234 /// * B - the bounding box for the error ellipse
235 /// * H - a line and horizontal axis for reading off the correlation coefficient
236 /// * V - a line and vertical axis for reading off the correlation coefficient
237 /// * A - draw axes for reading off the correlation coefficients with the H or V options
238 ///
239 /// You can change the attributes of objects in the returned RooPlot using the
240 /// various `RooPlot::getAttXxx(name)` member functions, e.g.
241 /// ```
242 /// plot->getAttLine("contour")->SetLineStyle(kDashed);
243 /// ```
244 /// Use `plot->Print()` for a list of all objects and their names (unfortunately most
245 /// of the ROOT builtin graphics objects like TLine are unnamed). Drag the left mouse
246 /// button along the labels of either axis button to interactively zoom in a plot.
247 
248 RooPlot *RooFitResult::plotOn(RooPlot *frame, const char *parName1, const char *parName2,
249  const char *options) const
250 {
251  // lookup the input parameters by name: we require that they were floated in our fit
252  const RooRealVar *par1= dynamic_cast<const RooRealVar*>(floatParsFinal().find(parName1));
253  if(0 == par1) {
254  coutE(InputArguments) << "RooFitResult::correlationPlot: parameter not floated in fit: " << parName1 << endl;
255  return 0;
256  }
257  const RooRealVar *par2= dynamic_cast<const RooRealVar*>(floatParsFinal().find(parName2));
258  if(0 == par2) {
259  coutE(InputArguments) << "RooFitResult::correlationPlot: parameter not floated in fit: " << parName2 << endl;
260  return 0;
261  }
262 
263  // options are not case sensitive
264  TString opt(options);
265  opt.ToUpper();
266 
267  // lookup the 2x2 covariance matrix elements for these variables
268  Double_t x1= par1->getVal();
269  Double_t x2= par2->getVal();
270  Double_t s1= par1->getError();
271  Double_t s2= par2->getError();
272  Double_t rho= correlation(parName1, parName2);
273 
274  // add a 1-sigma error ellipse, if requested
275  if(opt.Contains("E")) {
276  RooEllipse *contour= new RooEllipse("contour",x1,x2,s1,s2,rho);
277  contour->SetLineWidth(2) ;
278  frame->addPlotable(contour);
279  }
280 
281  // add the error bar for parameter 1, if requested
282  if(opt.Contains("1")) {
283  TLine *hline= new TLine(x1-s1,x2,x1+s1,x2);
284  hline->SetLineColor(kRed);
285  frame->addObject(hline);
286  }
287 
288  if(opt.Contains("2")) {
289  TLine *vline= new TLine(x1,x2-s2,x1,x2+s2);
290  vline->SetLineColor(kRed);
291  frame->addObject(vline);
292  }
293 
294  if(opt.Contains("B")) {
295  TBox *box= new TBox(x1-s1,x2-s2,x1+s1,x2+s2);
296  box->SetLineStyle(kDashed);
297  box->SetLineColor(kRed);
298  box->SetFillStyle(0);
299  frame->addObject(box);
300  }
301 
302  if(opt.Contains("H")) {
303  TLine *line= new TLine(x1-rho*s1,x2-s2,x1+rho*s1,x2+s2);
304  line->SetLineStyle(kDashed);
305  line->SetLineColor(kBlue);
306  line->SetLineWidth(2) ;
307  frame->addObject(line);
308  if(opt.Contains("A")) {
309  TGaxis *axis= new TGaxis(x1-s1,x2-s2,x1+s1,x2-s2,-1.,+1.,502,"-=");
310  axis->SetLineColor(kBlue);
311  frame->addObject(axis);
312  }
313  }
314 
315  if(opt.Contains("V")) {
316  TLine *line= new TLine(x1-s1,x2-rho*s2,x1+s1,x2+rho*s2);
317  line->SetLineStyle(kDashed);
318  line->SetLineColor(kBlue);
319  line->SetLineWidth(2) ;
320  frame->addObject(line);
321  if(opt.Contains("A")) {
322  TGaxis *axis= new TGaxis(x1-s1,x2-s2,x1-s1,x2+s2,-1.,+1.,502,"-=");
323  axis->SetLineColor(kBlue);
324  frame->addObject(axis);
325  }
326  }
327 
328  // add a marker at the fitted value, if requested
329  if(opt.Contains("M")) {
330  TMarker *marker= new TMarker(x1,x2,20);
331  marker->SetMarkerColor(kBlack);
332  frame->addObject(marker);
333  }
334 
335  return frame;
336 }
337 
338 
339 ////////////////////////////////////////////////////////////////////////////////
340 /// Return a list of floating parameter values that are perturbed from the final
341 /// fit values by random amounts sampled from the covariance matrix. The returned
342 /// object is overwritten with each call and belongs to the RooFitResult. Uses
343 /// the "square root method" to decompose the covariance matrix, which makes inverting
344 /// it unnecessary.
345 
346 const RooArgList& RooFitResult::randomizePars() const
347 {
348  Int_t nPar= _finalPars->getSize();
349  if(0 == _randomPars) { // first-time initialization
350  assert(0 != _finalPars);
351  // create the list of random values to fill
352  _randomPars= (RooArgList*)_finalPars->snapshot();
353  // calculate the elements of the upper-triangular matrix L that gives Lt*L = C
354  // where Lt is the transpose of L (the "square-root method")
355  TMatrix L(nPar,nPar);
356  for(Int_t iPar= 0; iPar < nPar; iPar++) {
357  // calculate the diagonal term first
358  L(iPar,iPar)= covariance(iPar,iPar);
359  for(Int_t k= 0; k < iPar; k++) {
360  Double_t tmp= L(k,iPar);
361  L(iPar,iPar)-= tmp*tmp;
362  }
363  L(iPar,iPar)= sqrt(L(iPar,iPar));
364  // then the off-diagonal terms
365  for(Int_t jPar= iPar+1; jPar < nPar; jPar++) {
366  L(iPar,jPar)= covariance(iPar,jPar);
367  for(Int_t k= 0; k < iPar; k++) {
368  L(iPar,jPar)-= L(k,iPar)*L(k,jPar);
369  }
370  L(iPar,jPar)/= L(iPar,iPar);
371  }
372  }
373  // remember Lt
374  _Lt= new TMatrix(TMatrix::kTransposed,L);
375  }
376  else {
377  // reset to the final fit values
378  *_randomPars= *_finalPars;
379  }
380 
381  // create a vector of unit Gaussian variables
382  TVector g(nPar);
383  for(Int_t k= 0; k < nPar; k++) g(k)= RooRandom::gaussian();
384  // multiply this vector by Lt to introduce the appropriate correlations
385  g*= (*_Lt);
386  // add the mean value offsets and store the results
387  TIterator *iter= _randomPars->createIterator();
388  RooRealVar *par(0);
389  Int_t index(0);
390  while((0 != (par= (RooRealVar*)iter->Next()))) {
391  par->setVal(par->getVal() + g(index++));
392  }
393  delete iter;
394 
395  return *_randomPars;
396 }
397 
398 
399 ////////////////////////////////////////////////////////////////////////////////
400 /// Return the correlation between parameters 'par1' and 'par2'
401 
402 Double_t RooFitResult::correlation(const char* parname1, const char* parname2) const
403 {
404  Int_t idx1 = _finalPars->index(parname1) ;
405  Int_t idx2 = _finalPars->index(parname2) ;
406  if (idx1<0) {
407  coutE(InputArguments) << "RooFitResult::correlation(" << GetName() << ") parameter " << parname1 << " is not a floating fit parameter" << endl ;
408  return 0 ;
409  }
410  if (idx2<0) {
411  coutE(InputArguments) << "RooFitResult::correlation(" << GetName() << ") parameter " << parname2 << " is not a floating fit parameter" << endl ;
412  return 0 ;
413  }
414  return correlation(idx1,idx2) ;
415 }
416 
417 
418 
419 ////////////////////////////////////////////////////////////////////////////////
420 /// Return the set of correlation coefficients of parameter 'par' with
421 /// all other floating parameters
422 
423 const RooArgList* RooFitResult::correlation(const char* parname) const
424 {
425  if (_globalCorr==0) {
426  fillLegacyCorrMatrix() ;
427  }
428 
429  RooAbsArg* arg = _initPars->find(parname) ;
430  if (!arg) {
431  coutE(InputArguments) << "RooFitResult::correlation: variable " << parname << " not a floating parameter in fit" << endl ;
432  return 0 ;
433  }
434  return (RooArgList*)_corrMatrix.At(_initPars->index(arg)) ;
435 }
436 
437 
438 
439 ////////////////////////////////////////////////////////////////////////////////
440 /// Return the global correlation of the named parameter
441 
442 Double_t RooFitResult::globalCorr(const char* parname)
443 {
444  if (_globalCorr==0) {
445  fillLegacyCorrMatrix() ;
446  }
447 
448  RooAbsArg* arg = _initPars->find(parname) ;
449  if (!arg) {
450  coutE(InputArguments) << "RooFitResult::globalCorr: variable " << parname << " not a floating parameter in fit" << endl ;
451  return 0 ;
452  }
453 
454  if (_globalCorr) {
455  return ((RooAbsReal*)_globalCorr->at(_initPars->index(arg)))->getVal() ;
456  } else {
457  return 1.0 ;
458  }
459 }
460 
461 
462 
463 ////////////////////////////////////////////////////////////////////////////////
464 /// Return the list of all global correlations
465 
466 const RooArgList* RooFitResult::globalCorr()
467 {
468  if (_globalCorr==0) {
469  fillLegacyCorrMatrix() ;
470  }
471 
472  return _globalCorr ;
473 }
474 
475 
476 
477 ////////////////////////////////////////////////////////////////////////////////
478 /// Return a correlation matrix element addressed with numeric indices.
479 
480 Double_t RooFitResult::correlation(Int_t row, Int_t col) const
481 {
482  return (*_CM)(row,col) ;
483 }
484 
485 
486 ////////////////////////////////////////////////////////////////////////////////
487 /// Return the covariance matrix element addressed with numeric indices.
488 
489 Double_t RooFitResult::covariance(Int_t row, Int_t col) const
490 {
491  return (*_VM)(row,col) ;
492 }
493 
494 
495 
496 ////////////////////////////////////////////////////////////////////////////////
497 /// Print fit result to stream 'os'. In Verbose mode, the constant parameters and
498 /// the initial and final values of the floating parameters are printed.
499 /// Standard mode only the final values of the floating parameters are printed
500 
501 void RooFitResult::printMultiline(ostream& os, Int_t /*contents*/, Bool_t verbose, TString indent) const
502 {
503 
504  os << endl
505  << indent << " RooFitResult: minimized FCN value: " << _minNLL << ", estimated distance to minimum: " << _edm << endl
506  << indent << " covariance matrix quality: " ;
507  switch(_covQual) {
508  case -1 : os << "Unknown, matrix was externally provided" ; break ;
509  case 0 : os << "Not calculated at all" ; break ;
510  case 1 : os << "Approximation only, not accurate" ; break ;
511  case 2 : os << "Full matrix, but forced positive-definite" ; break ;
512  case 3 : os << "Full, accurate covariance matrix" ; break ;
513  }
514  os << endl ;
515  os << indent << " Status : " ;
516  for (vector<pair<string,int> >::const_iterator iter = _statusHistory.begin() ; iter != _statusHistory.end() ; ++iter) {
517  os << iter->first << "=" << iter->second << " " ;
518  }
519  os << endl << endl ;;
520 
521  Int_t i ;
522  if (verbose) {
523  if (_constPars->getSize()>0) {
524  os << indent << " Constant Parameter Value " << endl
525  << indent << " -------------------- ------------" << endl ;
526 
527  for (i=0 ; i<_constPars->getSize() ; i++) {
528  os << indent << " " << setw(20) << ((RooAbsArg*)_constPars->at(i))->GetName()
529  << " " << setw(12) << Form("%12.4e",((RooRealVar*)_constPars->at(i))->getVal())
530  << endl ;
531  }
532 
533  os << endl ;
534  }
535 
536  // Has any parameter asymmetric errors?
537  Bool_t doAsymErr(kFALSE) ;
538  for (i=0 ; i<_finalPars->getSize() ; i++) {
539  if (((RooRealVar*)_finalPars->at(i))->hasAsymError()) {
540  doAsymErr=kTRUE ;
541  break ;
542  }
543  }
544 
545  if (doAsymErr) {
546  os << indent << " Floating Parameter InitialValue FinalValue (+HiError,-LoError) GblCorr." << endl
547  << indent << " -------------------- ------------ ---------------------------------- --------" << endl ;
548  } else {
549  os << indent << " Floating Parameter InitialValue FinalValue +/- Error GblCorr." << endl
550  << indent << " -------------------- ------------ -------------------------- --------" << endl ;
551  }
552 
553  for (i=0 ; i<_finalPars->getSize() ; i++) {
554  os << indent << " " << setw(20) << ((RooAbsArg*)_finalPars->at(i))->GetName() ;
555  os << indent << " " << setw(12) << Form("%12.4e",((RooRealVar*)_initPars->at(i))->getVal())
556  << indent << " " << setw(12) << Form("%12.4e",((RooRealVar*)_finalPars->at(i))->getVal()) ;
557 
558  if (((RooRealVar*)_finalPars->at(i))->hasAsymError()) {
559  os << setw(21) << Form(" (+%8.2e,-%8.2e)",((RooRealVar*)_finalPars->at(i))->getAsymErrorHi(),
560  -1*((RooRealVar*)_finalPars->at(i))->getAsymErrorLo()) ;
561  } else {
562  Double_t err = ((RooRealVar*)_finalPars->at(i))->getError() ;
563  os << (doAsymErr?" ":"") << " +/- " << setw(9) << Form("%9.2e",err) ;
564  }
565 
566  if (_globalCorr) {
567  os << " " << setw(8) << Form("%8.6f" ,((RooRealVar*)_globalCorr->at(i))->getVal()) ;
568  } else {
569  os << " <none>" ;
570  }
571 
572  os << endl ;
573  }
574 
575  } else {
576  os << indent << " Floating Parameter FinalValue +/- Error " << endl
577  << indent << " -------------------- --------------------------" << endl ;
578 
579  for (i=0 ; i<_finalPars->getSize() ; i++) {
580  Double_t err = ((RooRealVar*)_finalPars->at(i))->getError() ;
581  os << indent << " " << setw(20) << ((RooAbsArg*)_finalPars->at(i))->GetName()
582  << " " << setw(12) << Form("%12.4e",((RooRealVar*)_finalPars->at(i))->getVal())
583  << " +/- " << setw(9) << Form("%9.2e",err)
584  << endl ;
585  }
586  }
587 
588 
589  os << endl ;
590 }
591 
592 
593 ////////////////////////////////////////////////////////////////////////////////
594 /// Function called by RooMinimizer
595 
596 void RooFitResult::fillCorrMatrix(const std::vector<double>& globalCC, const TMatrixDSym& corrs, const TMatrixDSym& covs)
597 {
598  // Sanity check
599  if (globalCC.empty() || corrs.GetNoElements() < 1 || covs.GetNoElements() < 1) {
600  coutI(Minimization) << "RooFitResult::fillCorrMatrix: number of floating parameters is zero, correlation matrix not filled" << endl ;
601  return ;
602  }
603 
604  if (!_initPars) {
605  coutE(Minimization) << "RooFitResult::fillCorrMatrix: ERROR: list of initial parameters must be filled first" << endl ;
606  return ;
607  }
608 
609  // Delete eventual prevous correlation data holders
610  if (_CM) delete _CM ;
611  if (_VM) delete _VM ;
612  if (_GC) delete _GC ;
613 
614  // Build holding arrays for correlation coefficients
615  _CM = new TMatrixDSym(corrs) ;
616  _VM = new TMatrixDSym(covs) ;
617  _GC = new TVectorD(_CM->GetNcols()) ;
618  for(int i=0 ; i<_CM->GetNcols() ; i++) {
619  (*_GC)[i] = globalCC[i] ;
620  }
621  //fillLegacyCorrMatrix() ;
622 }
623 
624 
625 
626 
627 
628 ////////////////////////////////////////////////////////////////////////////////
629 /// Sanity check
630 
631 void RooFitResult::fillLegacyCorrMatrix() const
632 {
633  if (!_CM) return ;
634 
635  // Delete eventual prevous correlation data holders
636  if (_globalCorr) delete _globalCorr ;
637  _corrMatrix.Delete();
638 
639  // Build holding arrays for correlation coefficients
640  _globalCorr = new RooArgList("globalCorrelations") ;
641 
642  TIterator* vIter = _initPars->createIterator() ;
643  RooAbsArg* arg ;
644  Int_t idx(0) ;
645  while((arg=(RooAbsArg*)vIter->Next())) {
646  // Create global correlation value holder
647  TString gcName("GC[") ;
648  gcName.Append(arg->GetName()) ;
649  gcName.Append("]") ;
650  TString gcTitle(arg->GetTitle()) ;
651  gcTitle.Append(" Global Correlation") ;
652  _globalCorr->addOwned(*(new RooRealVar(gcName.Data(),gcTitle.Data(),0.))) ;
653 
654  // Create array with correlation holders for this parameter
655  TString name("C[") ;
656  name.Append(arg->GetName()) ;
657  name.Append(",*]") ;
658  RooArgList* corrMatrixRow = new RooArgList(name.Data()) ;
659  _corrMatrix.Add(corrMatrixRow) ;
660  TIterator* vIter2 = _initPars->createIterator() ;
661  RooAbsArg* arg2 ;
662  while((arg2=(RooAbsArg*)vIter2->Next())) {
663 
664  TString cName("C[") ;
665  cName.Append(arg->GetName()) ;
666  cName.Append(",") ;
667  cName.Append(arg2->GetName()) ;
668  cName.Append("]") ;
669  TString cTitle("Correlation between ") ;
670  cTitle.Append(arg->GetName()) ;
671  cTitle.Append(" and ") ;
672  cTitle.Append(arg2->GetName()) ;
673  corrMatrixRow->addOwned(*(new RooRealVar(cName.Data(),cTitle.Data(),0.))) ;
674  }
675  delete vIter2 ;
676  idx++ ;
677  }
678  delete vIter ;
679 
680  TIterator *gcIter = _globalCorr->createIterator() ;
681  TIterator *parIter = _finalPars->createIterator() ;
682  RooRealVar* gcVal = 0;
683  for (unsigned int i = 0; i < (unsigned int)_CM->GetNcols() ; ++i) {
684 
685  // Find the next global correlation slot to fill, skipping fixed parameters
686  gcVal = (RooRealVar*) gcIter->Next() ;
687  gcVal->setVal((*_GC)(i)) ; // WVE FIX THIS
688 
689  // Fill a row of the correlation matrix
690  TIterator* cIter = ((RooArgList*)_corrMatrix.At(i))->createIterator() ;
691  for (unsigned int it = 0; it < (unsigned int)_CM->GetNcols() ; ++it) {
692  RooRealVar* cVal = (RooRealVar*) cIter->Next() ;
693  double value = (*_CM)(i,it) ;
694  cVal->setVal(value);
695  (*_CM)(i,it) = value;
696  }
697  delete cIter ;
698  }
699 
700  delete gcIter ;
701  delete parIter ;
702 
703 }
704 
705 
706 
707 
708 
709 ////////////////////////////////////////////////////////////////////////////////
710 /// Internal utility method to extract the correlation matrix and the
711 /// global correlation coefficients from the MINUIT memory buffer and
712 /// fill the internal arrays.
713 
714 void RooFitResult::fillCorrMatrix()
715 {
716  // Sanity check
717  if (gMinuit->fNpar < 1) {
718  coutI(Minimization) << "RooFitResult::fillCorrMatrix: number of floating parameters is zero, correlation matrix not filled" << endl ;
719  return ;
720  }
721 
722  if (!_initPars) {
723  coutE(Minimization) << "RooFitResult::fillCorrMatrix: ERROR: list of initial parameters must be filled first" << endl ;
724  return ;
725  }
726 
727  // Delete eventual prevous correlation data holders
728  if (_CM) delete _CM ;
729  if (_VM) delete _VM ;
730  if (_GC) delete _GC ;
731 
732  // Build holding arrays for correlation coefficients
733  _CM = new TMatrixDSym(_initPars->getSize()) ;
734  _VM = new TMatrixDSym(_initPars->getSize()) ;
735  _GC = new TVectorD(_initPars->getSize()) ;
736 
737  // Extract correlation information for MINUIT (code taken from TMinuit::mnmatu() )
738 
739  // WVE: This code directly manipulates minuit internal workspace,
740  // if TMinuit code changes this may need updating
741  Int_t ndex, i, j, m, n, it /* nparm,id,ix */ ;
742  Int_t ndi, ndj /*, iso, isw2, isw5*/;
743  for (i = 1; i <= gMinuit->fNpar; ++i) {
744  ndi = i*(i + 1) / 2;
745  for (j = 1; j <= gMinuit->fNpar; ++j) {
746  m = TMath::Max(i,j);
747  n = TMath::Min(i,j);
748  ndex = m*(m-1) / 2 + n;
749  ndj = j*(j + 1) / 2;
750  gMinuit->fMATUvline[j-1] = gMinuit->fVhmat[ndex-1] / TMath::Sqrt(TMath::Abs(gMinuit->fVhmat[ndi-1]*gMinuit->fVhmat[ndj-1]));
751  }
752 
753  (*_GC)(i-1) = gMinuit->fGlobcc[i-1] ;
754 
755  // Fill a row of the correlation matrix
756  for (it = 1; it <= gMinuit->fNpar ; ++it) {
757  (*_CM)(i-1,it-1) = gMinuit->fMATUvline[it-1] ;
758  }
759  }
760 
761  for (int ii=0 ; ii<_finalPars->getSize() ; ii++) {
762  for (int jj=0 ; jj<_finalPars->getSize() ; jj++) {
763  (*_VM)(ii,jj) = (*_CM)(ii,jj) * ((RooRealVar*)_finalPars->at(ii))->getError() * ((RooRealVar*)_finalPars->at(jj))->getError() ;
764  }
765  }
766 }
767 
768 ////////////////////////////////////////////////////////////////////////////////
769 
770 void RooFitResult::fillPrefitCorrMatrix()
771 {
772 
773  // Delete eventual prevous correlation data holders
774  if (_CM)
775  delete _CM;
776  if (_VM)
777  delete _VM;
778  if (_GC)
779  delete _GC;
780 
781  // Build holding arrays for correlation coefficients
782  _CM = new TMatrixDSym(_initPars->getSize());
783  _VM = new TMatrixDSym(_initPars->getSize());
784  _GC = new TVectorD(_initPars->getSize());
785 
786  for (int ii = 0; ii < _finalPars->getSize(); ii++) {
787  (*_CM)(ii, ii) = 1;
788  (*_VM)(ii, ii) = ((RooRealVar *)_finalPars->at(ii))->getError() * ((RooRealVar *)_finalPars->at(ii))->getError();
789  (*_GC)(ii) = 0;
790  }
791 }
792 
793 ////////////////////////////////////////////////////////////////////////////////
794 /// Return true if this fit result is identical to other within tolerances.
795 /// \param[in] other Fit result to test against.
796 /// \param[in] tol **Relative** tolerance for parameters and NLL.
797 /// \param[in] tolCorr **absolute** tolerance for correlation coefficients.
798 /// \param[in] verbose Ignored.
799 
800 Bool_t RooFitResult::isIdentical(const RooFitResult& other, Double_t tol, Double_t tolCorr, Bool_t /*verbose*/) const
801 {
802  Bool_t ret = kTRUE ;
803  auto deviation = [tol](const double left, const double right){
804  if (right != 0.)
805  return fabs((left - right)/right) >= tol;
806  else
807  return fabs(left) >= tol;
808  };
809 
810  auto errMsg = [](std::string msgHead, const RooAbsReal* tv, const RooAbsReal* ov) {
811  cout << "RooFitResult::isIdentical: " << msgHead << " " << tv->GetName() << " differs in value:\t"
812  << tv->getVal() << " vs.\t" << ov->getVal()
813  << "\t(" << (tv->getVal()-ov->getVal())/ov->getVal() << ")" << endl;
814  };
815 
816  if (deviation(_minNLL, other._minNLL)) {
817  cout << "RooFitResult::isIdentical: minimized value of -log(L) is different " << _minNLL << " vs. " << other._minNLL << endl ;
818  ret = kFALSE ;
819  }
820 
821  for (Int_t i=0 ; i<_constPars->getSize() ; i++) {
822  auto tv = static_cast<const RooAbsReal*>(_constPars->at(i));
823  auto ov = static_cast<const RooAbsReal*>(other._constPars->find(tv->GetName())) ;
824  if (!ov) {
825  cout << "RooFitResult::isIdentical: cannot find constant parameter " << _constPars->at(i)->GetName() << " in reference" << endl ;
826  ret = kFALSE ;
827  }
828  if (ov && deviation(tv->getVal(), ov->getVal())) {
829  errMsg("constant parameter", tv, ov);
830  ret = kFALSE ;
831  }
832  }
833 
834  for (Int_t i=0 ; i<_initPars->getSize() ; i++) {
835  auto ov = static_cast<const RooAbsReal*>(other._initPars->find(_initPars->at(i)->GetName())) ;
836  auto tv = static_cast<const RooAbsReal*>(_initPars->at(i));
837  if (!ov) {
838  cout << "RooFitResult::isIdentical: cannot find initial parameter " << _initPars->at(i)->GetName() << " in reference" << endl ;
839  ret = kFALSE ;
840  }
841  if (ov && deviation(tv->getVal(), ov->getVal())) {
842  errMsg("initial parameter", tv, ov);
843  ret = kFALSE ;
844  }
845  }
846 
847  for (Int_t i=0 ; i<_finalPars->getSize() ; i++) {
848  auto tv = static_cast<const RooAbsReal*>(_finalPars->at(i));
849  auto ov = static_cast<const RooAbsReal*>(other._finalPars->find(tv->GetName())) ;
850  if (!ov) {
851  cout << "RooFitResult::isIdentical: cannot find final parameter " << tv->GetName() << " in reference" << endl ;
852  ret = kFALSE ;
853  }
854  if (ov && deviation(tv->getVal(), ov->getVal())) {
855  errMsg("final parameter", tv, ov);
856  ret = kFALSE ;
857  }
858  }
859 
860  auto deviationCorr = [tolCorr](const double left, const double right){
861  return fabs(left - right) >= tolCorr;
862  };
863 
864  // Only examine correlations for cases with >1 floating parameter
865  if (_finalPars->getSize()>1) {
866 
867  fillLegacyCorrMatrix() ;
868  other.fillLegacyCorrMatrix() ;
869 
870  for (Int_t i=0 ; i<_globalCorr->getSize() ; i++) {
871  auto tv = static_cast<const RooAbsReal*>(_globalCorr->at(i));
872  auto ov = static_cast<const RooAbsReal*>(other._globalCorr->find(_globalCorr->at(i)->GetName())) ;
873  if (!ov) {
874  cout << "RooFitResult::isIdentical: cannot find global correlation coefficient " << tv->GetName() << " in reference" << endl ;
875  ret = kFALSE ;
876  }
877  if (ov && deviationCorr(tv->getVal(), ov->getVal())) {
878  errMsg("global correlation coefficient", tv, ov);
879  ret = kFALSE ;
880  }
881  }
882 
883  for (Int_t j=0 ; j<_corrMatrix.GetSize() ; j++) {
884  RooArgList* row = (RooArgList*) _corrMatrix.At(j) ;
885  RooArgList* orow = (RooArgList*) other._corrMatrix.At(j) ;
886  for (Int_t i=0 ; i<row->getSize() ; i++) {
887  auto tv = static_cast<const RooAbsReal*>(row->at(i));
888  auto ov = static_cast<const RooAbsReal*>(orow->find(tv->GetName())) ;
889  if (!ov) {
890  cout << "RooFitResult::isIdentical: cannot find correlation coefficient " << tv->GetName() << " in reference" << endl ;
891  ret = kFALSE ;
892  }
893  if (ov && deviationCorr(tv->getVal(), ov->getVal())) {
894  errMsg("correlation coefficient", tv, ov);
895  ret = kFALSE ;
896  }
897  }
898  }
899  }
900 
901  return ret ;
902 }
903 
904 
905 
906 ////////////////////////////////////////////////////////////////////////////////
907 /// Import the results of the last fit performed by gMinuit, interpreting
908 /// the fit parameters as the given varList of parameters.
909 
910 RooFitResult* RooFitResult::lastMinuitFit(const RooArgList& varList)
911 {
912  // Verify length of supplied varList
913  if (varList.getSize()>0 && varList.getSize()!=gMinuit->fNu) {
914  oocoutE((TObject*)0,InputArguments) << "RooFitResult::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
915  << " or match the number of variables of the last fit (" << gMinuit->fNu << ")" << endl ;
916  return 0 ;
917  }
918 
919  // Verify that all members of varList are of type RooRealVar
920  TIterator* iter = varList.createIterator() ;
921  RooAbsArg* arg ;
922  while((arg=(RooAbsArg*)iter->Next())) {
923  if (!dynamic_cast<RooRealVar*>(arg)) {
924  oocoutE((TObject*)0,InputArguments) << "RooFitResult::lastMinuitFit: ERROR: variable '" << arg->GetName() << "' is not of type RooRealVar" << endl ;
925  return 0 ;
926  }
927  }
928  delete iter ;
929 
930  RooFitResult* r = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
931 
932  // Extract names of fit parameters from MINUIT
933  // and construct corresponding RooRealVars
934  RooArgList constPars("constPars") ;
935  RooArgList floatPars("floatPars") ;
936 
937  Int_t i ;
938  for (i = 1; i <= gMinuit->fNu; ++i) {
939  if (gMinuit->fNvarl[i-1] < 0) continue;
940  Int_t l = gMinuit->fNiofex[i-1];
941  TString varName(gMinuit->fCpnam[i-1]) ;
942  Bool_t isConst(l==0) ;
943 
944  Double_t xlo = gMinuit->fAlim[i-1];
945  Double_t xhi = gMinuit->fBlim[i-1];
946  Double_t xerr = gMinuit->fWerr[l-1];
947  Double_t xval = gMinuit->fU[i-1] ;
948 
949  RooRealVar* var ;
950  if (varList.getSize()==0) {
951 
952  if ((xlo<xhi) && !isConst) {
953  var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
954  } else {
955  var = new RooRealVar(varName,varName,xval) ;
956  }
957  var->setConstant(isConst) ;
958  } else {
959 
960  var = (RooRealVar*) varList.at(i-1)->Clone() ;
961  var->setConstant(isConst) ;
962  var->setVal(xval) ;
963  if (xlo<xhi) {
964  var->setRange(xlo,xhi) ;
965  }
966  if (varName.CompareTo(var->GetName())) {
967  oocoutI((TObject*)0,Eval) << "RooFitResult::lastMinuitFit: fit parameter '" << varName
968  << "' stored in variable '" << var->GetName() << "'" << endl ;
969  }
970 
971  }
972 
973  if (isConst) {
974  constPars.addOwned(*var) ;
975  } else {
976  var->setError(xerr) ;
977  floatPars.addOwned(*var) ;
978  }
979  }
980 
981  Int_t icode,npari,nparx ;
982  Double_t fmin,edm,errdef ;
983  gMinuit->mnstat(fmin,edm,errdef,npari,nparx,icode) ;
984 
985  r->setConstParList(constPars) ;
986  r->setInitParList(floatPars) ;
987  r->setFinalParList(floatPars) ;
988  r->setMinNLL(fmin) ;
989  r->setEDM(edm) ;
990  r->setCovQual(icode) ;
991  r->setStatus(gMinuit->fStatus) ;
992  r->fillCorrMatrix() ;
993 
994  return r ;
995 }
996 
997 
998 
999 ////////////////////////////////////////////////////////////////////////////////
1000 /// Import the results of the last fit performed by gMinuit, interpreting
1001 /// the fit parameters as the given varList of parameters.
1002 
1003 RooFitResult *RooFitResult::prefitResult(const RooArgList &paramList)
1004 {
1005  // Verify that all members of varList are of type RooRealVar
1006  TIterator *iter = paramList.createIterator();
1007  RooAbsArg *arg;
1008  while ((arg = (RooAbsArg *)iter->Next())) {
1009  if (!dynamic_cast<RooRealVar *>(arg)) {
1010  oocoutE((TObject *)0, InputArguments) << "RooFitResult::lastMinuitFit: ERROR: variable '" << arg->GetName()
1011  << "' is not of type RooRealVar" << endl;
1012  return 0;
1013  }
1014  }
1015 
1016  RooFitResult *r = new RooFitResult("lastMinuitFit", "Last MINUIT fit");
1017 
1018  // Extract names of fit parameters from MINUIT
1019  // and construct corresponding RooRealVars
1020  RooArgList constPars("constPars");
1021  RooArgList floatPars("floatPars");
1022 
1023  iter->Reset();
1024  while ((arg = (RooAbsArg *)iter->Next())) {
1025  if (arg->isConstant()) {
1026  constPars.addClone(*arg);
1027  } else {
1028  floatPars.addClone(*arg);
1029  }
1030  }
1031  delete iter;
1032 
1033  r->setConstParList(constPars);
1034  r->setInitParList(floatPars);
1035  r->setFinalParList(floatPars);
1036  r->setMinNLL(0);
1037  r->setEDM(0);
1038  r->setCovQual(0);
1039  r->setStatus(0);
1040  r->fillPrefitCorrMatrix();
1041 
1042  return r;
1043 }
1044 
1045 ////////////////////////////////////////////////////////////////////////////////
1046 /// Store externally provided correlation matrix in this RooFitResult ;
1047 
1048 void RooFitResult::setCovarianceMatrix(TMatrixDSym& V)
1049 {
1050  // Delete any previous matrices
1051  if (_VM) {
1052  delete _VM ;
1053  }
1054  if (_CM) {
1055  delete _CM ;
1056  }
1057 
1058  // Clone input covariance matrix ;
1059  _VM = (TMatrixDSym*) V.Clone() ;
1060 
1061  // Now construct correlation matrix from it
1062  _CM = (TMatrixDSym*) _VM->Clone() ;
1063  for (Int_t i=0 ; i<_CM->GetNrows() ; i++) {
1064  for (Int_t j=0 ; j<_CM->GetNcols() ; j++) {
1065  if (i!=j) {
1066  (*_CM)(i,j) = (*_CM)(i,j) / sqrt((*_CM)(i,i)*(*_CM)(j,j)) ;
1067  }
1068  }
1069  }
1070  for (Int_t i=0 ; i<_CM->GetNrows() ; i++) {
1071  (*_CM)(i,i) = 1.0 ;
1072  }
1073 
1074  _covQual = -1 ;
1075 }
1076 
1077 
1078 
1079 ////////////////////////////////////////////////////////////////////////////////
1080 /// Return TH2D of correlation matrix
1081 
1082 TH2* RooFitResult::correlationHist(const char* name) const
1083 {
1084  Int_t n = _CM->GetNcols() ;
1085 
1086  TH2D* hh = new TH2D(name,name,n,0,n,n,0,n) ;
1087 
1088  for (Int_t i = 0 ; i<n ; i++) {
1089  for (Int_t j = 0 ; j<n; j++) {
1090  hh->Fill(i+0.5,n-j-0.5,(*_CM)(i,j)) ;
1091  }
1092  hh->GetXaxis()->SetBinLabel(i+1,_finalPars->at(i)->GetName()) ;
1093  hh->GetYaxis()->SetBinLabel(n-i,_finalPars->at(i)->GetName()) ;
1094  }
1095  hh->SetMinimum(-1) ;
1096  hh->SetMaximum(+1) ;
1097 
1098 
1099  return hh ;
1100 }
1101 
1102 
1103 
1104 
1105 ////////////////////////////////////////////////////////////////////////////////
1106 /// Return covariance matrix
1107 
1108 const TMatrixDSym& RooFitResult::covarianceMatrix() const
1109 {
1110  return *_VM ;
1111 }
1112 
1113 
1114 
1115 
1116 ////////////////////////////////////////////////////////////////////////////////
1117 /// Return a reduced covariance matrix (Note that Vred _is_ a simple sub-matrix of V,
1118 /// row/columns are ordered to matched the convention given in input argument 'params'
1119 
1120 TMatrixDSym RooFitResult::reducedCovarianceMatrix(const RooArgList& params) const
1121 {
1122  const TMatrixDSym& V = covarianceMatrix() ;
1123 
1124 
1125  // Make sure that all given params were floating parameters in the represented fit
1126  RooArgList params2 ;
1127  TIterator* iter = params.createIterator() ;
1128  RooAbsArg* arg ;
1129  while((arg=(RooAbsArg*)iter->Next())) {
1130  if (_finalPars->find(arg->GetName())) {
1131  params2.add(*arg) ;
1132  } else {
1133  coutW(InputArguments) << "RooFitResult::reducedCovarianceMatrix(" << GetName() << ") WARNING input variable "
1134  << arg->GetName() << " was not a floating parameters in fit result and is ignored" << endl ;
1135  }
1136  }
1137  delete iter ;
1138 
1139  // fix for bug ROOT-8044
1140  // use same order given bby vector params
1141  vector<int> indexMap(params2.getSize());
1142  for (int i=0 ; i<params2.getSize() ; i++) {
1143  indexMap[i] = _finalPars->index(params2[i].GetName());
1144  assert(indexMap[i] < V.GetNrows());
1145  }
1146 
1147  TMatrixDSym Vred(indexMap.size());
1148  for (int i = 0; i < Vred.GetNrows(); ++i) {
1149  for (int j = 0; j < Vred.GetNcols(); ++j) {
1150  Vred(i,j) = V( indexMap[i], indexMap[j]);
1151  }
1152  }
1153  return Vred;
1154 }
1155 
1156 
1157 
1158 ////////////////////////////////////////////////////////////////////////////////
1159 /// Return a reduced covariance matrix, which is calculated as
1160 /// \f[
1161 /// V_\mathrm{red} = \bar{V_{22}} = V_{11} - V_{12} \cdot V_{22}^{-1} \cdot V_{21},
1162 /// \f]
1163 /// where \f$ V_{11},V_{12},V_{21},V_{22} \f$ represent a block decomposition of the covariance matrix into observables that
1164 /// are propagated (labeled by index '1') and that are not propagated (labeled by index '2'), and \f$ \bar{V_{22}} \f$
1165 /// is the Shur complement of \f$ V_{22} \f$, calculated as shown above.
1166 ///
1167 /// (Note that \f$ V_\mathrm{red} \f$ is *not* a simple sub-matrix of \f$ V \f$)
1168 
1169 TMatrixDSym RooFitResult::conditionalCovarianceMatrix(const RooArgList& params) const
1170 {
1171  const TMatrixDSym& V = covarianceMatrix() ;
1172 
1173  // Handle case where V==Vred here
1174  if (V.GetNcols()==params.getSize()) {
1175  return V ;
1176  }
1177 
1178  Double_t det = V.Determinant() ;
1179 
1180  if (det<=0) {
1181  coutE(Eval) << "RooFitResult::conditionalCovarianceMatrix(" << GetName() << ") ERROR: covariance matrix is not positive definite (|V|="
1182  << det << ") cannot reduce it" << endl ;
1183  throw string("RooFitResult::conditionalCovarianceMatrix() ERROR, input covariance matrix is not positive definite") ;
1184  }
1185 
1186  // Make sure that all given params were floating parameters in the represented fit
1187  RooArgList params2 ;
1188  TIterator* iter = params.createIterator() ;
1189  RooAbsArg* arg ;
1190  while((arg=(RooAbsArg*)iter->Next())) {
1191  if (_finalPars->find(arg->GetName())) {
1192  params2.add(*arg) ;
1193  } else {
1194  coutW(InputArguments) << "RooFitResult::conditionalCovarianceMatrix(" << GetName() << ") WARNING input variable "
1195  << arg->GetName() << " was not a floating parameters in fit result and is ignored" << endl ;
1196  }
1197  }
1198  delete iter ;
1199 
1200  // Need to order params in vector in same order as in covariance matrix
1201  RooArgList params3 ;
1202  iter = _finalPars->createIterator() ;
1203  while((arg=(RooAbsArg*)iter->Next())) {
1204  if (params2.find(arg->GetName())) {
1205  params3.add(*arg) ;
1206  }
1207  }
1208  delete iter ;
1209 
1210  // Find (subset) of parameters that are stored in the covariance matrix
1211  vector<int> map1, map2 ;
1212  for (int i=0 ; i<_finalPars->getSize() ; i++) {
1213  if (params3.find(_finalPars->at(i)->GetName())) {
1214  map1.push_back(i) ;
1215  } else {
1216  map2.push_back(i) ;
1217  }
1218  }
1219 
1220  // Rearrange matrix in block form with 'params' first and 'others' last
1221  // (preserving relative order)
1222  TMatrixDSym S11, S22 ;
1223  TMatrixD S12, S21 ;
1224  RooMultiVarGaussian::blockDecompose(V,map1,map2,S11,S12,S21,S22) ;
1225 
1226  // Constructed conditional matrix form -1
1227  // F(X1|X2) --> CovI --> S22bar = S11 - S12 S22 S21
1228 
1229  // Do eigenvalue decomposition
1230  TMatrixD S22Inv(TMatrixD::kInverted,S22) ;
1231  TMatrixD S22bar = S11 - S12 * (S22Inv * S21) ;
1232 
1233  // Convert explicitly to symmetric form
1234  TMatrixDSym Vred(S22bar.GetNcols()) ;
1235  for (int i=0 ; i<Vred.GetNcols() ; i++) {
1236  for (int j=i ; j<Vred.GetNcols() ; j++) {
1237  Vred(i,j) = (S22bar(i,j) + S22bar(j,i))/2 ;
1238  Vred(j,i) = Vred(i,j) ;
1239  }
1240  }
1241 
1242  return Vred ;
1243 }
1244 
1245 
1246 
1247 ////////////////////////////////////////////////////////////////////////////////
1248 /// Return correlation matrix ;
1249 
1250 const TMatrixDSym& RooFitResult::correlationMatrix() const
1251 {
1252  return *_CM ;
1253 }
1254 
1255 
1256 
1257 ////////////////////////////////////////////////////////////////////////////////
1258 /// Return a p.d.f that represents the fit result as a multi-variate probability densisty
1259 /// function on the floating fit parameters, including correlations
1260 
1261 RooAbsPdf* RooFitResult::createHessePdf(const RooArgSet& params) const
1262 {
1263  const TMatrixDSym& V = covarianceMatrix() ;
1264  Double_t det = V.Determinant() ;
1265 
1266  if (det<=0) {
1267  coutE(Eval) << "RooFitResult::createHessePdf(" << GetName() << ") ERROR: covariance matrix is not positive definite (|V|="
1268  << det << ") cannot construct p.d.f" << endl ;
1269  return 0 ;
1270  }
1271 
1272  // Make sure that all given params were floating parameters in the represented fit
1273  RooArgList params2 ;
1274  TIterator* iter = params.createIterator() ;
1275  RooAbsArg* arg ;
1276  while((arg=(RooAbsArg*)iter->Next())) {
1277  if (_finalPars->find(arg->GetName())) {
1278  params2.add(*arg) ;
1279  } else {
1280  coutW(InputArguments) << "RooFitResult::createHessePdf(" << GetName() << ") WARNING input variable "
1281  << arg->GetName() << " was not a floating parameters in fit result and is ignored" << endl ;
1282  }
1283  }
1284  delete iter ;
1285 
1286  // Need to order params in vector in same order as in covariance matrix
1287  RooArgList params3 ;
1288  iter = _finalPars->createIterator() ;
1289  while((arg=(RooAbsArg*)iter->Next())) {
1290  if (params2.find(arg->GetName())) {
1291  params3.add(*arg) ;
1292  }
1293  }
1294  delete iter ;
1295 
1296 
1297  // Handle special case of representing full covariance matrix here
1298  if (params3.getSize()==_finalPars->getSize()) {
1299 
1300  RooArgList mu ;
1301  for (Int_t i=0 ; i<_finalPars->getSize() ; i++) {
1302  RooRealVar* parclone = (RooRealVar*) _finalPars->at(i)->Clone(Form("%s_centralvalue",_finalPars->at(i)->GetName())) ;
1303  parclone->setConstant(kTRUE) ;
1304  mu.add(*parclone) ;
1305  }
1306 
1307  string name = Form("pdf_%s",GetName()) ;
1308  string title = Form("P.d.f of %s",GetTitle()) ;
1309 
1310  // Create p.d.f.
1311  RooAbsPdf* mvg = new RooMultiVarGaussian(name.c_str(),title.c_str(),params3,mu,V) ;
1312  mvg->addOwnedComponents(mu) ;
1313  return mvg ;
1314  }
1315 
1316  // -> ->
1317  // Handle case of conditional p.d.f. MVG(p1|p2) here
1318 
1319  // Find (subset) of parameters that are stored in the covariance matrix
1320  vector<int> map1, map2 ;
1321  for (int i=0 ; i<_finalPars->getSize() ; i++) {
1322  if (params3.find(_finalPars->at(i)->GetName())) {
1323  map1.push_back(i) ;
1324  } else {
1325  map2.push_back(i) ;
1326  }
1327  }
1328 
1329  // Rearrange matrix in block form with 'params' first and 'others' last
1330  // (preserving relative order)
1331  TMatrixDSym S11, S22 ;
1332  TMatrixD S12, S21 ;
1333  RooMultiVarGaussian::blockDecompose(V,map1,map2,S11,S12,S21,S22) ;
1334 
1335  // Calculate offset vectors mu1 and mu2
1336  RooArgList mu1 ;
1337  for (UInt_t i=0 ; i<map1.size() ; i++) {
1338  RooRealVar* parclone = (RooRealVar*) _finalPars->at(map1[i])->Clone(Form("%s_centralvalue",_finalPars->at(map1[i])->GetName())) ;
1339  parclone->setConstant(kTRUE) ;
1340  mu1.add(*parclone) ;
1341  }
1342 
1343  // Constructed conditional matrix form -1
1344  // F(X1|X2) --> CovI --> S22bar = S11 - S12 S22 S21
1345 
1346  // Do eigenvalue decomposition
1347  TMatrixD S22Inv(TMatrixD::kInverted,S22) ;
1348  TMatrixD S22bar = S11 - S12 * (S22Inv * S21) ;
1349 
1350  // Convert explicitly to symmetric form
1351  TMatrixDSym Vred(S22bar.GetNcols()) ;
1352  for (int i=0 ; i<Vred.GetNcols() ; i++) {
1353  for (int j=i ; j<Vred.GetNcols() ; j++) {
1354  Vred(i,j) = (S22bar(i,j) + S22bar(j,i))/2 ;
1355  Vred(j,i) = Vred(i,j) ;
1356  }
1357  }
1358  string name = Form("pdf_%s",GetName()) ;
1359  string title = Form("P.d.f of %s",GetTitle()) ;
1360 
1361  // Create p.d.f.
1362  RooAbsPdf* ret = new RooMultiVarGaussian(name.c_str(),title.c_str(),params3,mu1,Vred) ;
1363  ret->addOwnedComponents(mu1) ;
1364  return ret ;
1365 }
1366 
1367 
1368 
1369 ////////////////////////////////////////////////////////////////////////////////
1370 /// Change name of RooFitResult object
1371 
1372 void RooFitResult::SetName(const char *name)
1373 {
1374  if (_dir) _dir->GetList()->Remove(this);
1375  TNamed::SetName(name) ;
1376  if (_dir) _dir->GetList()->Add(this);
1377 }
1378 
1379 
1380 ////////////////////////////////////////////////////////////////////////////////
1381 /// Change name and title of RooFitResult object
1382 
1383 void RooFitResult::SetNameTitle(const char *name, const char* title)
1384 {
1385  if (_dir) _dir->GetList()->Remove(this);
1386  TNamed::SetNameTitle(name,title) ;
1387  if (_dir) _dir->GetList()->Add(this);
1388 }
1389 
1390 
1391 ////////////////////////////////////////////////////////////////////////////////
1392 /// Print name of fit result
1393 
1394 void RooFitResult::printName(ostream& os) const
1395 {
1396  os << GetName() ;
1397 }
1398 
1399 
1400 ////////////////////////////////////////////////////////////////////////////////
1401 /// Print title of fit result
1402 
1403 void RooFitResult::printTitle(ostream& os) const
1404 {
1405  os << GetTitle() ;
1406 }
1407 
1408 
1409 ////////////////////////////////////////////////////////////////////////////////
1410 /// Print class name of fit result
1411 
1412 void RooFitResult::printClassName(ostream& os) const
1413 {
1414  os << IsA()->GetName() ;
1415 }
1416 
1417 
1418 ////////////////////////////////////////////////////////////////////////////////
1419 /// Print arguments of fit result, i.e. the parameters of the fit
1420 
1421 void RooFitResult::printArgs(ostream& os) const
1422 {
1423  os << "[constPars=" << *_constPars << ",floatPars=" << *_finalPars << "]" ;
1424 }
1425 
1426 
1427 
1428 ////////////////////////////////////////////////////////////////////////////////
1429 /// Print the value of the fit result, i.e.g the status, minimized FCN, edm and covariance quality code
1430 
1431 void RooFitResult::printValue(ostream& os) const
1432 {
1433  os << "(status=" << _status << ",FCNmin=" << _minNLL << ",EDM=" << _edm << ",covQual=" << _covQual << ")" ;
1434 }
1435 
1436 
1437 ////////////////////////////////////////////////////////////////////////////////
1438 /// Configure default contents to be printed
1439 
1440 Int_t RooFitResult::defaultPrintContents(Option_t* /*opt*/) const
1441 {
1442  return kName|kClassName|kArgs|kValue ;
1443 }
1444 
1445 
1446 ////////////////////////////////////////////////////////////////////////////////
1447 /// Configure mapping of Print() arguments to RooPrintable print styles
1448 
1449 RooPrintable::StyleOption RooFitResult::defaultPrintStyle(Option_t* opt) const
1450 {
1451  if (!opt || strlen(opt)==0) {
1452  return kStandard ;
1453  }
1454  return RooPrintable::defaultPrintStyle(opt) ;
1455 }
1456 
1457 
1458 ////////////////////////////////////////////////////////////////////////////////
1459 /// Stream an object of class RooFitResult.
1460 
1461 void RooFitResult::Streamer(TBuffer &R__b)
1462 {
1463  if (R__b.IsReading()) {
1464  UInt_t R__s, R__c;
1465  Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
1466  if (R__v>3) {
1467  R__b.ReadClassBuffer(RooFitResult::Class(),this,R__v,R__s,R__c);
1468  RooAbsArg::ioStreamerPass2Finalize();
1469  _corrMatrix.SetOwner();
1470  } else {
1471  // backward compatibitily streaming
1472  TNamed::Streamer(R__b);
1473  RooPrintable::Streamer(R__b);
1474  RooDirItem::Streamer(R__b);
1475  R__b >> _status;
1476  R__b >> _covQual;
1477  R__b >> _numBadNLL;
1478  R__b >> _minNLL;
1479  R__b >> _edm;
1480  R__b >> _constPars;
1481  R__b >> _initPars;
1482  R__b >> _finalPars;
1483  R__b >> _globalCorr;
1484  _corrMatrix.Streamer(R__b);
1485  R__b.CheckByteCount(R__s, R__c, RooFitResult::IsA());
1486 
1487  // Now fill new-style covariance and correlation matrix information
1488  // from legacy form
1489  _CM = new TMatrixDSym(_finalPars->getSize()) ;
1490  _VM = new TMatrixDSym(_CM->GetNcols()) ;
1491  _GC = new TVectorD(_CM->GetNcols()) ;
1492 
1493  TIterator *gcIter = _globalCorr->createIterator() ;
1494  TIterator *parIter = _finalPars->createIterator() ;
1495  RooRealVar* gcVal = 0;
1496  for (unsigned int i = 0; i < (unsigned int)_CM->GetNcols() ; ++i) {
1497 
1498  // Find the next global correlation slot to fill, skipping fixed parameters
1499  gcVal = (RooRealVar*) gcIter->Next() ;
1500  (*_GC)(i) = gcVal->getVal() ;
1501 
1502  // Fill a row of the correlation matrix
1503  TIterator* cIter = ((RooArgList*)_corrMatrix.At(i))->createIterator() ;
1504  for (unsigned int it = 0; it < (unsigned int)_CM->GetNcols() ; ++it) {
1505  RooRealVar* cVal = (RooRealVar*) cIter->Next() ;
1506  double value = cVal->getVal() ;
1507  (*_CM)(it,i) = value ;
1508  (*_CM)(i,it) = value;
1509  (*_VM)(it,i) = value*((RooRealVar*)_finalPars->at(i))->getError()*((RooRealVar*)_finalPars->at(it))->getError() ;
1510  (*_VM)(i,it) = (*_VM)(it,i) ;
1511  }
1512  delete cIter ;
1513  }
1514 
1515  delete gcIter ;
1516  delete parIter ;
1517  }
1518 
1519  } else {
1520  R__b.WriteClassBuffer(RooFitResult::Class(),this);
1521  }
1522 }
1523