void Plot(RooRealVar *mass, RooDataSet *data, RooAbsPdf *pdf, pair<double,double> sigRange, vector<double> fwhmRange, string title, string savename){

  double semin=sigRange.first;
  double semax=sigRange.second;
  double fwmin=fwhmRange[0];
  double fwmax=fwhmRange[1];
  double halfmax=fwhmRange[2];
  double binwidth=fwhmRange[3];

  RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
  if (data) data->plotOn(plot,Invisible());
  pdf->plotOn(plot,NormRange("higgsRange"),Range(semin,semax),FillColor(19),DrawOption("F"),LineWidth(2),FillStyle(1001),VLines(),LineColor(15));
  TObject *seffLeg = plot->getObject(int(plot->numItems()-1));
  pdf->plotOn(plot,NormRange("higgsRange"),Range(semin,semax),LineColor(15),LineWidth(2),FillStyle(1001),VLines());
  pdf->plotOn(plot,NormRange("higgsRange"),Range("higgsRange"),LineColor(kBlue),LineWidth(2),FillStyle(0));
  TObject *pdfLeg = plot->getObject(int(plot->numItems()-1));
  if (data) data->plotOn(plot,MarkerStyle(kOpenSquare));
  TObject *dataLeg = plot->getObject(int(plot->numItems()-1));
  TLegend *leg = new TLegend(0.15,0.89,0.5,0.55);
  leg->SetFillStyle(0);
  leg->SetLineColor(0);
  leg->SetTextSize(0.03);
  if (data) leg->AddEntry(dataLeg,"Simulation","lep");
  leg->AddEntry(pdfLeg,"Parametric model","l");
  leg->AddEntry(seffLeg,Form("#sigma_{eff} = %1.2f GeV",0.5*(semax-semin)),"fl");

  plot->GetXaxis()->SetNdivisions(509);
  halfmax*=(plot->getFitRangeBinW()/binwidth);
  TArrow *fwhmArrow = new TArrow(fwmin,halfmax,fwmax,halfmax,0.02,"<>");
  fwhmArrow->SetLineWidth(2.);
  TPaveText *fwhmText = new TPaveText(0.15,0.45,0.45,0.58,"brNDC");
  fwhmText->SetFillColor(0);
  fwhmText->SetLineColor(kWhite);
  fwhmText->SetTextSize(0.03);
  fwhmText->AddText(Form("FWHM = %1.2f GeV",(fwmax-fwmin)));

  TLatex lat1(0.65,0.85,"#splitline{CMS Preliminary}{Simulation}");
  lat1.SetNDC(1);
  lat1.SetTextSize(0.03);
  TLatex lat2(0.65,0.75,title.c_str());
  lat2.SetNDC(1);
  lat2.SetTextSize(0.025);

  TCanvas *canv = new TCanvas("c","c",600,600);
  plot->SetTitle("");
  plot->GetXaxis()->SetTitle("m_{#gamma#gamma} (GeV)");
  plot->Draw();
  leg->Draw("same");
  fwhmArrow->Draw("same <>");
  fwhmText->Draw("same");
  lat1.Draw("same");
  lat2.Draw("same");
  canv->Print(Form("%s.pdf",savename.c_str()));
  canv->Print(Form("%s.png",savename.c_str()));
  string path = savename.substr(0,savename.find('/'));
  canv->Print(Form("%s/animation.gif+100",path.c_str()));
  delete canv;

}
void ComputeUpperLimit(RooAbsData *data, RooStats::ModelConfig *model, float &UpperLimit, float &signif, RooRealVar *mu, RooArgSet *nullParams,RooWorkspace *ws,REGION region,const char* tag) {

  bool StoreEverything=false; // activate if you want to store frames and all
  
  RooStats::ProfileLikelihoodCalculator *plc = new RooStats::ProfileLikelihoodCalculator(*data, *model);
  plc->SetParameters(*mu);
  plc->SetNullParameters(*nullParams);
  plc->SetTestSize(0.05);
  RooStats::LikelihoodInterval *interval = plc->GetInterval();

  bool ComputationSuccessful=false;
  UpperLimit = interval->UpperLimit(*mu,ComputationSuccessful);
  signif = 0.0; // plc->GetHypoTest()->Significance();   // deactivated significance (to make algorithm faster)

  if(!ComputationSuccessful) {
    cout << "There seems to have been a problem. Returned upper limit is " << UpperLimit << " but it will be set to -999" << endl;
    UpperLimit=-999;
    signif=-999;
  }

  if(StoreEverything) {
    // Store it all
    RooRealVar* minv = (RooRealVar*)model->GetObservables()->first();
    minv->setBins(static_cast<int>((minv->getMax()-minv->getMin())/5.));

    RooPlot* frameEE = minv->frame(RooFit::Title("ee sample"));
    frameEE->GetXaxis()->CenterTitle(1);
    frameEE->GetYaxis()->CenterTitle(1);
    
    RooPlot* frameMM = minv->frame(RooFit::Title("mm sample"));
    frameMM->GetXaxis()->CenterTitle(1);
    frameMM->GetYaxis()->CenterTitle(1);
    
    RooPlot* frameOF = minv->frame(RooFit::Title("OF sample"));
    frameOF->GetXaxis()->CenterTitle(1);
    frameOF->GetYaxis()->CenterTitle(1);
    
    data->plotOn(frameMM,RooFit::Cut("catCentral==catCentral::MMCentral"));
    model->GetPdf()->plotOn(frameMM,RooFit::Slice(*ws->cat("catCentral"), "MMCentral"),RooFit::ProjWData(*data));
    
    data->plotOn(frameEE,RooFit::Cut("catCentral==catCentral::EECentral"));
    model->GetPdf()->plotOn(frameEE,RooFit::Slice(*ws->cat("catCentral"), "EECentral"),RooFit::ProjWData(*data));
    
    data->plotOn(frameOF,RooFit::Cut("catCentral==catCentral::OFOSCentral"));
    model->GetPdf()->plotOn(frameOF,RooFit::Slice(*ws->cat("catCentral"), "OFOSCentral"),RooFit::ProjWData(*data));
    
    TFile *fout = new TFile("fout.root","UPDATE");
    frameMM->Write(Concatenate(Concatenate(data->GetName(),"_MM"),tag),TObject::kOverwrite);
    frameEE->Write(Concatenate(Concatenate(data->GetName(),"_EE"),tag),TObject::kOverwrite);
    frameOF->Write(Concatenate(Concatenate(data->GetName(),"_OF"),tag),TObject::kOverwrite);
    fout->Close();
  }

  delete plc;
  plc=0;
}
Esempio n. 3
0
void Plot(RooRealVar *mass, RooCategory *category, RooDataSet *data, RooSimultaneous *pdf, int nBDTCats, int nSpinCats, bool sm, string name, bool correlateCosThetaCategories=false){

  TCanvas *canv = new TCanvas();
  for (int c=0; c<nBDTCats; c++){
    for (int s=0; s<nSpinCats; s++){
      RooPlot *plot = mass->frame();
      data->plotOn(plot,Cut(Form("category==category::cat%d_spin%d",c,s)));
      if(!correlateCosThetaCategories)
        pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("data_pol_model_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineStyle(kDashed),LineColor(kRed));
      else
        pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("data_pol_model_cat%d",c)),ProjWData(*category,*data),LineStyle(kDashed),LineColor(kRed));
      if (sm) pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("sigModel_SM_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kRed));
      else pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("sigModel_GRAV_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kBlue));
      pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kRed));
      plot->GetXaxis()->SetTitle("m_{#gamma#gamma}");
      plot->SetTitle(Form("cat%d_spin%d",c,s));
      plot->Draw();
      canv->Print(Form("%s_cat%d_spin%d.pdf",name.c_str(),c,s));
      canv->Print(Form("%s_cat%d_spin%d.png",name.c_str(),c,s));
    }
  }
  delete canv;

}
Esempio n. 4
0
void fastEfficiencyNadir(unsigned int iEG, int iECAL1, int iColl1, int iECAL2, int iColl2,
			 TString dirIn="/home/llr/cms/ndaci/SKWork/macro/skEfficiency/tagAndProbe/EfficiencyStudy/SingEle-May10ReReco/UPDATE2/Tag80Probe95/", 
			 TString lumi="200 pb", int nCPU=4, 
			 int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
			 TString probe="WP80", TString tag="WP80", TString fileIn="tree_effi_TagProbe.root")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // EG THRESHOLDS //
  const int nEG = 71;
  double thres[nEG];
  for(int i=0 ; i<nEG ; i++) thres[i]=i;

  TString names[nEG];
  ostringstream ossi;
  for(int i=0;i<(int)nEG;i++) {
    ossi.str("");
    ossi << thres[i] ;
    names[i] = ossi.str();
  }

  // NAMES //
  const int nECAL=2;
  const int nColl=2;

  TString name_leg_ecal[nECAL] = {"Barrel","Endcaps"};
  TString name_leg_coll[nColl] = {"Online","Emulation"};  

  TString name_ecal[nECAL] = {"_EB","_EE"};
  TString name_coll[nColl] = {"_N","_M"};

  TString dirResults = dirIn + "/turnons/EG"+names[iEG]+"/" ;
  TString name_image = 
    dirResults + "eff_EG"+names[iEG]+"_tag"+tag+"_probe"+probe+name_ecal[iECAL1]+name_coll[iColl1]+"_vs"+name_ecal[iECAL2]+name_coll[iColl2] ;

  // Output log //
  ofstream fichier(name_image+".txt", ios::out);


  // BINNING //
  const int nbins[nEG] = {29,29,29,29,21,21,21,22,22,21,22,21,22,18,19,18,18,18,18,20,20,20,20,19,20,20,20,20,21,21,
			  21,21,21,21,21,21,21,21,21,21, //EG30
			  22,22,22,22,22,22,22,22,22,22, //EG40
			  29,29,29,29,29,29,29,29,29,29, //EG50
			  29,29,29,29,29,29,29,29,29,29};//EG60

  Double_t bins_0[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG0
  Double_t bins_1[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG1
  Double_t bins_2[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG2 
  Double_t bins_3[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG3

  Double_t bins_4[21] = {1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 27, 32, 41, 50, 60, 70, 150}; // EG4
  Double_t bins_5[21] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 31, 40, 50, 60, 70, 150}; // EG5
  Double_t bins_6[21] = {3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 21, 23, 27, 32, 41, 50, 60, 70, 150}; // EG6

  Double_t bins_7[22] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG7
  Double_t bins_8[22] = {3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 32, 41, 50, 60, 70, 150}; // EG8
  Double_t bins_9[21] = {4, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG9

  Double_t bins_10[22] = {5, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG10
  Double_t bins_11[21] = {6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 26, 28, 31, 40, 50, 60, 70, 150}; // EG11
  Double_t bins_12[22] = {5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG12

  Double_t bins_13[18] = {5, 7, 9, 11, 12, 13, 14, 15, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG13
  Double_t bins_14[19] = {6, 8, 10, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG14
  Double_t bins_15[18] = {5, 7, 9, 11, 13, 14, 15, 16, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG15

  Double_t bins_16[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG16
  Double_t bins_17[18] = {9, 11, 13, 15, 16, 17, 18, 19, 21, 23, 25, 30, 35, 40, 50, 60, 70, 150}; // EG17
  Double_t bins_18[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG18

  Double_t bins_19[20] = {9, 11, 13, 15, 17, 18, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG19
  Double_t bins_20[20] = {8, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 30, 35, 40, 45, 50, 60, 70, 100}; // EG20
  Double_t bins_21[20] = {9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG21

  Double_t bins_22[20] = {10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG22
  Double_t bins_23[19] = {11, 13, 15, 17, 19, 21, 22, 23, 24, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG23
  Double_t bins_24[20] = {10, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG24

  Double_t bins_25[20] = {11, 13, 15, 17, 19, 21, 23, 24, 25, 26, 27, 29, 30, 35, 40, 45, 50, 60, 70, 150}; // EG25
  Double_t bins_26[20] = {10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG26
  Double_t bins_27[20] = {11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 33, 35, 40, 45, 50, 60, 70, 150}; // EG27

  Double_t bins_28[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 29, 30, 32, 35, 40, 45, 50, 60, 70, 150}; // EG28
  Double_t bins_29[21] = {11, 13, 15, 17, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 35, 40, 45, 50, 60, 70, 150}; // EG29
  Double_t bins_30[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 29, 30, 31, 32, 35, 40, 45, 50, 60, 70, 150}; // EG30

  Double_t bins_40[22] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 39, 40, 42, 45, 50, 60, 70, 150}; // EG40
  Double_t bins_50[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG50
  Double_t bins_60[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG60

  vector< Double_t* > bins;
  bins.push_back( bins_0 ); bins.push_back( bins_1 ); bins.push_back( bins_2 ); bins.push_back( bins_3 ); bins.push_back( bins_4 ); 
  bins.push_back( bins_5 ); bins.push_back( bins_6 ); bins.push_back( bins_7 ); bins.push_back( bins_8 ); bins.push_back( bins_9 ); 
  bins.push_back( bins_10 ); bins.push_back( bins_11 ); bins.push_back( bins_12 ); bins.push_back( bins_13 ); bins.push_back( bins_14 ); 
  bins.push_back( bins_15 ); bins.push_back( bins_16 ); bins.push_back( bins_17 ); bins.push_back( bins_18 ); bins.push_back( bins_19 ); 
  bins.push_back( bins_20 ); bins.push_back( bins_21 ); bins.push_back( bins_22 ); bins.push_back( bins_23 ); bins.push_back( bins_24 ); 
  bins.push_back( bins_25 ); bins.push_back( bins_26 ); bins.push_back( bins_27 ); bins.push_back( bins_28 ); bins.push_back( bins_29 ); 

  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_30 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_40 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_50 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_60 );

  RooBinning binning = RooBinning(nbins[iEG]-1, bins[iEG], "binning");


  // INPUT DATA //
  TFile* f1 = TFile::Open(dirIn+"/"+fileIn);

  TTree* treenew;
  TTree* treenew_2;

  treenew = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL1]+name_coll[iColl1] ) ;
  treenew_2 = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL2]+name_coll[iColl2] ) ;

  TString name_scet[2], name_scdr[2], name_l1bin[2];
  name_scet[0] = "sc_et"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scet[1] = "sc_et"+name_ecal[iECAL2]+name_coll[iColl2];
  name_scdr[0] = "sc_dr"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scdr[1] = "sc_dr"+name_ecal[iECAL2]+name_coll[iColl2];
  
  name_l1bin[0] = "l1_"+names[iEG]+name_ecal[iECAL1]+name_coll[iColl1];
  name_l1bin[1] = "l1_"+names[iEG]+name_ecal[iECAL2]+name_coll[iColl2];

  RooRealVar et_plot(name_scet[0],name_scet[0],0,150) ;
  RooRealVar dr(name_scdr[0],name_scdr[0],0.5,1.5) ; 
  RooRealVar et_plot2(name_scet[1],name_scet[1],0,150) ;
  RooRealVar dr2(name_scdr[1],name_scdr[1],0.5,1.5) ;

  // Acceptance state cut (1 or 0)
  RooCategory cut(name_l1bin[0],name_l1bin[0]) ;
  cut.defineType("accept",1) ;
  cut.defineType("reject",0) ;
  RooCategory cut2(name_l1bin[1],name_l1bin[1]) ;
  cut2.defineType("accept",1) ;
  cut2.defineType("reject",0) ;
  
  // PARAMETRES ROOFIT CRYSTAL BALL
  RooRealVar norm("norm","N",1,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.671034,0.01,8);
  RooRealVar n("n","n",4.07846,1.1,35);
  RooRealVar mean("mean","mean",20.8,0,100);
  //mean.setVal(thres[iEG]);
  RooRealVar sigma("sigma","#sigma",0.972825,0.01,5);
  //RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  RooRealVar norm2("norm2","N",0.999069,0.6,1);
  RooRealVar alpha2("alpha2","#alpha",0.492303,0.01,8);
  RooRealVar n2("n2","n",11.6694,1.1,35);
  RooRealVar mean2("mean2","mean",21.4582,0,100);
  //mean2.setVal(thres[iEG]);
  RooRealVar sigma2("sigma2","#sigma",1.19,0.01,5);
  //RooRealVar pedestal2("pedestal2","pedestal",0.01,0,0.4);

  FuncCB cb("cb","Crystal Ball Integree",et_plot,mean,sigma,alpha,n,norm) ;
  FuncCB cb2("cb2","Crystal Ball Integree",et_plot2,mean2,sigma2,alpha2,n2,norm2) ;
  
  // EFFICIENCY //
  RooEfficiency eff("eff","efficiency",cb,cut,"accept");
  RooEfficiency eff2("eff2","efficiency",cb2,cut2,"accept");

  // DATASETS //
  RooDataSet dataSet("data","data",RooArgSet(et_plot, cut,dr),Import(*treenew)); 
  RooDataSet dataSet2("data2","data2",RooArgSet(et_plot2, cut2,dr2),Import(*treenew_2));

  dataSet.Print();
  dataSet2.Print();
  
  // PLOT //
  RooPlot* frame = et_plot.frame(Bins(18000),Title("Fitted efficiency")) ;
  RooPlot* frame2 = et_plot2.frame(Bins(18000),Title("Fitted efficiency")) ;

  dataSet.plotOn(frame, Binning(binning), Efficiency(cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSet2.plotOn(frame2, Binning(binning), Efficiency(cut2), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );


  /////////////////////// FITTING /////////////////////////////

  double fit_cuts_min = thres[iEG]-1.5 ;
  double fit_cuts_max = 150;

  et_plot.setRange("interesting",fit_cuts_min,fit_cuts_max);
  et_plot2.setRange("interesting",fit_cuts_min,fit_cuts_max);

  RooFitResult* roofitres1 = new RooFitResult("roofitres1","roofitres1");
  RooFitResult* roofitres2 = new RooFitResult("roofitres2","roofitres2");

  fichier << "Fit characteristics :"   << endl ;
  fichier << "EG "     << names[iEG] << endl ;
  fichier << "Fit Range , EB Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "Fit Range , EE Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "----------------------"  << endl ;

  // Fit #1 //
  roofitres1 = eff.fitTo(dataSet,ConditionalObservables(et_plot),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
  
  cb.plotOn(frame,LineColor(color1),LineWidth(2));

  double res_norm1  = norm.getVal();
  double err_norm1  = norm.getErrorLo();
  double res_mean1  = mean.getVal();
  double err_mean1  = mean.getError();
  double res_sigma1 = sigma.getVal();
  double err_sigma1 = sigma.getError();
  double res_n1     = n.getVal();
  double err_n1     = n.getError();
  double res_alpha1 = alpha.getVal();
  double err_alpha1 = alpha.getError();

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << res_mean1  << "; "
	  << "double res_sigma=" << res_sigma1 << "; "
          << "double res_alpha=" << res_alpha1 << "; "
          << "double res_n="     << res_n1     << "; "
          << "double res_norm="  << res_norm1  << "; "
	  << endl
	  << "double err_mean="  << err_mean1  << "; "
	  << "double err_sigma=" << err_sigma1 << "; "
          << "double err_alpha=" << err_alpha1 << "; "
          << "double err_n="     << err_n1     << "; "
          << "double err_norm="  << err_norm1  << "; "
	  << endl;

  // Fit #2 //
  roofitres2 = eff2.fitTo(dataSet2,ConditionalObservables(et_plot2),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
 
  cb2.plotOn(frame2,LineColor(color2),LineWidth(2));

  double res_norm2  = norm2.getVal();
  double err_norm2  = norm2.getErrorLo();
  double res_mean2  = mean2.getVal();
  double err_mean2  = mean2.getError();
  double res_sigma2 = sigma2.getVal();
  double err_sigma2 = sigma2.getError();
  double res_n2     = n2.getVal();
  double err_n2     = n2.getError();
  double res_alpha2 = alpha2.getVal();
  double err_alpha2 = alpha2.getError();

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << res_mean2  << "; "
	  << "double res_sigma=" << res_sigma2 << "; "
	  << "double res_alpha=" << res_alpha2 << "; "
	  << "double res_n="     << res_n2     << "; "
	  << "double res_norm="  << res_norm2  << "; "
	  << endl
	  << "double err_mean="  << err_mean2  << "; "
	  << "double err_sigma=" << err_sigma2 << "; "
	  << "double err_alpha=" << err_alpha2 << "; "
	  << "double err_n="     << err_n2     << "; "
	  << "double err_norm="  << err_norm2  << "; "
	  << endl;
    

  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,100.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  frame2->GetYaxis()->SetRangeUser(0,1.05);
  frame2->GetXaxis()->SetRangeUser(1,100.);
  frame2->GetYaxis()->SetTitle("Efficiency");
  frame2->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame2->Draw("same") ;

  TH1F *SCeta1 = new TH1F("SCeta1","SCeta1",50,-2.5,2.5);
  TH1F *SCeta2 = new TH1F("SCeta2","SCeta2",50,-2.5,2.5);

  SCeta1->SetLineColor(color1) ;
  SCeta1->SetMarkerColor(color1);
  SCeta1->SetMarkerStyle(style1);

  SCeta2->SetLineColor(color2) ;
  SCeta2->SetMarkerColor(color2);
  SCeta2->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.246,0.435,0.461,0.560,NULL,"brNDC"); // mid : x=353.5
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);
  leg->SetMargin(0.25);
  TLegendEntry *entry=leg->AddEntry("NULL","L1_SingleEG"+names[iEG],"h");
//   leg->AddEntry(SCeta1,name_leg_ecal[iECAL1]+" "+name_leg_coll[iColl1],"p");
//   leg->AddEntry(SCeta2,name_leg_ecal[iECAL2]+" "+name_leg_coll[iColl2],"p");
  leg->AddEntry(SCeta1,name_leg_ecal[iECAL1],"p");
  leg->AddEntry(SCeta2,name_leg_ecal[iECAL2],"p");
  leg->Draw();

  leg = new TLegend(0.16,0.725,0.58,0.905,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+names[iEG]+" GeV","h");
  leg->Draw();

  TPaveText *pt2 = new TPaveText(0.220,0.605,0.487,0.685,"brNDC"); // mid : x=353.5                                          
  pt2->SetLineColor(1);
  pt2->SetTextColor(1);
  pt2->SetTextFont(42);
  pt2->SetTextSize(0.03);
  pt2->SetFillColor(kWhite);
  pt2->SetShadowColor(kWhite);
  pt2->AddText("L1 E/Gamma Trigger");
  pt2->AddText("Electrons from Z");
  pt2->Draw();
  
  //TString name_image="eff_EG20_2012_12fb";

  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");
  ca->Print(name_image+".eps","eps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSet);
  w->import(dataSet2);
  
  w->import(*roofitres1,"roofitres1");
  w->import(*roofitres2,"roofitres2");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  //f1->Close();
}
void plot( TString var, TString data, TString pdf, double low=-1, double high=-1 ) {

  TFile *tf = TFile::Open( "root/FitOut.root" );
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");
  TCanvas *canv = new TCanvas("c","c",800,800);
  TPad *upperPad = new TPad(Form("%s_upper",canv->GetName()),"",0.,0.33,1.,1.);
  TPad *lowerPad = new TPad(Form("%s_lower",canv->GetName()),"",0.,0.,1.,0.33);
  canv->cd();
  upperPad->Draw();
  lowerPad->Draw();

  if ( low < 0 ) low = w->var(var)->getMin();
  if ( high < 0 ) high = w->var(var)->getMax();
  RooPlot *plot = w->var(var)->frame(Range(low,high));
  w->data(data)->plotOn(plot);
  w->pdf(pdf)->plotOn(plot);

  RooHist *underHist = plot->pullHist();
  underHist->GetXaxis()->SetRangeUser(plot->GetXaxis()->GetXmin(), plot->GetXaxis()->GetXmax());
  underHist->GetXaxis()->SetTitle(plot->GetXaxis()->GetTitle());
  underHist->GetYaxis()->SetTitle("Pull");
  underHist->GetXaxis()->SetLabelSize(0.12);
  underHist->GetYaxis()->SetLabelSize(0.12);
  underHist->GetXaxis()->SetTitleSize(0.2);
  underHist->GetXaxis()->SetTitleOffset(0.7);
  underHist->GetYaxis()->SetTitleSize(0.18);
  underHist->GetYaxis()->SetTitleOffset(0.38);

  plot->GetXaxis()->SetTitle("");
  upperPad->SetBottomMargin(0.1);
  upperPad->cd();
  plot->Draw();

  canv->cd();
  lowerPad->SetTopMargin(0.05);
  lowerPad->SetBottomMargin(0.35);
  lowerPad->cd();
  underHist->Draw("AP");

  double ymin = underHist->GetYaxis()->GetXmin();
  double ymax = underHist->GetYaxis()->GetXmax();
  double yrange = Max( Abs( ymin ), Abs( ymax ) );
  underHist->GetYaxis()->SetRangeUser( -1.*yrange, 1.*yrange );

  double xmin = plot->GetXaxis()->GetXmin();
  double xmax = plot->GetXaxis()->GetXmax();

  TColor *mycol3sig = gROOT->GetColor( kGray );
  mycol3sig->SetAlpha(0.5);
  TColor *mycol2sig = gROOT->GetColor( kGray+1 );
  mycol2sig->SetAlpha(0.5);
  TColor *mycol1sig = gROOT->GetColor( kGray+2 );
  mycol1sig->SetAlpha(0.5);

  TBox box3sig;
  box3sig.SetFillColor( mycol3sig->GetNumber() );
  //box3sig.SetFillColorAlpha( kGray, 0.5 );
  box3sig.SetFillStyle(1001);
  box3sig.DrawBox( xmin, -3., xmax, 3.);
  TBox box2sig;
  box2sig.SetFillColor( mycol2sig->GetNumber() );
  //box2sig.SetFillColorAlpha( kGray+1, 0.5 );
  box2sig.SetFillStyle(1001);
  box2sig.DrawBox( xmin, -2., xmax, 2.);
  TBox box1sig;
  box1sig.SetFillColor( mycol1sig->GetNumber() );
  //box1sig.SetFillColorAlpha( kGray+2, 0.5 );
  box1sig.SetFillStyle(1001);
  box1sig.DrawBox( xmin, -1., xmax, 1.);

  TLine lineErr;
  lineErr.SetLineWidth(1);
  lineErr.SetLineColor(kBlue-9);
  lineErr.SetLineStyle(2);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),1.,plot->GetXaxis()->GetXmax(),1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-1.,plot->GetXaxis()->GetXmax(),-1.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),2.,plot->GetXaxis()->GetXmax(),2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-2.,plot->GetXaxis()->GetXmax(),-2.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),3.,plot->GetXaxis()->GetXmax(),3.);
  lineErr.DrawLine(plot->GetXaxis()->GetXmin(),-3.,plot->GetXaxis()->GetXmax(),-3.);

  TLine line;
  line.SetLineWidth(3);
  line.SetLineColor(kBlue);
  line.DrawLine(plot->GetXaxis()->GetXmin(),0.,plot->GetXaxis()->GetXmax(),0.);
  underHist->Draw("Psame");

  RooHist *redPull = new RooHist();
  int newp=0;
  for (int p=0; p<underHist->GetN(); p++) {
    double x,y;
    underHist->GetPoint(p,x,y);
    if ( TMath::Abs(y)>3 ) {
      redPull->SetPoint(newp,x,y);
      redPull->SetPointError(newp,0.,0.,underHist->GetErrorYlow(p),underHist->GetErrorYhigh(p));
      newp++;
    }
  }
  redPull->SetLineWidth(underHist->GetLineWidth());
  redPull->SetMarkerStyle(underHist->GetMarkerStyle());
  redPull->SetMarkerSize(underHist->GetMarkerSize());
  redPull->SetLineColor(kRed);
  redPull->SetMarkerColor(kRed);
  redPull->Draw("Psame");

  canv->Print(Form("tmp/%s.pdf",var.Data()));
  tf->Close();

}
Esempio n. 6
0
void paper_fit_plot()
{
  SetAtlasStyle();

  // get the stuff from the file
  char fname_postfit[200] = "monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root";
  TFile *tf = new TFile(fname_postfit);
  RooWorkspace *ws_post = (RooWorkspace*)tf->Get("wspace");

  // data and pdf
  RooAbsData *data = ws_post->data("data");
  RooAbsPdf *pdfc = ws_post->pdf("jointModeld");
  
  // variables to be constrained
  RooRealVar *mh = ws_post->var("mh");
  RooRealVar *sigma_h = ws_post->var("sigma_h");
  RooRealVar *eff = ws_post->var("eff");
  RooRealVar *theory = ws_post->var("theory");
  RooRealVar *lumi = ws_post->var("lumi");
  RooRealVar *x_mgg = ws_post->var("mgg");
  RooArgSet cas(*mh,*sigma_h,*eff,*theory,*lumi);  

  // redo the fit
  RooFitResult *r = pdfc->fitTo(*data,RooFit::Constrain(cas),RooFit::Save(true));

  // make the frame
  RooPlot *frame = x_mgg->frame();
  TCanvas *tc = new TCanvas("tc","",700,500);
  frame->GetXaxis()->SetTitle("m_{#gamma#gamma} [GeV]");
  frame->GetYaxis()->SetTitle("Events / 1 GeV");

  // add the data
  data->plotOn(frame,RooFit::Binning(55),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));
  //data->plotOn(frame,RooFit::Binning(11),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));


  ///  PDFs
  pdfc->plotOn(frame, RooFit::Components("E"), RooFit::LineColor(kRed),   RooFit::Name("xbackground"));
  pdfc->plotOn(frame, RooFit::Components("S"), RooFit::LineColor(kBlue),RooFit::LineStyle(kDotted),   RooFit::Name("xsm"));
  pdfc->plotOn(frame, RooFit::Components("G"), RooFit::LineColor(kGreen),RooFit::LineStyle(kDotted),   RooFit::Name("xbsm"));
  pdfc->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed),RooFit::Name("xtotal"));

  frame->SetMinimum(1e-7);
  frame->SetMaximum(9);

  // Legend
  double x1,y1,x2,y2;
  GetX1Y1X2Y2(tc,x1,y1,x2,y2);
  TLegend *legend_sr=FastLegend(x1+0.02,y2-0.3,x1+0.35,y2-0.02,0.045);
  legend_sr->AddEntry(frame->findObject("xdata"),"Data","LEP");
  legend_sr->AddEntry(frame->findObject("xbackground"),"Background fit","L");
  legend_sr->AddEntry(frame->findObject("xsm"),"SM H","L");
  legend_sr->AddEntry(frame->findObject("xbsm"),"Best-fit BSM H","L");
  legend_sr->AddEntry(frame->findObject("xtotal"),"Total","L");
  frame->Draw();
  legend_sr->Draw("SAME");

  // descriptive text
  vector<TString> pavetext11;
  pavetext11.push_back("#bf{#it{ATLAS Internal}}");
  pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}#it{L} dt = 20.3 fb^{-1}");
  pavetext11.push_back("#it{H + E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV");

  TPaveText* text11=CreatePaveText(x2-0.47,y2-0.25,x2-0.05,y2-0.05,pavetext11,0.045);
  text11->Draw();
  tc->Print("paper_fit_plot.pdf");
 }
Esempio n. 7
0
void RooToyMCFit(){
    stringstream out;
   out.str("");
   out << "toyMC_" << _sigma_over_tau << "_" << _purity << "_" << mistag_rate << ".root";
   TFile* file = TFile::Open(out.str().c_str());
   TTree* tree = (TTree*)file->Get("ToyTree");
   tree->Print();

//    TFile* file = TFile::Open("ToyData/toyMC_453_0.912888_0.3_0.8_0.root");
//    TFile* file = TFile::Open("ToyData/toyMC_10000_0.9_0.3_0.8_0.root");
//    TTree* tree = (TTree*)file->Get("ToyTree1");

    RooRealVar tau("tau","tau",_tau,"ps"); tau.setConstant(kTRUE);
    RooRealVar dm("dm","dm",_dm,"ps^{-1}"); dm.setConstant(kTRUE);

    RooAbsReal* sin2beta;
    RooAbsReal* cos2beta;
    if(softlimit){
      RooRealVar x("x","x",_cos2beta,-3.,30000.); if(constBeta) x.setConstant(kTRUE);
      RooRealVar y("y","y",_sin2beta,-3.,30000.); if(constBeta) y.setConstant(kTRUE);
      cos2beta = new RooFormulaVar("cos2beta","cos2beta","@0/sqrt(@0*@0+@1*@1)",RooArgSet(x,y));
      sin2beta = new RooFormulaVar("sin2beta","sin2beta","@0/sqrt(@0*@0+@1*@1)",RooArgSet(y,x));
//      sin2beta = new RooFormulaVar("sin2beta","sin2beta","2/TMath::Pi()*TMath::ATan(@0)",RooArgSet(y));
//      cos2beta = new RooFormulaVar("cos2beta","cos2beta","2/TMath::Pi()*TMath::ATan(@0)",RooArgSet(x));
    }
    else{ 
      sin2beta = new RooRealVar("sin2beta","sin2beta",_sin2beta,-3.,3.); if(constBeta) ((RooRealVar*)sin2beta)->setConstant(kTRUE);
      cos2beta = new RooRealVar("cos2beta","cos2beta",_cos2beta,-3.,3.); if(constBeta) ((RooRealVar*)cos2beta)->setConstant(kTRUE);
    }
    RooRealVar dt("dt","#Deltat",-5.,5.,"ps");
    RooRealVar avgMisgat("avgMisgat","avgMisgat",mistag_rate,0.0,0.5); if(constMistag) avgMisgat.setConstant(kTRUE);
    RooRealVar delMisgat("delMisgat","delMisgat",0); delMisgat.setConstant(kTRUE);
    RooRealVar mu("mu","mu",0); mu.setConstant(kTRUE);

    tau.Print();
    dm.Print();
    sin2beta->Print();
    cos2beta->Print();
    avgMisgat.Print();

    RooRealVar moment("moment","moment",0.); moment.setConstant(kTRUE);
    RooRealVar parity("parity","parity",-1.); parity.setConstant(kTRUE);

    RooRealVar* K[8];
    RooAbsReal* Kb[8];
    RooArgList Kset;
    RooRealVar* C[8];
    RooRealVar* S[8];
    RooFormulaVar* a1[2][8];
    RooFormulaVar* b1[2][8];
    RooFormulaVar* a2[2][8];
    RooFormulaVar* b2[2][8];

    for(int i=0; i<8; i++){
        out.str("");
        out << "K" << i+1;
        K[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_K[i],0.,1.); Kset.add(*K[i]); if(constK) K[i]->setConstant(kTRUE);
        K[i]->Print();
        if(i!=7){
          out.str("");
          out << "Kb" << i+1;
          Kb[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_Kb[i],0.,1.); Kset.add(*Kb[i]); if(constK) ((RooRealVar*)Kb[i])->setConstant(kTRUE);
          Kb[i]->Print();
        }
        out.str("");
        out << "C" << i+1;
        C[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_C[i]); C[i]->setConstant(kTRUE);
        C[i]->Print();
        out.str("");
        out << "S" << i+1;
        S[i] = new RooRealVar(out.str().c_str(),out.str().c_str(),_S[i]); S[i]->setConstant(kTRUE);
        S[i]->Print();
    }
    Kb[7] = new RooFormulaVar("K8b","K8b","1-@0-@1-@2-@3-@4-@5-@6-@7-@8-@9-@10-@11-@12-@13-@14",Kset);

    for(int i=0; i<8; i++){
        out.str("");
        out << "a10_" << i+1;
        a1[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a1[0][i]->Print();
        out.str("");
        out << "a11_" << i+1;
        a1[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a1[1][i]->Print();
        out.str("");
        out << "a20_" << i+1;
        a2[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a2[0][i]->Print();
        out.str("");
        out << "a21_" << i+1;
        a2[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-(@0-@1)/(@0+@1)",RooArgList(*K[i],*Kb[i]));
        a2[1][i]->Print();

        out.str("");
        out << "b10_" << i+1;
        b1[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b1[0][i]->Print();
        out.str("");
        out << "b11_" << i+1;
        b1[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b1[1][i]->Print();
        out.str("");
        out << "b20_" << i+1;
        b2[0][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b2[0][i]->Print();
        out.str("");
        out << "b21_" << i+1;
        b2[1][i] = new RooFormulaVar(out.str().c_str(),out.str().c_str(),"-2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1)",RooArgList(*K[i],*Kb[i],*C[i],*S[i],*sin2beta,*cos2beta));
        b2[1][i]->Print();

        cout << "bin = " << i+1 << endl;
        cout << "  a11 = " << a1[0][i]->getVal() << " b11 = " << b1[0][i]->getVal() << endl;
        cout << "  a12 = " << a1[1][i]->getVal() << " b12 = " << b1[1][i]->getVal() << endl;
        cout << "  a21 = " << a2[0][i]->getVal() << " b21 = " << b2[0][i]->getVal() << endl;
        cout << "  a22 = " << a2[1][i]->getVal() << " b22 = " << b2[1][i]->getVal() << endl;
    }

    RooRealVar* dgamma = new RooRealVar("dgamma","dgamma",0.); dgamma->setConstant(kTRUE);
    RooRealVar* f0 = new RooRealVar("f0","f0",1.);             f0->setConstant(kTRUE);
    RooRealVar* f1 = new RooRealVar("f1","f1",0.);             f1->setConstant(kTRUE);

    RooCategory tag("tag","tag");
    tag.defineType("B0",1);
    tag.defineType("anti-B0",-1);

    RooCategory bin("bin","bin");
    bin.defineType("1",1);
    bin.defineType("2",2);
    bin.defineType("3",3);
    bin.defineType("4",4);
    bin.defineType("5",5);
    bin.defineType("6",6);
    bin.defineType("7",7);
    bin.defineType("8",8);
    bin.defineType("-1",-1);
    bin.defineType("-2",-2);
    bin.defineType("-3",-3);
    bin.defineType("-4",-4);
    bin.defineType("-5",-5);
    bin.defineType("-6",-6);
    bin.defineType("-7",-7);
    bin.defineType("-8",-8);

    
    RooSuperCategory bintag("bintag","bintag",RooArgSet(bin,tag));

    tree->Print();

    RooDataSet d("data","data",tree,RooArgSet(dt,bin,tag));
    cout << "DataSet is ready." << endl;
    d.Print();

    RooRealVar mean("mean","mean",0.,"ps"); mean.setConstant(kTRUE);
    RooRealVar sigma("sigma","sigma",_sigma_over_tau*_tau,0.,1.5*_tau,"ps"); if(constSigma) sigma.setConstant(kTRUE);
    RooGaussModel rf("rf","rf",dt,mean,sigma);
//    RooTruthModel rf("rf","rf",dt);
    RooGaussian rfpdf("rfpdf","rfpdf",dt,mean,sigma);

    cout << "Preparing PDFs..." << endl;
//    RooRealVar* fsigs1[8];
//    RooRealVar* fsigs1b[8];
//    RooRealVar* fsigs2[8];
//    RooRealVar* fsigs2b[8];
    RooBDecay* sigpdfs1[8];
    RooBDecay* sigpdfs1b[8];
    RooBDecay* sigpdfs2[8];
    RooBDecay* sigpdfs2b[8];
    RooAddPdf* PDFs1[8];
    RooAddPdf* PDFs1b[8];
    RooAddPdf* PDFs2[8];
    RooAddPdf* PDFs2b[8];
    RooAddPdf* pdfs1[8];
    RooAddPdf* pdfs1b[8];
    RooAddPdf* pdfs2[8];
    RooAddPdf* pdfs2b[8];
    RooSimultaneous pdf("pdf","pdf",bintag);
    RooRealVar fsig("fsig","fsig",_purity,0.,1.); if(constFSig) fsig.setConstant(kTRUE);
    fsig.Print();
    for(int j=0; j<8; j++){
//        out.str("");
//        out << "fsig1" << j+1;
//        fsigs1[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.);  if(constFSig) fsigs1[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig1b" << j+1;
//        fsigs1b[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.); if(constFSig) fsigs1b[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig2" << j+1;
//        fsigs2[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.);  if(constFSig) fsigs2[j]->setConstant(kTRUE);
//        out.str("");
//        out << "fsig2b" << j+1;
//        fsigs2b[j] = new RooRealVar(out.str().c_str(),out.str().c_str(),_purity,0.,1.); if(constFSig) fsigs2b[j]->setConstant(kTRUE);

        out.str("");
        out << "sigpdf1" << j+1;
        sigpdfs1[j]  = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a1[0][j],*b1[0][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf1b" << j+1;
        sigpdfs1b[j] = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a1[1][j],*b1[1][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf2" << j+1;
        sigpdfs2[j]  = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a2[0][j],*b2[0][j],dm,rf,RooBDecay::DoubleSided);
        out.str("");
        out << "sigpdf2b" << j+1;
        sigpdfs2b[j] = new RooBDecay(out.str().c_str(),out.str().c_str(),dt,tau,*dgamma,*f0,*f1,*a2[1][j],*b2[1][j],dm,rf,RooBDecay::DoubleSided);

        out.str("");
        out << "PDF1" << j+1;
        PDFs1[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs1[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF1b" << j+1;
        PDFs1b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs1b[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF2" << j+1;
        PDFs2[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs2[j],rfpdf),RooArgList(fsig));
        out.str("");
        out << "PDF2b" << j+1;
        PDFs2b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*sigpdfs2b[j],rfpdf),RooArgList(fsig));

        //Adding mistaging
        out.str("");
        out << "pdf1" << j+1;
        pdfs1[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs2[j],*PDFs1[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf1b" << j+1;
        pdfs1b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs2b[j],*PDFs1b[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf2" << j+1;
        pdfs2[j]  = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs1[j],*PDFs2[j]),RooArgList(avgMisgat));
        out.str("");
        out << "pdf2b" << j+1;
        pdfs2b[j] = new RooAddPdf(out.str().c_str(),out.str().c_str(),RooArgList(*PDFs1b[j],*PDFs2b[j]),RooArgList(avgMisgat));

        out.str("");
        out << "{" << j+1 << ";B0}";
        pdf.addPdf(*pdfs1[j],out.str().c_str());
        out.str("");
        out << "{" << -(j+1) << ";B0}";
        pdf.addPdf(*pdfs1b[j],out.str().c_str());
        out.str("");
        out << "{" << j+1 << ";anti-B0}";
        pdf.addPdf(*pdfs2[j],out.str().c_str());
        out.str("");
        out << "{" << -(j+1) << ";anti-B0}";
        pdf.addPdf(*pdfs2b[j],out.str().c_str());
    }

    cout << "Fitting..." << endl;
    pdf.fitTo(d,Verbose(),Timer());
    dt.setBins(50);

    cout << "Drawing plots." << endl;
    for(int i=0; i<8; i++){
        RooPlot* dtFrame = dt.frame();
        out.str("");
        out << "tag == 1 && bin == " << i+1;
        RooDataSet* ds = d.reduce(out.str().c_str());
        ds->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kBlue));

        out.str("");
        out << "{" << j+1 << ";B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds),Slice(bintag),LineColor(kBlue));
        double chi2 = dtFrame->chiSquare();

        out.str("");
        out << "tag == -1 && bin == " << i+1;
        RooDataSet* dsb = d.reduce(out.str().c_str());
        dsb->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kRed));

        out.str("");
        out << "{" << j+1 << ";anti-B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*dsb),Slice(bintag),LineColor(kRed));
        double chi2b = dtFrame->chiSquare();

        out.str("");
        out << "#Delta t, toy MC, bin == " << i+1;
        TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
        cm->cd();
        dtFrame->GetXaxis()->SetTitleSize(0.05);
        dtFrame->GetXaxis()->SetTitleOffset(0.85);
        dtFrame->GetXaxis()->SetLabelSize(0.05);
        dtFrame->GetYaxis()->SetTitleOffset(1.6);

        TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
        ptB->SetFillColor(0);
        ptB->SetTextAlign(12);
        out.str("");
        out << "bin = " << (i+1);
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(B^{0}) = " << chi2;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(#barB^{0}) = " << chi2b;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#sigma/#tau = " << _sigma_over_tau;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "purity = " << _purity;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "mistag = " << mistag_rate;
        ptB->AddText(out.str().c_str());

        dtFrame->Draw();
        ptB->Draw();

        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << (i+1) << ".root";
        cm->Print(out.str().c_str());
        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << (i+1) << ".png";
        cm->Print(out.str().c_str());
    }

    for(int i=0; i<8; i++){
        RooPlot* dtFrame = dt.frame();
        out.str("");
        out << "tag == 1 && bin == " << -(i+1);
        RooDataSet* ds2 = (RooDataSet*)d.reduce(out.str().c_str());
        ds2->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kBlue));

        out.str("");
        out << "{" << -(j+1) << ";B0}";
        bintag = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds2),Slice(bintag),LineColor(kBlue));
        double chi2 = dtFrame->chiSquare();

        out.str("");
        out << "tag == -1 && bin == " << -(i+1);
        RooDataSet* ds2b = (RooDataSet*)d.reduce(out.str().c_str());
        ds2b->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),Cut(out.str().c_str()),MarkerColor(kRed));

        out.str("");
        out << "{" << -(j+1) << ";anti-B0}";
        bin = out.str().c_str();
        pdf.plotOn(dtFrame,ProjWData(*ds2b),Slice(bintag),LineColor(kRed));
        double chi2b = dtFrame->chiSquare();

        out.str("");
        out << "#Delta t, toy MC, bin == " << -(i+1);
        TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
        cm->cd();
        dtFrame->GetXaxis()->SetTitleSize(0.05);
        dtFrame->GetXaxis()->SetTitleOffset(0.85);
        dtFrame->GetXaxis()->SetLabelSize(0.05);
        dtFrame->GetYaxis()->SetTitleOffset(1.6);

        TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
        ptB->SetFillColor(0);
        ptB->SetTextAlign(12);
        out.str("");
        out << "bin = " << -(i+1);
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(B^{0}) = " << chi2;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#chi^{2}(#barB^{0}) = " << chi2b;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "#sigma/#tau = " << _sigma_over_tau;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "purity = " << _purity;
        ptB->AddText(out.str().c_str());
        out.str("");
        out << "mistag = " << mistag_rate;
        ptB->AddText(out.str().c_str());

        dtFrame->Draw();
        ptB->Draw();

        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << -(i+1) << ".root";
        cm->Print(out.str().c_str());
        out.str("");
        out << "../Reports/cpfitfigs/dt_bin" << -(i+1) << ".png";
        cm->Print(out.str().c_str());
    }

    return;
}
Esempio n. 8
0
TCanvas* comparePlots2(RooPlot *plot_bC, RooPlot *plot_bS, TH1F *data, TH1F *qcd, std::string title)
{
    
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    TCanvas *c=new TCanvas(("c_RooFit_"+title).c_str(), "c", 700, 700);
    TPad *p_1=new TPad("p_1", "p_1", 0, 0.35, 1, 1);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gROOT->SetStyle("Plain");
    p_1->SetFrameFillColor(0);
    TPad *p_2 = new TPad("p_2", "p_2",0,0.003740648,0.9975278,0.3391022);
    p_2->Range(160.1237,-0.8717948,1008.284,2.051282);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetTopMargin(0.02);
    p_2->SetBottomMargin(0.3);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    double maxdata=data->GetMaximum();
    double maxqcd=qcd->GetMaximum();
    double maxy=(maxdata>maxqcd) ? maxdata : maxqcd;
    
    title=";m_{X} (GeV); Events / "+itoa(data->GetBinWidth(1))+" GeV";
    p_1->DrawFrame(SR_lo, 0, SR_hi, maxy*1., title.c_str());
    plot_bS->SetMarkerStyle(20);
    plot_bS->Draw("same");
    // plot_bS->Draw("same");
    CMS_lumi( p_1, iPeriod, iPos );
    p_2->cd();
    /* TH1F *h_ratio=(TH1F*)data->Clone("h_ratio");
     h_ratio->GetYaxis()->SetTitle("VR/VSB Ratio");
     h_ratio->GetXaxis()->SetTitle("m_{X} (GeV)");
     h_ratio->SetTitle("");//("VR/VR-SB Ratio "+title+" ; VR/VR-SB Ratio").c_str());
     h_ratio->GetYaxis()->SetTitleSize(0.07);
     h_ratio->GetYaxis()->SetTitleOffset(0.5);
     h_ratio->GetXaxis()->SetTitleSize(0.09);
     h_ratio->GetXaxis()->SetTitleOffset(1.0);
     h_ratio->GetXaxis()->SetLabelSize(0.07);
     h_ratio->GetYaxis()->SetLabelSize(0.06);
     
     h_ratio->Divide(qcd);
     h_ratio->SetLineColor(1);
     h_ratio->SetMarkerStyle(20);
     h_ratio->GetXaxis()->SetRangeUser(SR_lo, SR_hi-10);
     h_ratio->GetYaxis()->SetRangeUser(0.,2.);
     */
    RooHist* hpull;
    hpull = plot_bS->pullHist();
    hpull->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetYaxis()->SetTitle("Pull");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetTitle("Pull");
    
    frameP->GetYaxis()->SetTitleSize(0.07);
    frameP->GetYaxis()->SetTitleOffset(0.5);
    frameP->GetXaxis()->SetTitleSize(0.09);
    frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize(0.07);
    frameP->GetYaxis()->SetLabelSize(0.06);
    
    frameP->Draw();
    
    
    //  TLine *m_one_line = new TLine(SR_lo,1,SR_hi,1);
    
    
    // h_ratio->Draw("");
    // m_one_line->Draw("same");
    p_1->cd();
    return c;
}
Esempio n. 9
0
vector<double> FitBkg(TH1D* histo, TString _bkg ){

	setTDRStyle();

	vector<double> vec;

	int n = histo->GetEntries();
	double w = histo->GetXaxis()->GetBinWidth(1);
	int ndf;

	RooPlot* frame;

	double hmin0 = histo->GetXaxis()->GetXmin();
	double hmax0 = histo->GetXaxis()->GetXmax();

	histo->GetXaxis()->SetRangeUser(hmin0,hmax0);

	// Declare observable x
	RooRealVar x("x","x",hmin0,hmax0) ;
	RooDataHist dh("dh","dh",x,Import(*histo,kFALSE)) ;

	frame = x.frame(Title(histo->GetName())) ;
	dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7)); 
	dh.statOn(frame);  

	x.setRange("R0",0,200) ;

	//Defining the fitting functions
	if(_bkg == "Novo"){
		//Novo

		RooRealVar peak("peak","peak",45.,0.,100.);
		RooRealVar width("width","width",20.,0.,40.) ;
		RooRealVar tail("tail","tail",0.01,0.,1.) ;


		RooNovosibirsk bkg("bkg","Background",x,peak,width,tail);

		//Fitting
		RooFitResult* filters = bkg.fitTo(dh/*,Range("R0"),"qr"*/);
		bkg.plotOn(frame,LineColor(2));
		bkg.paramOn(frame); 

		vec.push_back(peak.getVal());
		vec.push_back(width.getVal());
		vec.push_back(tail.getVal());
	}

	if(_bkg == "Cheb"){
		//Chebychev


		RooRealVar a0("a0","a0",-1,-5.,0.) ;
		RooRealVar a1("a1","a1",0,-2,1.2) ;
		RooRealVar a2("a2","a2",0,-1.,1.) ;
		RooRealVar a3("a3","a3",0,-2.5,0.) ;
		RooRealVar a4("a4","a4",0,-1.,1.) ;
		RooRealVar a5("a5","a5",0,-1.,1.) ;
		RooRealVar a6("a6","a6",0,-1.,1.) ;

		RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6));

		//Fitting
		RooFitResult* filters = bkg.fitTo(dh,Range("R0"),"qr");
		bkg.plotOn(frame,LineColor(2));
		bkg.paramOn(frame); 

		vec.push_back(a0.getVal());
		vec.push_back(a1.getVal());
		vec.push_back(a2.getVal());
		vec.push_back(a3.getVal());
		vec.push_back(a4.getVal());
		vec.push_back(a5.getVal());
		vec.push_back(a6.getVal());

	}

	if(_bkg == "Land"){
		//Background fitting function
		//Landau (X) Gauss
		RooRealVar resp_mean("resp_mean","resp_mean",1,0.,20) ;
		RooRealVar resp_sigma("resp_sigma","resp_sigma",20,5,30) ;
		RooGaussian resp_bkg("resp","gauss",x,resp_mean,resp_sigma) ;

		RooRealVar mean_bkg("mean_bkg","mean",40,30,70) ;
		RooRealVar sigma_bkg("sigma_bkg","sigma",10,0,20) ;

		RooLandau Land_bkg("Land","Background",x,mean_bkg,sigma_bkg);

		sigma_bkg.setRange(30,50);
		resp_sigma.setRange(5,10);

		x.setBins(10000,"cache") ;

		RooFFTConvPdf bkg("bkg","Background",x,Land_bkg,resp_bkg);

		//Fitting
		RooFitResult* filters = bkg.fitTo(dh,Range("R0"),"qr");
	        frame->Draw();
		bkg.plotOn(frame,LineColor(2));
		bkg.paramOn(frame); 

		vec.push_back(0);
		vec.push_back(0);
		vec.push_back(0);

	}


	frame->GetXaxis()->SetTitle("Z mass (in GeV/c^{2})");  
	frame->GetXaxis()->SetTitleOffset(1.2);
	float binsize = histo->GetBinWidth(1); 

	//Store result in .root file
	frame->Write(histo->GetName());

	return vec;

}
Esempio n. 10
0
void MEPdfPartialB::DrawDeltaE(RooDataSet* ds){
  mbc->setRange("mbcSignal",cuts->get_mbc_min_h0(m_mode,m_h0mode),cuts->get_mbc_max_h0(m_mode,m_h0mode));
  RooPlot* deFrame = de->frame();
  ds->plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf_part->plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds->plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf_part->plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de->frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->AddText(cuts->GetLabel(m_mode,m_h0mode).c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(cuts->get_de_min_h0(m_mode,m_h0mode),0,cuts->get_de_min_h0(m_mode,m_h0mode),80);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(cuts->get_de_max_h0(m_mode,m_h0mode),0,cuts->get_de_max_h0(m_mode,m_h0mode),80);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(cuts->get_de_fit_min(),3,cuts->get_de_fit_max(),3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(cuts->get_de_fit_min(),0,cuts->get_de_fit_max(),0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(cuts->get_de_fit_min(),-3,cuts->get_de_fit_max(),-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  out.str("");
  out << "pics/de_part_m" << m_mode << "_h0m" << m_h0mode << ".eps";
  cm->Print(out.str().c_str());
  string line = string("evince ") + out.str() + string(" &");
  system(line.c_str());
  out.str("");
  out << "pics/de_part_m" << m_mode << "_h0m" << m_h0mode << ".root";
  cm->Print(out.str().c_str());
}
Esempio n. 11
0
void dzRooFit(const int _mode = 1, const int _h0mode = 10,const int EXP = -1){
    TFile *omegafile;
    switch(_mode){
    case 1:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigPi0_s4_full.root");
      break;
    case 2:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigEta_full.root");
      break;
    case 3:
      omegafile = TFile::Open("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_sigOmega_s1_full.root");
      break;
    }
    TTree *omegatree = (TTree*)omegafile->Get("TEvent");

  const double dz_min = -1.5;
  const double dz_max =  1.5;

  RooArgSet argset;
  RooCategory b0f("b0f","b0f");
  b0f.defineType("sig",1);
  b0f.defineType("badpi0",5);
  argset.add(b0f);

  RooCategory exp("exp","exp");
  if(EXP>0){
    exp.defineType("expNo",EXP);
  }
  if(EXP == -2 || EXP == -3){
    exp.defineType("7",7);
    exp.defineType("9",9);
    exp.defineType("11",11);
    exp.defineType("13",13);
    exp.defineType("15",15);
    exp.defineType("17",17);
    exp.defineType("21",21);
    exp.defineType("23",23);
    exp.defineType("25",25);
    exp.defineType("27",27);
  }
  if(EXP == -1 || EXP == -3){
    exp.defineType("31",31);
    exp.defineType("33",33);
    exp.defineType("35",35);
    exp.defineType("37",37);
    exp.defineType("39",39);
    exp.defineType("41",41);
    exp.defineType("43",43);
    exp.defineType("45",45);
    exp.defineType("47",47);
    exp.defineType("49",49);
    exp.defineType("51",51);
    exp.defineType("55",55);
    exp.defineType("61",61);
    exp.defineType("63",63);
    exp.defineType("65",65);
  }
  argset.add(exp); 

  RooCategory nptag("nptag","nptag");
  nptag.defineType("nonp",0);
//  argset.add(nptag);

  RooRealVar dz("dz","dz",dz_min,dz_max,"mm");    argset.add(dz);
  RooRealVar sz_asc("sz_asc","dz_asc",0.01,0.15); argset.add(sz_asc);
  RooRealVar sz_sig("sz_sig","dz_sig",0.01,0.15); argset.add(sz_sig);
  RooRealVar chisq_z_asc("chisq_z_asc","chisq_z_asc",0.,200); argset.add(chisq_z_asc);
  RooRealVar chisq_z_sig("chisq_z_sig","chisq_z_sig",0.,200); argset.add(chisq_z_sig);

//  RooDataSet pids("pids","pids",pitree,argset);
  RooDataSet omegads("omegads","omegads",omegatree,argset,"(dz>0 || dz<0) && sz_asc>0 && sz_sig>0 && chisq_z_asc>0 && chisq_z_sig>0");
//  pids.Print();
  omegads.Print();

  RooRealVar tau("tau","tau",0.196,0.01,1,"mm"); tau.setConstant(kTRUE);
  RooRealVar dz0Om("dz0Om","dz0Om",0,-3.,3.,"mm"); dz0Om.setConstant(kTRUE);
  RooRealVar s01sigOm("s01sigOm","s01sigOm",2,0.1,5.);
  RooRealVar s02sigOm("s02sigOm","s02sigOm",13,0.1,27.);
  RooRealVar fsigOm("fsigOm","fsigOm",0.9,0.,1.);

//  RooGaussModel g1Om("g1Om","g1Om",dz,dz0Om,s01Om,sz);
//  RooGaussModel g2Om("g2Om","g2Om",dz,dz0Om,s02Om,sz);
  RooDecay dec1SigOm("dec1SigOm","dec1SigOm",dz,tau,g1sigOm,RooDecay::DoubleSided);
  RooDecay dec2SigOm("dec2SigOm","dec2SigOm",dz,tau,g2sigOm,RooDecay::DoubleSided);
  RooAddPdf pdfsigOm("pdfsigOm","pdfsigOm",RooArgList(dec1SigOm,dec2SigOm),RooArgSet(fsigOm));
  if(EXP!=55 && EXP>0){
    fsigOm.setVal(1.);
    fsigOm.setConstant(kTRUE);
    s02sigOm.setConstant(kTRUE);
  }
//  RooDecay pdfsigOm("pdfsigOm","pdpsigOm",z_sig,tau,g1sigOm,RooDecay::SingleSided);

//  pdfsigPi.fitTo(pids,ConditionalObservables(szSigPi));
  RooFitResult* fitRes = pdfsigOm.fitTo(omegads,Verbose(),ConditionalObservables(sz_asc));
//  fitRes->Print();

///////////
// Plots //
///////////
  RooPlot* zFrameSig = z_asc.frame();

  omegads.plotOn(zFrameSig,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdfsigOm.plotOn(zFrameSig,LineColor(kRed),ProjWData(omegads));
  TCanvas* z_cm_sig = new TCanvas("z_{sig}, cm","z_{sig}, mm",700,500);
  z_cm_sig->cd();
  omegads.statOn(zFrameSig,Layout(0.6,0.98,0.9),What("MR"),Label("#omega^{0}"),Format("NE",AutoPrecision(1)));
  TPad *pad1 = new TPad("pad1","pad1",0.01,0.00,0.99,0.99);
  pad1->Draw();
  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);
  zFrameSig->GetXaxis()->SetTitleOffset(0.75);
  zFrameSig->GetXaxis()->SetLabelSize(0.05);
  zFrameSig->GetXaxis()->SetTitleSize(0.06);
  zFrameSig->GetYaxis()->SetTitleOffset(1.6);
  zFrameSig->Draw();
  z_cm_sig->Update();
  stringstream out;
  out.str("");
  out << "pics/zAscFit_Exp" << EXP << ".png";
  z_cm_sig->Print(out.str().c_str());
  out.str("");
  out << "pics/zAscFit_Exp" << EXP << ".root";
  z_cm_sig->Print(out.str().c_str());

  return;
}
Esempio n. 12
0
double FitInvMassBkg_v3(TH1D* histo, TH1D* histo_bkg, TString signal = "CBxBW",TString _bkg = "Cheb", TString option = ""){


	//Set Style
	setTDRStyle();

	if(option.Contains("nentries")){return histo->GetEntries()-histo_bkg->GetEntries();}
	else{

	//Getting info about the histogram to fit
	int n = histo->GetEntries();
	double w = histo->GetXaxis()->GetBinWidth(1);
	int ndf;
	double hmin0 = histo->GetXaxis()->GetXmin();
	double hmax0 = histo->GetXaxis()->GetXmax();
	histo->GetXaxis()->SetRangeUser(hmin0,hmax0);

	//Declare observable x
	//Try to rebin using this. Doesn't work for now
        //RooBinning xbins = Rebin2(histo);
	RooRealVar x("x","x",hmin0,hmax0) ;
	RooDataHist dh("dh","dh",x,Import(*histo)) ;

	//Define the frame
	RooPlot* frame;
	frame = x.frame();
	dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7));  //this will show histogram data points on canvas

	//x.setRange("R0",0,200) ;
	x.setRange("R1",55,200) ;
	x.setRange("D",55,120) ;

        /////////////////////
	//Define fit function 
	/////////////////////
	cout<<"Debug4"<<endl;
	
	//fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x)
	//RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.);
	RooRealVar nsig("nsig","signal events",histo->GetEntries()/2., 1,histo->GetEntries());
	RooRealVar nbkg("nbkg","background events",histo_bkg->GetEntries()/2.,1,histo_bkg->GetEntries());
	RooArgList pdfval(nsig,nbkg);

	//Various parameters
	
	//True mean
	RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0);
	//For the BW
	RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.);
	//For the Gauss and the CB alone 
	RooRealVar sigma("sigma","sigma",1, 0., 10.);
	RooRealVar alpha("alpha","alpha",0.7, 0., 7);
	RooRealVar ncb("ncb","ncb",7, 0, 150);
	//For the CB used for convolution, i.e. CBxBW
	RooRealVar cb_bias("cb_bias","bias",0, -3.,3.);
	RooRealVar cb_sigma("cb_sigma","response",1, 0.,5);
	RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7);
	RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10);
	//Gauss used for convolution
	RooRealVar gau_bias("gau_bias","alpha",0, -3., 3.);
	RooRealVar gau_sigma("gau_sigma","bias",1, 0., 7.);
	cout<<"Debug5"<<endl;

	mean.setRange(88,94);
	width.setRange(0,20);
	sigma.setRange(0.5,10);
	//fsig.setConstant(kTRUE);
	//alpha.setConstant(kTRUE);

	RooVoigtian sig_voigtian("sig_voigtian","Voigtian",x,mean,width,sigma);
	RooBreitWigner sig_bw("sig_bw","BW",x,mean,width);
	//RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma);
	RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb);
	RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb);
	RooGaussian sig_gau_resp("sig_gau_resp", "Gaussian for conv.",x,gau_bias,gau_sigma);

	x.setBins(10000,"cache");
	RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw);
	RooFFTConvPdf sig_bwgau("sig_bwgau","BWxGau",x,sig_bw,sig_gau_resp);

	//NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. 
	cout<<"Debug6"<<endl;

	RooAbsPdf* sig;
	if(signal == "Vo"){sig = &sig_bwgau;}
	else if(signal == "BW"){sig = &sig_bw;}
	//else if(signal == "Gau"){sig = &sig_gau;}
	else if(signal == "CB"){sig = &sig_cb;}
	else if(signal == "CBxBW"){ sig = &sig_cbbw;}
	else if(signal == "BWxGau"){ sig = &sig_bwgau;}
	else{ cout<<"Wrong signal function name"<<endl;
		return 1;
	}

	/////////////////////////////
	//Background fitting function
	/////////////////////////////
	
	//Get the initial parameter of the background
	//


	cout<<"Debug7"<<endl;
	vector<double> vec = FitBkg(histo_bkg,_bkg);

	//Chebychev
	RooRealVar a0("a0","a0",vec[0],-5.,0.) ;
	RooRealVar a1("a1","a1",vec[1],-2.5,1.2) ;
	RooRealVar a2("a2","a2",vec[2],-1.5,1.) ;
	RooRealVar a3("a3","a3",vec[3],-3,1.) ;
	RooRealVar a4("a4","a4",vec[4],-1.5,1.) ;
	RooRealVar a5("a5","a5",vec[5],-1.,1.) ;
	RooRealVar a6("a6","a6",vec[6],-1.,1.) ;

	RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6));

	//Novo

	RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250);
	RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ;
	RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ;

	RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg);

	RooAbsPdf* bkg;

	if(_bkg == "Cheb"){bkg = &bkg_cheb;}
	if(_bkg == "Novo"){bkg = &bkg_nov;}


	//////////////////////////
	//Adding the two functions
	//////////////////////////
	
	//RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig);
	RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),pdfval);
	 
	//Perform the fit
	RooAbsPdf* fit_func;
	fit_func = &model;
	
	RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr");
	fit_func->plotOn(frame);
	fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed));
	fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen));
	frame->SetAxisRange(50,120);
	frame->Draw();
	fit_func->paramOn(frame); 
	dh.statOn(frame);  //this will display hist stat on canvas

	frame->SetTitle(histo->GetTitle());  
	frame->GetXaxis()->SetTitle("m (in GeV/c^{2})");  
	frame->GetXaxis()->SetTitleOffset(1.2);
	float binsize = histo->GetBinWidth(1); 

	//Store result in .root file
	frame->SetName(histo->GetName());
	frame->Write();

	///////////////////////
	//Plot the efficiency//
	///////////////////////
	
	//Old stuff
	
	//ofstream myfile;
	//myfile.open("/Users/GLP/Desktop/integrals.txt");
	//This one doesn't take the normalisation into account !
	//myfile<<"integral 1 "<<histo->GetName()<<endl;
	////Integral of sig
	//RooAbsReal* integral_sig = sig->createIntegral(x,x,"D") ;
	//myfile<<fsig.getVal()*integral_sig->getVal()<<endl;
	//Integral of sig+bkg
	//RooAbsReal* total = fit_func->createIntegral(x, NormSet(x), Range("D")) ;
	//Integral of sig only
	//RooAbsReal* background = bkg->createIntegral(x, NormSet(x), Range("D"));
	//cout<<"The total integral is"<<n*total->getVal();
	//cout<<"The bkg integral is"<<n*bkg->getVal();
	//cout<<"The bkg with the fsig is"<<fsig.getVal()*n*bkg->getVal();
	//cout<<"The returned value is"<<n*(total->getVal()-fsig.getVal()*background->getVal());
	//myfile<<"integral 2 "<<endl;
	//myfile<<n*(total->getVal()-(1-fsig.getVal())*background->getVal())<<endl;
	//myfile.close();
	//return n*(total->getVal()-(1-fsig.getVal())*background->getVal());
	
	return nsig.getVal();
	
	}
}
void test(int numbersigmas = 0, Bool_t debugtest = true)
{

    using namespace RooFit;
    using namespace std;

    TCanvas *canvas = new TCanvas("canvas","canvas",900,100,500,500);

    gSystem->Load("libRooFit");
    gSystem->AddIncludePath("-I$ROOFITSYS/include");


    float ptbinsarray[] = {20.,40.,60.,80.,100.,120.,200.,600.};

    std::vector<float> ptbins(ptbinsarray,ptbinsarray+sizeof(ptbinsarray)/sizeof(ptbinsarray[0]));

    std::vector<std::vector<float> > allbins;
    allbins.push_back(ptbins);

    std::vector<TString> VarString;
    VarString.push_back("VsPt");

    std::vector<TString> HistoNameString;
    HistoNameString.push_back("ptbin");

    std::vector<TString> GraphXTitleString;
    GraphXTitleString.push_back("p_{t} (GeV)");

    std::vector<TString> SideBandDefinitions;
    SideBandDefinitions.push_back("SideBand5_10");



    //   ------------FOR TESTING----------------
    unsigned int sidebandloopmax = 1;//5_10, 5_20, ...
    unsigned int templatevarsloopmax = 1;//sinin with conv safe veto, sinin, ch isol
    unsigned int binsloopmax = 1;//pt, eta, phi, pu

    //----------Open .root Templates

    //All the Jet Templates
    TFile *histojetfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/TemplateHistosJetCheckBinsEndcapsLoose.root");
    //TFile *histojetdenfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Denominator_FREndCaps.root");
// TFile *histojetdatafile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Num_Templates.root");

    //Real Photon Templates
    TFile *historealmcfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/RealPhotonTemplatesEndCaps.root");

    //--- Write NEW .root Historams for Fake Rate
    TFile *FRhistosfile = new TFile("FakeRatePlotsCheckBins.root","recreate");

    //loop on error systematics

    for(unsigned int m = 0; m<templatevarsloopmax; m++) {
        for(unsigned int l = 0; l<binsloopmax; l++) {


            TMultiGraph *mg = new TMultiGraph();
            TLegend *legendAllGraphs = new TLegend(0.37,0.59,0.57,0.79);
            legendAllGraphs->SetTextSize(0.02);
            legendAllGraphs->SetFillColor(kWhite);
            legendAllGraphs->SetLineColor(kWhite);


            std::vector<float> fakeratevalues;
            std::vector<float> fakerateptvalues;
            std::vector<float> fakerateerrorvalues;

            for(unsigned int k = 0; k<allbins[0].size()-1; k++) {
// for(unsigned int k = 0;k<1;k++){
                float binlow = allbins[0][k];
                float binmax = allbins[0][k+1];

                TString binstring = TString::Format("%4.2f_%4.2f",binlow,binmax);
                binstring.ReplaceAll(".00","");
                binstring.ReplaceAll("-","m");
                binstring.ReplaceAll(".","p");
                binstring.ReplaceAll("10000","Inf");
                cout<<binstring.Data()<<endl;

                //Histograms for templates
                //Get histograms from each of the histojetfiles declared earlier

                //Numerator Fakes - FakePhotonNumEndCaps.root - FakePhoton_num2040...
                TH1F *h1 = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedFakeJetptbin"+binstring).Data());// .Data() changes to char*
                h1->Print();

                //Numerator Real Photons - RealPhotonTemplatesEndCaps.root - EndCapsMCReal_20_40
                TH1F *h2 = (TH1F*)historealmcfile->Get(("EndCapsMCReal_"+binstring).Data());
                h2->Print();

                //Numerator Templates - Num_Templates.root - num2040...
                TH1F *hData = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedDataJetptbin"+binstring).Data());
                hData->Print();

                //Denominator Templates - Denominator_FREndCaps.root -FakePhoton_den2040...
                TH1F *hnum = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedTightAndFakeJetptbin"+binstring).Data());
                hnum->Print();

                //avoiding 0 entries in the histograms
                //fake and real mc histos are the most critical
                for(int bincount = 1; bincount <= h1->GetNbinsX(); bincount++) {
                    if(h1->GetBinContent(bincount) == 0.) h1->SetBinContent(bincount,1.e-6);
                }
                for(int bincount = 1; bincount <= h2->GetNbinsX(); bincount++) {
                    if(h2->GetBinContent(bincount) == 0.) h2->SetBinContent(bincount,1.e-6);
                }

                int ndataentries = hData->GetEntries();

                float sininmin = 0.; //? sigmaIetaIeta
                float sininmax = 0.1; //? sigmaIetaIeta

                // ----------------- Probability Density Function

                TString roofitvartitle = "#sigma_{i #eta i #eta}";

                RooRealVar sinin("sinin",roofitvartitle.Data(),sininmin,sininmax);
                sinin.setRange("sigrange",0.018,0.06); //? this is the range because? Need to recall.
                //sinin.setRange("sigrange",0.005, 0.011);

                //Fake Template pdf
                RooDataHist faketemplate("faketemplate","fake template",sinin,h1);
                RooHistPdf fakepdf("fakepdf","test hist fake pdf",sinin,faketemplate);

                //Real Template pdf
                RooDataHist realtemplate("realtemplate","real template",sinin,h2);
                RooHistPdf realpdf("realpdf","test hist real pdf",sinin,realtemplate);

                //Data to be fitted to
                RooDataHist data("data","data to be fitted to",sinin,hData);


                //Declaration of Variables for Fake Rate
                RooRealVar fsig("fsig","signal fraction",0.1,0,1);//

                RooRealVar signum("signum","signum",0,ndataentries);// #of real contamination
                RooRealVar fakenum("fakenum","fakenum",0,ndataentries); //# of fake

                //Extend
                RooExtendPdf extpdfsig("Signal","extpdfsig",realpdf,signum,"sigrange");
                RooExtendPdf extpdffake("Background","extpdffake",fakepdf,fakenum,"sigrange");

                RooAddPdf model("model","sig + background",RooArgList(extpdfsig,extpdffake));


                //----------- FITTING TO DATA -------------------
                model.fitTo(data,RooFit::Minos());

                //Define Plot Frame
                RooPlot *xframe = sinin.frame();
                xframe->SetTitle("");

                data.plotOn(xframe);
                model.plotOn(xframe);
                model.plotOn(xframe,Components(extpdfsig),LineColor(2),LineStyle(2));
                model.plotOn(xframe,Components(extpdffake),LineColor(8),LineStyle(2));

                canvas->cd();
                canvas->SetGridx(true);
                canvas->SetGridy(true);

                xframe->GetXaxis()->SetRangeUser(0.,0.1);
                float xframemax = xframe->GetMaximum();
                xframe->GetYaxis()->SetRangeUser(1.e-1,1.1*xframemax);

                xframe->Draw();

                // ----- DEFINE LEGENDS and their position
                TLegend *legend = new TLegend(0.62,0.65,0.82,0.85); //Why these values?
                legend->SetTextSize(0.02);
                legend->SetFillColor(kWhite);
                legend->SetLineColor(kWhite);

                //Legend Header which tells the bin
                TString legendheader = "Pt (GeV):["+ binstring;

                legendheader.ReplaceAll("_",",");
                legendheader.ReplaceAll("m","-");
                legendheader.ReplaceAll("p",".");
                legendheader.Append("]");

                cout<<"legend "<<legendheader.Data()<<endl;
                legend->SetHeader(legendheader.Data());

                TObject *objdata;  //What is TObect?
                TObject *objmodel;
                TObject *objsignal;
                TObject *objfake;

                for(int i=0; i<xframe->numItems(); i++) {
                    cout<<xframe->nameOf(i)<<endl;
                    TString objname = xframe->nameOf(i);
                    if(objname.Contains("data")) objdata = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && !objname.Contains("Comp")) objmodel = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && objname.Contains("Signal")) objsignal = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && objname.Contains("Background")) objfake = (TObject*)xframe->findObject(objname.Data());
                }

                //------ LEGEND --------
                legend->AddEntry(objdata,"Data","lp");
                legend->AddEntry(objsignal,"Signal","l");
                legend->AddEntry(objfake,"Background","l");
                legend->AddEntry(objmodel,"Signal + Background","l");
                legend->Draw("same");//make them overlap for comparison

                canvas->Print(("Endcapfits"+binstring+".png").Data());
                canvas->Print(("TemplateFitResultEndcap"+binstring+".C").Data());

                float fakevalue = fakenum.getValV();
                float fakeerrorhi = fakenum.getErrorHi();
                float fakeerrorlo = fakenum.getErrorLo();
                float fakeerrormax = max(fabs(fakeerrorhi),fabs(fakeerrorlo));
                TString fakeresults = TString::Format("Fake results %f +%f %f",fakevalue,fakeerrorhi,fakeerrorlo);

                canvas->SetLogy(0);

                float sigvalue = signum.getValV();
                float sigerrorhi = signum.getErrorHi();
                float sigerrorlo = signum.getErrorLo();
                float sigerrormax = max(fabs(sigerrorhi),fabs(sigerrorlo));
                TString sigresults = TString::Format("Signal results %f +%f %f",sigvalue,sigerrorhi,sigerrorlo);

                cout<<"sigvalue "<<sigvalue<<" sigerrormax "<<sigerrormax<<" sigerrormax/sigvalue "<<sigerrormax/sigvalue<<endl;
                cout<<"fakevalue "<<fakevalue<<" fakeerrormax "<<fakeerrormax<<" fakeerrormax/fakevalue "<<fakeerrormax/fakevalue<<endl;

                cout<<fakeresults.Data()<<endl;
                cout<<sigresults.Data()<<endl;

                float Ratio = (fakevalue/(fakevalue+sigvalue));
                float RatioError = Ratio*sqrt( ((fakeerrormax/fakevalue)*(fakeerrormax/fakevalue) + (sigerrormax/sigvalue)*(sigerrormax/sigvalue)) );
                cout<<"Ratio "<<Ratio<<" +- "<<RatioError<<endl;

                //---------------------- FAKE RATE CALCULATOR -------------------------
                //find the bin corresponding to 0.011
                //int binnr = 22;
                int binnr = 34;


                //compute the integral of tight and fake in that range
                float numerator = hData->Integral(0,binnr); //Is the Integral function part of RooFit?
                float denominator = hnum->Integral();


                float contamination = sigvalue;
                cout<<numerator<<" "<<denominator<<" "<<contamination<<endl;

                float fakerate = (numerator-contamination)/denominator;
                float fakerateerror = fakerate * sqrt( (1./numerator) + (1./denominator) + ((sigerrormax/sigvalue)*(sigerrormax/sigvalue)) );

                cout<<"Here: "<<fakerate<<" "<<fakerateerror<<endl;

                //fakerateptvalues.push_back(hnumvspt->GetMean());
                fakeratevalues.push_back(fakerate);
                fakerateerrorvalues.push_back(fakerateerror);

                cout<<""<<endl;
                cout<<"***********************************************************"<<endl;
                cout<<"So in sigmaietaieta < 0.011 there are "<<contamination<<" to subtract from "<<numerator<<endl;
                cout<<"and thus there are "<<(numerator-contamination)<<" total tight entries "<<endl;
                cout<<"and there are "<<denominator<<" entries in the tight and fake sample "<<endl;
                cout<<"and so the fake rate for the pt range "<<binlow<<"-"<<binmax<<" is "<<fakerate<<"+-"<<fakerateerror<<endl;
                cout<<"***********************************************************"<<endl;
                cout<<""<<endl;

            }//loop on all bins


            /*
            	  cout<<fakeratevalues.size()<<endl;
            	  for(int k=0;k<fakeratevalues.size();k++){
            	    cout<<"Range: ["<<allbins[l][k]<<"-"<<allbins[l][k+1]<<"] --> fake rate: ("<<fakeratevalues[k]*100<<" +- "<<fakerateerrorvalues[k]*100<<")%"<<endl;
            	  }//end of loop over all fake rate values


                // *************************************************************-//

                //
            	  TGraphErrors *FRgraph = new TGraphErrors(fakeratevalues.size());
            	  for(int k=0;k<fakeratevalues.size();k++){
            	    cout<<(allbins[l][k+1]+allbins[l][k])/2.<<endl;
            	    FRgraph->SetPoint(k,(allbins[l][k+1]+allbins[l][k])/2.,fakeratevalues[k]);
            	    FRgraph->SetPointError(k,(allbins[l][k+1]-allbins[l][k])/2.,fakerateerrorvalues[k]);
            	  }//end of filling TGraph

               //// FRGraph->SetName(FakeRate.Data());
            	  FRgraph->SetTitle("");

            	  canvas->cd();
                canvas->SetLogy(0);
            	  FRgraph->Draw("a*");


                // **********************************************************-//



                 //  *****************************************

            	  //float maxFRvalue = max_element(fakeratevalues.begin(),fakeratevalues.end());
            	  FRgraph->GetYaxis()->SetRangeUser(0.,0.2);
            	  FRgraph->GetYaxis()->SetTitle("#epsilon_{FR}");
            	  FRgraph->GetXaxis()->SetTitle((GraphXTitleString[l]).Data());

                TString FakeRateFunctionName = "
                TF1 *FRfunc = new TF1(FakeRateFunctionName.Data(),"[0]+[1]/pow(x,[2])", allbins[l][0],allbins[l][fakeratevalues.size()]);
                FRfunc->SetParameters(1.,1.,1.);
                if(l==0){
            	    FRgraph->Fit(FakeRateFunctionName.Data(),"R");
            	    FRgraph->Fit(FakeRateFunctionName.Data());
            	    FRfunc->Draw("same");
            	  }


                // ********************************************
            	  cout<<"***** Fit function parameters *****"<<endl;
            	  cout<<FRfunc->GetParameter(0)<<" "
            	      <<FRfunc->GetParameter(1)<<" "
            	      <<FRfunc->GetParameter(2)<<" "
            	      <<endl;

            	  cout<<"***** Fit function errors *****"<<endl;
            	  cout<<FRfunc->GetParError(0)<<" "
            	      <<FRfunc->GetParError(1)<<" "
            	      <<FRfunc->GetParError(2)<<" "
            	      <<endl;

            	  if(!debugtest){
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.png").Data(),"png");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.gif").Data(),"gif");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.eps").Data(),"eps");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoos.pdf").Data(),"pdf");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.C").Data(),"cxx");
            	  }

                canvas->Print(("FakeRateEndCaps.png").Data(),"png");
                canvas->Print(("FakeRateEndCaps.C").Data(),"cxx");
                // ************************************************

            	  if(!debugtest){
            	    if(count == 0){
            	      FRhistosfile->cd();
            	      FRgraph->Write();
            	      FRfunc->Write();
            	    }
            	  }
            	  if(numbersigmas != 0){
            	    FRgraph->SetLineColor(count+numbersigmas+1);
            	    FRgraph->SetMarkerColor(count+numbersigmas+1);
            	    TString numsigmastring = TString::Format("%d #sigma",count);
            	    legendAllGraphs->AddEntry(FRgraph,numsigmastring.Data(),"lep");
            	  }

            	  mg->Add(FRgraph);*/
//	}//end of loop over systematic errors


            if(numbersigmas != 0) {
                mg->Draw();
                legendAllGraphs->Draw("same");
            }

        }//end of loop over all variables (pt, eta, phi, pu)

    }//end of loop over template variables

    histojetfile->cd();
    histojetfile->Close();

    historealmcfile->cd();
    historealmcfile->Close();

    FRhistosfile->cd();
    FRhistosfile->Close();

// }//end of loop over sideband definitions

}//end of method
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================    
  TRandom3 *randomnumber = new TRandom3(seed);
//   RooRealVar m("m","mass",60,130);

  RooCategory sample("sample","");
  sample.defineType("Pass",1);
  sample.defineType("Fail",2);

  //--------------------------------------------------------------------------------------------------------------
  //Load Workspace
  //==============================================================================================================    
  TFile *f = new TFile (workspaceFile.c_str(), "READ");
  RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace");

  //--------------------------------------------------------------------------------------------------------------
  //Setup output tree
  //==============================================================================================================    
  TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE");
  float varEff = 0;
  float varEffErrL = 0;
  float varEffErrH = 0;
  TTree *outTree = new TTree("eff","eff");
  outTree->Branch("eff",&varEff, "eff/F");
  outTree->Branch("efferrl",&varEffErrL, "efferrl/F");
  outTree->Branch("efferrh",&varEffErrH, "efferrh/F");
  
  //--------------------------------------------------------------------------------------------------------------
  //Load Model
  //==============================================================================================================    
  RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf");
  RooRealVar *m_default = (RooRealVar*)w->var("m");
  m_default->setRange("signalRange",85, 95);
  
  //get default models
  RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass");
  RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail");

  //get variables
  RooRealVar *Nsig = (RooRealVar*)w->var("Nsig");
  RooRealVar *eff = (RooRealVar*)w->var("eff");
  RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail");

  RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig));	 
  RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig));

  //get number of expected events
  Double_t npass = 100;
  Double_t nfail = 169;

  //*************************************************************************************
  //make alternative model
  //*************************************************************************************
  RooRealVar *tFail_default = (RooRealVar*)w->var("tFail");
  RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail");
 

  RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail");
  RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail");
  RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail");
  RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail");
  RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail");
  RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail");
  RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail");
  RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail");
  RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail");
  RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail");

  //shifted mean
  RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5);
  meanFail_shifted->setVal(meanFail_default->getVal());
  if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0);
  else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0);  
  else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0);
  else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0);  

  RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5);
  sigmaFail_shifted->setVal(sigmaFail_default->getVal());
  if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2);
  else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8);

  CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted");
  bkgFailModel->t->setVal(tFail_default->getVal());
  bkgFailModel->frac->setVal(fracFail_default->getVal());

  cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl;
  cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl;
  cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl;
  cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl;
  
  cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl;
  cout << "NbkgFail: " << NbkgFail->getVal() << endl;


  //make alternative fail model
  RooAddPdf *modelFail=0;
  RooExtendPdf *esignalFail=0, *ebackgroundFail=0;
  ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange");
  modelFail       = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail));



  cout << "*************************************\n";
  ebackgroundFail->Print();
  cout << "*************************************\n";
  ebackgroundFail_default->Print();
  cout << "*************************************\n";
  modelFail->Print();
  cout << "*************************************\n";
  modelFail_default->Print();
  cout << "*************************************\n";

  TCanvas *cv = new TCanvas("cv","cv",800,600);

  RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail_default->plotOn(mframeFail_default);
  modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
  modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail_default->GetYaxis()->SetTitle("");
  mframeFail_default->GetYaxis()->SetTitleOffset(1.2);
  mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail_default->GetXaxis()->SetTitleOffset(1.05);
  mframeFail_default->SetTitle("");
  mframeFail_default->Draw();

  cv->SaveAs("DefaultModel.gif");

  RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail->plotOn(mframeFail);
  modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
  modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail->GetYaxis()->SetTitle("");
  mframeFail->GetYaxis()->SetTitleOffset(1.2);
  mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail->GetXaxis()->SetTitleOffset(1.05);
  mframeFail->SetTitle("");
  mframeFail->Draw();
  cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


  //*************************************************************************************
  //Do Toys
  //*************************************************************************************
  for(uint t=0; t < NToys; ++t) {

    RooDataSet *pseudoData_pass    = modelPass_default->generate(*m_default, randomnumber->Poisson(npass));
    RooDataSet *pseudoData_fail  = 0;
    pseudoData_fail    = modelFail->generate(*m_default, randomnumber->Poisson(nfail));
    RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default),
                                                    RooFit::Index(sample),
                                                    RooFit::Import("Pass",*pseudoData_pass),
                                                    RooFit::Import("Fail",*pseudoData_fail));

    pseudoDataCombined->write(Form("toy%d.txt",t));

    RooFitResult *fitResult=0;
    fitResult = totalPdf->fitTo(*pseudoDataCombined,
                                RooFit::Extended(),
                                RooFit::Strategy(2),
                                //RooFit::Minos(RooArgSet(eff)),
                                RooFit::Save());

    cout << "\n\n";
    cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl;

    //Fill Tree
    varEff = eff->getVal();
    varEffErrL = fabs(eff->getErrorLo());
    varEffErrH = eff->getErrorHi();
    outTree->Fill();


//   //*************************************************************************************
//   //Plot Toys
//   //*************************************************************************************
//   TCanvas *cv = new TCanvas("cv","cv",800,600);
//   char pname[50];
//   char binlabelx[100];
//   char binlabely[100];
//   char yield[50];
//   char effstr[100];
//   char nsigstr[100];
//   char nbkgstr[100];
//   char chi2str[100];

//   //
//   // Plot passing probes
//   //

//   RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2));
//   modelFail_default->plotOn(mframeFail_default);
//   modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
//   modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
//   mframeFail_default->Draw();
//   cv->SaveAs("DefaultModel.gif");





//   RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2));
//   modelFail->plotOn(mframeFail);
//   modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
//   modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));

//   sprintf(yield,"%u Events",(Int_t)passTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult));
//     plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);
//     plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str);

//   mframeFail->Draw();
//   cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


 
//   //
//   // Plot failing probes
//   //
//   sprintf(pname,"fail%s_%i",name.Data(),ibin);
//   sprintf(yield,"%u Events",(Int_t)failTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult));
//   sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult));
//   sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail));
//   CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}");
//   plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1);
//   if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) {
//     plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1);    
//     plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   } else {
//     plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1);
//   }
//   plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);  
//   plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str);
//   plotFail.Draw(cfail,kTRUE,format);  




  } //for loop over all toys
  



  //*************************************************************************************
  //Save To File
  //*************************************************************************************
  outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete");

}
Esempio n. 15
0
void plotPdf_7D_VWW(double mH=125) {
    
    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    TGaxis::SetMaxDigits(3);
    gROOT->ForceStyle();
    

    // Declaration of the PDFs to use
    gROOT->ProcessLine(".L PDFs/RooSpinOne_7D.cxx++");
    
    // W/Z mass and decay width constants
    double mV = 80.399;
    double gamV = 2.085;
    bool offshell = false;
    if ( mH < 2 * mV ) offshell = true;

    // for the pole mass and decay width of W 
    RooRealVar* mX = new RooRealVar("mX","mX", mH);
    RooRealVar* mW = new RooRealVar("mW","mW", mV);
    RooRealVar* gamW = new RooRealVar("gamW","gamW",gamV);

    //
    // Observables (7D)
    // 
    RooRealVar* wplusmass = new RooRealVar("wplusmass","m(W+)",mV,1e-09,120);
    wplusmass->setBins(50);
    RooRealVar* wminusmass = new RooRealVar("wminusmass","m(W-)",mV,1e-09,120);
    wminusmass->setBins(50);
    RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
    hs->setBins(20);
    RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());
    Phi1->setBins(20);
    RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
    h1->setBins(20);
    RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
    h2->setBins(20);
    RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
    Phi->setBins(20);
    
    // 1-
    RooRealVar* g1ValV = new RooRealVar("g1ValV","g1ValV",1.);
    RooRealVar* g2ValV = new RooRealVar("g2ValV","g2ValV",0.);
    // Even more parameters, do not have to touch, based on W couplings
    RooRealVar* R1Val = new RooRealVar("R1Val","R1Val",-1.);
    RooRealVar* R2Val = new RooRealVar("R2Val","R2Val",-1.);
    
    // these are the acceptance terms associated with the production angles
    // the default setting is for setting no-acceptance
    RooRealVar* aParam = new RooRealVar("aParam","aParam",0);
    
    RooSpinOne_7D *myPDFV;

    if ( offshell ) 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1, 
				 *g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFV = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1, 
				*g1ValV, *g2ValV, *R1Val, *R2Val, *aParam, *mW, *gamW);
    
    // Grab input file to convert to RooDataSet
    TFile* finV = new TFile(Form("VWW_%.0f_JHU.root", mH));
    TTree* tinV = (TTree*) finV->Get("angles");
    if ( offshell ) 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*wplusmass, *wminusmass, *h1,*h2, *hs, *Phi, *Phi1));
    else 
      RooDataSet dataV("dataV","dataV",tinV,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    
    for (int i=1;i<1;i++) {
      RooArgSet* row = dataV.get(i);
      row->Print("v");
    }
    

    // 
    // 1+
    // 
    RooRealVar* g1ValA = new RooRealVar("g1ValA","g1ValA",0);
    RooRealVar* g2ValA = new RooRealVar("g2ValA","g2ValA",1);
    RooSpinOne_7D *myPDFA;
    
    if ( offshell ) 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);
    else 
      myPDFA = new RooSpinOne_7D("myPDF","myPDF", *mX, *mW, *mW, *h1, *h2, *hs, *Phi, *Phi1,
				 *g1ValA, *g2ValA, *R1Val, *R2Val, *aParam, *mW, *gamW);

    TFile* finA = new TFile(Form("AVWW_%.0f_JHU.root", mH));
    TTree* tinA = (TTree*) finA->Get("angles");
    if ( offshell ) 
      RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
     else 
       RooDataSet dataA("dataA","dataA",tinA,RooArgSet(*h1,*h2, *hs, *Phi, *Phi1));
    //
    // P L O T   . . .  
    // 

    bool drawv = true;
    bool drawa = true;
    bool drawpaper = true;

    double rescale = 1.0;
    if (drawpaper ) 
      rescale = 0.001;


    // for 1-
    TH1F* dum0 = new TH1F("dum0","dum0",1,0,1); dum0->SetLineColor(kRed); dum0->SetMarkerColor(kBlack); dum0->SetLineWidth(3);
    // for 1+
    TH1F* dum1 = new TH1F("dum1","dum1",1,0,1); dum1->SetLineColor(kBlue); dum1->SetMarkerColor(kBlack); dum1->SetMarkerStyle(24), dum1->SetLineWidth(3);
    TLegend * box3 = new TLegend(0.1,0.1,0.9,0.92);
    box3->SetFillColor(0);
    box3->SetBorderSize(0);
    if ( drawa ) 
      box3->AddEntry(dum0,"X#rightarrow WW JP = 1+","lp");
    if ( drawv )
    box3->AddEntry(dum1,"X#rightarrow WW JP = 1-","lp");

    // 
    //  h1
    // 
    RooPlot* h1frame =  h1->frame(20);
    h1frame->GetXaxis()->CenterTitle();
    h1frame->GetYaxis()->CenterTitle();
    h1frame->GetYaxis()->SetTitle(" ");

    double ymax_h1;
    TH1F *h1a = new TH1F("h1a", "h1a", 20, -1, 1);
    tinA->Project("h1a", "costheta1");
    ymax_h1 = h1a->GetMaximum();

    TH1F *h1_minus = new TH1F("h1_minus", "h1_minus", 20, -1, 1);
    tinV->Project("h1_minus", "costheta1");
    ymax_h1 = h1_minus->GetMaximum() > ymax_h1 ? h1_minus->GetMaximum() : ymax_h1;
    
    if ( drawa ) {
      dataA.plotOn(h1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      // tempoary
      dataV.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.)
      h1frame->GetYaxis()->SetRangeUser(0, ymax_h1 / 1000. * 1.3);

    
    // 
    //  h2
    // 
    
    RooPlot* h2frame =  h2->frame(20);
    h2frame->GetXaxis()->CenterTitle();
    h2frame->GetYaxis()->CenterTitle();
    h2frame->GetYaxis()->SetTitle(" ");

    double ymax_h2;
    TH1F *h2a = new TH1F("h2a", "h2a", 20, -1, 1);
    tinA->Project("h2a", "costheta2");
    ymax_h2 = h2a->GetMaximum();

    TH1F *h2_minus = new TH1F("h2_minus", "h2_minus", 20, -1, 1);
    tinV->Project("h2_minus", "costheta2");
    ymax_h2 = h2_minus->GetMaximum() > ymax_h2 ? h2_minus->GetMaximum() : ymax_h2;

    if ( drawa ) {
      dataA.plotOn(h2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(h2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), yDataError(RooAbsData::None));
      // myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1.) 
      h2frame->GetYaxis()->SetRangeUser(0, ymax_h2 / 1000. * 1.3);

    //
    // Phi
    // 
    RooPlot* Phiframe =  Phi->frame(20);
    Phiframe->GetXaxis()->CenterTitle();
    Phiframe->GetYaxis()->CenterTitle();
    Phiframe->GetYaxis()->SetTitle(" ");

    double ymax_Phi;
    TH1F *Phia = new TH1F("Phia", "Phia", 20,  -TMath::Pi(), TMath::Pi());
    tinA->Project("Phia", "phi");
    ymax_Phi = Phia->GetMaximum();

    TH1F *Phi_minus = new TH1F("Phi_minus", "Phi_minus", 20,  -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi_minus", "phi");
    ymax_Phi = Phi_minus->GetMaximum() > ymax_Phi ? Phi_minus->GetMaximum() : ymax_Phi;
    
    if ( drawa ) {
      dataA.plotOn(Phiframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phiframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phiframe->GetYaxis()->SetRangeUser(0, ymax_Phi / 1000. * 1.3);
    
    // 
    //  hs 
    // 
    RooPlot* hsframe =  hs->frame(20);

    hsframe->GetXaxis()->CenterTitle();
    hsframe->GetYaxis()->CenterTitle();
    hsframe->GetYaxis()->SetTitle(" ");

    double ymax_hs;
    TH1F *hsa = new TH1F("hsa", "hsa", 20, -1, 1);
    tinA->Project("hsa", "costhetastar");
    ymax_hs = hsa->GetMaximum();

    TH1F *hs_minus = new TH1F("hs_minus", "hs_minus", 20, -1, 1);
    tinV->Project("hs_minus", "costhetastar");
    ymax_hs = hs_minus->GetMaximum() > ymax_hs ? hs_minus->GetMaximum() : ymax_hs;
    
    if ( drawa ) {
      dataA.plotOn(hsframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(hsframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      //dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      //myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      hsframe->GetYaxis()->SetRangeUser(0, ymax_hs / 1000. * 1.3);

    
    //
    // Phi1
    // 
    RooPlot* Phi1frame =  Phi1->frame(20);
 
    Phi1frame->GetXaxis()->CenterTitle();
    Phi1frame->GetYaxis()->CenterTitle();
    Phi1frame->GetYaxis()->SetTitle(" ");

    double ymax_Phi1;
    TH1F *Phi1a = new TH1F("Phi1a", "Phi1a", 20, -TMath::Pi(), TMath::Pi());
    tinA->Project("Phi1a", "phistar1");
    ymax_Phi1 = Phi1a->GetMaximum();

    TH1F *Phi1_minus = new TH1F("Phi1_minus", "Phi1_minus", 20, -TMath::Pi(), TMath::Pi());
    tinV->Project("Phi1_minus", "phistar1");
    ymax_Phi1 = Phi1_minus->GetMaximum() > ymax_Phi1 ? Phi1_minus->GetMaximum() : ymax_Phi1;
    
    if ( drawa ) {
      dataA.plotOn(Phi1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      myPDFA->plotOn(Phi1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
    }
    if ( drawv ) {
      // dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
      // myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      dataV.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
      myPDFV->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
    }
    if ( rescale != 1. ) 
      Phi1frame->GetYaxis()->SetRangeUser(0, ymax_Phi1 / 1000. * 1.3);


    if ( offshell ) {
      RooPlot* w1frame =  wplusmass->frame(50);
      w1frame->GetXaxis()->CenterTitle();
      w1frame->GetYaxis()->CenterTitle();
      w1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w1;
      TH1F *w1a = new TH1F("w1a", "w1a", 50, 1e-09, 120);
      tinA->Project("w1a", "wplusmass");
      ymax_w1 = w1a->GetMaximum();
      
      TH1F *w1_minus = new TH1F("w1_minus", "w1_minus", 50, 1e-09, 120);
      tinV->Project("w1_minus", "wplusmass")
      ymax_w1 = w1_minus->GetMaximum() > ymax_w1 ? w1_minus->GetMaximum() : ymax_w1;
      
      if ( drawa ) {
	dataA.plotOn(w1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	// dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	// myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. )
      w1frame->GetYaxis()->SetRangeUser(0, ymax_w1 / 1000. * 1.5);

      // 
      //  wminus
      // 
      RooPlot* w2frame =  wminusmass->frame(50);

      w2frame->GetXaxis()->CenterTitle();
      w2frame->GetYaxis()->CenterTitle();
      w2frame->GetYaxis()->SetTitle(" ");
      
      double ymax_w2;
      TH1F *w2a = new TH1F("w2a", "w2a", 50, 1e-09, 120);
      tinA->Project("w2a", "wminusmass");
      ymax_w2 = w2a->GetMaximum();
      
      TH1F *w2_minus = new TH1F("w2_minus", "w2_minus", 50, 1e-09, 120);
      tinV->Project("w2_minus", "wminusmass")
      ymax_w2 = w2_minus->GetMaximum() > ymax_w2 ? w2_minus->GetMaximum() : ymax_w2;
      
      if ( drawa ) {
	dataA.plotOn(w2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFA->plotOn(w2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawv ) {
	//dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	//myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	dataV.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale*.95823), DataError(RooAbsData::None));
	myPDFV->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale*.95823));
      }
      if ( rescale != 1. ) 
	w2frame->GetYaxis()->SetRangeUser(0, ymax_w2 / 1000. * 1.5);
    }
    if ( drawpaper ) {
      TCanvas* can =new TCanvas("can","can",600,600);

      if ( offshell ) {
	w1frame->GetXaxis()->SetTitle("m_{l#nu} [GeV]");
	w1frame->Draw();
	can->Print(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.eps", mH));
	can->SaveAs(Form("paperplots/wplusmass_%.0fGeV_spin1_2in1_ww.C", mH));
      }
      
      can->Clear();
      hsframe->Draw();
      can->Print(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/costhetastar_%.0fGeV_spin1_2in1_ww.C", mH));      
      
      can->Clear();
      Phi1frame->Draw();
      can->Print(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phistar1_%.0fGeV_spin1_2in1_ww.C", mH));      

      can->Clear();
      h1frame->GetXaxis()->SetTitle("cos#theta_{1} or cos#theta_{2}");
      h1frame->Draw();
      can->Print(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.eps", mH));
      can->SaveAs(Form("paperplots/costheta1_%.0fGeV_spin1_2in1_ww.C", mH));

      can->Clear();
      Phiframe->Draw();
      can->Print(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phi_%.0fGeV_spin1_2in1_ww.C", mH));      


    }

    else {
      
      TCanvas* cww = new TCanvas( "cww", "cww", 1000, 600 );
      cww->Divide(4,2);
      if ( offshell ) {
	cww->cd(1);
	w1frame->Draw();
	cww->cd(2);
	w2frame->Draw();
      }
      cww->cd(3);
      hsframe->Draw();
      cww->cd(4);
      box3->Draw();
      cww->cd(5);
      Phi1frame->Draw();
      cww->cd(6);
      h1frame->Draw();
      cww->cd(7);
      h2frame->Draw();
      cww->cd(8);
      Phiframe->Draw();
      
      cww->Print(Form("epsfiles/angles_VWW%.0f_JHU_7D.eps", mH));
      cww->Print(Form("pngfiles/angles_VWW%.0f_JHU_7D.png", mH));
      delete cww;
    }

}
Esempio n. 16
0
void plot_pll(TString fname="monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root")
{
  SetAtlasStyle();



  TFile* file =  TFile::Open(fname);
  RooWorkspace* wspace = (RooWorkspace*) file->Get("wspace");

  cout << "\n\ncheck that eff and reco terms included in BSM component to make fiducial cross-section" <<endl;
  wspace->function("nsig")->Print();
  RooRealVar* reco = wspace->var("reco");
  if(  wspace->function("nsig")->dependsOn(*reco) ) {
    cout << "all good." <<endl;
  } else {
    cout << "need to rerun fit_withsm using DO_FIDUCIAL_LIMIT true" <<endl;
    return;
  }

  /*
  // DANGER
  // TEST WITH EXAGGERATED UNCERTAINTY
  wspace->var("unc_theory")->setMax(1);
  wspace->var("unc_theory")->setVal(1);
  wspace->var("unc_theory")->Print();
  */

  // this was for making plot about decoupling/recoupling approach
  TCanvas* tc = new TCanvas("tc","",400,400);
  RooPlot *frame = wspace->var("xsec_bsm")->frame();
  RooAbsPdf* pdfc = wspace->pdf("jointModeld");
  RooAbsData* data = wspace->data("data");
  RooAbsReal *nllJoint = pdfc->createNLL(*data, RooFit::Constrained()); // slice with fixed xsec_bsm
  RooAbsReal *profileJoint = nllJoint->createProfile(*wspace->var("xsec_bsm"));

  wspace->allVars().Print("v");
  pdfc->fitTo(*data);
  wspace->allVars().Print("v");
  wspace->var("xsec_bsm")->Print();
  double nllmin = 2*nllJoint->getVal();
  wspace->var("xsec_bsm")->setVal(0);
  double nll0 = 2*nllJoint->getVal();
  cout << Form("nllmin = %f, nll0 = %f, Z=%f", nllmin, nll0, sqrt(nll0-nllmin)) << endl;
  nllJoint->plotOn(frame, RooFit::LineColor(kGreen), RooFit::LineStyle(kDotted), RooFit::ShiftToZero(), RooFit::Name("nll_statonly")); // no error
  profileJoint->plotOn(frame,RooFit::Name("pll") );
  wspace->var("xsec_sm")->Print();
  wspace->var("theory")->Print();
  wspace->var("theory")->setConstant();
  profileJoint->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed), RooFit::Name("pll_smfixed") );

  frame->GetXaxis()->SetTitle("#sigma_{BSM, fid} [fb]");
  frame->GetYaxis()->SetTitle("-log #lambda  ( #sigma_{BSM, fid} )");
  double temp = frame->GetYaxis()->GetTitleOffset();
  frame->GetYaxis()->SetTitleOffset( 1.1* temp );

  frame->SetMinimum(1e-7);
  frame->SetMaximum(4);


  // Legend
  double x1,y1,x2,y2;
  GetX1Y1X2Y2(tc,x1,y1,x2,y2);
  TLegend *legend_sr=FastLegend(x2-0.75,y2-0.3,x2-0.25,y2-0.5,0.045);
  legend_sr->AddEntry(frame->findObject("pll"),"with #sigma_{SM} uncertainty","L");
  legend_sr->AddEntry(frame->findObject("pll_smfixed"),"with #sigma_{SM} constant","L");
  legend_sr->AddEntry(frame->findObject("nll_statonly"),"no systematics","L");
  frame->Draw();
  legend_sr->Draw("SAME");



  // descriptive text
  vector<TString> pavetext11;
  pavetext11.push_back("#bf{#it{ATLAS Internal}}");
  pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}Ldt = 20.3 fb^{-1}");
  pavetext11.push_back("#it{H}+#it{E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV");

  TPaveText* text11=CreatePaveText(x2-0.75,y2-0.25,x2-0.25,y2-0.05,pavetext11,0.045);
  text11->Draw();

  tc->SaveAs("pll.pdf");



  /*
  wspace->var("xsec_bsm")->setConstant(true);
  wspace->var("eff"     )->setConstant(true);
  wspace->var("mh"      )->setConstant(true);
  wspace->var("sigma_h" )->setConstant(true);
  wspace->var("lumi"    )->setConstant(true);
  wspace->var("xsec_sm" )->setVal(v_xsec_sm);
  wspace->var("eff"     )->setVal(1.0);
  wspace->var("lumi"    )->setVal(v_lumi);
  TH1* nllHist = profileJoint->createHistogram("xsec_bsm",100);
  TFile* out = new TFile("nllHist.root","REPLACE");
  nllHist->Write()
  out->Write();
  out->Close();
  */

}
Esempio n. 17
0
void drawMassFrom2DPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  map<string, string>  parIni,   // Variable containing all initial parameters
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the type of object to fit
                  bool incJpsi,         // Includes Jpsi model
                  bool incPsi2S,        // Includes Psi(2S) model
                  bool incBkg,          // Includes Background model                  
                  // Select the fitting options
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  double  binWidth,     // Bin width
                  bool paperStyle=false // if true, print less info
                  ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
  
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
  
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiPRName  = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiNoPRName  = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SPRName  = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SNoPRName  = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  bool isMC = (DSTAG.find("MC")!=std::string::npos);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  
  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

 
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
 
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                       FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed)
                                       );
  if (!paperStyle) {
    if (incJpsi) {
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
    }
    if (incPsi2S) {
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }      
    } 
  }
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  // Create the pull distribution of the fit 
  RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP");
  int nBinsTMP = nBins;
  RooHist *hpull = frameTMP->pullHist(0, 0, true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  frame2->addPlotable(hpull, "PX"); 
  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setMassFrom2DRange(myws, frame, dsOSName, setLogScale);
  if (paperStyle) {
     double Ydown = 0.;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } else {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;}
  else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;}
  t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); }
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); }
  if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); }
  if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); }
  if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  if (!paperStyle) {
     //---plot pull
     pad2->Draw();
     pad2->cd();

     frame2->SetTitle("");
     frame2->GetYaxis()->CenterTitle(kTRUE);
     frame2->GetYaxis()->SetTitleOffset(0.4);
     frame2->GetYaxis()->SetTitleSize(0.1);
     frame2->GetYaxis()->SetLabelSize(0.1);
     frame2->GetYaxis()->SetTitle("Pull");
     frame2->GetXaxis()->CenterTitle(kTRUE);
     frame2->GetXaxis()->SetTitleOffset(1);
     frame2->GetXaxis()->SetTitleSize(0.12);
     frame2->GetXaxis()->SetLabelSize(0.1);
     frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

     frame2->Draw(); 

     // *** Print chi2/ndof 
     printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false);

     pline->Draw("same");
     pad2->Update();
  }

  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
};
Esempio n. 18
0
void roo_fitWHSStudyBG()
{

    gSystem->Load("libRooFit");
    gSystem->Load("libRooFitCore");
    gSystem->Load("libMatrix");
    gSystem->Load("libGpad");
    using namespace RooFit;

    TString poscharge = "Plus";
    TString negcharge = "Minus";

    std::vector<TString> charge(2);
    charge.at(0) = poscharge;
    charge.at(1) = negcharge;

    TString bin1 = "50toinf";
    TString bin2 = "70toinf";
    TString bin3 = "90toinf";

    TString folder = "hltmu9_goodevsel";
    TString noMTpath = "";

    bool makePlots = true;
    bool printPlots = false;
    bool doToyMC = false;
    bool AddQCD = false;
    bool AddQCDbgtemplate = false;
    bool AddZ = true;
    bool AddZbgtemplate = true;
    bool AddTT = true;
    bool AddTTbgtemplate = true;
    bool noMT = false;
    bool realdata = false;
    if(noMT) noMTpath = "_noMT";

    std::vector<TString> bins(1);
    bins.at(0) = bin1;
    //bins.at(1) = bin2;
    //bins.at(2) = bin3;

    //define the data files
    TFile * templates = new TFile("results/" + folder + "/RecoRoutines_W-selection_WJets_madgraph_June2010.root");
    //TFile * dataplus = new TFile("results/" + folder + "/RecoRoutines_W-selection_realdata.root");
    TFile * dataplus = new TFile("results/" + folder + "/RecoRoutines_W-selection_WJets_madgraph_June2010.root");
    TFile * QCDbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_QCD_AllPtBins_7TeV_Pythia.root");
    TFile * TTbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_TTbarJets_tauola_madgraph_June2010.root");
    TFile * Zbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_ZJets_madgraph_June2010.root");

    //define the reference template file
    TFile * refTemplates = new TFile("results/GenRoutines_WJets_JuneMadgraph_1muonextra.root");

    double err1=0.0;
    double comberr=0.0;
    double value1=0.0;

    double lowlim_fit = -0.5;
    double uplim_fit = 1.8;
    Int_t rbin=10;

    TString canvas_name_plus = "MC_WHelicityFramePlots_PlusLPVar";
    TCanvas *c0 = new TCanvas(canvas_name_plus,"",450,470);//900,320);
    //c0->Divide(3,1);

    TString canvas_name_minus = "MC_WHelicityFramePlots_MinusLPVar";
    TCanvas *c1 = new TCanvas(canvas_name_minus,"",450,470);//900,320);
    //c1->Divide(3,1);

    TString pulls_plus = "MC_WHelicityFramePlots_PlusICVarPull";
    TCanvas *cpp = new TCanvas(pulls_plus,"",450,470);//900,320);
    //cpp->Divide(3,1);

    TString pulls_minus = "MC_WHelicityFramePlots_MinusICVarPull";
    TCanvas *cpm = new TCanvas(pulls_minus,"",450,470);//900,320);
    //cpm->Divide(3,1);

    for(unsigned int i=0; i<bins.size(); i++) {
        for(unsigned int j=0; j<charge.size(); j++) {
            //unsigned int index = i*charge.size() + j;
            //cout << "INDEX= " << index << endl;

            //these histograms define the number of events in the complete templates so we can apply correction factors for acceptance etc.
            //do not change these histograms!
            TString refHist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
            TString refHist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
            TString refHist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
            TString refHistData = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
            TH1D *refTempHist1 = (TH1D*)refTemplates->Get(refHist1);
            TH1D *refTempHist2 = (TH1D*)refTemplates->Get(refHist2);
            TH1D *refTempHist3 = (TH1D*)refTemplates->Get(refHist3);
            TH1D *refTempHistData = (TH1D*)refTemplates->Get(refHistData);
            refTempHist1->Rebin(rbin);
            refTempHist2->Rebin(rbin);
            refTempHist3->Rebin(rbin);
            refTempHistData->Rebin(rbin);

            double mLHint=0.0, mRHint=0.0, mLOint=0.0, mDATAint=0.0;
            mLHint = refTempHist1->Integral(refTempHist1->GetXaxis()->FindBin(lowlim_fit), refTempHist1->GetXaxis()->FindBin(uplim_fit));
            mRHint = refTempHist2->Integral(refTempHist2->GetXaxis()->FindBin(lowlim_fit), refTempHist2->GetXaxis()->FindBin(uplim_fit));
            mLOint = refTempHist3->Integral(refTempHist3->GetXaxis()->FindBin(lowlim_fit), refTempHist3->GetXaxis()->FindBin(uplim_fit));
            mDATAint = refTempHistData->Integral(refTempHistData->GetXaxis()->FindBin(lowlim_fit), refTempHistData->GetXaxis()->FindBin(uplim_fit));

            bool firstbg = true;

            if(AddQCD) {
                //add the two QCD charge templates together to get average shape
                TH1D * qcdbg = (TH1D*)((TH1D*)QCDbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFPlus"))->Clone();
                TH1D * qcdbg2 = (TH1D*)((TH1D*)QCDbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFMinus"))->Clone();
                qcdbg->Rebin(rbin);
                qcdbg2->Rebin(rbin);
                qcdbg->Add(qcdbg2);
                qcdbg->Scale(0.5);
                if(AddQCDbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)qcdbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(qcdbg);
                }
            }

            if(AddTT) {
                //Since the shape expected is the same for both charges, do the same as in the QCD case
                TH1D * ttbg = (TH1D*)((TH1D*)TTbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFPlus"))->Clone();
                TH1D * ttbg2 = (TH1D*)((TH1D*)TTbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFMinus"))->Clone();
                ttbg->Rebin(rbin);
                ttbg2->Rebin(rbin);
                ttbg->Add(ttbg2);
                ttbg->Scale(0.5);
                if(AddTTbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)ttbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(ttbg);
                }
            }

            if(AddZ) {
                //check to add the Z bg - but do this separately for both charges (templates expected to be slightly different)
                TH1D *zbg =(TH1D*)((TH1D*)Zbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF" + charge.at(j)))->Clone();
                zbg->Rebin(rbin);
                if(AddZbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)zbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(zbg);
                }
            }

            //these histograms are the ones we want to fit
            //TString Hist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
            //TString Hist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
            //TString Hist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
            //TString Hist_data1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
            TString Hist1 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_LH";
            TString Hist2 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_RH";
            TString Hist3 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_LO";
            TString Hist_data1 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j);

            TH1D *mc1 = (TH1D*)templates->Get(Hist1);
            TH1D *mc2 = (TH1D*)templates->Get(Hist2);
            TH1D *mc3 = (TH1D*)templates->Get(Hist3);
            TH1D *datahist = (TH1D*)dataplus->Get(Hist_data1);

            mc1->Rebin(rbin);
            mc2->Rebin(rbin);
            mc3->Rebin(rbin);
            datahist->Rebin(rbin);

            //calculate the acceptance corrections at this stage - before adding anything to the W templates
            double LHint=0.0, RHint=0.0, LOint=0.0, DATAint=0.0;
            LHint = mc1->Integral(mc1->GetXaxis()->FindBin(lowlim_fit), mc1->GetXaxis()->FindBin(uplim_fit));
            RHint = mc2->Integral(mc2->GetXaxis()->FindBin(lowlim_fit), mc2->GetXaxis()->FindBin(uplim_fit));
            LOint = mc3->Integral(mc3->GetXaxis()->FindBin(lowlim_fit), mc3->GetXaxis()->FindBin(uplim_fit));
            DATAint = datahist->Integral(datahist->GetXaxis()->FindBin(lowlim_fit), datahist->GetXaxis()->FindBin(uplim_fit));

            if(!realdata) {
                if(AddQCD) datahist->Add(qcdbg);
                if(AddTT) datahist->Add(ttbg);
                if(AddZ) datahist->Add(zbg);
            }
            Double_t istat=datahist->Integral();

            // Start RooFit session

            RooRealVar x("x","ICVar",lowlim_fit,uplim_fit);
            // Import binned Data
            RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1);
            RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2);
            RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3);
            RooDataHist data4("data4","dataset with WHICVar",x,bgtemplate);
            RooDataHist test("test_data","dataset with WHICVarPlus",x,datahist);

            //Float_t fr = (1./3.)*istat;
            Float_t fr = (1.0/3.0);

            // Relative fractions - allow them to float to negative values too if needs be
            RooRealVar f1("fL","fL fraction",fr,0.0,1.0);
            RooRealVar f2("fR","fR fraction", fr,0.0,1.0);
            RooRealVar f3("f0","f0 fraction",fr,0.0,1.0);
            RooRealVar f4("fs","fs fraction",1.0 - (bgtemplate->Integral()/istat));//to fix the backgrounds i.e. subtract them
            //RooRealVar f4("fs","fs fraction",0.988);//to fix the backgrounds i.e. subtract them
            //RooRealVar f4("fs","fs fraction",fr,0.0,1.0);//to fit for the QCD (+Z) bg

            // Templates
            RooHistPdf h1("h1","h1",x,data1);
            RooHistPdf h2("h2","h2",x,data2);
            RooHistPdf h3("h3","h3",x,data3);

            // composite PDF
            RooHistPdf bkg("bkg","bkg",x,data4);
            RooAddPdf sig("sig","sig",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;
            RooAddPdf model("model","model",RooArgList(sig,bkg),f4);
            //RooAddPdf model("model","model",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;

            // Generate data
            Int_t nevt=static_cast<int>(istat);

            //do {
            //RooDataSet *gtest = model.generate(x,nevt);

            // Fitting
            RooFitResult * res1 = model.fitTo(test,Minos(kTRUE), Save());//replace test with *gtest etc
            //res1->Print();
            //} while((f1.getVal() * (1.0/3.0) / accFactor1) < 0.45 || (f1.getVal() * (1.0/3.0) / accFactor1) > 0.55 || (1.0 - f1.getVal() - f2.getVal()) < 0.0);


            if(makePlots) {
                // Plotting
                gROOT->SetStyle("Plain");
                gStyle->SetOptFit(111);
                gStyle->SetOptTitle(0);
                gStyle->SetOptStat(0);
                //gStyle->SetCanvasDefH(600); //Height of canvas
                //gStyle->SetCanvasDefW(600); //Width of canvas
                //TString canvas_name = "MC_CSFramePlots_" + bins.at(i) + charge.at(j) + "Phi";
                //TCanvas *c0 = new TCanvas(canvas_name,"",300,320);
                if(charge.at(j) == "Plus") c0->cd();//(i+1);
                if(charge.at(j) == "Minus") c1->cd();//(i+1);
                RooPlot* frame = x.frame();
                test.plotOn(frame); //either test or *gtest
                model.plotOn(frame);
                //model.paramOn(frame);
                model.plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed));
                model.plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed));
                model.plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed));
                model.plotOn(frame, Components(bkg),LineColor(kBlack),LineStyle(kDashed)) ;
                frame->GetXaxis()->SetRangeUser(-2.5,2.5);
                TString xaxislabel = "";
                if(charge.at(j) == "Plus") xaxislabel = "LP(#mu^{+})";
                else xaxislabel = "LP(#mu^{-})";
                frame->GetXaxis()->SetTitle(xaxislabel);
                frame->Draw();
                //c0->cd(i)->Update();
                //c0->Update();
                //c0->Print(canvas_name+".png");
            }

            const TMatrixDSym& cor = res1->correlationMatrix();
            const TMatrixDSym& cov = res1->covarianceMatrix();
            //Print correlation, covariance matrix
            //cout << "correlation matrix" << endl;
            //cor.Print();
            //cout << "covariance matrix" << endl;
            //cout << "(0,0) = " << cov[0][0] << endl;
            //cout << f1.getVal() << endl;
            cov.Print();

            double F1 = f1.getVal();
            double F2 = f2.getVal();
            double F3 = (1.0 - F1 - F2);

            double F1_err = sqrt(cov[0][0]);
            double F2_err = sqrt(cov[1][1]);
            double COV = cov[0][1];

            cout << "Fitting bin " << bins.at(i) << " for " << charge.at(j) << " charge: " << endl;
            cout << "NO ACCEPTANCE CORRECTIONS: " << endl;
            cout << "fL = " << F1 << " +/- " << F1_err << endl;
            cout << "fR = " << F2 << " +/- " << F2_err << endl;
            //cout << "f0 = " << F3 << " +/- " << "N/A" << endl;
            cout << "Covariance Term = " << COV << endl;

            double accLH=0.0, accRH=0.0;
            accLH = (mLHint / mDATAint) / (LHint / DATAint);
            accRH = (mRHint / mDATAint) / (RHint / DATAint);
            F1 *= accLH;
            F2 *= accRH;
            F1_err *= accLH;
            F2_err *= accRH;
            COV *= accLH;
            COV *= accRH;

            cout << "accLH = " << accLH << endl;
            cout << "accRH = " << accRH << endl;

            cout << "WITH ACCEPTANCE CORRECTIONS: " << endl;
            cout << "fL = " << F1 << " +/- " << F1_err << endl;
            cout << "fR = " << F2 << " +/- " << F2_err << endl;
            cout << "(fL - fR) = " << F1 - F2 << " +/- " << sqrt((F1_err*F1_err) + (F2_err*F2_err) - (2.0 * COV)) << endl;
            cout << "f0 = " << (1.0 - F1 - F2) << " +/- " << sqrt((F1_err*F1_err) + (F2_err*F2_err) + (2.0 * COV)) << endl;
            // toy MC study
            if(doToyMC) {
                RooMCStudy mgr(model,model,x,"","mhv");
                mgr.generateAndFit(1000,nevt,kTRUE);
                RooPlot* m1pframe = mgr.plotPull(f1,-3,3,20,kTRUE);
                if(charge.at(j) == "Plus") cpp->cd();//(i+1);
                if(charge.at(j) == "Minus") cpm->cd();//(i+1);
                m1pframe->Draw();
            }

        }
    }
    if(makePlots && printPlots) {
        c0->Print(canvas_name_plus+".png");
        c1->Print(canvas_name_minus+".png");
        if(doToyMC) {
            cpp->Print(pulls_plus+".png");
            cpm->Print(pulls_minus+".png");
        }
    }

    return;

}
Esempio n. 19
0
void BackgroundPrediction(std::string pname,int rebin_factor,int model_number = 0,int imass=750, bool plotBands = false)
{
    rebin = rebin_factor;
    std::string fname = std::string("../fitFilesMETPT34/") + pname + std::string("/histos_bkg.root");
    
    stringstream iimass ;
    iimass << imass;
    std::string dirName = "info_"+iimass.str()+"_"+pname;
    
    
    gStyle->SetOptStat(000000000);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    
    setTDRStyle();
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetOptStat(0000);
    
    writeExtraText = true;       // if extra text
    extraText  = "Preliminary";  // default extra text is "Preliminary"
    lumi_13TeV  = "2.7 fb^{-1}"; // default is "19.7 fb^{-1}"
    lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
    
    
    double ratio_tau=-1;
    
    TFile *f=new TFile(fname.c_str());
    TH1F *h_mX_CR_tau=(TH1F*)f->Get("distribs_18_10_1")->Clone("CR_tau");
    TH1F *h_mX_SR=(TH1F*)f->Get("distribs_18_10_0")->Clone("The_SR");
    double maxdata = h_mX_SR->GetMaximum();
    double nEventsSR = h_mX_SR->Integral(600,4000);
    ratio_tau=(h_mX_SR->GetSumOfWeights()/(h_mX_CR_tau->GetSumOfWeights()));
    //double nEventsSR = h_mX_SR->Integral(600,4000);
    
    std::cout<<"ratio tau "<<ratio_tau<<std::endl;
    
    TH1F *h_SR_Prediction;
    TH1F *h_SR_Prediction2;
    
    if(blind) {
        h_SR_Prediction2 = (TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction2");
        h_mX_CR_tau->Rebin(rebin);
        h_mX_CR_tau->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction");
    } else {
        h_SR_Prediction2=(TH1F*)h_mX_SR->Clone("h_SR_Prediction2");
        h_mX_SR->Rebin(rebin);
        h_mX_SR->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_SR->Clone("h_SR_Prediction");
        
    }
    h_SR_Prediction->SetMarkerSize(0.7);
    h_SR_Prediction->GetYaxis()->SetTitleOffset(1.2);
    h_SR_Prediction->Sumw2();
    
    /*TFile *f_sig = new TFile((dirName+"/w_signal_"+iimass.str()+".root").c_str());
    RooWorkspace* xf_sig = (RooWorkspace*)f_sig->Get("Vg");
    RooAbsPdf *xf_sig_pdf = (RooAbsPdf *)xf_sig->pdf((std::string("signal_fixed_")+pname).c_str());
    
    RooWorkspace w_sig("w");
    w_sig.import(*xf_sig_pdf,RooFit::RenameVariable((std::string("signal_fixed_")+pname).c_str(),(std::string("signal_fixed_")+pname+std::string("low")).c_str()),RooFit::RenameAllVariablesExcept("low","x"));
    xf_sig_pdf = w_sig.pdf((std::string("signal_fixed_")+pname+std::string("low")).c_str());
   
    RooArgSet* biasVars = xf_sig_pdf->getVariables();
    TIterator *it = biasVars->createIterator();
    RooRealVar* var = (RooRealVar*)it->Next();
    while (var) {
        var->setConstant(kTRUE);
        var = (RooRealVar*)it->Next();
    }
    */
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    
    RooRealVar nBackground((std::string("bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    RooRealVar nBackground2((std::string("alt_bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    std::string blah = pname;
    //pname=""; //Antibtag=tag to constrain b-tag to the anti-btag shape
    
    
    /* RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 4.2, 0, 200.);
     RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", 4.5, 0, 300.);
     RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", 0.000047, 0, 10.1);
     RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(1-@0/13000,@1)/pow(@0/13000,@2+@3*log(@0/13000)))",RooArgList(x,bg_p0,bg_p1,bg_p2));
   */
    RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 0., -1000, 200.);
    RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", -13, -1000, 1000.);
    RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", -1.4, -1000, 1000.);
    bg_p0.setConstant(kTRUE);
    //RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
    RooGenericPdf bg = RooGenericPdf((std::string("bg_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
  

    /*TF1* biasFunc = new TF1("biasFunc","(0.63*x/1000-1.45)",1350,3600);
    TF1* biasFunc2 = new TF1("biasFunc2","TMath::Min(2.,2.3*x/1000-3.8)",1350,3600);
    double bias_term_s = 0;
    if ((imass > 2450 && blah == "antibtag") || (imass > 1640 && blah == "btag")) {
        if (blah == "antibtag") {
            bias_term_s = 2.7*biasFunc->Eval(imass);
        } else {
            bias_term_s = 2.7*biasFunc2->Eval(imass);
        }
       bias_term_s/=nEventsSR;
    }
    
    RooRealVar bias_term((std::string("bias_term_")+blah).c_str(), "bias_term", 0., -bias_term_s, bias_term_s);
    //bias_term.setConstant(kTRUE);
    RooAddPdf bg((std::string("bg_")+blah).c_str(), "bg_all", RooArgList(*xf_sig_pdf, bg_pure), bias_term);
    */
    string name_output = "CR_RooFit_Exp";
    
    std::cout<<"Nevents "<<nEventsSR<<std::endl;
    RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_SR_Prediction);
    RooFitResult *r_bg=bg.fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save(),RooFit::SumW2Error(kTRUE));
    std::cout<<" --------------------- Building Envelope --------------------- "<<std::endl;
    //std::cout<< "bg_p0_"<< pname << "   param   "<<bg_p0.getVal() <<  " "<<bg_p0.getError()<<std::endl;
    std::cout<< "bg_p1_"<< pname << "   param   "<<bg_p1.getVal() <<  " "<<100*bg_p1.getError()<<std::endl;
    std::cout<< "bg_p2_"<< pname << "   param   "<<bg_p2.getVal() <<  " "<<100*bg_p2.getError()<<std::endl;
    //std::cout<< "bias_term_"<< blah << "   param   0 "<<bias_term_s<<std::endl;
    
    RooPlot *aC_plot=x.frame();
    pred.plotOn(aC_plot, RooFit::MarkerColor(kPink+2));
    if (!plotBands) {
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 2), RooFit::FillColor(kYellow));
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 1), RooFit::FillColor(kGreen));
    }
    bg.plotOn(aC_plot, RooFit::LineColor(kBlue));
    //pred.plotOn(aC_plot, RooFit::LineColor(kBlack), RooFit::MarkerColor(kBlack));
    
    TGraph* error_curve[5]; //correct error bands
    TGraphAsymmErrors* dataGr = new TGraphAsymmErrors(h_SR_Prediction->GetNbinsX()); //data w/o 0 entries

    for (int i=2; i!=5; ++i) {
        error_curve[i] = new TGraph();
    }
    error_curve[2] = (TGraph*)aC_plot->getObject(1)->Clone("errs");
    int nPoints = error_curve[2]->GetN();
    
    error_curve[0] = new TGraph(2*nPoints);
    error_curve[1] = new TGraph(2*nPoints);
    
    error_curve[0]->SetFillStyle(1001);
    error_curve[1]->SetFillStyle(1001);
    
    error_curve[0]->SetFillColor(kGreen);
    error_curve[1]->SetFillColor(kYellow);
    
    error_curve[0]->SetLineColor(kGreen);
    error_curve[1]->SetLineColor(kYellow);
    
    if (plotBands) {
        RooDataHist pred2("pred2", "Prediction from SB", RooArgList(x), h_SR_Prediction2);

        error_curve[3]->SetFillStyle(1001);
        error_curve[4]->SetFillStyle(1001);
        
        error_curve[3]->SetFillColor(kGreen);
        error_curve[4]->SetFillColor(kYellow);
        
        error_curve[3]->SetLineColor(kGreen);
        error_curve[4]->SetLineColor(kYellow);
        
        error_curve[2]->SetLineColor(kBlue);
        error_curve[2]->SetLineWidth(3);
        
        double binSize = rebin;
        
        for (int i=0; i!=nPoints; ++i) {
            double x0,y0, x1,y1;
            error_curve[2]->GetPoint(i,x0,y0);
            
            RooAbsReal* nlim = new RooRealVar("nlim","y0",y0,-100000,100000);
            //double lowedge = x0 - (SR_hi - SR_lo)/double(2*nPoints);
            //double upedge = x0 + (SR_hi - SR_lo)/double(2*nPoints);
            
            double lowedge = x0 - binSize/2.;
            double upedge = x0 + binSize/2.;
            
            x.setRange("errRange",lowedge,upedge);
            
            RooExtendPdf* epdf = new RooExtendPdf("epdf","extpdf",bg, *nlim,"errRange");
            
            // Construct unbinned likelihood
            RooAbsReal* nll = epdf->createNLL(pred2,NumCPU(2));
            // Minimize likelihood w.r.t all parameters before making plots
            RooMinimizer* minim = new RooMinimizer(*nll);
            minim->setMinimizerType("Minuit2");
            minim->setStrategy(2);
            minim->setPrintLevel(-1);
            minim->migrad();
            
            minim->hesse();
            RooFitResult* result = minim->lastMinuitFit();
            double errm = nlim->getPropagatedError(*result);
            
            //std::cout<<x0<<" "<<lowedge<<" "<<upedge<<" "<<y0<<" "<<nlim->getVal()<<" "<<errm<<std::endl;
            
            error_curve[0]->SetPoint(i,x0,(y0-errm));
            error_curve[0]->SetPoint(2*nPoints-i-1,x0,y0+errm);
            
            error_curve[1]->SetPoint(i,x0,(y0-2*errm));
            error_curve[1]->SetPoint(2*nPoints-i-1,x0,(y0+2*errm));
            
            error_curve[3]->SetPoint(i,x0,-errm/sqrt(y0));
            error_curve[3]->SetPoint(2*nPoints-i-1,x0,errm/sqrt(y0));
            
            error_curve[4]->SetPoint(i,x0,-2*errm/sqrt(y0));
            error_curve[4]->SetPoint(2*nPoints-i-1,x0,2*errm/sqrt(y0));
            
        }
        
        int npois = 0;
        dataGr->SetMarkerSize(1.0);
        dataGr->SetMarkerStyle (20);
        
        const double alpha = 1 - 0.6827;
        
        for (int i=0; i!=h_SR_Prediction->GetNbinsX(); ++i){
            if (h_SR_Prediction->GetBinContent(i+1) > 0) {
                
                int N = h_SR_Prediction->GetBinContent(i+1);
                double L =  (N==0) ? 0  : (ROOT::Math::gamma_quantile(alpha/2,N,1.));
                double U =  ROOT::Math::gamma_quantile_c(alpha/2,N+1,1) ;
                
                dataGr->SetPoint(npois,h_SR_Prediction->GetBinCenter(i+1),h_SR_Prediction->GetBinContent(i+1));
                dataGr->SetPointEYlow(npois, N-L);
                dataGr->SetPointEYhigh(npois, U-N);
                npois++;
            }
        }
    }
    
    double xG[2] = {-10,4000};
    double yG[2] = {0.0,0.0};
    TGraph* unityG = new TGraph(2, xG, yG);
    unityG->SetLineColor(kBlue);
    unityG->SetLineWidth(1);

    double xPad = 0.3;
    TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 800*(1.-xPad), 600);
    c_rooFit->SetFillStyle(4000);
    c_rooFit->SetFrameFillColor(0);
    
    TPad *p_1=new TPad("p_1", "p_1", 0, xPad, 1, 1);
    p_1->SetFillStyle(4000);
    p_1->SetFrameFillColor(0);
    p_1->SetBottomMargin(0.02);
    TPad* p_2 = new TPad("p_2", "p_2",0,0,1,xPad);
    p_2->SetBottomMargin((1.-xPad)/xPad*0.13);
    p_2->SetTopMargin(0.03);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    
    int nbins = (int) (SR_hi- SR_lo)/rebin;
    x.setBins(nbins);
    
    std::cout << "chi2(data) " <<  aC_plot->chiSquare()<<std::endl;
    
    //std::cout << "p-value: data     under hypothesis H0:  " << TMath::Prob(chi2_data->getVal(), nbins - 1) << std::endl;
    
    aC_plot->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    aC_plot->GetXaxis()->SetLabelOffset(0.02);
    aC_plot->GetYaxis()->SetRangeUser(0.1, 1000.);
    h_SR_Prediction->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    string rebin_ = itoa(rebin);
    
    aC_plot->GetXaxis()->SetTitle("M_{Z#gamma} [GeV] ");
    aC_plot->GetYaxis()->SetTitle(("Events / "+rebin_+" GeV ").c_str());
    aC_plot->SetMarkerSize(0.7);
    aC_plot->GetYaxis()->SetTitleOffset(1.2);
    aC_plot->Draw();
    
    if (plotBands) {
        error_curve[1]->Draw("Fsame");
        error_curve[0]->Draw("Fsame");
        error_curve[2]->Draw("Lsame");
        dataGr->Draw("p e1 same");
    }
    
    aC_plot->SetTitle("");
    TPaveText *pave = new TPaveText(0.85,0.4,0.67,0.5,"NDC");
    pave->SetBorderSize(0);
    pave->SetTextSize(0.05);
    pave->SetTextFont(42);
    pave->SetLineColor(1);
    pave->SetLineStyle(1);
    pave->SetLineWidth(2);
    pave->SetFillColor(0);
    pave->SetFillStyle(0);
    char name[1000];
    sprintf(name,"#chi^{2}/n = %.2f",aC_plot->chiSquare());
    pave->AddText(name);
    //pave->Draw();
    
    TLegend *leg = new TLegend(0.88,0.65,0.55,0.90,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextSize(0.05);
    leg->SetTextFont(42);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(2);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    h_SR_Prediction->SetMarkerColor(kBlack);
    h_SR_Prediction->SetLineColor(kBlack);
    h_SR_Prediction->SetMarkerStyle(20);
    h_SR_Prediction->SetMarkerSize(1.0);
    //h_mMMMMa_3Tag_SR->GetXaxis()->SetTitleSize(0.09);
    if (blind)
        leg->AddEntry(h_SR_Prediction, "Data: sideband", "ep");
    else {
        if (blah == "antibtag" )
            leg->AddEntry(h_SR_Prediction, "Data: anti-b-tag SR", "ep");
        else
            leg->AddEntry(h_SR_Prediction, "Data: b-tag SR", "ep");
        
    }
    
    leg->AddEntry(error_curve[2], "Fit model", "l");
    leg->AddEntry(error_curve[0], "Fit #pm1#sigma", "f");
    leg->AddEntry(error_curve[1], "Fit #pm2#sigma", "f");
    leg->Draw();
    
    aC_plot->Draw("axis same");
    
    
    CMS_lumi( p_1, iPeriod, iPos );
    
    p_2->cd();
    RooHist* hpull;
    hpull = aC_plot->pullHist();
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetRangeUser(-7,7);
    frameP->GetYaxis()->SetNdivisions(505);
    frameP->GetYaxis()->SetTitle("#frac{(data-fit)}{#sigma_{stat}}");
    
    frameP->GetYaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    frameP->GetYaxis()->SetTitleOffset(1.0/((1.-xPad)/xPad));
    frameP->GetXaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    //frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    frameP->GetYaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    
    
    frameP->Draw();
    if (plotBands) {
        error_curve[4]->Draw("Fsame");
        error_curve[3]->Draw("Fsame");
        unityG->Draw("same");
        hpull->Draw("psame");
        
        frameP->Draw("axis same");
    }
    
    
    c_rooFit->SaveAs((dirName+"/"+name_output+".pdf").c_str());
    
    const int nModels = 9;
    TString models[nModels] = {
        "env_pdf_0_13TeV_dijet2", //0
        "env_pdf_0_13TeV_exp1", //1
        "env_pdf_0_13TeV_expow1", //2
        "env_pdf_0_13TeV_expow2", //3 => skip
        "env_pdf_0_13TeV_pow1", //4
        "env_pdf_0_13TeV_lau1", //5
        "env_pdf_0_13TeV_atlas1", //6
        "env_pdf_0_13TeV_atlas2", //7 => skip
        "env_pdf_0_13TeV_vvdijet1" //8
    };
    
    int nPars[nModels] = {
        2, 1, 2, 3, 1, 1, 2, 3, 2
    };
    
    TString parNames[nModels][3] = {
        "env_pdf_0_13TeV_dijet2_log1","env_pdf_0_13TeV_dijet2_log2","",
        "env_pdf_0_13TeV_exp1_p1","","",
        "env_pdf_0_13TeV_expow1_exp1","env_pdf_0_13TeV_expow1_pow1","",
        "env_pdf_0_13TeV_expow2_exp1","env_pdf_0_13TeV_expow2_pow1","env_pdf_0_13TeV_expow2_exp2",
        "env_pdf_0_13TeV_pow1_p1","","",
        "env_pdf_0_13TeV_lau1_l1","","",
        "env_pdf_0_13TeV_atlas1_coeff1","env_pdf_0_13TeV_atlas1_log1","",
        "env_pdf_0_13TeV_atlas2_coeff1","env_pdf_0_13TeV_atlas2_log1","env_pdf_0_13TeV_atlas2_log2",
        "env_pdf_0_13TeV_vvdijet1_coeff1","env_pdf_0_13TeV_vvdijet1_log1",""
    }
    
    if(bias){
        //alternative model
        gSystem->Load("libHiggsAnalysisCombinedLimit");
        gSystem->Load("libdiphotonsUtils");
        
        TFile *f = new TFile("antibtag_multipdf.root");
        RooWorkspace* xf = (RooWorkspace*)f->Get("wtemplates");
        RooWorkspace *w_alt=new RooWorkspace("Vg");
        for(int i=model_number; i<=model_number; i++){
            RooMultiPdf *alternative = (RooMultiPdf *)xf->pdf("model_bkg_AntiBtag");
            std::cout<<"Number of pdfs "<<alternative->getNumPdfs()<<std::endl;
            for (int j=0; j!=alternative->getNumPdfs(); ++j){
                std::cout<<alternative->getPdf(j)->GetName()<<std::endl;
            }
            RooAbsPdf *alt_bg = alternative->getPdf(alternative->getCurrentIndex()+i);//->clone();
            w_alt->import(*alt_bg, RooFit::RenameVariable(alt_bg->GetName(),("alt_bg_"+blah).c_str()));
            w_alt->Print("V");
            std::cerr<<w_alt->var("x")<<std::endl;
            RooRealVar * range_ = w_alt->var("x");
            range_->setRange(SR_lo,SR_hi);
            char* asd = ("alt_bg_"+blah).c_str()	;
            w_alt->import(nBackground2);
            std::cout<<alt_bg->getVal() <<std::endl;
            w_alt->pdf(asd)->fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());

    	    RooArgSet* altVars = w_alt->pdf(asd)->getVariables();
            TIterator *it2 = altVars->createIterator();
            RooRealVar* varAlt = (RooRealVar*)it2->Next();
            while (varAlt) {
               varAlt->setConstant(kTRUE);
               varAlt = (RooRealVar*)it2->Next();
            }



            alt_bg->plotOn(aC_plot, RooFit::LineColor(i+1), RooFit::LineStyle(i+2));
            p_1->cd();
            aC_plot->GetYaxis()->SetRangeUser(0.01, maxdata*50.);
            aC_plot->Draw("same");
            TH1F *h=new TH1F();
            h->SetLineColor(1+i);
            h->SetLineStyle(i+2);
            leg->AddEntry(h, alt_bg->GetName(), "l");
            
            
            w_alt->SaveAs((dirName+"/w_background_alternative.root").c_str());
        }
        leg->Draw();
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+blah+"_multipdf.pdf").c_str());
        
        for (int i=0; i!=nPars[model_number]; ++i) {
            std::cout<<parNames[model_number][i]<<" param "<< w_alt->var(parNames[model_number][i])->getVal()<<"   "<<w_alt->var(parNames[model_number][i])->getError()<<std::endl;
        }
        
        
    } else {
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+"_log.pdf").c_str());
    }
    
    RooWorkspace *w=new RooWorkspace("Vg");
    w->import(bg);
    w->import(nBackground);
    w->SaveAs((dirName+"/w_background_GaussExp.root").c_str());
    
    TH1F *h_mX_SR_fakeData=(TH1F*)h_mX_SR->Clone("h_mX_SR_fakeData");
    h_mX_SR_fakeData->Scale(nEventsSR/h_mX_SR_fakeData->GetSumOfWeights());
    RooDataHist data_obs("data_obs", "Data", RooArgList(x), h_mX_SR_fakeData);
    std::cout<<" Background number of events = "<<nEventsSR<<std::endl;
    RooWorkspace *w_data=new RooWorkspace("Vg");
    w_data->import(data_obs);
    w_data->SaveAs((dirName+"/w_data.root").c_str());
    
}
Esempio n. 20
0
void RooToyMCFit1Bin(const int _bin){
    if(_bin<1 || _bin>8){
        cout << "Bin number should be between 1 and 8" << endl;
        return;
    }
    stringstream out;
    out.str("");
    out << "toyMC_" << _sigma_over_tau << "_" << _purity << "_" << mistag_rate << ".root";
    TFile* file = TFile::Open(out.str().c_str());
    TTree* tree = (TTree*)file->Get("ToyTree");
    cout << "The tree has been readed from the file " << out.str().c_str() << endl;

    RooRealVar tau("tau","tau",_tau,"ps"); tau.setConstant(kTRUE);
    RooRealVar dm("dm","dm",_dm,"ps^{-1}"); dm.setConstant(kTRUE);
    RooRealVar sin2beta("sin2beta","sin2beta",_sin2beta,-5.,5.); if(constBeta) sin2beta.setConstant(kTRUE);
    RooRealVar cos2beta("cos2beta","cos2beta",_cos2beta,-5.,5.); if(constBeta) cos2beta.setConstant(kTRUE);
    RooRealVar dt("dt","#Deltat",-5.,5.,"ps");
    RooRealVar avgMisgat("avgMisgat","avgMisgat",mistag_rate,0.0,0.5); if(constMistag) avgMisgat.setConstant(kTRUE);
    RooRealVar delMisgat("delMisgat","delMisgat",0); delMisgat.setConstant(kTRUE);
    RooRealVar mu("mu","mu",0); mu.setConstant(kTRUE);
    RooRealVar moment("moment","moment",0.);  moment.setConstant(kTRUE);
    RooRealVar parity("parity","parity",-1.); parity.setConstant(kTRUE);

    cout << "Preparing coefficients..." << endl;
    RooRealVar*    K  = new RooRealVar("K","K",K8[_bin-1],0.,1.); if(constK) K->setConstant(kTRUE);
    RooFormulaVar* Kb = new RooFormulaVar("Kb","Kb","1-@0",RooArgList(*K));

    RooRealVar* C = new RooRealVar("C","C",_C[_bin-1]); C->setConstant(kTRUE);
    RooRealVar* S = new RooRealVar("S","S",_S[_bin-1]); S->setConstant(kTRUE);

    RooFormulaVar* a1  = new RooFormulaVar("a1","a1","-(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a1b = new RooFormulaVar("a1b","a1b","(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a2  = new RooFormulaVar("a2","a2","(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a2b = new RooFormulaVar("a2b","a2b","-(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));

    RooFormulaVar* b1  = new RooFormulaVar("b1","b1","2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b1b = new RooFormulaVar("b1b","b1b","2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b2  = new RooFormulaVar("b2","b2","-2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b2b = new RooFormulaVar("b2b","b2b","-2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));

    RooRealVar* dgamma = new RooRealVar("dgamma","dgamma",0.); dgamma->setConstant(kTRUE);
    RooRealVar* f0 = new RooRealVar("f0","f0",1.); f0->setConstant(kTRUE);
    RooRealVar* f1 = new RooRealVar("f1","f1",0.); f1->setConstant(kTRUE);

    RooCategory tag("tag","tag");
    tag.defineType("B0",1);
    tag.defineType("anti-B0",-1);

    RooCategory bin("bin","bin");
    bin.defineType("bin",_bin);
    bin.defineType("binb",-_bin);

    RooSuperCategory bintag("bintag","bintag",RooArgSet(bin,tag));

    RooDataSet d("data","data",tree,RooArgSet(dt,bin,tag));
    cout << "DataSet is ready." << endl;
    d.Print();

    RooRealVar mean("mean","mean",0.,"ps"); mean.setConstant(kTRUE);
    RooRealVar sigma("sigma","sigma",_sigma_over_tau*_tau,0.,_tau,"ps"); if(constSigma) sigma.setConstant(kTRUE);
    RooGaussModel rf("rf","rf",dt,mean,sigma);
//    RooTruthModel rf("rf","rf",dt);
    RooGaussian rfpdf("rfpdf","rfpdf",dt,mean,sigma);

    cout << "Preparing PDFs..." << endl;
    RooBDecay* sigpdf1  = new RooBDecay("sigpdf1","sigpdf1",dt,tau,*dgamma,*f0,*f1,*a1,*b1,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf2  = new RooBDecay("sigpdf2","sigpdf2",dt,tau,*dgamma,*f0,*f1,*a2,*b2,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf1b  = new RooBDecay("sigpdf1b","sigpdf1b",dt,tau,*dgamma,*f0,*f1,*a1b,*b1b,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf2b  = new RooBDecay("sigpdf2b","sigpdf2b",dt,tau,*dgamma,*f0,*f1,*a2b,*b2b,dm,rf,RooBDecay::DoubleSided);

    RooRealVar fsig("fsig","fsigs",_purity,0.,1.);  if(constFSig) fsig.setConstant(kTRUE);
    RooAddPdf* PDF1 = new RooAddPdf("PDF1","PDF1",RooArgList(*sigpdf1,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF2 = new RooAddPdf("PDF2","PDF2",RooArgList(*sigpdf2,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF1b= new RooAddPdf("PDF1b","PDF1b",RooArgList(*sigpdf1b,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF2b= new RooAddPdf("PDF2b","PDF2b",RooArgList(*sigpdf2b,rfpdf),RooArgList(fsig));

    //Adding mistaging
    RooAddPdf* pdf1 = new RooAddPdf("pdf1","pdf1",RooArgList(*PDF2,*PDF1),RooArgList(avgMisgat));
    RooAddPdf* pdf2 = new RooAddPdf("pdf2","pdf2",RooArgList(*PDF1,*PDF2),RooArgList(avgMisgat));
    RooAddPdf* pdf1b= new RooAddPdf("pdf1b","pdf1b",RooArgList(*PDF2b,*PDF1b),RooArgList(avgMisgat));
    RooAddPdf* pdf2b= new RooAddPdf("pdf2b","pdf2b",RooArgList(*PDF1b,*PDF2b),RooArgList(avgMisgat));

    RooSimultaneous pdf("pdf","pdf",bintag);
    pdf.addPdf(*pdf1,"{bin;B0}");
    pdf.addPdf(*pdf2,"{bin;anti-B0}");
    pdf.addPdf(*pdf1b,"{binb;B0}");
    pdf.addPdf(*pdf2b,"{binb;anti-B0}");

    cout << "Fitting..." << endl;
    pdf.fitTo(d,Verbose(),Timer());

    cout << "Drawing plots." << endl;
    // Plus bin
    RooPlot* dtFrame = dt.frame();

    // B0
    out.str("");
    out << "tag == 1 && bin == " << _bin;
    cout << out.str() << endl;
    RooDataSet* ds = d.reduce(out.str().c_str());
    ds->Print();
    ds->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kBlue));
    bintag = "{bin;B0}";
    pdf.plotOn(dtFrame,ProjWData(RooArgSet(),*ds),Slice(bintag),LineColor(kBlue));
    double chi2 = dtFrame->chiSquare();

    // anti-B0
    out.str("");
    out << "tag == -1 && bin == " << _bin;
    cout << out.str() << endl;
    RooDataSet* dsb = d.reduce(out.str().c_str());
    dsb->Print();
    dsb->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kRed));
    bintag = "{bin;anti-B0}";
    pdf.plotOn(dtFrame,ProjWData(RooArgSet(),*dsb),Slice(bintag),LineColor(kRed));
    double chi2b = dtFrame->chiSquare();

    // Canvas
    out.str("");
    out << "#Delta t, toy MC, bin == " << _bin;
    TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
    cm->cd();
    dtFrame->GetXaxis()->SetTitleSize(0.05);
    dtFrame->GetXaxis()->SetTitleOffset(0.85);
    dtFrame->GetXaxis()->SetLabelSize(0.05);
    dtFrame->GetYaxis()->SetTitleOffset(1.6);

    TPaveText *pt = new TPaveText(0.7,0.6,0.98,0.99,"brNDC");
    pt->SetFillColor(0);
    pt->SetTextAlign(12);
    out.str("");
    out << "bin = " << _bin;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(B^{0}) = " << chi2;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(#barB^{0}) = " << chi2b;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#sigma/#tau = " << sigma.getVal()/tau.getVal();
    pt->AddText(out.str().c_str());
    out.str("");
    out << "purity = " << _purity;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "mistag = " << mistag_rate;
    pt->AddText(out.str().c_str());

    dtFrame->Draw();
    pt->Draw();

    // Minus bin
    RooPlot* dtFrameB = dt.frame();

    // B0
    out.str("");
    out << "tag == 1 && bin == " << -_bin;
    cout << out.str() << endl;
    RooDataSet* ds2 = d.reduce(out.str().c_str());
    ds2->Print();
    ds2->plotOn(dtFrameB,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kBlue));
    bintag = "{binb;B0}";
    pdf.plotOn(dtFrameB,ProjWData(RooArgSet(),*ds2),Slice(bintag),LineColor(kBlue));
    chi2 = dtFrameB->chiSquare();

    //anti-B0
    out.str("");
    out << "tag == -1 && bin == " << -_bin;
    cout << out.str() << endl;
    RooDataSet* dsb2 = d.reduce(out.str().c_str());
    dsb2->Print();
    dsb2->plotOn(dtFrameB,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kRed));
    bintag = "{binb;anti-B0}";
    pdf.plotOn(dtFrameB,ProjWData(RooArgSet(),*dsb2),Slice(bintag),LineColor(kRed));
    chi2b = dtFrameB->chiSquare();

    //Canvas
    out.str("");
    out << "#Delta t, toy MC, bin == " << -_bin;
    TCanvas* cm2 = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
    cm2->cd();
    dtFrameB->GetXaxis()->SetTitleSize(0.05);
    dtFrameB->GetXaxis()->SetTitleOffset(0.85);
    dtFrameB->GetXaxis()->SetLabelSize(0.05);
    dtFrameB->GetYaxis()->SetTitleOffset(1.6);

    TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
    ptB->SetFillColor(0);
    ptB->SetTextAlign(12);
    out.str("");
    out << "bin = " << -_bin;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(B^{0}) = " << chi2;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(#barB^{0}) = " << chi2b;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#sigma/#tau = " << sigma.getVal()/tau.getVal();
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "purity = " << _purity;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "mistag = " << mistag_rate;
    ptB->AddText(out.str().c_str());

    dtFrameB->Draw();
    ptB->Draw();

    return;
}
Esempio n. 21
0
int FitInvMassBkg(TH1D* histo, TH1D* histo_bkg, TString signal,TString _bkg){

	//Set Style
	setTDRStyle();

	cout<<"21"<<endl;

	//Path for input and output file. Written in FitDataPath.txt
	ifstream file("FitDataPath.txt");
	string str;
	getline(file,str);
	TString _path = str;

	//Rebin(histo);

	//Getting info about the histogram to fit
	int n = histo->GetEntries();
	double w = histo->GetXaxis()->GetBinWidth(1);
	int ndf;
	double hmin0 = histo->GetXaxis()->GetXmin();
	double hmax0 = histo->GetXaxis()->GetXmax();
	histo->GetXaxis()->SetRangeUser(hmin0,hmax0);

	//Declare observable x
	//Try to rebin using this. Doesn't work for now
        //RooBinning xbins = Rebin2(histo);
	RooRealVar x("x","x",hmin0,hmax0) ;
	RooDataHist dh("dh","dh",x,Import(*histo)) ;

	//Define the frame
	RooPlot* frame;
	frame = x.frame();
	dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7));  //this will show histogram data points on canvas

	//x.setRange("R0",0,200) ;
	x.setRange("R1",55,200) ;

        /////////////////////
	//Define fit function 
	/////////////////////
	
	//fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x)
	RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.);//before 0.9

	//Various parameters
	
	//True mean
	RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0);
	//For the BW
	RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.);
	//For the Gauss and the CB alone 
	RooRealVar sigma("sigma","sigma",1, 0., 10.);
	RooRealVar alpha("alpha","alpha",0.7, 0., 7);
	RooRealVar ncb("ncb","ncb",7, 0, 150);
	//For the CB used for convolution, i.e. CBxBW
	RooRealVar cb_bias("cb_bias","bias",0, -3.,3.);
	RooRealVar cb_sigma("cb_sigma","response",1, 0.,5);
	RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7);
	RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10);

	mean.setRange(88,94);
	width.setRange(0,20);
	sigma.setRange(0.5,10);
	//fsig.setConstant(kTRUE);
	//alpha.setConstant(kTRUE);

	RooVoigtian sig_bwgau("sig_bwgau","BWxgauss",x,mean,width,sigma);
	RooBreitWigner sig_bw("sig_bw","BW",x,mean,width);
	RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma);
	RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb);
	RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb);

	x.setBins(10000,"cache");
	RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw);

	//NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. 

	RooAbsPdf* sig;
	if(signal == "BWxGau"){sig = &sig_bwgau;}
	else if(signal == "BW"){sig = &sig_bw;}
	else if(signal == "Gau"){sig = &sig_gau;}
	else if(signal == "CB"){sig = &sig_cb;}
	else if(signal == "CBxBW"){ sig = &sig_cbbw;}
	else{ cout<<"Wrong signal function name"<<endl;
		return 1;
	}

	/////////////////////////////
	//Background fitting function
	/////////////////////////////
	
	//Get the initial parameter of the background
	//


	vector<double> vec = FitBkg(histo_bkg,_bkg);

	//Chebychev
	RooRealVar a0("a0","a0",vec[0],-5.,0.) ;
	RooRealVar a1("a1","a1",vec[1],-2,1.2) ;
	RooRealVar a2("a2","a2",vec[2],-1.,1.) ;
	RooRealVar a3("a3","a3",vec[3],-2.5,0.) ;
	RooRealVar a4("a4","a4",vec[4],-1.,1.) ;
	RooRealVar a5("a5","a5",vec[5],-1.,1.) ;
	RooRealVar a6("a6","a6",vec[6],-1.,1.) ;

	RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6));

	//Novo

	RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250);
	RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ;
	RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ;

	RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg);

	RooAbsPdf* bkg;

	if(_bkg == "Cheb"){bkg = &bkg_cheb;}
	if(_bkg == "Novo"){bkg = &bkg_nov;}


	//////////////////////////
	//Adding the two functions
	//////////////////////////
	
	RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig);
	 
	//Perform the fit
	RooAbsPdf* fit_func;
	fit_func = &model;
	
	RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr");
	fit_func->plotOn(frame);
	fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed));
	fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen));
	frame->Draw();
	fit_func->paramOn(frame); 
	dh.statOn(frame);  //this will display hist stat on canvas

	frame->SetTitle(histo->GetTitle());  
	frame->GetXaxis()->SetTitle("m (in GeV/c^{2})");  
	frame->GetXaxis()->SetTitleOffset(1.2);
	float binsize = histo->GetBinWidth(1); 

	//Store result in .root file
	frame->SetName(histo->GetName());
	frame->Write();
	
	return 0;

}
Esempio n. 22
0
void CreateBkgTemplates(float XMIN, float XMAX, TString OUTPATH, bool MERGE)
{
  gROOT->ProcessLineSync(".x ../common/styleCMSTDR.C");
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  const int NSEL(2);
  if (!MERGE) {const int NCAT[NSEL] = {4,3};}
  else {const int NCAT[NSEL] = {4,2};}
  if (!MERGE) {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};}
  else {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,1}};}
  float LUMI[2] = {19784,18281};
  TString SELECTION[2] = {"NOM","VBF"};
  TString SELNAME[2] = {"NOM","PRK"};
  TString MASS_VAR[2] = {"mbbReg[1]","mbbReg[2]"};
  TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
  TString PATH("flat/");
  TFile *inf[9];
  TTree *tr;
  TH1F *hMbb[9],*hMbbYield[9],*hPass;
  TH1F *hZ,*hW,*hTT,*hST,*hTop;
  TH1F *hZYield,*hWYield,*hTTYield,*hSTYield,*hTopYield;
  char name[1000];
  float LUMI;
  float XSEC[9] = {56.4,11.1,3.79,30.7,11.1,1.76,245.8,650,1.2*1205};
  RooDataHist *roohist_Z[5],*roohist_T[5];
  RooRealVar *kJES[10],*kJER[10];
  RooWorkspace *w = new RooWorkspace("w","workspace");
  
  TString tMERGE = MERGE ? "_CATmerge56" : "";
  
  //RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
  int counter(0);
  for(int isel=0;isel<NSEL;isel++) {
    inf[0] = TFile::Open(PATH+"Fit_T_t-channel_sel"+SELECTION[isel]+".root");
    inf[1] = TFile::Open(PATH+"Fit_T_tW-channel_sel"+SELECTION[isel]+".root");
    inf[2] = TFile::Open(PATH+"Fit_T_s-channel_sel"+SELECTION[isel]+".root");
    inf[3] = TFile::Open(PATH+"Fit_Tbar_t-channel_sel"+SELECTION[isel]+".root");
    inf[4] = TFile::Open(PATH+"Fit_Tbar_tW-channel_sel"+SELECTION[isel]+".root");
    inf[5] = TFile::Open(PATH+"Fit_Tbar_s-channel_sel"+SELECTION[isel]+".root");
    inf[6] = TFile::Open(PATH+"Fit_TTJets_sel"+SELECTION[isel]+".root");
    inf[7] = TFile::Open(PATH+"Fit_ZJets_sel"+SELECTION[isel]+".root");
    inf[8] = TFile::Open(PATH+"Fit_WJets_sel"+SELECTION[isel]+".root");
     
    TCanvas *canZ = new TCanvas("canZ_"+SELECTION[isel],"canZ_"+SELECTION[isel],900,600); 
    TCanvas *canT = new TCanvas("canT_"+SELECTION[isel],"canT_"+SELECTION[isel],900,600);  
    canZ->Divide(2,2);
    canT->Divide(2,2);
    TCanvas *can = new TCanvas(); 
    
    sprintf(name,"CMS_vbfbb_scale_mbb_sel%s",SELECTION[isel].Data()); 
    kJES[isel] = new RooRealVar(name,name,1.0);
    sprintf(name,"CMS_vbfbb_res_mbb_sel%s",SELECTION[isel].Data()); 
    kJER[isel] = new RooRealVar(name,name,1.0);
    kJES[isel]->setConstant(kTRUE);
    kJER[isel]->setConstant(kTRUE);
  
    for(int icat=0;icat<NCAT[isel];icat++) {
		if (MERGE && SELECTION[isel]=="VBF" && icat==1) counter = 56;
      /*
      sprintf(name,"CMS_vbfbb_scale_mbb_CAT%d",counter); 
      kJES[counter] = new RooRealVar(name,name,1.0);
      sprintf(name,"CMS_vbbb_res_mbb_CAT%d",counter); 
      kJER[counter] = new RooRealVar(name,name,1.0);
      kJES[counter]->setConstant(kTRUE);
      kJER[counter]->setConstant(kTRUE);
      */ 
      for(int i=0;i<9;i++) {
        hPass = (TH1F*)inf[i]->Get("TriggerPass");
        sprintf(name,"Hbb/events",icat);
        tr = (TTree*)inf[i]->Get(name); 
        sprintf(name,"puWt[0]*%s*(mva%s>%1.2f && mva%s<=%1.2f)",TRIG_WT[isel].Data(),SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
        TCut cut(name); 
        int NBINS(20);
        //if (icat > 1 && icat<=2) NBINS = 20; 
        if (icat > 2) NBINS = 12;
        sprintf(name,"hMbb%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbb[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbb[i]->Sumw2();
        can->cd();        
        tr->Draw(MASS_VAR[isel]+">>"+hMbb[i]->GetName(),cut);
        sprintf(name,"hMbbYield%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbbYield[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbbYield[i]->Sumw2();
        tr->Draw(MASS_VAR[isel]+">>"+hMbbYield[i]->GetName(),cut);
        hMbbYield[i]->Scale(LUMI[isel]*XSEC[i]/hPass->GetBinContent(1)); 
      }
      hZ  = (TH1F*)hMbb[7]->Clone("Z");
      hW  = (TH1F*)hMbb[8]->Clone("W");
      hTT = (TH1F*)hMbb[6]->Clone("TT");
      hST = (TH1F*)hMbb[0]->Clone("ST");
      hST->Add(hMbb[1]);
      hST->Add(hMbb[2]);
      hST->Add(hMbb[3]);
      hST->Add(hMbb[4]);
      hST->Add(hMbb[5]);
      hTop = (TH1F*)hTT->Clone("Top");
      hTop->Add(hST);
      //hZ->Add(hW);
      hZYield  = (TH1F*)hMbbYield[7]->Clone("ZYield");
      hWYield  = (TH1F*)hMbbYield[8]->Clone("WYield");
      hTTYield = (TH1F*)hMbbYield[6]->Clone("TTYield");
      hSTYield = (TH1F*)hMbbYield[0]->Clone("STYield");
      hSTYield->Add(hMbbYield[1]);
      hSTYield->Add(hMbbYield[2]);
      hSTYield->Add(hMbbYield[3]);
      hSTYield->Add(hMbbYield[4]);
      hSTYield->Add(hMbbYield[5]);
      hTopYield = (TH1F*)hTTYield->Clone("TopYield");
      hTopYield->Add(hSTYield);
      hZYield->Add(hWYield); 

      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *YieldZ = new RooRealVar(name,name,hZYield->Integral());
      sprintf(name,"yield_WJets_CAT%d",counter);
      RooRealVar *YieldW = new RooRealVar(name,name,hWYield->Integral());
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *YieldT = new RooRealVar(name,name,hTopYield->Integral());
      sprintf(name,"yield_TT_CAT%d",counter);
      RooRealVar *YieldTT = new RooRealVar(name,name,hTTYield->Integral());
      sprintf(name,"yield_ST_CAT%d",counter);
      RooRealVar *YieldST = new RooRealVar(name,name,hSTYield->Integral());

      sprintf(name,"roohist_Z_CAT%d",counter);
      roohist_Z[icat] = new RooDataHist(name,name,x,hZ);

      sprintf(name,"Z_mean_CAT%d",counter);
      RooRealVar mZ(name,name,95,80,110);
      sprintf(name,"Z_sigma_CAT%d",counter);
      RooRealVar sZ(name,name,12,9,20);

      sprintf(name,"Z_mean_shifted_CAT%d",counter);
      RooFormulaVar mZShift(name,"@0*@1",RooArgList(mZ,*(kJES[isel])));
      sprintf(name,"Z_sigma_shifted_CAT%d",counter);
      RooFormulaVar sZShift(name,"@0*@1",RooArgList(sZ,*(kJER[isel])));

      sprintf(name,"Z_a_CAT%d",counter);
      RooRealVar aZ(name,name,-1,-10,10);
      sprintf(name,"Z_n_CAT%d",counter);
      RooRealVar nZ(name,name,1,0,10);

      RooRealVar Zb0("Z_b0_CAT"+TString::Format("%d",counter),"Z_b0_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb1("Z_b1_CAT"+TString::Format("%d",counter),"Z_b1_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb2("Z_b2_CAT"+TString::Format("%d",counter),"Z_b2_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooBernstein Zbkg("Z_bkg_CAT"+TString::Format("%d",counter),"Z_bkg_CAT"+TString::Format("%d",counter),x,RooArgSet(Zb0,Zb1,Zb2));
      
      RooRealVar fZsig("fZsig_CAT"+TString::Format("%d",counter),"fZsig_CAT"+TString::Format("%d",counter),0.7,0.,1.);
      RooCBShape Zcore("Zcore_CAT"+TString::Format("%d",counter),"Zcore_CAT"+TString::Format("%d",counter),x,mZShift,sZShift,aZ,nZ);
    
      RooAddPdf modelZ("Z_model_CAT"+TString::Format("%d",counter),"Z_model_CAT"+TString::Format("%d",counter),RooArgList(Zcore,Zbkg),fZsig);
    
      RooFitResult *resZ = modelZ.fitTo(*roohist_Z[icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); 
  
      canZ->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_Z[icat]->plotOn(frame);
      modelZ.plotOn(frame,RooFit::LineWidth(2));
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      TPaveText *pave = new TPaveText(0.7,0.76,0.9,0.9,"NDC");
		pave->SetTextAlign(11);
      pave->SetFillColor(0);
      pave->SetBorderSize(0);
      pave->SetTextFont(62);
      pave->SetTextSize(0.045);
      pave->AddText(TString::Format("%s selection",SELNAME[isel].Data()));
		pave->AddText(TString::Format("CAT%d",counter));
		TText *lastline = pave->AddText("Z template");
		pave->SetY1NDC(pave->GetY2NDC()-0.055*3);
		TPaveText *paveorig = (TPaveText*)pave->Clone();
      paveorig->Draw();
    
      sprintf(name,"roohist_T_CAT%d",counter);
      if (icat < 3) { 
        roohist_T[icat] = new RooDataHist(name,name,x,hTopYield);
      }
      else {
        roohist_T[icat] = new RooDataHist(name,name,x,hSTYield);
      }

      sprintf(name,"Top_mean_CAT%d",counter);
      RooRealVar mT(name,name,130,0,200);
      sprintf(name,"Top_sigma_CAT%d",counter);
      RooRealVar sT(name,name,50,0,200);

      sprintf(name,"Top_mean_shifted_CAT%d",counter);
      RooFormulaVar mTShift(name,"@0*@1",RooArgList(mT,*(kJES[isel])));
      sprintf(name,"Top_sigma_shifted_CAT%d",counter);
      RooFormulaVar sTShift(name,"@0*@1",RooArgList(sT,*(kJER[isel])));

      sprintf(name,"Top_model_CAT%d",counter);

      RooGaussian *modelT = new RooGaussian(name,name,x,mTShift,sTShift); 
    
      RooFitResult *resT = modelT->fitTo(*roohist_T[icat],Save(),SumW2Error(kTRUE),"q");
      /*
      TF1 *tmp_func = new TF1("tmpFunc","gaus",XMIN,XMAX);
      tmp_func->SetParameters(1,a0.getVal(),a1.getVal());
      if (icat < 3) {
        float norm = tmp_func->Integral(XMIN,XMAX)/hTopYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hTopYield->Integral()/norm);
      }
      else {
        float norm = tmp_func->Integral(XMIN,XMAX)/hSTYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hSTYield->Integral()/norm);
      }  
      */
      canT->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_T[icat]->plotOn(frame);
      modelT->plotOn(frame,RooFit::LineWidth(2));
      //modelT->plotOn(frame,VisualizeError(*resT,1,kTRUE),FillColor(kGray),MoveToBack());
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      //tmp_func->Draw("sameL");
		lastline->SetTitle("Top template");
		pave->Draw();

      mZ.setConstant(kTRUE);
      sZ.setConstant(kTRUE);
      aZ.setConstant(kTRUE);
      nZ.setConstant(kTRUE);
      Zb0.setConstant(kTRUE);
      Zb1.setConstant(kTRUE);
      Zb2.setConstant(kTRUE);
      fZsig.setConstant(kTRUE);
      
      mT.setConstant(kTRUE);
      sT.setConstant(kTRUE);

      w->import(modelZ);
      w->import(*modelT);
      w->import(*YieldZ);
      w->import(*YieldT);
      w->import(*YieldTT);
      w->import(*YieldST);
      YieldZ->Print();
      YieldW->Print();
      YieldT->Print();
      YieldTT->Print();
      YieldST->Print();
      counter++;
    }// category loop
	 system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots ] && mkdir %s/plots",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots/bkgTemplates ] && mkdir %s/plots/bkgTemplates",OUTPATH.Data(),OUTPATH.Data()).Data());
	 TString FULLPATH(OUTPATH+"/plots/bkgTemplates");
	 canT->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canZ->GetName()));
	 canT->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canZ->GetName()));
	 delete can;
  }// selection loop
  system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
  system(TString::Format("[ ! -d %s/output ] && mkdir %s/output",OUTPATH.Data(),OUTPATH.Data()).Data());
  w->Print();
  w->writeToFile(TString::Format("%s/output/bkg_shapes_workspace%s.root",OUTPATH.Data(),tMERGE.Data()).Data());
}
Esempio n. 23
0
void Back_2dFit(void){
  TFile *ifile = TFile::Open("/home/vitaly/B0toDh0/TMVA/fil_b2dh_gen.root");
  TTree *tree = (TTree*)ifile->Get("TEvent");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("comb",-1);

  RooArgSet argset;
  
  const double mbcMin = 5.20;
  const double mbcMax = 5.29;
  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",mbc_min,mbc_max);
  mbc.setRange("mbcSignal",mbc_min,mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset);
  RooDataSet* ds0 = ds.reduce(RooArgSet(de,mbc));
  RooDataHist* dh = ds0->binnedClone();
  ds.Print();
  dh->Print();

  ////////////
  // de pdf //
  ////////////
//  RooRealVar c1("c1","c1",mc_c1,-1.,0.); if(cComb) c1.setConstant(kTRUE);
//  RooRealVar c2("c2","c2",mc_c2,0.,0.1); if(cComb) c2.setConstant(kTRUE);
  RooRealVar c3("c3","c3",mc_c1,-1.,0.); if(cComb) c3.setConstant(kTRUE);
  RooRealVar c4("c4","c4",mc_c2,0.,0.1); if(cComb) c4.setConstant(kTRUE);
  RooChebychev pdf_de("pdf_de","pdf_de",de,RooArgSet(c3,c4));

  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argpar("argpar","argus shape parameter",mc_argpar,-100.,-1.); if(cComb)
  argpar.setConstant(kTRUE);
  RooRealVar argedge("argedge","argedge",mc_argedge,5.285,5.292); if(cComb) argedge.setConstant(kTRUE);
  RooArgusBG pdf_mbc("pdf_mbc","Argus PDF",mbc,argedge,argpar);

  /////////
  // pdf //
  /////////
  RooProdPdf pdf("pdf","pdf",RooArgList(pdf_de,pdf_mbc));

  pdf.fitTo(*dh,Verbose(),Timer(true));

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(deFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out;
  out.str("");
  out << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  TPaveText *pt = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  pt->AddText(out.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,200);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,200);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kGreen));
  pdf.plotOn(mbcFrame,LineWidth(2),LineColor(kGreen));
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  out.str("");
  out << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  TPaveText *ptmbc = new TPaveText(0.6,0.8,0.98,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  ptmbc->AddText(out.str().c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT = new TLine(mbc_max,0,mbc_max,150);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT = new TLine(mbc_min,0,mbc_min,150);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();
  
  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();
  
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,-0.15,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  cmmbc->Update();
}
Esempio n. 24
0
void PurityFit(const int _mode){
  TChain* tree = new TChain("TEvent");
//  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_uds_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_charm_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_charged_2_12.root");
  tree->Add("/home/vitaly/B0toDh0/TMVA/FIL1_b2dh_mixed_2_12.root");

  gROOT->ProcessLine(".L pdfs/RooRhoDeltaEPdf.cxx+");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho2",2);
  b0f.defineType("rho3",3);
  b0f.defineType("rho4",4);
  b0f.defineType("rho11",11);
  b0f.defineType("comb",-1);

  RooCategory mode("mode","mode");
  RooCategory h0mode("h0mode","h0mode");

  double BDTG_MIN = 0;
  double BDTG_MAX = 1;
  bool gg_flag = true;
  double Mbc_min;
  double Mbc_max;
  double dE_min;
  double dE_max;
  int m_mode,m_h0mode;
  double mh0_min, mh0_max;
  string label;
  switch(_mode){
  case 1:
    label = string("#pi^{0}");
    BDTG_MIN = bdt_cut_pi0;
    mode.defineType("pi0",1);
    h0mode.defineType("gg",10);
    Mbc_min = mbc_min_pi0;
    Mbc_max = mbc_max_pi0;
    dE_min  = de_min_pi0;
    dE_max  = de_max_pi0;
    m_mode = 1;
    m_h0mode = 10;
    mh0_min = mpi0_min;
    mh0_max = mpi0_max;
    break;
  case 2:
    label = string("#eta#rightarrow#gamma#gamma");
    BDTG_MIN = bdtg_cut_etagg;
    mode.defineType("eta",2);
    h0mode.defineType("gg",10);
    Mbc_min = mbc_min;
    Mbc_max = mbc_max;
    dE_min  = de_min;
    dE_max  = de_max;
    m_mode = 2;
    m_h0mode = 10;
    mh0_min = EtaGGMass-metagg_cut;
    mh0_max = EtaGGMass+metagg_cut;
    break;
  case 3:
    label = string("#eta#rightarrow#pi^{+}#pi^{-}#pi^{0}");
    BDTG_MIN = bdtg_cut_etappp;
    gg_flag = false;
    mode.defineType("eta",2);
    h0mode.defineType("ppp",20);
    Mbc_min = mbc_min;
    Mbc_max = mbc_max;
    dE_min  = de_min_etappp;
    dE_max  = de_max_etappp;
    m_mode = 2;
    m_h0mode = 20;
    mh0_min = EtaMass-metappp_cut;
    mh0_max = EtaMass+metappp_cut;
    break;
  case 4:
    label = string("#omega");
    BDTG_MIN = bdtg_cut_omega;
    gg_flag = false;
    mode.defineType("omega",3);
    h0mode.defineType("ppp",20);
    Mbc_min = mbc_min_omega;
    Mbc_max = mbc_max_omega;
    dE_min  = de_min_omega;
    dE_max  = de_max_omega;
    m_mode = 3;
    m_h0mode = 20;
    mh0_min = OmegaMass-momega_cut;
    mh0_max = OmegaMass+momega_cut;
    break;
  default:
    return;
  }

  RooArgSet argset;
  argset.add(mode);
  argset.add(h0mode);
  argset.add(b0f);

  RooCategory flv("flv_mc","flv_mc");
  flv.defineType("B0",1);
  flv.defineType("anti-B0",-1);
  argset.add(flv);

  RooCategory bin("bin","bin");
  bin.defineType("1",1); bin.defineType("-1",-1);
  bin.defineType("2",2); bin.defineType("-2",-2);
  bin.defineType("3",3); bin.defineType("-3",-3);
  bin.defineType("4",4); bin.defineType("-4",-4);
  bin.defineType("5",5); bin.defineType("-5",-5);
  bin.defineType("6",6); bin.defineType("-6",-6);
  bin.defineType("7",7); bin.defineType("-7",-7);
  bin.defineType("8",8); bin.defineType("-8",-8);
  argset.add(bin);

  RooSuperCategory binflv("binflv","binflv",RooArgSet(bin,flv));

  const double mbcMin = 5.20;
  const double mbcMax = 5.2885;
  const double deMin = -0.15;
  const double deMax = 0.3;
  const double elliscaleDe  = TMath::Sqrt(4./TMath::Pi());
  const double elliscaleMbc = TMath::Sqrt(4./TMath::Pi());

  RooRealVar mbc_center("mbc_center","mbc_center",0.5*(Mbc_min+Mbc_max),Mbc_min,Mbc_max); mbc_center.setConstant(kTRUE);
  RooRealVar mbc_center_eq("mbc_center_eq","mbc_center_eq",mr_argedge_3-0.5*(Mbc_max-Mbc_min)*elliscaleMbc,Mbc_min,Mbc_max); mbc_center_eq.setConstant(kTRUE);
  RooRealVar de_center("de_center","de_center",0.5*(dE_min+dE_max),dE_min,dE_max); de_center.setConstant(kTRUE);
  RooRealVar mbc_radius("mbc_radius","mbc_radius",0.5*(Mbc_max-Mbc_min)*elliscaleMbc,0,0.5*(mbcMax-mbcMin)); mbc_radius.setConstant(kTRUE);
  RooRealVar de_radius("de_radius","de_radius",0.5*(dE_max-dE_min)*elliscaleDe,0.,0.5*(deMax-deMin)); de_radius.setConstant(kTRUE);
  RooRealVar mbc_radius1("mbc_radius1","mbc_radius1",0.5*(Mbc_max-Mbc_min),0,0.5*(mbcMax-mbcMin)); mbc_radius1.setConstant(kTRUE);
  RooRealVar de_radius1("de_radius1","de_radius1",0.5*(dE_max-dE_min),0.,0.5*(deMax-deMin)); de_radius1.setConstant(kTRUE);

  cout << 0.5*(Mbc_min+Mbc_max) << " " << 0.5*(Mbc_max-Mbc_min) << endl;
  cout << 0.5*(dE_min+dE_max) << " " << 0.5*(dE_max-dE_min) << endl;

  mbc_center.Print();
  mbc_center_eq.Print();

  RooRealVar mbc("mbc","M_{bc}",0.5*(Mbc_min+Mbc_max),mbcMin,mbcMax,"GeV"); argset.add(mbc);
  mbc.setRange("Signal",Mbc_min,Mbc_max);
  mbc.setRange("mbcSignal",Mbc_min,Mbc_max);
  mbc.setRange("deSignal",mbcMin,mbcMax);

  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",dE_min,dE_max);
  de.setRange("mbcSignal",deMin,deMax);
  de.setRange("deSignal",dE_min,dE_max);

//   de.setRange("Ellips",dE_min,dE_max);
//   RooFormulaVar mbclo("mbclo","@1-@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4+0.00001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
//   RooFormulaVar mbchi("mbchi","@1+@2*TMath::Sqrt(1-(@0-@3)/@4*(@0-@3)/@4+0.00001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
//   mbc.setRange("Ellips",mbclo,mbchi);

  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mh0("mh0","mh0",mh0_min,mh0_max,"GeV"); argset.add(mh0);
  RooRealVar mpi0("mpi0","mpi0",mpi0_min,mpi0_max,"GeV"); if(_mode!=2) argset.add(mpi0);
  RooRealVar bdt("bdt","bdt",BDTG_MIN,BDTG_MAX); argset.add(bdt);

  argset.add(b0f);
  RooDataSet ds_sig("ds_sig","ds_sig",tree,argset,"mbc>0||mbc<=0 && (b0f == 1 || b0f == 5 || b0f == 10)");
  RooDataSet ds_bkg("ds_bkg","ds_bkg",tree,argset,"mbc>0||mbc<=0 && !(b0f == 1 || b0f == 5 || b0f == 10)");
  RooDataHist dh("dh","dh");
  dh.add(ds_sig,"",1./0.563);
  dh.add(ds_bkg,"",1./0.949);

  stringstream out;
  out.str("");
  out << "de<" << dE_max << " && de>" << dE_min;
  out << " && mbc>" << Mbc_min << " && mbc<" << Mbc_max;
  Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
  sigtable->Print();
  sigtable->Print("v");

  Roo1DTable* fulltable = ds.table(b0f);
  fulltable->Print();
  fulltable->Print("v");

//  RooDataHist* dh = ds0->binnedClone();

  ds.Print();
  int _b0f = -1;
  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  if(gg_flag){
    RooRealVar  de0("de0","de0",get_de0(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) de0.setConstant(kTRUE);
    RooRealVar  s1("s1","s1",get_s1(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) s1.setConstant(kTRUE);
    RooGaussian g1("g1","g1",de,de0,s1);

    RooRealVar deCBl("deCBl","deCBl",get_deCBl(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) deCBl.setConstant(kTRUE);
    RooRealVar sCBl("sCBl","sCBl",get_sCBl(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) sCBl.setConstant(kTRUE);
    RooRealVar alphal("alphal","alphal", get_alphal(m_mode,m_h0mode,_b0f), 0.,10.);                          if(cSIG) alphal.setConstant(kTRUE);
    RooRealVar nl("nl","nl",2.,0.,100.); nl.setConstant(kTRUE);

    RooRealVar deCBr("deCBr","deCBr",get_deCBr(m_mode,m_h0mode,_b0f),-0.2,0.1); if(cSig) deCBr.setConstant(kTRUE);
    RooRealVar sCBr("sCBr","sCBr",get_sCBr(m_mode,m_h0mode,_b0f),0.,0.5);       if(cSig) sCBr.setConstant(kTRUE);
    RooRealVar alphar("alphar","alphar",get_alphar(m_mode,m_h0mode,_b0f),-10.,0.);                          if(cSig) alphar.setConstant(kTRUE);
    RooRealVar nr("nr","nr",2,0.,100.); nr.setConstant(kTRUE);

    RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
    RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

    RooRealVar fCBl("fCBl","fCBl",get_fCBl(m_mode,m_h0mode,_b0f),0.,1.); if(cSig) fCBl.setConstant(kTRUE);
    RooRealVar fCBr("fCBr","fCBr",get_fCBr(m_mode,m_h0mode,_b0f),0.,1.); if(cSig) fCBr.setConstant(kTRUE);

    RooAddPdf pdf_de_sig("pdf_de_sig","pdf_de_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));
  } else{
    RooRealVar de0_201("de0_201","de0_201",get_de0(m_mode,m_h0mode,1),-0.1,0.1); if(cSig) de0_201.setConstant(kTRUE);
    RooRealVar  s1_201("s1_201","s1_201",get_s1(m_mode,m_h0mode,1),0.,0.5); if(cSig) s1_201.setConstant(kTRUE);
    RooGaussian g1_201("g1_201","g1_201",de,de0_201,s1_201);

    RooRealVar deCBl_201("deCBl_201","deCBl_201",get_deCBl(m_mode,m_h0mode,1),-0.1,0.1);     if(cSig) deCBl_201.setConstant(kTRUE);
    RooRealVar sCBl_201("sCBl_201","sCBl_201",get_sCBl(m_mode,m_h0mode,1),0.,0.5);           if(cSig) sCBl_201.setConstant(kTRUE);
    RooRealVar nl_201("nl_201","nl_201",2.,0.,100.); nl_201.setConstant(kTRUE);
    RooRealVar alphal_201("alphal_201","alphal_201",get_alphal(m_mode,m_h0mode,1),-10.,10.); if(cSig) alphal_201.setConstant(kTRUE);
    RooRealVar deCBr_201("deCBr_201","deCBr_201",get_deCBr(m_mode,m_h0mode,1),-0.1,0.1);     if(cSig) deCBr_201.setConstant(kTRUE);
    RooRealVar sCBr_201("sCBr_201","sCBr_201",get_sCBr(m_mode,m_h0mode,1),0.,0.5);           if(cSig) sCBr_201.setConstant(kTRUE);
    RooRealVar nr_201("nr_201","nr_201",2.,0.,100.); nr_201.setConstant(kTRUE);
    RooRealVar alphar_201("alphar_201","alphar_201",get_alphar(m_mode,m_h0mode,1),-10.,10.); if(cSig) alphar_201.setConstant(kTRUE);

    RooCBShape CBl_201("CBl_201","CBl_201",de,deCBl_201,sCBl_201,alphal_201,nl_201);
    RooCBShape CBr_201("CBr_201","CBr_201",de,deCBr_201,sCBr_201,alphar_201,nr_201);

    RooRealVar fCBl_201("fCBl_201","fCBl_201",get_fCBl(m_mode,m_h0mode,1),0.,1.); if(cSig) fCBl_201.setConstant(kTRUE);
    if(_mode == 3){
      fCBl_201.setVal(0.);
      fCBl_201.setConstant(kTRUE);
      alphal_201.setConstant(kTRUE);
    }
    RooRealVar fCBr_201("fCBr_201","fCBr_201",get_fCBr(m_mode,m_h0mode,1),0.,1.); if(cSig) fCBr_201.setConstant(kTRUE);

    RooAddPdf pdf_de1("pdf_de1","pdf_de1",RooArgList(CBl_201,CBr_201,g1_201),RooArgSet(fCBl_201,fCBr_201));

    RooRealVar  de0_205("de0_205","de0_205",get_de0(m_mode,m_h0mode,5),-0.2,0.1); if(cSig) de0_205.setConstant(kTRUE);
    RooRealVar  s1_205("s1_205","s1_205",get_s1(m_mode,m_h0mode,5),0.,0.5);       if(cSig) s1_205.setConstant(kTRUE);
    RooGaussian g1_205("g1_205","g1_205",de,de0_205,s1_205);

    RooRealVar deCBl_205("deCBl_205","deCBl_205",get_deCBl(m_mode,m_h0mode,5),-0.1,0.1); if(cSig) deCBl_205.setConstant(kTRUE);
    RooRealVar sCBl_205("sCBl_205","sCBl_205",get_sCBl(m_mode,m_h0mode,5),0.,0.5);       if(cSig) sCBl_205.setConstant(kTRUE);
    RooRealVar nl_205("nl_205","nl_205",2,0.,100.); nl_205.setConstant(kTRUE);
    RooRealVar alphal_205("alphal_205","alphal_205",get_alphal(m_mode,m_h0mode,5),-10.,10.);  if(cSig) alphal_205.setConstant(kTRUE);
    RooCBShape CBl_205("CBl_205","CBl_205",de,deCBl_205,sCBl_205,alphal_205,nl_205);

    RooRealVar fCBl_205("fCBl_205","fCBl_205",get_fCBl(m_mode,m_h0mode,5),0.,1.); if(cSig) fCBl_205.setConstant(kTRUE);

    RooAddPdf pdf_de5("pdf_de5","pdf_de5",RooArgList(CBl_205,g1_205),RooArgSet(fCBl_205));
  }

  /////////////
  // mbc pdf //
  /////////////
  if(gg_flag){
    RooRealVar a_s("a_s","a_s",get_a_s(_mode)); if(cSig) a_s.setConstant(kTRUE);
    RooRealVar b_s("b_s","b_s",get_b_s(_mode)); if(cSig) b_s.setConstant(kTRUE);
    RooRealVar c_s("c_s","c_s",get_c_s(_mode),0.0015,0.0035);// if(cSig) c_s.setConstant(kTRUE);
    RooFormulaVar S("S","S","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s,b_s,a_s));

    RooRealVar alpha("alpha","alpha",0.139,0.01,2.); alpha.setConstant(kTRUE);

    RooRealVar a_mbc0("a_mbc0","a_mbc0",get_a_mbc0(_mode)); if(cSig) a_mbc0.setConstant(kTRUE);
    RooRealVar b_mbc0("b_mbc0","b_mbc0",get_b_mbc0(_mode)); if(cSig) b_mbc0.setConstant(kTRUE);
    RooRealVar c_mbc0("c_mbc0","c_mbc0",get_c_mbc0(_mode),5.277,5.285);// if(cSig) c_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0("MBC0","MBC0","@1+@2*@0+@3*@0*@0",RooArgList(de,c_mbc0,b_mbc0,a_mbc0));
    RooNovosibirsk pdf_mbc_sig("pdf_mbc_sig","pdf_mbc_sig",mbc,MBC0,S,alpha);
  } else{
    RooRealVar alpha("alpha","alpha",0.139,0.01,2.); alpha.setConstant(kTRUE);
    RooRealVar c0("c0","c0",get_c0(_mode)); if(cSig) c0.setConstant(kTRUE);
    RooRealVar c1("c1","c1",get_c1(_mode)); if(cSig) c1.setConstant(kTRUE);
    RooRealVar c2("c2","c2",get_c2(_mode)); if(cSig) c2.setConstant(kTRUE);
    RooRealVar mbc0("mbc0","mbc0",5.284,5.277,5.29);// if(cSig) mbc0.setConstant(kTRUE);
    RooFormulaVar MBC("MBC","MBC","@0+@1*TMath::Erf((@2-@3))/@4",RooArgList(mbc0,c0,c1,de,c2));

    RooRealVar a_s1("a_s1","a_s1",get_a_s(_mode),0.15,0.45); if(cSig) a_s1.setConstant(kTRUE);
    RooRealVar b_s1("b_s1","b_s1",get_b_s(_mode),-0.05,0.05); if(cSig) b_s1.setConstant(kTRUE);
    RooRealVar c_s1("c_s1","c_s1",get_c_s(_mode),0.0015,0.0035);// if(cSig) c_s1.setConstant(kTRUE);
    RooFormulaVar S1("S1","S1","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s1,b_s1,a_s1));
    RooNovosibirsk pdf_mbc1("pdf_mbc1","pdf_mbc1",mbc,MBC,S1,alpha);

    RooRealVar a_s5("a_s5","a_s5",get_a5_s(_mode)); if(cSig) a_s5.setConstant(kTRUE);
    RooRealVar b_s5("b_s5","b_s5",get_b5_s(_mode)); if(cSig) b_s5.setConstant(kTRUE);
    RooRealVar c_s5("c_s5","c_s5",get_c5_s(_mode),0.0015,0.0055); if(cSig) c_s5.setConstant(kTRUE);
    RooFormulaVar S5("S5","S5","@1+@2*@0+@3*@0*@0",RooArgList(de,c_s5,b_s5,a_s5));

    RooRealVar a_mbc0("a_mbc0","a_mbc0",get_a5_mbc0(_mode)); if(cSig) a_mbc0.setConstant(kTRUE);
    RooRealVar b_mbc0("b_mbc0","b_mbc0",get_b5_mbc0(_mode)); if(cSig) b_mbc0.setConstant(kTRUE);
    RooRealVar c_mbc0("c_mbc0","c_mbc0",get_c5_mbc0(_mode),5.27,5.29); if(cSig) c_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0("MBC0","MBC0","@1+@2*@0+@3*@0*@0",RooArgList(de,c_mbc0,b_mbc0,a_mbc0));
    RooNovosibirsk pdf_mbc5("pdf_mbc5","pdf_mbc5",mbc,MBC0,S5,alpha);
  }

  /////////
  // pdf //
  /////////
  if(gg_flag){
    RooProdPdf pdf_sig("pdf_sig","pdf_sig",pdf_de_sig,Conditional(pdf_mbc_sig,mbc));
  } else{
    RooRealVar f_201("f_201","f_201",get_f201(m_mode,m_h0mode),0.,1.); if(cSig) f_201.setConstant(kTRUE);
    RooProdPdf pdf1_sig("pdf1_sig","pdf1_sig",pdf_de1,Conditional(pdf_mbc1,mbc));
    RooProdPdf pdf5_sig("pdf5_sig","pdf5_sig",pdf_de5,Conditional(pdf_mbc5,mbc));
    RooAddPdf  pdf_sig("pdf_sig","pdf_sig",RooArgList(pdf1_sig,pdf5_sig),RooArgSet(f_201));
  }

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c10("c10","c10",get_cmb_c10(_mode),-10,50.); if(cComb) c10.setConstant(kTRUE);
  RooRealVar c11("c11","c11",get_cmb_c11(_mode),-50,0.);  if(cComb) c11.setConstant(kTRUE);
  RooFormulaVar c1_cmb("c1_cmb","@0+@1*@2",RooArgSet(c10,c11,mbc));
  RooRealVar c2_cmb("c2_cmb","c2_cmb",get_cmb_c20(_mode),-0.1,1);     if(cComb) c2_cmb.setConstant(kTRUE);
  RooChebychev pdf_de_comb_bb("pdf_de_comb_bb","pdf_de_comb_bb",de,RooArgSet(c1_cmb,c2_cmb));

  RooRealVar C1("C1","C1",get_cmb_c1(_mode),-10,50.); if(cComb) C1.setConstant(kTRUE);
  RooRealVar C2("C2","C2",get_cmb_c2(_mode),-0.1,1);  if(cComb) C2.setConstant(kTRUE);
  RooChebychev pdf_de_comb_qq("pdf_de_comb_qq","pdf_de_comb_qq",de,RooArgSet(C1,C2));
  /////////////
  // mbc pdf //
  /////////////
  RooRealVar argedge("argedge","argedge",5.288,5.285,5.29); //argedge.setConstant(kTRUE);
  RooRealVar argpar_cmb_bb("argpar_cmb_bb","argpar_cmb_bb",get_argpar_bb(_mode),-300,-10.); if(cComb) argpar_cmb_bb.setConstant(kTRUE);
  RooArgusBG pdf_mbc_comb_ar("pdf_mbc_comb_ar","Argus PDF",mbc,argedge,argpar_cmb_bb);

  RooRealVar mbc0_cmb_bb("mbc0_cmb_bb","mbc0_cmb_bb",get_mbc0_cmb_bb(_mode),5.25,5.29,"GeV");// if(cComb) mbc0_cmb_bb.setConstant(kTRUE);
  RooRealVar mbcWidth_cmb_bb("mbcWidth","mbcWidth",get_mbcw_cmb_bb(_mode),0.,0.1,"GeV"); if(cComb) mbcWidth_cmb_bb.setConstant(kTRUE);
  RooGaussian mbcGaus_cmb_bb("mbcGaus","mbcGaus",mbc,mbc0_cmb_bb,mbcWidth_cmb_bb);

  RooRealVar f_g("f_g","f_g",get_f_g_cmb_bb(_mode),0.4,0.7);if(_mode == 2 || !gg_flag){ f_g.setConstant(kTRUE);}
  RooAddPdf pdf_mbc_cmb_bb("pdf_mbc_cmb_bb","pdf_mbc_cmb_bb",RooArgList(mbcGaus_cmb_bb,pdf_mbc_comb_ar),RooArgSet(f_g));

  RooRealVar argpar_cmb_qq("argpar_cmb_qq","argpar_cmb_qq",get_argpar_qq(_mode),-300,-10.); if(cComb) argpar_cmb_qq.setConstant(kTRUE);
  RooArgusBG pdf_mbc_cmb_qq("pdf_mbc_cmb_qq","pdf_mbc_cmb_qq",mbc,argedge,argpar_cmb_qq);
  
  /////////
  // pdf //
  /////////
  RooRealVar f_bb("f_bb","f_bb",0.3,0.,1.);
  RooProdPdf pdf_cmb_bb("pdf_cmb_bb","pdf_cmb_bb",pdf_mbc_cmb_bb,Conditional(pdf_de_comb_bb,de));
  RooProdPdf pdf_cmb_qq("pdf_cmb_qq","pdf_cmb_qq",pdf_mbc_cmb_qq,Conditional(pdf_de_comb_qq,de));
  RooAddPdf pdf_comb("pdf_comb","pdf_comb",RooArgSet(pdf_cmb_bb,pdf_cmb_qq),RooArgList(f_bb));

  /////////////////////
  // Peaking bkg PDF //
  /////////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0r("de0r","de0r",get_de0r(_mode),-0.2,0.12);         if(cPeak) de0r.setConstant(kTRUE);
  RooRealVar slopel("slopel","slopel",get_slopel(_mode),-1.e5,0.);  if(cPeak) slopel.setConstant(kTRUE);
  RooRealVar sloper("sloper","sloper",get_sloper(_mode),-10000,0.); if(cPeak) sloper.setConstant(kTRUE);
  RooRealVar steep("steep","steep",get_steep(_mode),0.,1000.);      if(cPeak) steep.setConstant(kTRUE);
  RooRealVar p5("p5","p5",get_p5(_mode),0.01,1000.);                if(cPeak) p5.setConstant(kTRUE);
  RooRhoDeltaEPdf pdf_de_peak("pdf_de_peak","pdf_de_peak",de,de0r,slopel,sloper,steep,p5);
//  RooGenericPdf pdf_de_peak("pdf_de_peak","1+(@0-@1)*@2+@4*TMath::Log(1+@5*TMath::Exp((@3-@2)*(@0-@1)/@4)) > 0 ? 1+(@0-@1)*@2+@4*TMath::Log(1+@5*TMath::Exp((@3-@2)*(@0-@1)/@4)) : 0.001",RooArgSet(de,de0r,slopel,sloper,steep,p5));
  /////////////
  // mbc pdf //
  /////////////
  if(gg_flag){
    RooRealVar b_peak_s("b_peak_s","b_peak_s",get_peak_b_s(_mode),-0.1,0.1); if(cPeak) b_peak_s.setConstant(kTRUE);
    RooRealVar k_peak_s("k_peak_s","k_peak_s",get_peak_k_s(_mode),-0.1,0.1); if(cPeak) k_peak_s.setConstant(kTRUE);
    RooFormulaVar S_peak("S_peak","S_peak","@0+@1*@2",RooArgList(b_peak_s,de,k_peak_s));
    RooRealVar alpha_peak("alpha_peak","alpha_peak",0.139,0.01,2.); alpha_peak.setConstant(kTRUE);
    RooRealVar b_peak_mbc0("b_peak_mbc0","b_peak_mbc0",get_peak_b_mbc0(_mode),5.25,5.29); if(cPeak) b_peak_mbc0.setConstant(kTRUE);
    RooRealVar k_peak_mbc0("k_peak_mbc0","k_peak_mbc0",get_peak_k_mbc0(_mode),-0.1,0.1);  if(cPeak) k_peak_mbc0.setConstant(kTRUE);
    RooFormulaVar MBC0_peak("MBC0_peak","MBC0_peak","@0+@1*@2",RooArgList(b_peak_mbc0,de,k_peak_mbc0));
    RooNovosibirsk pdf_mbc_peak("pdf_mbc_peak","pdf_mbc_peak",mbc,MBC0_peak,S_peak,alpha_peak);
  } else{
//    RooRealVar argedge("argedge","argedge",5.288,5.285,5.29); //argedge.setConstant(kTRUE);
    RooRealVar argpar_peak_bb("argpar_peak_bb","argpar_peak_bb",get_argpar_bb(_mode),-300,-10.); if(cPeak) argpar_peak_bb.setConstant(kTRUE);
    RooArgusBG pdf_mbc_peak_ar("pdf_mbc_peak_ar","Argus PDF",mbc,argedge,argpar_peak_bb);

    RooRealVar mbc0_peak("mbc0_peak","mbc0_peak",get_peak_b_mbc0(_mode),5.25,5.291,"GeV"); if(cPeak) mbc0_peak.setConstant(kTRUE);
    RooRealVar mbcWidth_peak("mbcWidth_peak","mbcWidth_peak",get_peak_b_s(_mode),0.,0.1,"GeV"); if(cPeak) mbcWidth_peak.setConstant(kTRUE);
    RooGaussian mbcGaus_peak("mbcGaus_peak","mbcGaus_peak",mbc,mbc0_peak,mbcWidth_peak);
    RooRealVar f_g_peak("f_g_peak","f_g_peak",get_f_g_cmb_bb(_mode),0.,1.); if(cPeak) f_g_peak.setConstant(kTRUE);

    RooAddPdf pdf_mbc_peak("pdf_mbc_peak","pdf_mbc_peak",RooArgList(mbcGaus_peak,pdf_mbc_peak_ar),RooArgSet(f_g_peak));
  }
  /////////
  // pdf //
  /////////
  RooProdPdf pdf_peak("pdf_peak","pdf_peak",pdf_de_peak,Conditional(pdf_mbc_peak,mbc));

  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",1150,0.,10000.);
//  RooRealVar Npbg("Npbg","Npbg",100,0,100000.);
  RooRealVar Ncmb("Ncmb","Ncmb",2288,0,100000);
  switch(_mode){
  case 1:
    RooRealVar Npbg("Npbg","Npbg",100,0,100000.);
    break;
  case 2:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0051);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  case 3:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0081);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  case 4:
    RooConstVar f_p_f_bbc("f_p_f_bbc","f_p_f_bbc",0.0031);
    RooFormulaVar Npbg("Npbg","Npbg","@0*@1*@2",RooArgList(Ncmb,f_bb,f_p_f_bbc));
    break;
  default:
    return -1;
  }

  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_peak,pdf_comb),RooArgList(Nsig,Npbg,Ncmb));

  RooArgSet* params = pdf.getParameters(RooArgSet(de,mbc));
//  RooArgset* initParams = (RooArgSet*) params->snapshot();

  pdf.fitTo(ds,Verbose(),Timer(true));

  params->printLatex(OutputFile("PurityFit.tex"));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intRho  = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Npbg.getVal();
   const double nrho_err = _mode == 1 ? intRho->getVal()*Npbg.getError() : intRho->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Npbg.getVal()-nrho)/Npbg.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);

   de.setRange("Ellips",dE_min,dE_max);
   RooFormulaVar mbclo("mbclo","@1-@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   RooFormulaVar mbchi("mbchi","@1+@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius,de_center,de_radius));
   mbc.setRange("Ellips",mbclo,mbchi);

   de.setRange("Elli",dE_min,dE_max);
   RooFormulaVar mbclo1("mbclo1","@1-@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   RooFormulaVar mbchi1("mbchi1","@1+@2*TMath::Sqrt(TMath::Abs(1-(@0-@3)/@4*(@0-@3)/@4)+0.0000001)",RooArgSet(de,mbc_center,mbc_radius1,de_center,de_radius1));
   mbc.setRange("Elli",mbclo1,mbchi1);

   RooAbsReal* intSigEl = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intRhoEl = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   RooAbsReal* intCmbEl = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Ellips"));
   const double nsigEl = intSigEl->getVal()*Nsig.getVal();
   const double nsig_errEl = intSigEl->getVal()*Nsig.getError();
   const double nsig_errEl_npq = TMath::Sqrt(fabs(nsigEl*(Nsig.getVal()-nsigEl)/Nsig.getVal()));
   const double nsig_errEl_total = TMath::Sqrt(fabs(nsig_errEl*nsig_errEl+nsig_errEl_npq*nsig_errEl_npq));
   const double nrhoEl = intRhoEl->getVal()*Npbg.getVal();
   const double nrho_errEl = _mode == 1 ? intRhoEl->getVal()*Npbg.getError() : intRhoEl->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_errEl_npq = TMath::Sqrt(fabs(nrhoEl*(Npbg.getVal()-nrhoEl)/Npbg.getVal()));
   const double nrho_errEl_total = TMath::Sqrt(fabs(nrho_errEl*nrho_errEl+nrho_errEl_npq*nrho_errEl_npq));
   const double ncmbEl = intCmbEl->getVal()*Ncmb.getVal();
   const double ncmb_errEl = intCmbEl->getVal()*Ncmb.getError();
   const double ncmb_errEl_npq = TMath::Sqrt(fabs(ncmbEl*(Ncmb.getVal()-ncmbEl)/Ncmb.getVal()));
   const double ncmb_errEl_total = TMath::Sqrt(ncmb_errEl*ncmb_errEl+ncmb_errEl_npq*ncmb_errEl_npq);
   const double purityEl = nsigEl/(nsigEl+nrhoEl+ncmbEl);
   const double purity_errEl = nsig_errEl_total/(nsigEl+nrhoEl+ncmbEl);


   RooAbsReal* intSigEl1 = pdf_sig.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   const double intElli = intSigEl1->getVal();
   RooAbsReal* intRhoEl1 = pdf_peak->createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   RooAbsReal* intCmbEl1 = pdf_comb.createIntegral(RooArgSet(de,mbc),NormSet(RooArgSet(de,mbc)),Range("Elli"));
   const double nsigEl1 = intSigEl1->getVal()*Nsig.getVal();
   const double nsig_errEl1 = intSigEl1->getVal()*Nsig.getError();
   const double nsig_errEl1_npq = TMath::Sqrt(fabs(nsigEl1*(Nsig.getVal()-nsigEl1)/Nsig.getVal()));
   const double nsig_errEl1_total = TMath::Sqrt(fabs(nsig_errEl1*nsig_errEl1+nsig_errEl1_npq*nsig_errEl1_npq));
   const double nrhoEl1 = intRhoEl1->getVal()*Npbg.getVal();
   const double nrho_errEl1 = _mode == 1 ? intRhoEl1->getVal()*Npbg.getError() : intRhoEl1->getVal()*f_bb.getError()*Ncmb.getVal()*f_p_f_bbc.getVal();
   const double nrho_errEl1_npq = TMath::Sqrt(fabs(nrhoEl1*(Npbg.getVal()-nrhoEl1)/Npbg.getVal()));
   const double nrho_errEl1_total = TMath::Sqrt(fabs(nrho_errEl1*nrho_errEl1+nrho_errEl1_npq*nrho_errEl1_npq));
   const double ncmbEl1 = intCmbEl1->getVal()*Ncmb.getVal();
   const double ncmb_errEl1 = intCmbEl1->getVal()*Ncmb.getError();
   const double ncmb_errEl1_npq = TMath::Sqrt(ncmbEl1*(Ncmb.getVal()-ncmbEl1)/Ncmb.getVal());
   const double ncmb_errEl1_total = TMath::Sqrt(ncmb_errEl1*ncmb_errEl1+ncmb_errEl1_npq*ncmb_errEl1_npq);
   const double purityEl1 = nsigEl1/(nsigEl1+nrhoEl1+ncmbEl1);
   const double purity_errEl1 = nsig_errEl1_total/(nsigEl1+nrhoEl1+ncmbEl1);

  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_peak),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_cmb_bb),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,Components(pdf_cmb_qq),LineStyle(kDashed),ProjectionRange("mbcSignal"));
  pdf.plotOn(deFrame,LineWidth(2),ProjectionRange("mbcSignal"));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("#Delta E, Signal","#Delta E, Signal",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  out.str("");
  out << "(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius1.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius1.getVal() << "<1";
  Roo1DTable* ellitable1 = ds.table(b0f,out.str().c_str());

  out.str("");
  out << "(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius.getVal() << "<1";
  Roo1DTable* ellitable = ds.table(b0f,out.str().c_str());

  const int NSIGNAL_ELLI   = ellitable1->get("signal") + ellitable1->get("fsr") + ellitable1->get("bad_pi0");
//  const int NSIGNAL_ELLIPS = ellitable->get("signal")  + ellitable->get("fsr")  + ellitable->get("bad_pi0");

  stringstream out1;
  TPaveText *pt = new TPaveText(0.5,0.6,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsigEl1+0.5) << " #pm " << (int)(nsig_errEl1_total+0.5) << " (" << NSIGNAL_ELLI << ")";
//  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
//  out1.str("");
//  out1 << "S_{2}: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5) << " (" << NSIGNAL_ELLIPS << ")";
//  pt->AddText(out1.str().c_str());
  out1.str("");
//  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  out1 << "P: " << std::fixed << std::setprecision(2) << purityEl1*100. << " #pm " << purity_errEl1*100;
  pt->AddText(out1.str().c_str());
  pt->AddText(label.c_str());
  pt->Draw();

  TLine *de_line_RIGHT;
  de_line_RIGHT = new TLine(dE_max,0,dE_max,120);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT;
  de_line_LEFT = new TLine(dE_min,0,dE_min,120);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();

  // mbc //
  RooPlot* mbcFrame = mbc.frame();
  ds.plotOn(mbcFrame,DataError(RooAbsData::SumW2),MarkerSize(1),CutRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_cmb_bb),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_cmb_qq),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_sig),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,Components(pdf_peak),LineStyle(kDashed),ProjectionRange("deSignal"));
  pdf.plotOn(mbcFrame,LineWidth(2),ProjectionRange("deSignal"));

  RooHist* hmbcpull = mbcFrame->pullHist();
  RooPlot* mbcPull  = mbc.frame(Title("#Delta E pull distribution"));
  mbcPull->addPlotable(hmbcpull,"P");
  mbcPull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cmmbc = new TCanvas("M_{bc}, Signal","M_{bc}, Signal",600,700);
  cmmbc->cd();

  TPad *pad1 = new TPad("pad1","pad1",0.01,0.20,0.99,0.99);
  TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.20);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLeftMargin(0.15);
  pad1->SetFillColor(0);

  mbcFrame->GetXaxis()->SetTitleSize(0.05);
  mbcFrame->GetXaxis()->SetTitleOffset(0.85);
  mbcFrame->GetXaxis()->SetLabelSize(0.04);
  mbcFrame->GetYaxis()->SetTitleOffset(1.6);
  mbcFrame->Draw();

  TPaveText *ptmbc = new TPaveText(0.2,0.6,0.7,0.9,"brNDC");
  ptmbc->SetFillColor(0);
  ptmbc->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << mbcFrame->chiSquare();
  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsigEl1+0.5) << " #pm " << (int)(nsig_errEl1_total+0.5) << " (" << NSIGNAL_ELLI << ")";
  ptmbc->AddText(out1.str().c_str());
//  out1.str("");
//  out1 << "S_{2}: " << (int)(nsigEl+0.5) << " #pm " << (int)(nsig_errEl_total+0.5) << " (" << NSIGNAL_ELLIPS << ")";
//  ptmbc->AddText(out1.str().c_str());
  out1.str("");
  out1 << "P: " << std::fixed << std::setprecision(2) << purityEl1*100. << " #pm " << purity_errEl1*100;
  ptmbc->AddText(out1.str().c_str());
  ptmbc->AddText(label.c_str());
  ptmbc->Draw();

  TLine *mbc_line_RIGHT;
  mbc_line_RIGHT = new TLine(Mbc_max,0,Mbc_max,40);
  mbc_line_RIGHT->SetLineColor(kRed);
  mbc_line_RIGHT->SetLineStyle(1);
  mbc_line_RIGHT->SetLineWidth((Width_t)2.);
  mbc_line_RIGHT->Draw();
  TLine *mbc_line_LEFT;
  mbc_line_LEFT = new TLine(Mbc_min,0,Mbc_min,40);
  mbc_line_LEFT->SetLineColor(kRed);
  mbc_line_LEFT->SetLineStyle(1);
  mbc_line_LEFT->SetLineWidth((Width_t)2.);
  mbc_line_LEFT->Draw();

  pad2->cd();
  pad2->SetLeftMargin(0.15);
  pad2->SetFillColor(0);
  mbcPull->SetMarkerSize(0.05);
  mbcPull->Draw();
  TLine *mbc_lineUP = new TLine(mbcMin,3,mbcMax,3);
  mbc_lineUP->SetLineColor(kBlue);
  mbc_lineUP->SetLineStyle(2);
  mbc_lineUP->Draw();
  TLine *mbc_line = new TLine(mbcMin,0,mbcMax,0);
  mbc_line->SetLineColor(kBlue);
  mbc_line->SetLineStyle(1);
  mbc_line->SetLineWidth((Width_t)2.);
  mbc_line->Draw();
  TLine *mbc_lineDOWN = new TLine(mbcMin,-3,mbcMax,-3);
  mbc_lineDOWN->SetLineColor(kBlue);
  mbc_lineDOWN->SetLineStyle(2);
  mbc_lineDOWN->Draw();

  cmmbc->Update();

  double DEMIN = -0.15;
  if(keysflag) DEMIN = -0.3;
  TH2D* hh_pdf = pdf.createHistogram("hh_data",de,Binning(50,DEMIN,0.1),YVar(mbc,Binning(50,5.26,5.30)));
  hh_pdf->SetLineColor(kBlue);
  TCanvas* hhc = new TCanvas("hhc","hhc",600,600);
  hhc->cd();
  hh_pdf->Draw("SURF");

  // Show signal ranges
  TEllipse* elli = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius.getVal(),mbc_radius.getVal());
  elli->SetFillColor(0);
  elli->SetFillStyle(0);
  elli->SetLineColor(kBlue);
  elli->SetLineWidth(2);
  TEllipse* elli1 = new TEllipse(de_center.getVal(),mbc_center.getVal(),de_radius1.getVal(),mbc_radius1.getVal());
  elli1->SetFillColor(0);
  elli1->SetFillStyle(0);
//  elli1->SetLineColor(kBlue);
  elli1->SetLineColor(kRed);
  elli1->SetLineWidth(2);
  TLine* l1 = new TLine(dE_min,Mbc_min,dE_max,Mbc_min);
  l1->SetLineColor(kRed);
  l1->SetLineStyle(1);
  l1->SetLineWidth(2);
  TLine* l2 = new TLine(dE_min,Mbc_max,dE_max,Mbc_max);
  l2->SetLineColor(kRed);
  l2->SetLineStyle(1);
  l2->SetLineWidth(2);
  TLine* l3 = new TLine(dE_min,Mbc_min,dE_min,Mbc_max);
  l3->SetLineColor(kRed);
  l3->SetLineStyle(1);
  l3->SetLineWidth(2);
  TLine* l4 = new TLine(dE_max,Mbc_min,dE_max,Mbc_max);
  l4->SetLineColor(kRed);
  l4->SetLineStyle(1);
  l4->SetLineWidth(2);

  TCanvas* ellican = new TCanvas("ellican","ellican",400,400);
  ellican->cd();
  out.str("");
  out << "bdtg>" << BDTG_MIN << " && de>-0.15 && de<0.20 && mbc>5.265 && b0f != 1 && b0f != 5 && b0f != 10 && b0f != 0";
  tree->Draw("mbc:de",out.str().c_str());
  tree->SetMarkerStyle(6);
  tree->SetMarkerColor(kBlue);
  out.str("");
  out << "bdtg>" << BDTG_MIN << " && de>-0.15 && de<0.20 && mbc>5.265 && (b0f == 1 || b0f == 5 || b0f == 10)";
  tree->Draw("mbc:de",out.str().c_str(),"same");
//  elli->Draw();
  elli1->Draw();
//  ellican->Pad().GetXaxis()->SetTitle("#DeltaE (GeV)");
//  l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

//  TCanvas* sigcan = new TCanvas("sigcan","sigcan",400,400);
//  sigcan->cd();
//  out <<
//  tree->Draw("mbc:de","bdtg>0.98 && de>-0.15 && de<0.20 && mbc>5.265 && (b0f == 1 || b0f == 5 || b0f == 10)");
//  elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

//  TCanvas* backcan = new TCanvas("backcan","backcan",400,400);
//  backcan->cd();
//  tree->Draw("mbc:de","bdtg>0.98 && de>-0.15 && de<0.20 && mbc>5.265 && !(b0f == 1 || b0f == 5 || b0f == 10)");
//  elli->Draw(); elli1->Draw(); l1->Draw(); l2->Draw(); l3->Draw(); l4->Draw();

  cout << "Rectangle:" << endl;
  out.str("");
  out << "de<" << dE_max << " && de>" << dE_min;
  out << " && mbc>" << Mbc_min << " && mbc<" << Mbc_max;
  Roo1DTable* recttable = ds.table(b0f,out.str().c_str());
  recttable->Print();
  recttable->Print("v");

  cout << "Ellips:" << endl;
//  out.str("");
//  out << "(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius.getVal() << "<1";
//  cout << out.str() << endl;
//  Roo1DTable* ellitable = ds.table(b0f,out.str().c_str());
  ellitable->Print();
  ellitable->Print("v");

  cout << "Elli:" << endl;
//  out.str("");
//  out << "(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "*(de-" << de_center.getVal() << ")/" << de_radius1.getVal() << "+(mbc-"<<mbc_center.getVal()<<")/" << mbc_radius1.getVal() << "*(mbc-" << mbc_center.getVal() << ")/" << mbc_radius1.getVal() << "<1";
//  cout << out.str() << endl;
//  Roo1DTable* ellitable1 = ds.table(b0f,out.str().c_str());
  ellitable1->Print();
  ellitable1->Print("v");

  Roo1DTable* fulltable = ds.table(b0f);
  fulltable->Print();
  fulltable->Print("v");
  const int NSigTotal = fulltable->get("signal") + fulltable->get("fsr") + fulltable->get("bad_pi0");
  const double TruePur = ((double)NSIGNAL_ELLI)/(NSIGNAL_ELLI+ellitable1->get("comb")+ellitable1->get("rho2")+ellitable1->get("rho3")+ellitable1->get("rho4")+ellitable1->get("rho11"));

  cout << "Rectangle:" << endl;
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Npbg = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;

  cout << "Ellips:" << endl;
  cout << "Nsig = " << nsigEl <<" +- " << nsig_errEl << " +- " << nsig_errEl_npq << " (" << nsig_errEl_total << ")" << endl;
  cout << "Npbg = " << nrhoEl <<" +- " << nrho_errEl << " +- " << nrho_errEl_npq << " (" << nrho_errEl_total << ")" << endl;
  cout << "Ncmb = " << ncmbEl <<" +- " << ncmb_errEl << " +- " << ncmb_errEl_npq << " (" << ncmb_errEl_total << ")" << endl;
  cout << "Pury = " << purityEl << " +- " << purity_errEl << endl;

  cout << "Elli:" << endl;
  cout << "Nsig = " << nsigEl1 <<" +- " << nsig_errEl1 << " +- " << nsig_errEl1_npq << " (" << nsig_errEl1_total << ")" << endl;
  cout << "Npbg = " << nrhoEl1 <<" +- " << nrho_errEl1 << " +- " << nrho_errEl1_npq << " (" << nrho_errEl1_total << ")" << endl;
  cout << "Ncmb = " << ncmbEl1 <<" +- " << ncmb_errEl1 << " +- " << ncmb_errEl1_npq << " (" << ncmb_errEl1_total << ")" << endl;
  cout << "Pury = " << purityEl1 << " +- " << purity_errEl1 << endl;

  cout << "Elli signal integral: " << intElli << endl;
  cout << "Nsig (full range): " << Nsig.getVal() << " +- " << Nsig.getError() << " (" << NSigTotal << ")" << endl;
  cout << "True purity: " << TruePur << endl;
}
Esempio n. 25
0
void Purity_1d_fit(int type = 0){
  TChain* tree = new TChain("TEvent");
  if(!type) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho",3);
  b0f.defineType("comb",-1);

  RooArgSet argset;

  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbc_min,mbc_max,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  if(!type) argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de));
  
  stringstream out;
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

//  RooDataHist* dh = ds0->binnedClone();

//  ds0->Print();

  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0("de0","de0",m_de0,-0.1,0.1); if(cSig) de0.setConstant(kTRUE);
  RooRealVar s1("s1","s1",m_s1,0.,0.5); if(cSig) s1.setConstant(kTRUE);
  RooGaussian g1("g1","g1",de,de0,s1);

  RooRealVar deCBl("deCBl","deCBl",m_deCBl,-0.1,0.1); if(cSig) deCBl.setConstant(kTRUE);
  RooRealVar sCBl("sCBl","sCBl",m_sCBl,0.,0.5); if(cSig) sCBl.setConstant(kTRUE);
  RooRealVar nl("nl","nl",m_nl,0.,100.); if(cSig) nl.setConstant(kTRUE);
  RooRealVar alphal("alphal","alphal",m_alphal,-10.,10.); if(cSig) alphal.setConstant(kTRUE);

  RooRealVar deCBr("deCBr","deCBr",m_deCBr,-0.1,0.1); if(cSig) deCBr.setConstant(kTRUE);
  RooRealVar sCBr("sCBr","sCBr",m_sCBr,0.,0.5); if(cSig) sCBr.setConstant(kTRUE);
  RooRealVar nr("nr","nr",m_nr,0.,100.); if(cSig) nr.setConstant(kTRUE);
  RooRealVar alphar("alphar","alphar",m_alphar,-10.,10.); if(cSig) alphar.setConstant(kTRUE);

  RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
  RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

  RooRealVar fCBl("fCBl","fCBl",m_fCBl,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
  RooRealVar fCBr("fCBr","fCBr",m_fCBr,0.,1.); if(cSig) fCBr.setConstant(kTRUE);

  RooAddPdf pdf_sig("pdf_sig","pdf_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c1("c1","c1",mc_c1_1d,-10.,10.); if(cComb) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",mc_c2_1d,-10.,10.); if(cComb) c2.setConstant(kTRUE);
  RooChebychev pdf_comb("pdf_comb","pdf_comb",de,RooArgSet(c1,c2));

  /////////////
  // Rho PDF //
  /////////////
  ////////////
  // de pdf //
  ////////////
if(de_rho_param == 0){
  RooRealVar exppar("exppar","exppar",mr_exppar,-40.,-25.);// if(cRho) exppar.setConstant(kTRUE);
  RooExponential pdf_rho("pdf_rho","pdf_rho",de,exppar);
  }
  
  RooRealVar de0r("de0r","de0r",mr_de0r,-0.2,0.12); if(cRho) de0r.setConstant(kTRUE);
  
  if(de_rho_param == 1){
   RooRealVar slopel("slopel","slopel",mr_slopel,-1000,-500.); if(cRho) slopel.setConstant(kTRUE);
   RooRealVar sloper("sloper","sloper",mr_sloper,-10000,0.); if(cRho) sloper.setConstant(kTRUE);
   RooRealVar steep("steep","steep",mr_steep,7.,9.); if(cRho) steep.setConstant(kTRUE);
   RooRealVar p5("p5","p5",mr_p5,0.01,1000.); if(cRho) p5.setConstant(kTRUE);
   RooRhoDeltaEPdf pdf_rho("pdf_rho","pdf_rho",de,de0r,slopel,sloper,steep,p5);
  }
  
  if(de_rho_param == -1){
   RooRealVar x0("x0","x0",mr_x0_1d,-0.2,0.12); if(cRho) x0.setConstant(kTRUE);
   RooRealVar p1("p1","p1",mr_p1_1d,-1000.,100.); if(cRho) p1.setConstant(kTRUE);
   RooRealVar p2("p2","p2",mr_p2_1d,0.,100.); if(cRho) p2.setConstant(kTRUE);
   RooGenericPdf pdf_rho("pdf_rho","1+@0*@1-@2*TMath::Log(1+TMath::Exp(@2*(@0-@1)/@3))",RooArgSet(de,x0,p1,p2));
  }
  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",700,100.,1500.);// fsig.setConstant(kTRUE);
  RooRealVar Nrho("Nrho","Nrho",400,100,1500.);// frho.setConstant(kTRUE);
  RooRealVar Ncmb("Ncmb","Ncmb",1000,100,100000);// frho.setConstant(kTRUE);
  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_rho,pdf_comb),RooArgList(Nsig,Nrho,Ncmb));

  pdf.fitTo(ds,Verbose(),Timer(true));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intRho  = pdf_rho.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Nrho.getVal();
   const double nrho_err = intRho->getVal()*Nrho.getError();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Nrho.getVal()-nrho)/Nrho.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);
   cout << "Nsig = " << nsig <<" +- " << nsig_err << endl;
   cout << "Nrho = " << nrho <<" +- " << nrho_err << endl;
   cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << endl;
   
  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_rho),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_comb),LineStyle(kDashed));
  pdf.plotOn(deFrame,LineWidth(2));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,50);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,50);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");
    
    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }
  
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Nrho = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;
}
void angularDistributions_spin0(int plotIndex=0, int binning=80){

  gROOT->ProcessLine(".L  ../PDFs/RooXZsZs_5D.cxx+");
  gROOT->ProcessLine(".L  ../PDFs/RooSpinOne_7D.cxx+");  
  gROOT->ProcessLine(".L  ../PDFs/RooSpinTwo_7D.cxx+");  
  gROOT->ProcessLine(".L  ../src/AngularPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/ScalarPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/VectorPdfFactory.cc+");
  gROOT->ProcessLine(".L  ../src/TensorPdfFactory.cc+");

  gROOT->ProcessLine(".L  ~/tdrstyle.C");
  setTDRStyle();

  // observables
  RooRealVar* z1mass = new RooRealVar("z1mass","m_{1} [GeV]",40,110);
  RooRealVar* z2mass = new RooRealVar("z2mass","m_{2} [GeV]",1e-09,65);
  RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
  RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
  RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
  RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
  RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());

  vector<RooRealVar*> measureables;
  measureables.push_back(z1mass);
  measureables.push_back(z2mass);
  measureables.push_back(hs);
  measureables.push_back(h1);
  measureables.push_back(h2);
  measureables.push_back(Phi);
  measureables.push_back(Phi1);

  RooRealVar* mzz = new RooRealVar("mzz","mzz",125,100,1000);

  ScalarPdfFactory* SMHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  SMHiggs->makeSMHiggs();
  SMHiggs->makeParamsConst(true);

  ScalarPdfFactory* PSHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  PSHiggs->makePSHiggs();
  PSHiggs->makeParamsConst(true);

  ScalarPdfFactory* LGHiggs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  LGHiggs->makeLGHiggs();
  LGHiggs->makeParamsConst(true);

  ScalarPdfFactory* A2Higgs = new ScalarPdfFactory(z1mass,z2mass,h1,h2,Phi,mzz);
  A2Higgs->makeCustom(0.0,1.0,0.0,0.0,0.0,0.0);
  A2Higgs->makeParamsConst(true);

  TChain* treeSM = new TChain("angles");
  treeSM->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/SMHiggs_store/SMHiggs_125GeV.root");
  RooDataSet* dataSM = new RooDataSet("dataSM","dataSM",treeSM,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  TChain* treePS = new TChain("angles");
  treePS->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/psScalar_store/psScalar_125GeV.root");
  RooDataSet* data = new RooDataSet("dataPS","dataPS",treePS,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  TChain* treeLG = new TChain("angles");
  treeLG->Add("/scratch0/hep/whitbeck/OLDHOME/4lHelicity/generatorJHU_V02-01-00/0hPlus_store/0hPlus_125GeV.root");
  RooDataSet* dataLG = new RooDataSet("dataLG","dataLG",treeLG,RooArgSet(*z1mass,*z2mass,*hs,*h1,*h2,*Phi,*Phi1));

  double normFix;
  if( ! strcmp( measureables[plotIndex]->GetName() , "phistar1" ) ) normFix=.001/(2.*3.1415);
  else if( ! strcmp( measureables[plotIndex]->GetName() , "costhetastar" ) ) normFix=.001/2.0;
  else normFix=.001;
  
  RooPlot* plot = measureables[plotIndex]->frame(binning);
  plot->GetXaxis()->CenterTitle();
  plot->GetYaxis()->CenterTitle();
  plot->GetYaxis()->SetTitle(" ");
  plot->GetXaxis()->SetNdivisions(-505);

  cout << 1./dataSM->sumEntries() << endl;
  double rescale=(double)(1./dataSM->sumEntries());
  dataSM->plotOn(plot,MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  SMHiggs.PDF->plotOn(plot,LineColor(kRed),LineWidth(2),Normalization( normFix ));
  cout << 1./dataPS->sumEntries() << endl;
  rescale=(double)(1./dataPS->sumEntries());
  dataPS->plotOn(plot,MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  PSHiggs.PDF->plotOn(plot,LineColor(kBlue),LineWidth(2),Normalization( normFix ));
  cout << 1./dataLG->sumEntries() << endl;
  rescale=(double)(1./dataLG->sumEntries());
  dataLG->plotOn(plot,MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0),Rescale(.001),DataError(RooAbsData::None));
  LGHiggs.PDF->plotOn(plot,LineColor(kGreen+3),LineWidth(2),Normalization( normFix ));

  TGaxis::SetMaxDigits(3);

  TCanvas* can =new TCanvas("can","can",600,600);

  gStyle->SetPadLeftMargin(0.05);

  char temp[150];
  sprintf(temp,"%s>>SM_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treeSM->Draw(temp);
  TH1F* SM_histo = (TH1F*) gDirectory->Get("SM_histo");
  sprintf(temp,"%s>>PS_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treePS->Draw(temp);
  TH1F* PS_histo = (TH1F*) gDirectory->Get("PS_histo");
  sprintf(temp,"%s>>LG_histo(%i,%i,%i)",measureables[plotIndex]->GetName(),binning,(int)measureables[plotIndex]->getMin(),(int)measureables[plotIndex]->getMin());
  treeLG->Draw(temp);
  TH1F* LG_histo = (TH1F*) gDirectory->Get("LG_histo");

  if(!strcmp(measureables[plotIndex]->GetName(),"z1mass"))
    plot->GetYaxis()->SetRangeUser(0,max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*.8/1000.);
  else
    plot->GetYaxis()->SetRangeUser(0,max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*1.3/1000.);

  //cout << "max range: " << max(max(LG_histo->GetMaximum(),PS_histo->GetMaximum()),SM_histo->GetMaximum())*.8/1000. << endl;

  plot->Draw();

  char temp[150];
  sprintf(temp,"epsfiles/%s_125GeV_spin0_3in1.eps",measureables[plotIndex]->GetName());
  can->SaveAs(temp);
  sprintf(temp,"pngfiles/%s_125GeV_spin0_3in1.png",measureables[plotIndex]->GetName());
  can->SaveAs(temp);

  delete SMHiggs;
  delete PSHiggs;
  delete LGHiggs;

}
Esempio n. 27
0
void roo_fitWH()
{

  gSystem->Load("libRooFit"); 
  gSystem->Load("libRooFitCore");
  gSystem->Load("libMatrix");
  gSystem->Load("libGpad");
  using namespace RooFit;

  TString poscharge = "Plus";
  TString negcharge = "Minus";

  std::vector<TString> charge(2);
  charge.at(0) = poscharge;
  charge.at(1) = negcharge;

  TString bin1 = "50to75";
  TString bin2 = "75to100";
  TString bin3 = "100toinf";

  std::vector<TString> bins(3);
  bins.at(0) = bin1;
  bins.at(1) = bin2;
  bins.at(2) = bin3;

  //we only set up the machinery for the plus charge
  //TFile *dataplus = new TFile("results/GenW_CS_WJets-lite_madgraph_50_75_100.root");
  TFile *dataplus = new TFile("results/RecoW_WJets-lite_madgraph_50_75_100.root");
  TFile *refTemplates = new TFile("results/GenW_CS_WJets-lite_madgraph_50_75_100.root");

  bool makePlots = false;

  TString canvas_name_plus = "MC_WHelicityFramePlots_PlusICVar";
  TCanvas *c0 = new TCanvas(canvas_name_plus,"",900,320);
  c0->Divide(3,1);

  TString canvas_name_minus = "MC_WHelicityFramePlots_MinusICVar";
  TCanvas *c1 = new TCanvas(canvas_name_minus,"",900,320);
  c1->Divide(3,1);
 
  for(unsigned int i=0; i<bins.size(); i++) {
    for(unsigned int j=0; j<charge.size(); j++) {
      //unsigned int index = i*charge.size() + j;
      //cout << "INDEX= " << index << endl;

      //these histograms define the number of events in the complete templates so we can apply correction factors for acceptance etc.
      //do not change these histograms!
      TString refHist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
      TString refHist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
      TString refHist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
      TH1D *refTempHist1 = (TH1D*)refTemplates->Get(refHist1);
      TH1D *refTempHist2 = (TH1D*)refTemplates->Get(refHist2);
      TH1D *refTempHist3 = (TH1D*)refTemplates->Get(refHist3);

      //these histograms are the ones we want to fit
      //TString Hist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
      //TString Hist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
      //TString Hist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
      //TString Hist_data1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
      TString Hist1 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_LH";
      TString Hist2 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_RH";
      TString Hist3 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_LO";
      TString Hist_data1 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j);

      Int_t rbin=10;
      TH1D *mc1 = (TH1D*)dataplus->Get(Hist1);
      TH1D *mc2 = (TH1D*)dataplus->Get(Hist2);
      TH1D *mc3 = (TH1D*)dataplus->Get(Hist3);
      TH1D *datahist = (TH1D*)dataplus->Get(Hist_data1);

      //we are only fitting for fL and fR
      double accFactor1 = refTempHist1->Integral() / mc1->Integral();
      double accFactor2 = refTempHist2->Integral() / mc2->Integral();
      double accFactor3 = refTempHist3->Integral() / mc3->Integral();
      double normFactor = (mc1->Integral() + mc2->Integral() + mc3->Integral()) / (refTempHist1->Integral() + refTempHist2->Integral() + refTempHist3->Integral());

      mc1->Rebin(rbin);
      mc2->Rebin(rbin);
      mc3->Rebin(rbin);
      datahist->Rebin(rbin);
      //datahist->Scale(10);
      //datahist->Scale(invWeightW);//to get MC errors - otherwise comment out

      Double_t istat=datahist->Integral();
      
      // Start RooFit session
  
      RooRealVar x("x","ICVar",-1.9,1.9);
      // Import binned Data
      RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1);
      RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2);
      RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3);
      RooDataHist test("test_data","dataset with WHICVarPlus",x,datahist);

      //Float_t fr = (1./3.)*istat;
      Float_t fr = (1.0/3.0);

      // Relative fractions - allow them to float to negative values too if needs be
      RooRealVar f1("fL","fL fraction",fr,0.0,1.0);
      RooRealVar f2("fR","fR fraction", fr,0.0,1.0);
      RooRealVar f3("f0","f0 fraction",fr,0.0,1.0);

      // Templates 
      RooHistPdf h1("h1","h1",x,data1);
      RooHistPdf h2("h2","h2",x,data2);
      RooHistPdf h3("h3","h3",x,data3);
      
      // composite PDF  
      RooAddPdf model("model","model",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;
 
      // Generate data 
      Int_t nevt=static_cast<int>(istat);

      RooDataSet *gtest = model.generate(x,nevt);

      // Fitting
      RooFitResult * res1 = model.fitTo(test,Minos(kTRUE), Save());
      res1->Print();

      if(makePlots) {
	// Plotting
	gROOT->SetStyle("Plain");  
	gStyle->SetOptFit(111);
	gStyle->SetOptTitle(0);
	gStyle->SetOptStat(0);
	 //gStyle->SetCanvasDefH(600); //Height of canvas
	 //gStyle->SetCanvasDefW(600); //Width of canvas   
	//TString canvas_name = "MC_CSFramePlots_" + bins.at(i) + charge.at(j) + "Phi";
	//TCanvas *c0 = new TCanvas(canvas_name,"",300,320);
	if(charge.at(j) == "Plus") c0->cd(i+1);
	if(charge.at(j) == "Minus") c1->cd(i+1);
	RooPlot* frame = x.frame();
	test.plotOn(frame); 
	model.plotOn(frame);
	//model.paramOn(frame);
	model.plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed));
	model.plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed));
	model.plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed));
	frame->GetXaxis()->SetTitle("LP Variable");
	frame->Draw();
	//c0->cd(i)->Update();
	//c0->Update();
	//c0->Print(canvas_name+".png");
      }

      const TMatrixDSym& cor = res1->correlationMatrix();
      const TMatrixDSym& cov = res1->covarianceMatrix();
      //Print correlation, covariance matrix
      //cout << "correlation matrix" << endl;
      //cor.Print();
      //cout << "covariance matrix" << endl;
      //cout << "(0,0) = " << cov[0][0] << endl;
      //cout << f1.getVal() << endl;
      //cov.Print();

      double F1 = f1.getVal() * accFactor1 * normFactor;
      double F2 = f2.getVal() * accFactor2 * normFactor;
      double F3 = (1.0 - F1 - F2);

      double F1_err = sqrt(cov[0][0]) * accFactor1 * normFactor;
      double F2_err = sqrt(cov[1][1]) * accFactor2 * normFactor;

      cout << "Fitting bin " << bins.at(i) << " for " << charge.at(j) << " charge: " << endl;
      cout << "fL = " << F1 << " +/- " << F1_err << endl;
      cout << "fR = " << F2 << " +/- " << F2_err << endl;
      cout << "f0 = " << F3 << " +/- " << "N/A" << endl;

    }
  }
  if(makePlots) {
    c0->Print(canvas_name_plus+".png");
    c1->Print(canvas_name_minus+".png");
  }
  return;

}
Esempio n. 28
0
void CreateTemplatesForW(TString CAT, TString CUT)
{
  gROOT->ForceStyle();
  
  RooMsgService::instance().setSilentMode(kTRUE);
  RooMsgService::instance().setStreamStatus(0,kFALSE);
  RooMsgService::instance().setStreamStatus(1,kFALSE);

  TFile *infMC   = TFile::Open("Histo_TT_TuneCUETP8M1_13TeV-powheg-pythia8.root");
  TFile *infData = TFile::Open("Histo_JetHT.root");
    
  TH1F *hMC,*hData;
  RooDataHist *roohMC,*roohData;
  RooAddPdf *signal,*qcd;
  
  TString VAR,TAG;
  float XMIN,XMAX;

  VAR = "mW";
  TAG = CUT+"_"+CAT;
  XMIN = 20.;
  XMAX = 160.;

  RooWorkspace *w = new RooWorkspace("w","workspace");

  //---- define observable ------------------------
  RooRealVar *x = new RooRealVar("mW","mW",XMIN,XMAX);
  w->import(*x);
  //---- first do the data template ---------------
  
  hData = (TH1F*)infData->Get("boosted/h_mW_"+CUT+"_0btag");
  hData->Rebin(5);
  roohData = new RooDataHist("roohistData","roohistData",RooArgList(*x),hData);  

  //---- QCD -----------------------------------
  RooRealVar bBkg0("qcd_b0","qcd_b0",0.5,0,1);
  RooRealVar bBkg1("qcd_b1","qcd_b1",0.5,0,1);
  RooRealVar bBkg2("qcd_b2","qcd_b2",0.5,0,1);
  RooRealVar bBkg3("qcd_b3","qcd_b3",0.5,0,1);

  RooBernstein qcd1("qcd_brn","qcd_brn",*x,RooArgList(bBkg0,bBkg1,bBkg2,bBkg3));

  RooRealVar mQCD("qcd_mean2" ,"qcd_mean2",40,0,100);
  RooRealVar sQCD("qcd_sigma2","qcd_sigma2",20,0,50);
  RooGaussian qcd2("qcd_gaus" ,"qcd_gaus",*x,mQCD,sQCD);

  RooRealVar fqcd("qcd_f1","qcd_f1",0.5,0,1);

  qcd = new RooAddPdf("qcd_pdf","qcd_pdf",qcd1,qcd2,fqcd);

  //---- plots ---------------------------------------------------
  TCanvas *canB = new TCanvas("Template_W_QCD_"+CUT+"_"+CAT,"Template_W_QCD_"+CUT+"_"+CAT,900,600);

  RooFitResult *res = qcd->fitTo(*roohData,RooFit::Save());
  res->Print();
  RooPlot *frameB = x->frame();
  roohData->plotOn(frameB);
  qcd->plotOn(frameB);
  qcd->plotOn(frameB,RooFit::Components("qcd_brn"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  qcd->plotOn(frameB,RooFit::Components("qcd_gaus"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameB->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameB->Draw();
  gPad->Update();
  canB->Print("plots/"+TString(canB->GetName())+".pdf");

  RooArgSet *parsQCD = (RooArgSet*)qcd->getParameters(roohData);
  parsQCD->setAttribAll("Constant",true);

  w->import(*qcd);

  //---- then do the signal templates -------------
  hMC = (TH1F*)infMC->Get("boosted/hWt_"+VAR+"_"+TAG);
  roohMC = new RooDataHist("roohistTT","roohistTT",RooArgList(*x),hMC);
  normMC = ((TH1F*)infMC->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
  hMC->Rebin(2);
      
  RooRealVar m("ttbar_mean","ttbar_mean",90,70,100);
  RooRealVar s("ttbar_sigma","ttbar_sigma",20,0,50);
    
  RooGaussian sig_core("ttbar_core","ttbar_core",*x,m,s);
  
  RooRealVar bSig0("ttbar_b0","ttbar_b0",0.5,0,1);
  RooRealVar bSig1("ttbar_b1","ttbar_b1",0.5,0,1);
  RooRealVar bSig2("ttbar_b2","ttbar_b2",0.5,0,1); 
  RooRealVar bSig3("ttbar_b3","ttbar_b3",0.5,0,1);
  RooRealVar bSig4("ttbar_b4","ttbar_b4",0.5,0,1);
  RooRealVar bSig5("ttbar_b5","ttbar_b5",0.5,0,1); 
  RooRealVar bSig6("ttbar_b6","ttbar_b6",0.5,0,1);
  RooRealVar bSig7("ttbar_b7","ttbar_b7",0.5,0,1);
  RooRealVar bSig8("ttbar_b8","ttbar_b8",0.5,0,1);

  RooBernstein sig_tail("ttbar_tail","ttbar_tail",*x,RooArgList(bSig0,bSig1,bSig2,bSig3,bSig4,bSig5,bSig6,bSig7,bSig8)); 

  RooRealVar fcore("ttbar_fcore","ttbar_fcore",0.5,0,1);

  signal = new RooAddPdf("ttbar_pdf","ttbar_pdf",RooArgList(sig_core,sig_tail),RooArgList(fcore));

  TCanvas *canS = new TCanvas("Template_W_TT_"+CAT+"_"+CUT,"Template_W_TT_"+CAT+"_"+CUT,900,600);

  res = signal->fitTo(*roohMC,RooFit::Save());

  cout<<"mean = "<<m.getVal()<<" +/ "<<m.getError()<<", sigma = "<<s.getVal()<<" +/- "<<s.getError()<<endl;

  //res->Print();
  RooPlot *frameS = x->frame();
  roohMC->plotOn(frameS);
  signal->plotOn(frameS);
  signal->plotOn(frameS,RooFit::Components("ttbar_core"),RooFit::LineColor(kRed),RooFit::LineWidth(2),RooFit::LineStyle(2));
  signal->plotOn(frameS,RooFit::Components("ttbar_tail"),RooFit::LineColor(kGreen+1),RooFit::LineWidth(2),RooFit::LineStyle(2));
  frameS->GetXaxis()->SetTitle("m_{W} (GeV)");
  frameS->Draw();
  gPad->Update();
  canS->Print("plots/"+TString(canS->GetName())+".pdf");

  RooArgSet *parsSig = (RooArgSet*)signal->getParameters(roohMC);
  parsSig->setAttribAll("Constant",true);

  w->import(*signal);
  
  //w->Print();
  w->writeToFile("templates_W_"+CUT+"_"+CAT+"_workspace.root");
}                            
Esempio n. 29
0
//---------------------------------------------------------------
void doTheFit()
//---------------------------------------------------------------
{
  gROOT->SetStyle("Plain");

  TFile *_file0 = TFile::Open("analyzeDmeson.root");
  gDirectory->cd("demo");
  TH1D* histo = (TH1D*)gDirectory->Get("HMASS4");

  RooRealVar x("x","D0 mass (GeV)",1.75,1.95);
  RooDataHist dh("dh","dh",x,histo);
  
  RooRealVar mean("mean","mean",1.86,1.8,2.0);
  RooRealVar sigma("sigma","sigma",0.005,0.001,0.200);

  RooRealVar lambda("lambda", "slope", -0.1, -5., 0.);

  RooGaussian sig("sig","sig",x,mean,sigma);
  RooExponential bck("bck", "exponential PDF", x, lambda);

  RooRealVar fsig("fsig","signal fraction 1",0.10,0.,1.);
  //  fsig.setConstant(kTRUE);

  // Signal+Background pdf
  RooAddPdf model("model","model",RooArgList(sig,bck),RooArgList(fsig)) ;
  // Fit and Plot

  RooPlot* frame = x.frame();
  
  model.fitTo(dh);
  dh.plotOn(frame);
  model.plotOn(frame);

  mass     = mean.getVal();
  masserr  = mean.getError();
  width    = sigma.getVal();
  widtherr = sigma.getError();

  mean.Print();
  sigma.Print();
  
  // Overlay the background component of model with a dashed line
  //  model.plotOn(frame,Components(bck),LineStyle(kDashed)) ;
  model.plotOn(frame,Components(bck),LineColor(kRed)) ;

  // Overlay the background+sig2 components of model with a dotted line
  //  model.plotOn(frame,Components(RooArgSet(sig)),LineStyle(kDotted)) ;
  model.plotOn(frame,Components(RooArgSet(sig)),LineColor(kGreen)) ;

  // Overlay the background+sig2 components of model with a dotted line
  //  model.plotOn(frame,Components(RooArgSet(sig2)),LineStyle(kDotted)) ;

  TCanvas* c = new TCanvas("D0 meson candidate","D0 meson candidate");

  gPad->SetLeftMargin(0.15); 
  frame->GetYaxis()->SetTitleOffset(1.4);
  frame->GetXaxis()->SetLabelSize(0.04);
  frame->Draw();

  c->Update();

}
Esempio n. 30
0
void plotPdf_7D_XWW(double mH = 125, bool draw=true) {

    gROOT->ProcessLine(".L tdrstyle.C");
    setTDRStyle();
    TGaxis::SetMaxDigits(3);
    gROOT->ForceStyle();
    
    // Declaration of the PDFs to use
    gROOT->ProcessLine(".L  PDFs/RooSpinTwo_7D.cxx+");

    // W/Z mass and decay width constants
    double mV = 80.399;
    double gamV = 2.085;
    bool offshell = false;
    if ( mH < 2 * mV ) offshell = true;

    
    // for the pole mass and decay width of W 
    RooRealVar* mX = new RooRealVar("mX","mX", mH);
    RooRealVar* mW = new RooRealVar("mW","mW", mV);
    RooRealVar* gamW = new RooRealVar("gamW","gamW",gamV);

    //
    // Observables (7D)
    // 
    RooRealVar* wplusmass = new RooRealVar("wplusmass","m(W+)",mV,1e-09,120);
    wplusmass->setBins(50);
    RooRealVar* wminusmass = new RooRealVar("wminusmass","m(W-)",mV,1e-09,120);
    wminusmass->setBins(50);
    RooRealVar* hs = new RooRealVar("costhetastar","cos#theta*",-1,1);
    hs->setBins(20);
    RooRealVar* Phi1 = new RooRealVar("phistar1","#Phi_{1}",-TMath::Pi(),TMath::Pi());
    Phi1->setBins(20);
    RooRealVar* h1 = new RooRealVar("costheta1","cos#theta_{1}",-1,1);
    h1->setBins(20);
    RooRealVar* h2 = new RooRealVar("costheta2","cos#theta_{2}",-1,1);
    h2->setBins(20);
    RooRealVar* Phi = new RooRealVar("phi","#Phi",-TMath::Pi(),TMath::Pi());
    Phi->setBins(20);
    
    //
    // coupling constants for 2m+
    // See equation 5,6,7 in PRD 91, 075022
    //
    double s = (mH*mH-2*mV*mV)/2.;
    double c1 = 2*(1+mV*mV/s);
    c1 = c1 * 2.0; // scale up to be consistent with the generator
    // std::cout << "c1 = " << c1 << "\n"; 

    RooRealVar* c1Val = new RooRealVar("c1Val", "c1Val", c1);
    RooRealVar* c2Val = new RooRealVar("c2Val", "c2Val", -0.5);
    RooRealVar* c3Val = new RooRealVar("c3Val", "c3Val", 0.);
    RooRealVar* c4Val = new RooRealVar("c4Val", "c4Val", -1.);
    RooRealVar* c5Val = new RooRealVar("c5Val", "c5Val", 0.);
    RooRealVar* c6Val = new RooRealVar("c6Val", "c6Val", 0.);
    RooRealVar* c7Val = new RooRealVar("c7Val", "c7Val", 0.);
    
    // 
    // Alternative definition in terms of g1->g10
    // 
    RooRealVar* useGTerm = new RooRealVar("useGTerm", "useGTerm",1.); // set to 1 if using g couplings
    RooRealVar* g1Val = new RooRealVar("g1Val", "g1Val", 1);
    RooRealVar* g2Val = new RooRealVar("g2Val", "g2Val", 0.);
    RooRealVar* g3Val = new RooRealVar("g3Val", "g3Val", 0.);
    RooRealVar* g4Val = new RooRealVar("g4Val", "g4Val", 0.);
    RooRealVar* g5Val = new RooRealVar("g5Val", "g5Val", 1.);
    RooRealVar* g6Val = new RooRealVar("g6Val", "g6Val", 0.);
    RooRealVar* g7Val = new RooRealVar("g7Val", "g7Val", 0.);
    RooRealVar* g8Val = new RooRealVar("g8Val", "g8Val", 0.);
    RooRealVar* g9Val = new RooRealVar("g9Val", "g9Val", 0.);
    RooRealVar* g10Val = new RooRealVar("g10Val", "g10Val", 0.);

    // related to the gg/qq productions 
    RooRealVar* fz1Val = new RooRealVar("fz1Val", "fz1Val", 0);
    RooRealVar* fz2Val = new RooRealVar("fz2Val", "fz2Val", 1.0);

    // Even more parameters, do not have to touch, based on Z couplings
    RooRealVar* R1Val = new RooRealVar("R1Val","R1Val",1);
    RooRealVar* R2Val = new RooRealVar("R2Val","R2Val",1);
    
      
    // PDF definition SM Higgs (JP = 2+)
    RooSpinTwo_7D *myPDF;
    if ( offshell )
      myPDF = new RooSpinTwo_7D("myPDF","myPDF", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				  *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				  *useGTerm, *g1Val, *g2Val, *g3Val, *g4Val, *g5Val, *g6Val, *g7Val, *g8Val, *g9Val, *g10Val,
				  *fz1Val, *fz2Val, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDF = new RooSpinTwo_7D("myPDF","myPDF", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				  *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				  *useGTerm, *g1Val, *g2Val, *g3Val, *g4Val, *g5Val, *g6Val, *g7Val, *g8Val, *g9Val, *g10Val,
				  *fz1Val, *fz2Val, *R1Val, *R2Val, *mW, *gamW);
    // dataset for (JP = 2+)
    TString fileName;
    if ( useGTerm->getVal() > 0.) {
      fileName = Form("TWW_2mplus_%.0f_JHU.root", mH);
    }
    else {
      fileName = Form("TWW_%.0f_JHU_GenFromC.root", mH);
    }
    std::cout << "Opening " << fileName << "\n";
    TFile* fin = new TFile(fileName);
    TTree* tin = (TTree*) fin->Get("angles");

    if ( offshell) 
      RooDataSet data("data","data",tin,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet data("data","data",tin,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));

    // 
    //  2h-
    // 
    RooRealVar* g1ValMinus = new RooRealVar("g1ValMinus", "g1ValMinus", 0);
    RooRealVar* g2ValMinus = new RooRealVar("g2ValMinus", "g2ValMinus", 0.);
    RooRealVar* g3ValMinus = new RooRealVar("g3ValMinus", "g3ValMinus", 0.);
    RooRealVar* g4ValMinus = new RooRealVar("g4ValMinus", "g4ValMinus", 0.);
    RooRealVar* g5ValMinus = new RooRealVar("g5ValMinus", "g5ValMinus", 0.);
    RooRealVar* g6ValMinus = new RooRealVar("g6ValMinus", "g6ValMinus", 0.);
    RooRealVar* g7ValMinus = new RooRealVar("g7ValMinus", "g7ValMinus", 0.);
    RooRealVar* g8ValMinus = new RooRealVar("g8ValMinus", "g8ValMinus", 1.);
    RooRealVar* g9ValMinus = new RooRealVar("g9ValMinus", "g9ValMinus", 0.);
    RooRealVar* g10ValMinus = new RooRealVar("g10ValMinus", "g10ValMinus", 0.);
    RooRealVar* fz1ValMinus = new RooRealVar("fz1ValMinus", "fz1ValMinus", 0.0);
    RooRealVar* fz2ValMinus = new RooRealVar("fz2ValMinus", "fz2ValMinus", 0.0);

    RooSpinTwo_7D *myPDFMinus;
    if ( offshell )
      myPDFMinus = new RooSpinTwo_7D("myPDFMinus","myPDFMinus", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValMinus, *g2ValMinus, *g3ValMinus, *g4ValMinus, 
				       *g5ValMinus, *g6ValMinus, *g7ValMinus, *g8ValMinus, *g9ValMinus, *g10ValMinus,
				       *fz1ValMinus, *fz2ValMinus, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDFMinus = new RooSpinTwo_7D("myPDFMinus","myPDFMinus", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValMinus, *g2ValMinus, *g3ValMinus, *g4ValMinus, 
				       *g5ValMinus, *g6ValMinus, *g7ValMinus, *g8ValMinus, *g9ValMinus, *g10ValMinus,
				       *fz1ValMinus, *fz2ValMinus, *R1Val, *R2Val, *mW, *gamW);

    // dataset for (JP = 2-)
    TString fileNameMinus;
    if ( useGTerm->getVal() > 0.) {
      fileNameMinus = Form("TWW_2hminus_%.0f_JHU.root", mH);
    }
    
    std::cout << "Opening " << fileNameMinus << "\n";
    TFile* finMinus = new TFile(fileNameMinus);
    TTree* tinMinus = (TTree*) finMinus->Get("angles");

    if ( offshell) 
      RooDataSet dataMinus("dataMinus","dataMinus",tinMinus,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet dataMinus("dataMinus","dataMinus",tinMinus,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));

    // 
    //  2h+
    // 
    RooRealVar* g1ValHPlus = new RooRealVar("g1ValHPlus", "g1ValHPlus", 0);
    RooRealVar* g2ValHPlus = new RooRealVar("g2ValHPlus", "g2ValHPlus", 0.);
    RooRealVar* g3ValHPlus = new RooRealVar("g3ValHPlus", "g3ValHPlus", 0.);
    RooRealVar* g4ValHPlus = new RooRealVar("g4ValHPlus", "g4ValHPlus", 1.);
    RooRealVar* g5ValHPlus = new RooRealVar("g5ValHPlus", "g5ValHPlus", 0.);
    RooRealVar* g6ValHPlus = new RooRealVar("g6ValHPlus", "g6ValHPlus", 0.);
    RooRealVar* g7ValHPlus = new RooRealVar("g7ValHPlus", "g7ValHPlus", 0.);
    RooRealVar* g8ValHPlus = new RooRealVar("g8ValHPlus", "g8ValHPlus", 0.);
    RooRealVar* g9ValHPlus = new RooRealVar("g9ValHPlus", "g9ValHPlus", 0.);
    RooRealVar* g10ValHPlus = new RooRealVar("g10ValHPlus", "g10ValHPlus", 0.);
    RooRealVar* fz1ValHPlus = new RooRealVar("fz1ValHPlus", "fz1ValHPlus", 0.0);
    RooRealVar* fz2ValHPlus = new RooRealVar("fz2ValHPlus", "fz2ValHPlus", 0.0);

    RooSpinTwo_7D *myPDFHPlus;
    if ( offshell )
      myPDFHPlus = new RooSpinTwo_7D("myPDFHPlus","myPDFHPlus", *mX, *wplusmass, *wminusmass, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValHPlus, *g2ValHPlus, *g3ValHPlus, *g4ValHPlus, 
				       *g5ValHPlus, *g6ValHPlus, *g7ValHPlus, *g8ValHPlus, *g9ValHPlus, *g10ValHPlus,
				       *fz1ValHPlus, *fz2ValHPlus, *R1Val, *R2Val, *mW, *gamW);
    else 
      myPDFHPlus = new RooSpinTwo_7D("myPDFHPlus","myPDFHPlus", *mX, *mW, *mW, *hs, *h1,*h2, *Phi, *Phi1, 
				       *c1Val, *c2Val, *c3Val, *c4Val, *c5Val, *c6Val, *c7Val, 
				       *useGTerm, *g1ValHPlus, *g2ValHPlus, *g3ValHPlus, *g4ValHPlus, 
				       *g5ValHPlus, *g6ValHPlus, *g7ValHPlus, *g8ValHPlus, *g9ValHPlus, *g10ValHPlus,
				       *fz1ValHPlus, *fz2ValHPlus, *R1Val, *R2Val, *mW, *gamW);
    TString fileNameHPlus;
    if ( useGTerm->getVal() > 0.) {
      fileNameHPlus = Form("TWW_2hplus_%.0f_JHU.root", mH);
    }
    
    std::cout << "Opening " << fileNameHPlus << "\n";
    TFile* finHPlus = new TFile(fileNameHPlus);
    TTree* tinHPlus = (TTree*) finHPlus->Get("angles");

    if ( offshell) 
      RooDataSet dataHPlus("dataHPlus","dataHPlus",tinHPlus,RooArgSet(*wplusmass, *wminusmass, *hs, *h1, *h2, *Phi, *Phi1));
    else 
      RooDataSet dataHPlus("dataHPlus","dataHPlus",tinHPlus,RooArgSet(*hs, *h1, *h2, *Phi, *Phi1));



    
    // P L O T   . . .  
    // (All parameters fixed, no fitting, just looking at the shape of the PDFs w.r.t. the data)
    if ( draw ) {

      bool drawmplus = true;
      bool drawhminus = true;
      bool drawhplus = true;
      bool drawpaper = true;
      double rescale = 1.0;
      if ( drawpaper ) 
	rescale = .001;

      TH1F* dum0 = new TH1F("dum0","dum0",1,0,1); dum0->SetLineColor(kRed); dum0->SetMarkerColor(kBlack); dum0->SetLineWidth(3);
      TH1F* dum1 = new TH1F("dum1","dum1",1,0,1); dum1->SetLineColor(kBlue); dum1->SetMarkerColor(kBlack); dum1->SetMarkerStyle(24), dum1->SetLineWidth(3);  
      TH1F* dum2 = new TH1F("dum2","dum2",1,0,1); dum2->SetLineColor(kGreen); dum2->SetMarkerColor(kBlack); dum2->SetMarkerStyle(21), dum2->SetLineWidth(3); // 2L+
      
      TLegend * box3 = new TLegend(0.1,0.1,0.9,0.92);
      box3->SetFillColor(0);
      box3->SetBorderSize(0);

      if ( drawmplus ) 
	box3->AddEntry(dum0,Form("X(%.0f)#rightarrow WW JP = 2m+", mH),"lp");
      if ( drawhminus )
	box3->AddEntry(dum1,Form("X(%.0f)#rightarrow WW JP = 2h-", mH),"lp");
      if ( drawhplus ) 
	box3->AddEntry(dum2,Form("X(%.0f)#rightarrow WW JP = 2h+,", mH),"lp");
  
      
      // 
      //  h1
      // 
      RooPlot* h1frame =  h1->frame(20);
      h1frame->GetXaxis()->CenterTitle();
      h1frame->GetYaxis()->CenterTitle();
      h1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_h1;
      TH1F *h1_mplus = new TH1F("h1_mplus", "h1_mplus", 20, -1, 1);
      tin->Project("h1_mplus", "costheta1");
      ymax_h1 = h1_mplus->GetMaximum();
      
      TH1F *h1_hminus = new TH1F("h1_hminus", "h1_hminus", 20, -1, 1);
      tinMinus->Project("h1_hminus", "costheta1");
      ymax_h1 = h1_hminus->GetMaximum() > ymax_h1 ? h1_hminus->GetMaximum() : ymax_h1;
      
      TH1F *h1_hplus = new TH1F("h1_hplus", "h1_hplus", 20, -1, 1);
      tinHPlus->Project("h1_hplus", "costheta1");
      ymax_h1 = h1_hplus->GetMaximum() > ymax_h1 ? h1_hplus->GetMaximum() : ymax_h1;
      
      if ( drawmplus ) {
	data.plotOn(h1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(h1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(h1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(h1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(h1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(h1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. )
	h1frame->GetYaxis()->SetRangeUser(0, ymax_h1  * rescale * 1.3);
      
      
      // 
      //  h2
      // 
      
      RooPlot* h2frame =  h2->frame(20);
      h2frame->GetXaxis()->CenterTitle();
      h2frame->GetYaxis()->CenterTitle();
      h2frame->GetYaxis()->SetTitle(" ");
      
      double ymax_h2;
      TH1F *h2_mplus = new TH1F("h2_mplus", "h2_mplus", 20, -1, 1);
      tin->Project("h2_mplus", "costheta2");
      ymax_h2 = h2_mplus->GetMaximum();
      
      TH1F *h2_hminus = new TH1F("h2_hminus", "h2_hminus", 20, -1, 1);
      tinMinus->Project("h2_hminus", "costheta2");
      ymax_h2 = h2_hminus->GetMaximum() > ymax_h2 ? h2_hminus->GetMaximum() : ymax_h2;
      
      TH1F *h2_hplus = new TH1F("h2_hplus", "h2_hplus", 20, -1, 1);
      tinHPlus->Project("h2_hplus", "costheta2");
      ymax_h2 = h2_hplus->GetMaximum() > ymax_h2 ? h2_hplus->GetMaximum() : ymax_h2;
      
      
      if ( drawmplus ) {
	data.plotOn(h2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(h2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(h2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(h2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(h2frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(h1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	h2frame->GetYaxis()->SetRangeUser(0, ymax_h2  * rescale * 1.3);
      
      //
      // Phi
      // 
      RooPlot* Phiframe =  Phi->frame(20);
      
      Phiframe->GetXaxis()->CenterTitle();
      Phiframe->GetYaxis()->CenterTitle();
      Phiframe->GetYaxis()->SetTitle(" ");
      
      double ymax_Phi;
      TH1F *Phi_mplus = new TH1F("Phi_mplus", "Phi_mplus", 20,  -TMath::Pi(), TMath::Pi());
      tin->Project("Phi_mplus", "phi");
      ymax_Phi = Phi_mplus->GetMaximum();
      
      TH1F *Phi_hminus = new TH1F("Phi_hminus", "Phi_hminus", 20,  -TMath::Pi(), TMath::Pi());
      tinMinus->Project("Phi_hminus", "phi");
      ymax_Phi = Phi_hminus->GetMaximum() > ymax_Phi ? Phi_hminus->GetMaximum() : ymax_Phi;
      
      TH1F *Phi_hplus = new TH1F("Phi_hplus", "Phi_hplus", 20,  -TMath::Pi(), TMath::Pi());
      tinHPlus->Project("Phi_hplus", "phi");
      ymax_Phi = Phi_hplus->GetMaximum() > ymax_Phi ? Phi_hplus->GetMaximum() : ymax_Phi;
      
      if ( drawmplus ) {
	data.plotOn(Phiframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(Phiframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(Phiframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(Phiframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(Phiframe, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(Phiframe, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	Phiframe->GetYaxis()->SetRangeUser(0, ymax_Phi  * rescale * 1.3);
      
      // 
      //  hs 
      // 
      RooPlot* hsframe =  hs->frame(20);
      
      hsframe->GetXaxis()->CenterTitle();
      hsframe->GetYaxis()->CenterTitle();
      hsframe->GetYaxis()->SetTitle(" ");
      
      double ymax_hs;
      TH1F *hs_mplus = new TH1F("hs_mplus", "hs_mplus", 20, -1, 1);
      tin->Project("hs_mplus", "costhetastar");
      ymax_hs = hs_mplus->GetMaximum();
      
      TH1F *hs_hminus = new TH1F("hs_hminus", "hs_hminus", 20, -1, 1);
      tinMinus->Project("hs_hminus", "costhetastar");
      ymax_hs = hs_hminus->GetMaximum() > ymax_hs ? hs_hminus->GetMaximum() : ymax_hs;
      
      TH1F *hs_hplus = new TH1F("hs_hplus", "hs_hplus", 20, -1, 1);
      tinHPlus->Project("hs_hplus", "costhetastar");
      ymax_hs = hs_hplus->GetMaximum() > ymax_hs ? hs_hplus->GetMaximum() : ymax_hs;
      
      if ( drawmplus ) {
	data.plotOn(hsframe, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(hsframe, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(hsframe, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(hsframe, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(hsframe, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(hsframe, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. )
	hsframe->GetYaxis()->SetRangeUser(0, ymax_hs  * rescale * 1.3);
      
      
      //
      // Phi1
      // 
      RooPlot* Phi1frame =  Phi1->frame(20);
      
      Phi1frame->GetXaxis()->CenterTitle();
      Phi1frame->GetYaxis()->CenterTitle();
      Phi1frame->GetYaxis()->SetTitle(" ");
      
      double ymax_Phi1;
      TH1F *Phi1_mplus = new TH1F("Phi1_mplus", "Phi1_mplus", 20, -TMath::Pi(), TMath::Pi());
      tin->Project("Phi1_mplus", "phistar1");
      ymax_Phi1 = Phi1_mplus->GetMaximum();
      
      TH1F *Phi1_hminus = new TH1F("Phi1_hminus", "Phi1_hminus", 20, -TMath::Pi(), TMath::Pi());
      tinMinus->Project("Phi1_hminus", "phistar1");
      ymax_Phi1 = Phi1_hminus->GetMaximum() > ymax_Phi1 ? Phi1_hminus->GetMaximum() : ymax_Phi1;
      
      TH1F *Phi1_hplus = new TH1F("Phi1_hplus", "Phi1_hplus", 20, -TMath::Pi(), TMath::Pi());
      tinHPlus->Project("Phi1_hplus", "phistar1");
      ymax_Phi1 = Phi1_hplus->GetMaximum() > ymax_Phi1 ? Phi1_hplus->GetMaximum() : ymax_Phi1;
      
      if ( drawmplus ) {
	data.plotOn(Phi1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDF->plotOn(Phi1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
      }
      if ( drawhminus ) {
	dataMinus.plotOn(Phi1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFMinus->plotOn(Phi1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
      }
      if ( drawhplus ) {
	dataHPlus.plotOn(Phi1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	myPDFHPlus->plotOn(Phi1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
      }
      if ( rescale != 1. ) 
	Phi1frame->GetYaxis()->SetRangeUser(0, ymax_Phi1  * rescale * 1.3);
      
      
      
      if ( offshell ) {
	RooPlot* w1frame =  wplusmass->frame(50);
	w1frame->GetXaxis()->CenterTitle();
	w1frame->GetYaxis()->CenterTitle();
	w1frame->GetYaxis()->SetTitle(" ");
	
	double ymax_w1;
	TH1F *w1_mplus = new TH1F("w1_mplus", "w1_mplus", 50, 1e-09, 120);
	tin->Project("w1_mplus", "wplusmass");
	ymax_w1 = w1_mplus->GetMaximum();
	
	TH1F *w1_hminus = new TH1F("w1_hminus", "w1_hminus", 50, 1e-09, 120);
	tinMinus->Project("w1_hminus", "wplusmass");
	ymax_w1 = w1_hminus->GetMaximum() > ymax_w1 ? w1_hminus->GetMaximum() : ymax_w1;
	
	TH1F *w1_hplus = new TH1F("w1_hplus", "w1_hplus", 50, 1e-09, 120);
	tinHPlus->Project("w1_hplus", "wplusmass");
	ymax_w1 = w1_hplus->GetMaximum() > ymax_w1 ? w1_hplus->GetMaximum() : ymax_w1;
	
	if ( drawmplus ) {
	  data.plotOn(w1frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDF->plotOn(w1frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
	}
	if ( drawhminus ) {
	  dataMinus.plotOn(w1frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFMinus->plotOn(w1frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	}
	if ( drawhplus ) {
	  dataHPlus.plotOn(w1frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFHPlus->plotOn(w1frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
	}
	if ( rescale != 1. ) 
	  w1frame->GetYaxis()->SetRangeUser(0, ymax_w1  * rescale * 1.5);
	
	// 
	//  wminus
	// 
	RooPlot* w2frame =  wminusmass->frame(50);
	
	w2frame->GetXaxis()->CenterTitle();
	w2frame->GetYaxis()->CenterTitle();
	w2frame->GetYaxis()->SetTitle(" ");
	
	double ymax_w2;
	TH1F *w2_mplus = new TH1F("w2_mplus", "w2_mplus", 50, 1e-09, 120);
	tin->Project("w2_mplus", "wminusmass");
	ymax_w2 = w2_mplus->GetMaximum();
	
	TH1F *w2_hminus = new TH1F("w2_hminus", "w2_hminus", 50, 1e-09, 120);
	tinMinus->Project("w2_hminus", "wminusmass");
	ymax_w2 = w2_hminus->GetMaximum() > ymax_w2 ? w2_hminus->GetMaximum() : ymax_w2;
	
	TH1F *w2_hplus = new TH1F("w2_hplus", "w2_hplus", 50, 1e-09, 120);
	tinHPlus->Project("w2_hplus", "wminusmass");
	ymax_w2 = w2_hplus->GetMaximum() > ymax_w2 ? w2_hplus->GetMaximum() : ymax_w2;
	
	if ( drawmplus ) {
	  data.plotOn(w2frame, MarkerColor(kRed),MarkerStyle(4),MarkerSize(1.5),LineWidth(0),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDF->plotOn(w2frame, LineColor(kRed),LineWidth(2), Normalization(rescale));
	}
	if ( drawhminus ) {
	  dataMinus.plotOn(w2frame, MarkerColor(kBlue),MarkerStyle(27),MarkerSize(1.9),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFMinus->plotOn(w2frame, LineColor(kBlue),LineWidth(2), Normalization(rescale));
	}
	if ( drawhplus ) {
	  dataHPlus.plotOn(w2frame, MarkerColor(kGreen+3),MarkerStyle(25),MarkerSize(1.5),XErrorSize(0), Rescale(rescale), DataError(RooAbsData::None));
	  myPDFHPlus->plotOn(w2frame, LineColor(kGreen+3),LineWidth(2), Normalization(rescale));
	}
	if ( rescale != 1. ) 
	  w2frame->GetYaxis()->SetRangeUser(0, ymax_w2  * rescale * 1.5);
      }
    }
    if ( drawpaper ) {
      TCanvas* can =new TCanvas("can","can",600,600);
      
      if ( offshell ) {
	w1frame->GetXaxis()->SetTitle("m_{l#nu} [GeV]");
	w1frame->Draw();
	can->Print(Form("paperplots/wplusmass_%.0fGeV_spin2_3in1_ww.eps", mH));
	can->SaveAs(Form("paperplots/wplusmass_%.0fGeV_spin2_3in1_ww.C", mH));
      }
      
      can->Clear();
      hsframe->Draw();
      can->Print(Form("paperplots/costhetastar_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/costhetastar_%.0fGeV_spin2_3in1_ww.C", mH));      
      
      can->Clear();
      Phi1frame->Draw();
      can->Print(Form("paperplots/phistar1_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phistar1_%.0fGeV_spin2_3in1_ww.C", mH));      

      can->Clear();
      h1frame->GetXaxis()->SetTitle("cos#theta_{1} or cos#theta_{2}");
      h1frame->Draw();
      can->Print(Form("paperplots/costheta1_%.0fGeV_spin2_3in1_ww.eps", mH));
      can->SaveAs(Form("paperplots/costheta1_%.0fGeV_spin2_3in1_ww.C", mH));

      can->Clear();
      Phiframe->Draw();
      can->Print(Form("paperplots/phi_%.0fGeV_spin2_3in1_ww.eps", mH));      
      can->SaveAs(Form("paperplots/phi_%.0fGeV_spin2_3in1_ww.C", mH));      

      }      else {
      
      TCanvas* czz = new TCanvas( "czz", "czz", 1000, 600 );
      czz->Divide(4,2);
      
      if ( offshell ) {
	czz->cd(1);
	w1frame->Draw();
	
	czz->cd(2);
	w2frame->Draw();
      }
      
      czz->cd(3);
      hsframe->Draw();
      
      czz->cd(4);
      box3->Draw();
      
      czz->cd(5);
      Phi1frame->Draw();
      
      czz->cd(6);
      h1frame->Draw();
      
      czz->cd(7);
      h2frame->Draw();
      
      czz->cd(8);
      Phiframe->Draw();
      
      if ( useGTerm->getVal() > 0.) {
	czz->SaveAs(Form("epsfiles/angles_TWW%.0f_JHU_7D.eps", mH));
	czz->SaveAs(Form("pngfiles/angles_TWW%.0f_JHU_7D.png", mH));
      } else {
	czz->SaveAs(Form("epsfiles/angles_TWW%.0f_JHU_7D_GenFromC.eps", mH));
	czz->SaveAs(Form("pngfiles/angles_TWW%.0f_JHU_7D_GenFromC.png", mH));
      }
    }
}