Esempio n. 1
0
//--------------------------------------------------------------------------------------------------
void printCorrelations(ostream& os, RooFitResult *res)
{
  ios_base::fmtflags flags = os.flags();
  const RooArgList parlist = res->floatParsFinal();
  
  os << "  Correlation Matrix" << endl;
  os << " --------------------" << endl;
  for(Int_t i=0; i<parlist.getSize(); i++) {
    for(Int_t j=0; j<parlist.getSize(); j++) 
      os << "  " << setw(7) << setprecision(4) << fixed << res->correlationMatrix()(i,j);    
    os << endl;
  }
  os.flags(flags);
}
Esempio n. 2
0
void logStatisticsPar(std::ostream& out, RooDataSet *dataSet, RooRealVar *realVar, int nBins, double chi2, const RooArgList &variables)
{
    TH1 *histogram = dataSet->createHistogram(Form("h%s", dataSet->GetName()), *realVar, RooFit::Binning(nBins));
    
    // Create the TeX file
    out << "\\documentclass[10pt]{article}" << std::endl;
    out << "\\usepackage[usenames]{color} %used for font color" << std::endl;
    out << "\\usepackage{fontspec}" << std::endl;
    out << "\\usepackage{xunicode}" << std::endl;
    out << "\\usepackage{xltxtra}" << std::endl;
    out << "\\defaultfontfeatures{Scale=MatchLowercase}" << std::endl;
    out << "\\setromanfont[Mapping=tex-text]{Myriad Pro}" << std::endl;
    out << "\\setsansfont[Mapping=tex-text]{Myriad Pro}" << std::endl;
    out << "\\setmonofont{Monaco}" << std::endl;
    out << "\\begin{document}" << std::endl;
    out << "\\thispagestyle{empty}" << std::endl;
    out << "\\setlength{\\tabcolsep}{1ex}" << std::endl;
    out << "\\setlength{\\fboxsep}{0ex}" << std::endl;
    out << "{\\fontsize{7pt}{0.9em}\\selectfont" << std::endl;
    out << "\\framebox{\\begin{tabular*}{60pt}{l@{\\extracolsep{\\fill}}r}" << std::endl;
    
    // This is the particular info for the histogram
    out << "Entries & " ;
    formatNumber(histogram->GetEntries(), out) << " \\\\" << std::endl;
    out << "Mean & " ;
    formatNumber(histogram->GetMean(), out) << " \\\\" << std::endl;
    out << "RMS & " ;
    formatNumber(histogram->GetRMS(), out) << " \\\\" << std::endl;
    if (chi2 > 0.0) {
        out << "Fit $\\chi^{2}$ & " ;
        formatNumber(chi2, out) << " \\\\" << std::endl;
    }
    RooRealVar *theVariable;
    for (int index = 0; index < variables.getSize(); index++) {
        theVariable = dynamic_cast<RooRealVar*>(variables.find(variables[index].GetName()));
        out << theVariable->GetTitle() << " & $\\textrm{" ;
        formatNumber(theVariable->getValV(), out) << "} \\pm \\textrm{" ;
        formatNumber(theVariable->getError(), out) << "}$ \\\\" << std::endl;
    }
    out << "\\end{tabular*}}}" << std::endl;
    out << "\\end{document}" << std::endl;
    histogram->Delete();
}
Esempio n. 3
0
RooAbsArg *cloneRecursiveRename(RooAbsArg *arg, const char *postfix) {
    
    RooAbsArg *clone = arg->cloneTree();
    
    RooArgSet *clonecomps = clone->getComponents();
    RooArgSet *clonevars = clone->getVariables();
    
    RooArgList cloneargs;
    cloneargs.add(*clonecomps);
    cloneargs.add(*clonevars);
    delete clonecomps;
    delete clonevars;
    
    for (int iarg=0; iarg<cloneargs.getSize(); ++iarg) {
      cloneargs.at(iarg)->SetName(TString::Format("%s_%s",cloneargs.at(iarg)->GetName(),postfix));
    }    
    
    return clone;
    
}
Esempio n. 4
0
    void ztonunu1() {

    // RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooPoisson"),OutputFile("debug.log")) ;

       float acc_mm_mean( 0.98 ) ; float acc_mm_err(  0.02 ) ;
       float acc_ee_mean( 0.98 ) ; float acc_ee_err(  0.02 ) ;
       float eff_mm_mean( 0.77 ) ; float eff_mm_err(  0.08 ) ;
       float eff_ee_mean( 0.76 ) ; float eff_ee_err(  0.08 ) ;


       RooRealVar* rv_Nsbee  = new RooRealVar( "Nsbee"  ,"Nsbee"  , 0., 100. ) ;
       RooRealVar* rv_Nsbmm  = new RooRealVar( "Nsbmm"  ,"Nsbmm"  , 0., 100. ) ;
       RooRealVar* rv_Nsigee = new RooRealVar( "Nsigee" ,"Nsigee" , 0., 100. ) ;
       RooRealVar* rv_Nsigmm = new RooRealVar( "Nsigmm" ,"Nsigmm" , 0., 100. ) ;

       rv_Nsbee->setVal( 5 ) ;
       rv_Nsbmm->setVal( 3 ) ;

       rv_Nsigee->setVal( 4 ) ;
       rv_Nsigmm->setVal( 3 ) ;


       RooRealVar* rv_mu_Znnsb  = new RooRealVar( "mu_Znnsb"  , "mu_Znnsb"  , 0., 100. ) ;
       RooRealVar* rv_mu_Znnsig = new RooRealVar( "mu_Znnsig" , "mu_Znnsig" , 0., 100. ) ;


       rv_mu_Znnsb->setVal( 37 ) ; // starting value
       rv_mu_Znnsig->setVal( 17. ) ; // starting value

       RooRealVar* rv_bfRatio = new RooRealVar( "bfRatio", "bfRatio", 0., 10. ) ;

       rv_bfRatio->setVal( 5.95 ) ;
       rv_bfRatio->setConstant( kTRUE ) ;

       RooRealVar* rv_acc_mm = new RooRealVar( "acc_mm", "acc_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_acc_ee = new RooRealVar( "acc_ee", "acc_ee", 0.001, 1.000 ) ;

       RooRealVar* rv_eff_mm = new RooRealVar( "eff_mm", "eff_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_eff_ee = new RooRealVar( "eff_ee", "eff_ee", 0.001, 1.000 ) ;

       rv_acc_mm->setVal( acc_mm_mean ) ;
       rv_acc_ee->setVal( acc_ee_mean ) ;
       rv_eff_mm->setVal( eff_mm_mean ) ;
       rv_eff_ee->setVal( eff_ee_mean ) ;

       RooRealVar* rv_lumi_ratio = new RooRealVar( "lumi_ratio", "lumi_ratio", 0., 10. ) ;

       rv_lumi_ratio -> setVal( 686./869. ) ;
       rv_lumi_ratio -> setConstant( kTRUE) ;



       RooFormulaVar* rv_mu_Zeesb = new RooFormulaVar( "mu_Zeesb",
                       "mu_Znnsb * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsb = new RooFormulaVar( "mu_Zmmsb",
                       "mu_Znnsb * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zeesig = new RooFormulaVar( "mu_Zeesig",
                       "mu_Znnsig * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsig = new RooFormulaVar( "mu_Zmmsig",
                       "mu_Znnsig * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;



       RooFormulaVar* rv_n_sbee  = new RooFormulaVar( "n_sbee"  , "mu_Zeesb"  , RooArgSet( *rv_mu_Zeesb  ) ) ;
       RooFormulaVar* rv_n_sbmm  = new RooFormulaVar( "n_sbmm"  , "mu_Zmmsb"  , RooArgSet( *rv_mu_Zmmsb  ) ) ;
       RooFormulaVar* rv_n_sigee = new RooFormulaVar( "n_sigee" , "mu_Zeesig" , RooArgSet( *rv_mu_Zeesig ) ) ;
       RooFormulaVar* rv_n_sigmm = new RooFormulaVar( "n_sigmm" , "mu_Zmmsig" , RooArgSet( *rv_mu_Zmmsig ) ) ;



       RooGaussian* pdf_acc_mm = new RooGaussian( "pdf_acc_mm", "Gaussian pdf for Z to mumu acceptance",
                       *rv_acc_mm, RooConst( acc_mm_mean ), RooConst( acc_mm_err ) ) ;


       RooGaussian* pdf_acc_ee = new RooGaussian( "pdf_acc_ee", "Gaussian pdf for Z to ee acceptance",
                       *rv_acc_ee, RooConst( acc_ee_mean ), RooConst( acc_ee_err ) ) ;




       RooGaussian* pdf_eff_mm = new RooGaussian( "pdf_eff_mm", "Gaussian pdf for Z to mumu efficiency",
                       *rv_eff_mm, RooConst( eff_mm_mean ), RooConst( eff_mm_err ) ) ;



       RooGaussian* pdf_eff_ee = new RooGaussian( "pdf_eff_ee", "Gaussian pdf for Z to ee efficiency",
                       *rv_eff_ee, RooConst( eff_ee_mean ), RooConst( eff_ee_err ) ) ;



       RooPoisson* pdf_Nsbee   = new RooPoisson( "pdf_Nsbee"  , "Nsb , Z to ee Poisson PDF", *rv_Nsbee  , *rv_n_sbee  ) ;
       RooPoisson* pdf_Nsbmm   = new RooPoisson( "pdf_Nsbmm"  , "Nsb , Z to mm Poisson PDF", *rv_Nsbmm  , *rv_n_sbmm  ) ;
       RooPoisson* pdf_Nsigee  = new RooPoisson( "pdf_Nsigee" , "Nsig, Z to ee Poisson PDF", *rv_Nsigee , *rv_n_sigee ) ;
       RooPoisson* pdf_Nsigmm  = new RooPoisson( "pdf_Nsigmm" , "Nsig, Z to mm Poisson PDF", *rv_Nsigmm , *rv_n_sigmm ) ;

       RooArgSet pdflist ;
       pdflist.add( *pdf_acc_mm ) ;
       pdflist.add( *pdf_acc_ee ) ;
       pdflist.add( *pdf_eff_mm ) ;
       pdflist.add( *pdf_eff_ee ) ;
       pdflist.add( *pdf_Nsbee  ) ;
       pdflist.add( *pdf_Nsbmm  ) ;
       pdflist.add( *pdf_Nsigee  ) ;
       pdflist.add( *pdf_Nsigmm  ) ;

       RooProdPdf* znnLikelihood = new RooProdPdf( "znnLikelihood", "Z to nunu likelihood", pdflist ) ;


       RooArgSet observedParametersList ;
       observedParametersList.add( *rv_Nsbee ) ;
       observedParametersList.add( *rv_Nsbmm ) ;
       observedParametersList.add( *rv_Nsigee ) ;
       observedParametersList.add( *rv_Nsigmm ) ;

       RooDataSet* dsObserved = new RooDataSet( "ztonn_rds", "Z to nunu dataset", observedParametersList ) ;
       dsObserved->add( observedParametersList ) ;
       //// RooDataSet* dsObserved = znnLikelihood->generate( observedParametersList, 1) ;

       RooWorkspace* znnWorkspace = new RooWorkspace("ztonn_ws") ;
       znnWorkspace->import( *znnLikelihood ) ;
       znnWorkspace->import( *dsObserved ) ;

       znnWorkspace->Print() ;

       dsObserved->printMultiline(cout, 1, kTRUE, "") ;
       RooFitResult* fitResult = znnLikelihood->fitTo( *dsObserved, Verbose(true), Save(true) ) ;

       printf("\n\n----- Constant parameters:\n") ;
       RooArgList constPars = fitResult->constPars() ;
       for ( int pi=0; pi<constPars.getSize(); pi++ ) {
          constPars[pi].Print() ;
       } // pi.

       printf("\n\n----- Floating parameters:\n") ;
       RooArgList floatPars = fitResult->floatParsFinal() ;
       for ( int pi=0; pi<floatPars.getSize(); pi++ ) {
          floatPars[pi].Print() ;
       } // pi.
       printf("\n\n") ;



       ProfileLikelihoodCalculator plc_znn_sb(  *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsb ) ) ;
       ProfileLikelihoodCalculator plc_znn_sig( *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsig ) ) ;

       plc_znn_sb.SetTestSize(0.32) ;
       plc_znn_sig.SetTestSize(0.32) ;

       ConfInterval* sb_znn_interval = plc_znn_sb.GetInterval() ;
       float sbZnnLow  = ((LikelihoodInterval*) sb_znn_interval)->LowerLimit(*rv_mu_Znnsb) ;
       float sbZnnHigh = ((LikelihoodInterval*) sb_znn_interval)->UpperLimit(*rv_mu_Znnsb) ;
       printf("\n\n znn SB interval %6.1f to %6.1f\n", sbZnnLow, sbZnnHigh ) ;

       ConfInterval* sig_znn_interval = plc_znn_sig.GetInterval() ;
       float sigZnnLow  = ((LikelihoodInterval*) sig_znn_interval)->LowerLimit(*rv_mu_Znnsig) ;
       float sigZnnHigh = ((LikelihoodInterval*) sig_znn_interval)->UpperLimit(*rv_mu_Znnsig) ;
       printf("\n\n znn SIG interval %6.1f to %6.1f\n", sigZnnLow, sigZnnHigh ) ;



       TCanvas* c_prof_sb = new TCanvas("c_prof_sb","SB Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sb((LikelihoodInterval*)sb_znn_interval) ;
       plot_znn_sb.Draw() ;
       c_prof_sb->SaveAs("znn_sb_profile.png") ;

       TCanvas* c_prof_sig = new TCanvas("c_prof_sig","sig Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sig((LikelihoodInterval*)sig_znn_interval) ;
       plot_znn_sig.Draw() ;
       c_prof_sig->SaveAs("znn_sig_profile.png") ;


    }
Esempio n. 5
0
prepDataFiles(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	int myIndex;	
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while ((file=(TSystemFile*)next())) {
		fname = file->GetName();
		if (fname.BeginsWith("TnP")&& fname.Contains("mc")) {
	
			ofstream myfile;

			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());
			TKey *key;
			while (key = (TKey*)nextkey()) {
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
				if ( theTypeClasse == "TDirectoryFile"){
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while (key2 = (TKey*)nextkey2()) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						myfile.open (theNomClasse2+".info");
						if ( theTypeClasse == "TDirectoryFile"){
							cout << "avant " << endl;
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2);
							cout << "apres " << endl;
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while (key3 = (TKey*)nextkey3()) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetTitle();	
								if ((theNomClasse3.Contains("FromMC"))) {

									TString localClasse3 = theNomClasse3;
									localClasse3.ReplaceAll("__","%");
									cout << "apres " << localClasse3 << endl;
									TObjArray* listBin = localClasse3.Tokenize('%');
									TString first = ((TObjString*)listBin->At(0))->GetString();
									TString second = ((TObjString*)listBin->At(2))->GetString();
									myfile << first;
									myfile << " " << second << " ";
									cout << "coucou la on va récupérer le rooFitResult " << endl;

									RooFitResult *theResults = (RooFitResult*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/"+theNomClasse3+"/fitresults");
									theResults->Print();
									RooArgList theParam = theResults->floatParsFinal();
									int taille = theParam.getSize();
									for (int m = 0 ; m < taille ; m++){
										cout << "m=" << m << endl;
									RooAbsArg *theArg = (RooAbsArg*) theParam.at(m);
									RooAbsReal *theReal = (RooAbsReal*) theArg;
										myfile << theReal->getVal() << " " ;
									}		
															
									myfile << "\n";

								}
							}
						}
						myfile.close();

					}
			
				}
			}
			delete myFile;
		}
	
	}

}
int compute(RooFitResult* fit, int nbdata, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
	    double et_plateau, double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin,                       
	    bool draw, bool verbose)                                                                                              
{
  
  // Extract fit parameters //
  std::cout<<"erereo4"<<std::endl;
  RooArgList param = fit->floatParsFinal() ;
  std::cout<<"erereo6"<<std::endl;
  double err[5] ;
  double mu[5] ;

  for(Int_t i = 0; i < param.getSize(); i++) {

    RooRealVar* var = ( dynamic_cast<RooRealVar*>( param.at(i) ) );
    //var->Print() ;
    mu[i] = var->getVal() ;
    err[i] = var->getError() ;
  }
  
  std::cout<<"erereo5"<<std::endl;
  double min, max;
  
  min = mu[0]-5*err[0] ;
  if (mu[0]-5*err[0]<0) min = 0. ;
  RooRealVar alpha("alpha","#alpha",mu[0],min,mu[0]+5*err[0]);
  
  min = mu[1]-5*err[1] ;
  if (mu[1]-5*err[1]<5) min = 5. ;
  RooRealVar mean("mean","mean",mu[1],min,mu[1]+5*err[1]);
  
  min = mu[2]-5*err[2] ;
  if (mu[2]-5*err[2]<1) min = 1. ;
  RooRealVar n("n","n",mu[2],min,mu[2]+5*err[2]);
  
  min = mu[3]-5*err[3] ;
  if (mu[3]-5*err[3]<0.6) min = 0.6 ; 

  max = mu[3]+5*err[3] ;
  if (mu[3]+5*err[3]>1.) max = 1. ; 
  RooRealVar norm("norm","N",mu[3],min,max);
  
  min = mu[4]-5*err[4] ;
  if (mu[4]-5*err[4]<0.) min = 0. ; 
  RooRealVar sigma("sigma","#sigma",mu[4],min,mu[4]+5*err[4]);
  
  RooRealVar xaxis("x","x",0,150) ;


  // Create PDF and generate nbdata sets of CB parameters
  RooAbsPdf* parabPdf = fit->createHessePdf(RooArgSet(norm,alpha,n,mean,sigma)) ;
  RooDataSet* data = parabPdf->generate(RooArgSet(norm,alpha,n,mean,sigma),nbdata) ;

  // Generate histo to extract error bar on efficiency(xaxis)
  xaxis = et_plateau ;
  cout << "Generate histo to extract error bars" << endl;
  genHisto(nbdata, data, nEff, eff, et, et_errmax, et_errmin, eff_plateau, eff_plateau_errmax, eff_plateau_errmin,
	   xaxis, mean, sigma, alpha, n, norm, draw, verbose);

  /* int genHisto(int nbdata, RooDataSet* data, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
                  double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin, 
		  RooRealVar xaxis, RooRealVar mean, RooRealVar sigma, RooRealVar alpha, RooRealVar n, RooRealVar norm,
		  bool draw, bool verbose)

     int compute(RooFitResult* fit, int nbdata, const int nEff, double* eff, double* et, double* et_errmax, double* et_errmin,
                 double et_plateau, double& eff_plateau, double& eff_plateau_errmax, double& eff_plateau_errmin,
                 bool draw, bool verbose)
  */

  return 1;
}
Esempio n. 7
0
void THSEventsPDF::AddSmearedModel(TTree* tree,RooArgList vars){
  //Construcnt a RooDataHist with MC data
  //y axis incorporates systematic uncertaintly on width of distribution
  //tree contains the MC events, 
  //vars provides all the variables that need to be cut to get same kinematics as data
  if(!tree) tree=fTree; //tree presumably aready set
  TH2F* temph=(TH2F*)fRHist->Clone("mctemp");
  temph->SetDirectory(0);
  //Loop over vars attaching branch values to brVal
  TVectorD brVal(vars.getSize());
  tree->SetBranchStatus("*","0");
  for(Int_t iv=0;iv<vars.getSize();iv++){
    //brVal[iv]=0;
    tree->SetBranchStatus((vars[iv].GetName()),"1");//STATUS must be called before ADDRESS!! see Important remarkse in TChain SetBranchStatus!
    tree->SetBranchAddress((vars[iv].GetName()),&brVal[iv]);
  }
  
  //get the fit variable branch
  Double_t tvar=0;
  tree->SetBranchStatus(fx_off->GetName(),"1");
  tree->SetBranchAddress(fx_off->GetName(),&tvar);
  TEntryList *Elist=0;
  //Loop over tree and create entry list that fits all variable limits
  if(vars.getSize()>0){ 
    Elist=new TEntryList();
    Elist->SetDirectory(0);
    //Loop over chain and create an entry list of events meet the cuts 
    //given in the vars variabels set
    for(Long64_t itr=0;itr<tree->GetEntries();itr++){
      tree->GetEntry(itr);
      //fit variable
      //if(tvar<fx_off->getMin("")||tvar>fx_off->getMax("")) continue;//remove as offset needs events outwith range
      //now other variables which may have been given
      Bool_t pass=kTRUE;
      for(Int_t iv=0;iv<vars.getSize();iv++){
	if(brVal[iv]<((RooRealVar*)&vars[iv])->getMin("")||brVal[iv]>((RooRealVar*)&vars[iv])->getMax("")) pass=kFALSE;}
      if(pass){Elist->Enter(itr,tree);}
    }
    //Set entry list for tree
    tree->SetEntryList(Elist);
  }
  else Elist=tree->GetEntryList();
  Int_t treenum=0;
  if(Elist)cout<<GetName()<<" THSEventsPDF::AddSmearedModel Using an EntryList with "<<Elist->GetN()<<" events "<<endl;
  TChain* chain=0; //need chain for proper entrylist access
  if(dynamic_cast<TChain*>(tree))chain=dynamic_cast<TChain*>(tree);
  
  //check if there is a valid weight histogram
  //this should be extended to other things than TH1s, even a weight branch
  TVectorD wVal(fNWdim);
  if(fWeightHist){
    if(tree->GetBranch(fWeightHist->GetXaxis()->GetTitle())){
      tree->SetBranchStatus(fWeightHist->GetXaxis()->GetTitle(),"1");
      tree->SetBranchAddress(fWeightHist->GetXaxis()->GetTitle(),&wVal[0]);
    }
    else cout<<"THSEventsPDF::AddSmearedModel tree has no branch named "<<fWeightHist->GetYaxis()->GetTitle()<<endl;
    if(fNWdim>1){
      if(tree->GetBranch(fWeightHist->GetYaxis()->GetTitle())){
	tree->SetBranchStatus(fWeightHist->GetYaxis()->GetTitle(),"1");
	tree->SetBranchAddress(fWeightHist->GetYaxis()->GetTitle(),&wVal[1]);
      }
      else cout<<"THSEventsPDF::AddSmearedModel tree has no branch named "<<fWeightHist->GetYaxis()->GetTitle()<<endl;
    }
    if(fNWdim>2){
      if(tree->GetBranch(fWeightHist->GetZaxis()->GetTitle())){
	tree->SetBranchStatus(fWeightHist->GetZaxis()->GetTitle(),"1");
	tree->SetBranchAddress(fWeightHist->GetZaxis()->GetTitle(),&wVal[2]);
      }
      else cout<<"THSEventsPDF::AddSmearedModel tree has no branch named "<<fWeightHist->GetYaxis()->GetTitle()<<endl;
    }
  }
  TTree* FastTree=fTree->CopyTree("");//make sure only loop over valid events for speedi.e. this enforces Elist
  cout<<GetName()<<" THSEvent final entries "<<FastTree->GetEntries()<<endl;
  for(Int_t ia=0;ia<fRHist->GetNbinsY();ia++){ 
    temph->Reset();
    Long64_t treeEntry=0;
    Long64_t chainEntry =0;
    Double_t vAlphb=fRHist->GetYaxis()->GetBinCenter(ia+1);
    Double_t vAlph=fRHist->GetYaxis()->GetBinLowEdge(ia+1);
    // for(Int_t itr=0;itr<Elist->GetN();itr++){
    //   treeEntry = Elist->GetEntryAndTree(itr,treenum);
    //   if(chain) treeEntry+=chain->GetTreeOffset()[treenum];
    //  tree->GetEntry(treeEntry);
    for(Int_t itr=0;itr<FastTree->GetEntries();itr++){
      tree->GetEntry(itr);
      Double_t weight=1;
      if(fNWdim==1)weight=GetDistWeight(wVal[0]);
      else if(fNWdim==2)weight=GetDistWeight(wVal[0],wVal[1]);
      else if(fNWdim==3)weight=GetDistWeight(wVal[0],wVal[1],wVal[2]);
      //  cout<<GetName()<<" Found weight "<<weight<<endl;
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      temph->Fill(gRandom->Gaus(tvar,vAlph),vAlphb,weight);
      //call it 3 times ! 3 times as slow...but should be a bit smoother...
      //Could add full function on each time but slow NbinsX x slower!
      // for(Int_t itemp=1;itemp<temph->GetNbinsX();itemp++){//fill with Gaussian function
      // 	Float_t varb=temph->GetXaxis()->GetBinCenter(itemp);
      // 	temph->SetBinContent(itemp,ia+1,TMath::Gaus(varb,tvar,fRHist->GetYaxis()->GetBinCenter(ia+1)));
      // }
    }
    fRHist->Add(temph);
  }
  cout<<"Done loop"<<endl;
  fRHist->Smooth();//some additional smoothing
  // for(Int_t ib=1;ib<=fRHist->GetNbinsX();ib++)//see if non-zero bins help fit stability
  // if(fRHist->GetBinContent(ib)==0) fRHist->SetBinContent(0.1);
  //Store mean value of distributions for scaling around
  // fMean=fRHist->GetMean();
  Int_t bx,by,bz;
  fRHist->GetBinXYZ(fRHist->GetMaximumBin(),bx,by,bz);
  fMean=fRHist->GetXaxis()->GetBinCenter(bx);
  cout<<"Mean value of distribution is "<<fMean<<endl;
  //create hist for getting weight

  fHist = new RooDataHist(fRHist->GetName(),fRHist->GetName(),RooArgSet(*fx_off,*falpha),RooFit::Import(*fRHist));
  //create pdf for getting analytical integral
  //fHistPdf = new RooHistPdf(TString("PDF")+fRHist->GetName(),TString("PDF")+fRHist->GetName(),RooArgSet(*fx_off,*falpha),*fHist,1); 
  fHistPdf = new RooHistPdf(TString("PDF")+fRHist->GetName(),TString("PDF")+fRHist->GetName(),RooArgSet(*fx_off,*falpha),RooArgSet(*fx,*falpha),*fHist,1); 
  delete temph;
  tree->SetEntryList(0); //detach entry list
  if(Elist) delete Elist;
  tree->SetBranchStatus("*",1);
  tree->ResetBranchAddresses();
  if(chain){chain->ResetBranchAddresses();chain->GetStatus()->Clear();}
  if(FastTree) delete FastTree;
  return;
}
Esempio n. 8
0
///
/// Find the global minimum in a more thorough way.
/// First fit with external start parameters, then
/// for each parameter that starts with "d" or "r" (typically angles and ratios):
///   - at upper scan range, rest at start parameters
///   - at lower scan range, rest at start parameters
/// This amounts to a maximum of 1+2^n fits, where n is the number
/// of parameters to be varied.
///
/// \param w Workspace holding the pdf.
/// \param name Name of the pdf without leading "pdf_".
/// \param forceVariables Apply the force method for these variables only. Format
/// "var1,var2,var3," (list must end with comma). Default is to apply for all angles,
/// all ratios except rD_k3pi and rD_kpi, and the k3pi coherence factor.
///
RooFitResult* Utils::fitToMinForce(RooWorkspace *w, TString name, TString forceVariables)
{
	bool debug = true;

	TString parsName = "par_"+name;
	TString obsName  = "obs_"+name;
	TString pdfName  = "pdf_"+name;
	RooFitResult *r = 0;
	int printlevel = -1;
	RooMsgService::instance().setGlobalKillBelow(ERROR);

	// save start parameters
	if ( !w->set(parsName) ){
		cout << "MethodProbScan::scan2d() : ERROR : parsName not found: " << parsName << endl;
		exit(1);
	}
	RooDataSet *startPars = new RooDataSet("startParsForce", "startParsForce", *w->set(parsName));
	startPars->add(*w->set(parsName));

	// set up parameters and ranges
	RooArgList *varyPars = new RooArgList();
	TIterator* it = w->set(parsName)->createIterator();
	while ( RooRealVar* p = (RooRealVar*)it->Next() )
	{
		if ( p->isConstant() ) continue;
		if ( forceVariables=="" && ( false
					|| TString(p->GetName()).BeginsWith("d") ///< use these variables
					// || TString(p->GetName()).BeginsWith("r")
					|| TString(p->GetName()).BeginsWith("k")
					|| TString(p->GetName()) == "g"
					) && ! (
						TString(p->GetName()) == "rD_k3pi"  ///< don't use these
						|| TString(p->GetName()) == "rD_kpi"
						// || TString(p->GetName()) == "dD_kpi"
						|| TString(p->GetName()) == "d_dk"
						|| TString(p->GetName()) == "d_dsk"
						))
		{
			varyPars->add(*p);
		}
		else if ( forceVariables.Contains(TString(p->GetName())+",") )
		{
			varyPars->add(*p);
		}
	}
	delete it;
	int nPars = varyPars->getSize();
	if ( debug ) cout << "Utils::fitToMinForce() : nPars = " << nPars << " => " << pow(2.,nPars) << " fits" << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : varying ";
	if ( debug ) varyPars->Print();

	//////////

	r = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

	//////////

	int nErrors = 0;

	// We define a binary mask where each bit corresponds
	// to parameter at max or at min.
	for ( int i=0; i<pow(2.,nPars); i++ )
	{
		if ( debug ) cout << "Utils::fitToMinForce() : fit " << i << "        \r" << flush;
		setParameters(w, parsName, startPars->get(0));

		for ( int ip=0; ip<nPars; ip++ )
		{
			RooRealVar *p = (RooRealVar*)varyPars->at(ip);
			float oldMin = p->getMin();
			float oldMax = p->getMax();
			setLimit(w, p->GetName(), "force");
			if ( i/(int)pow(2.,ip) % 2==0 ) { p->setVal(p->getMin()); }
			if ( i/(int)pow(2.,ip) % 2==1 ) { p->setVal(p->getMax()); }
			p->setRange(oldMin, oldMax);
		}

		// check if start parameters are sensible, skip if they're not
		double startParChi2 = getChi2(w->pdf(pdfName));
		if ( startParChi2>2000 ){
			nErrors += 1;
			continue;
		}

		// refit
		RooFitResult *r2 = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

		// In case the initial fit failed, accept the second one.
		// If both failed, still select the second one and hope the
		// next fit succeeds.
		if ( !(r->edm()<1 && r->covQual()==3) ){
			delete r;
			r = r2;
		}
		else if ( r2->edm()<1 && r2->covQual()==3 && r2->minNll()<r->minNll() ){
			// better minimum found!
			delete r;
			r = r2;
		}
		else{
			delete r2;
		}
	}

	if ( debug ) cout << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : nErrors = " << nErrors << endl;

	RooMsgService::instance().setGlobalKillBelow(INFO);

	// (re)set to best parameters
	setParameters(w, parsName, r);

	delete startPars;
	return r;
}