Esempio n. 1
0
void plot2(RooRealVar *mass, RooAbsPdf *pdf, RooAbsPdf *pdf1, RooAbsPdf *pdf2, float frac, RooDataSet *data, string name, int bins, int mhLow, int mhHigh){
 
 
  RooPlot *plot = mass->frame();
  mass->setRange("unblindReg_1",85,95);
  mass->setRange("unblindReg_2",110,120);
  if (BLIND) {
    data->plotOn(plot,Binning(bins),CutRange("unblindReg_1"));
    data->plotOn(plot,Binning(bins),CutRange("unblindReg_2"));
    data->plotOn(plot,Binning(bins),Invisible());
  }
  else data->plotOn(plot,Binning(bins));

  TCanvas *canv = new TCanvas();

  pdf->plotOn(plot);
  pdf->plotOn(plot,Components(*pdf1),LineColor(kRed),LineStyle(2)) ;
  pdf->plotOn(plot,Components(*pdf2),LineColor(kGreen),LineStyle(2)) ;

//,RooFit::NormRange("fitdata_1,fitdata_2"));
  //pdf->paramOn(plot,RooFit::Layout(0.35,0.89,0.89),RooFit::Format("NEA",AutoPrecision(1)));  
  //plot->getAttText()->SetTextSize(0.01); 
  //plot->SetMaximum(plot->GetMaximum()*2);    
  if (BLIND) plot->SetMinimum(0.0001);
  plot->SetTitle("");
  plot->SetYTitle(Form("Events / %.2fGeV",float(mhHigh-mhLow)/float(bins)));
  //plot->GetYaxis()->SetLabelSize(0.05);
  plot->SetTitleSize(0.045, "Y");
  plot->SetTitleOffset(1.,"Y");
  //plot->GetXaxis()->SetLabelSize(0.15);
  //plot->GetYaxis()->SetLabelSize(0.15);
  plot->SetXTitle("m_{#gamma#gamma}(GeV)");
  plot->SetTitleSize(0.15, "X");
  plot->Draw();

  TLatex *lat = new TLatex();
  lat->SetNDC();
  lat->SetTextFont(42);
  lat->DrawLatex(0.68,0.93,"19.7fb^{-1}(8TeV)"); 
  lat->DrawLatex(0.12,0.85,"CMS Preliminary");   
  lat->DrawLatex(0.7,0.7,Form("Frac = %.3f",frac));  
  string nameTemp = name;
  int catNum = nameTemp.find("cat");
  string catNameOLD = nameTemp.replace(0, catNum, "");
  string catName = catNameOLD.replace(catNameOLD.length()-4, 4, "");
  lat->DrawLatex(0.1,0.92, Form("%s", catName.c_str()));  

     TLegend *leg = new TLegend(0.12,0.7,0.32,0.8);
     leg->SetFillColor(0);
     leg->SetLineColor(1);
     leg->AddEntry(data,"Data","lep");
     leg->Draw("same");

  canv->SaveAs(Form("%s.png",name.c_str()));
  canv->SaveAs(Form("%s.pdf",name.c_str()));
 
  delete canv;
  delete lat;
}
//-------------------------------------------------------------
//Plot the model fitting function for signal+background
//=============================================================
void MakePlots(RooWorkspace *ws, RooFitResult *fitResult2D) {
  
  RooPlot* framex = 0;
  RooPlot* framey = 0;
  
  //Import yield variables
  RooRealVar *nsig = ws->var("N (Sig)");
  RooRealVar *nres = ws->var("N (ResBkg)");
  RooRealVar *nnonres = ws->var("N (NonResBkg)");
  //Select and plot only one experiment
  if (! (nsig->getVal() >= 15.6 && nsig->getVal() <= 17.0
  				&& nres->getVal() >= 27.9 && nres->getVal() <= 28.0
  				&& nnonres->getVal() <= 287.))
  	return;
  if (alreadyPlotted) return;  
  alreadyPlotted = 1;
  
  //Import the PDF's
  RooAbsPdf *model2Dpdf = ws->pdf("model2Dpdf");
  RooAbsPdf *sigPDFPho = ws->pdf("sigPDFPho");
  RooAbsPdf *resPDFPho = ws->pdf("resPDFPho");
  RooAbsPdf *nonresPDFPho = ws->pdf("nonresPDFPho");
  RooAbsPdf *sigPDFBjet = ws->pdf("sigPDFBjet");
  RooAbsPdf *sigPDFBjetCut = ws->pdf("sigPDFBjetCut");
  RooAbsPdf *resPDFBjet = ws->pdf("resPDFBjet");
  RooAbsPdf *resPDFBjetExt = ws->pdf("resPDFBjetExt");
  RooAbsPdf *nonresPDFBjet = ws->pdf("nonresPDFBjet");
  //x-axis variables
  RooRealVar *massPho = ws->var("massPho");
  RooRealVar *massBjet = ws->var("massBjet");
  RooRealVar *massBjetExt = ws->var("massBjetExt");
  RooRealVar *massBjetCut = ws->var("massBjetCut");
  //sig variables
  RooRealVar *sigMeanBjet = ws->var("sigMeanBjet");
  RooRealVar *sigSigmaBjet = ws->var("sigSigmaBjet");
  RooRealVar *sigAlpha = ws->var("sigAlpha");
  RooRealVar *sigPower = ws->var("sigPower");
  //res bkg variables
  RooRealVar *resMeanBjet = ws->var("resMeanBjet");
  RooRealVar *resSigmaBjet = ws->var("resSigmaBjet");
  RooRealVar *resAlpha = ws->var("resAlpha");
  RooRealVar *resPower = ws->var("resPower");
  RooRealVar *resExpo = ws->var("resExpo");
  RooRealVar *nbbH = ws->var("nbbH");
  RooRealVar *nOthers = ws->var("nOthers");
  //simulated data
  RooDataHist *sigBjetData = (RooDataHist *)ws->data("sigBjetData");
  RooDataHist *resBjetDataExt = (RooDataHist *)ws->data("resBjetDataExt");
  RooDataSet *pseudoData2D = (RooDataSet *)ws->data("pseudoData2D");
  
  //Plot of 2D generated data and fits
  TH1 *data2d = pseudoData2D->createHistogram("2D Data", *massBjet,Binning(25), YVar(*massPho,Binning(25)));
  data2d->SetStats(0);
  TH1 *fit2d = model2Dpdf->createHistogram("2D Fit", *massBjet, YVar(*massPho));
  fit2d->SetStats(0);
  
  cv = new TCanvas("cv","cv",1600,600);
  cv->Divide(2);
  cv->cd(1); gPad->SetLeftMargin(0.15); data2d->Draw("LEGO2");
  data2d->SetTitle("");
  data2d->GetXaxis()->SetTitleOffset(2); data2d->GetXaxis()->SetTitle("M_{bb} [GeV/c^{2}]");
  data2d->GetYaxis()->SetTitleOffset(2.2); data2d->GetYaxis()->SetTitle("M_{#gamma#gamma} [GeV/c^{2}]");
  data2d->GetZaxis()->SetTitleOffset(1.75);
  
  cv->cd(2); gPad->SetLeftMargin(0.15); fit2d->Draw("SURF1");
  fit2d->SetTitle("");
  fit2d->GetXaxis()->SetTitleOffset(2); data2d->GetXaxis()->SetTitle("M_{bb} [GeV/c^{2}]");
  fit2d->GetYaxis()->SetTitleOffset(2.2); data2d->GetYaxis()->SetTitle("M_{#gamma#gamma} [GeV/c^{2}]");
  fit2d->GetZaxis()->SetTitleOffset(1.75);
  cv->SaveAs(Form("Plots/AllSignalBkgd/Fits/Toys/twoDimensionalFits_%d.gif",1));
  
  //Plot of massBjet and massPho projections from 2D fit
  massPho->setRange("PhoWindow",120,130);
  framex = massBjet->frame(Bins(50)); 
  framex->SetTitle(""); framex->SetXTitle("M_{bb} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
  pseudoData2D->plotOn(framex, CutRange("PhoWindow"));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), VisualizeError(*fitResult2D), FillStyle(3001));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("sigPDFBjet"), LineStyle(kDashed), LineColor(kRed));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("resPDFBjet"), LineStyle(kDashed), LineColor(kOrange));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("nonresPDFBjet"), LineStyle(kDashed), LineColor(kGreen));
  
  framey = massPho->frame(Bins(50)); 
  framey->SetTitle(""); framey->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framey->SetYTitle("Number of Events");
  pseudoData2D->plotOn(framey);
  model2Dpdf->plotOn(framey, VisualizeError(*fitResult2D), FillStyle(3001));
  model2Dpdf->plotOn(framey);
  model2Dpdf->plotOn(framey,Components("sigPDFPho"), LineStyle(kDashed), LineColor(kRed));
  model2Dpdf->plotOn(framey,Components("resPDFPho"), LineStyle(kDashed), LineColor(kOrange));
  model2Dpdf->plotOn(framey,Components("nonresPDFPho"), LineStyle(kDashed), LineColor(kGreen));
  
  cv = new TCanvas("cv","cv",1600,600);
  cv->Divide(2);
  cv->cd(1); framex->Draw();
  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.042);
  tex->SetTextFont(42);
  tex->DrawLatex(0.52, 0.84, Form("N_{Sig} = %.2f +/- %.2f", nsig->getVal(), nsig->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.79, Form("N_{ResBkg} = %.2f +/- %.2f", nres->getVal(), nres->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.74, Form("N_{NonResBkg} = %.2f +/- %.2f", nnonres->getVal(), nnonres->getPropagatedError(*fitResult2D)));
  tex->Draw();
  cv->Update();
  cv->cd(2); framey->Draw();
  tex->DrawLatex(0.52, 0.84, Form("N_{Sig} = %.2f +/- %.2f", nsig->getVal(), nsig->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.79, Form("N_{ResBkg} = %.2f +/- %.2f", nres->getVal(), nres->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.74, Form("N_{NonResBkg} = %.2f +/- %.2f", nnonres->getVal(), nnonres->getPropagatedError(*fitResult2D)));
  tex->Draw();
  cv->Update();
  cv->SaveAs(Form("Plots/AllSignalBkgd/Fits/Toys/projectionFits_%d.gif",1));
}
Esempio n. 3
0
int main(){

  RooRealVar zero("zero","",0,0,150); 

  //input parameters for the distribution
  double alpha_double = 2.38;
  double beta_double = 0.092;
  double lambda_double = 2.21;
  double theta_double = 1.12;
  double c_frac = 0.5;
  //RooRealVar fsig("fsig","signal fraction",0.3) ;

  string epsname = "plots/gamma_pion20";

  
  hit_info multi_shower("fullsim/example_pi20Gev.root");
  //hit_info multi_shower("fullsim/example_ele_20GeV.root");
  
 
  double beta_gflash_factor = 1.49;
  double theta_gflash_factor = 16.42;

  beta_double = beta_double/beta_gflash_factor;
  theta_double = theta_double/theta_gflash_factor;
  
  // --- Observable --- 
  RooRealVar depth("depth","depth [cm]",0,800); 
  depth.removeMax(); // set infinite range
  // --- Weight ---
  RooRealVar* weight = new RooRealVar("weight","1/E dE/dr", 0.0, 1.0);
 
  // --- Gamma pdf --- 
  //if one of the Values is set to const you can not ask for it in RooFitModel, otherwise the program will crash
  //RooRealVar alpha("alpha","alpha",alpha_double,0.0,4);
  RooRealVar alpha("alpha","alpha",0.0,20.);
  //alpha.removeMax(); // set infinite range
  //RooRealVar beta("beta","beta",1./beta_double,0.0,100.);
  RooRealVar beta("beta","beta",0.1,.1,3.5);
  //beta.removeMax(); // set infinite range

  RooRealVar mu("mu","mu",0); // no ranges means variable is fixed in fit
  RooRealVar nu("nu","nu",0); // no ranges means variable is fixed in fit
  
  //RooRealVar lambda("lambda","lambda",lambda_double,0.0,6.);
  RooRealVar lambda("lambda","lambda",0.0,40.);
  //lambda.removeMax(); // set infinite range
  //RooRealVar theta("theta","theta",1./theta_double,0.0,100.) ;  
  RooRealVar theta("theta","theta",1.,47) ;  
  //theta.removeMax(); // set infinite range

  RooGamma gamma_one("gamma_one","gamma_one pdf",depth,alpha,beta,mu) ; 
  RooGamma gamma_two("gamma_two","gamma_two pdf",depth,lambda,theta,nu) ; 

  RooRealVar fsig("fsig","signal fraction",c_frac,0.0,1.);
  //RooRealVar fsig("fsig","signal fraction",c_frac);

  RooAddPdf model("model","model",RooArgList(gamma_two,gamma_one),fsig) ;
   
  RooDataSet mean("mean","mean",RooArgSet(depth,weight),"weight"); 
  TH1F* mean_fithist = new TH1F("mean_fithist"," mean fit hist",50,0,150);


  TH1F* log_alpha1 = new TH1F("log_alpha1"," log(#alpha_{1})",20,-1,3);
  TH1F* log_beta1  = new TH1F("log_beta1"," log(#beta_{1})",20,-1,3);
  TH2F* log_corr1  = new TH2F("log_corr1"," correlation #alpha_{1} #beta_{1}",20,-1,3,20,-1,3);
  TH1F* log_alpha2 = new TH1F("log_alpha2"," log(#alpha_{2})",20,-1,3);
  TH1F* log_beta2  = new TH1F("log_beta2"," log(#beta_{2})",20,-1,3);
  TH2F* log_corr2  = new TH2F("log_corr2"," correlation #alpha_{2} #beta_{2}",20,-1,3,20,-1,3);

  TH2F* mean_hist = new TH2F("mean_hist"," mean hist",100,0,150,100.,0.,.0015);
  
  TCanvas * can = new TCanvas("can", "can", 600, 500); 
  can->cd();
  set_style();
  
  
  //can->Print(epsname+"[");

  double c_tot =0;

  unsigned int n_part =100;

  for(unsigned int p = 0; p<n_part ; ++p){

    TLegend * legend = new TLegend(0.5,0.65,.88,0.88);
    legend->SetTextFont(72);
    legend->SetTextSize(0.04);
    legend->SetFillColor(kWhite);
    legend->SetBorderSize(0);

    one_shower shower =  multi_shower.all_shower.at(p); 
   
    //DataSet I am looking at
    RooDataSet full_sim_data("full_sim_data","full_sim_data",RooArgSet(depth,weight),"weight");
    TH1F* datahisto = new TH1F("datahist","datahist",15,0,120);

    double sumHCAL=0;

    double deltar =-1; 
    for(unsigned int i = 0; i < shower.mytype.size(); ++i){	
      sumHCAL += shower.myenergy.at(i);
      double x_val = shower.myz.at(i);
      double y_val = shower.myy.at(i);
      double z_val = shower.myz.at(i);
      
      z_val = z_val - shower.interactPoint; 
      double distance=-1;
      if(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10 < 200) distance = sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10;

      if(deltar < distance) deltar = z_val;
    }

    deltar=deltar/shower.mytype.size();
    
    c_tot += shower.ePi0first_energy/n_part;
    fsig.setVal(shower.ePi0first_energy);
    fsig.setRange(shower.ePi0first_energy-0.05 > 0 ? shower.ePi0first_energy-0.05: 0,shower.ePi0first_energy+0.05<1?shower.ePi0first_energy+0.05:1);
    //fsig.setRange(1-shower.ePi0first_energy-0.05 > 0 ? 1-shower.ePi0first_energy-0.05: 0,1-shower.ePi0first_energy+0.05<1 ? 1-shower.ePi0first_energy+0.05:1);

    for(unsigned int i = 0; i < shower.mytype.size(); ++i){	
      double x_val = shower.myx.at(i);
      double y_val = shower.myy.at(i);
      double z_val = shower.myz.at(i);

      // if(shower.mytype.at(i) !=2)continue;
     
      z_val = z_val - shower.interactPoint; 
      //if(z_val<=0) continue;
      depth.setVal(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10);
      //depth.setVal(z_val);
      //cout <<depth.getVal()<<endl;
      datahisto->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar);
      mean_fithist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar/n_part);
      mean_hist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar);
      full_sim_data.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0);
      mean.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0);
    }
  

    RooDataHist roodatahist("roodatahist","roodatahist",depth,Import(*datahisto)) ;

    //model.fitTo(roodatahist, Strategy(2) );
    model.fitTo(full_sim_data);
      
    RooDataHist* full_sim_binned = full_sim_data.binnedClone("full_sim_binned","full sim binned");
    //prepare to plot fits
    
    RooPlot * depthFrame = depth.frame(0,120,100);
    depthFrame->SetTitle("");
    depthFrame->SetTitleOffset(1.2,"Y");
    depthFrame->SetLabelSize(0.02,"Y");
    depthFrame->SetYTitle("1/E dE/dr");
    //zero.plotOn(depthFrame,LineStyle(kDashed),LineColor(kBlack));
    //full_sim_data.plotOn(depthFrame);
    roodatahist.plotOn(depthFrame);
    //full_sim_binned->plotOn(depthFrame);
    
    model.plotOn(depthFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one"));
    model.plotOn(depthFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two"));
    model.plotOn(depthFrame,Name("model"));
    
    stringstream gamma_one_text;
    gamma_one_text.precision(3);
    gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl;
    stringstream gamma_two_text; 
    gamma_two_text.precision(3);
    gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl;
    
    stringstream gamma_text; 
    gamma_text.precision(2);
    gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<<shower.ePi0first_energy<<")"<<endl;
    
    stringstream  chi2; 
    chi2.precision(2);
    chi2 << "#chi^{2} prob. = " << TMath::Prob(depthFrame->chiSquare(),14) <<endl;

    legend->AddEntry(depthFrame->findObject("gamma_one"),gamma_one_text.str().c_str(),"L");
    legend->AddEntry(depthFrame->findObject("gamma_two"),gamma_two_text.str().c_str(),"L");
    legend->AddEntry(depthFrame->findObject("model"),gamma_text.str().c_str(),"L");
    legend->AddEntry((TObject*)0, chi2.str().c_str(), "");
    cout << "alpha,  beta "<< alpha.getVal() << " " << 1/beta.getVal()*beta_gflash_factor << std::endl;
    cout << "lambda, theta "<<lambda.getVal() << " " << 1/theta.getVal()*theta_gflash_factor << std::endl;
    cout <<"c, chi2 "<< fsig.getVal() << " "<<depthFrame->chiSquare()<< std::endl;
    cout <<"starting , interacting Points "<<shower.startingPoint<<" "<<shower.interactPoint <<endl;
    cout<< "pi0first, pi0tot "<<shower.ePi0first_energy <<" "<<shower.ePi0tot_energy<<endl;
    
    /*
    log_alpha1->Fill(log10(alpha.getVal()));
    log_alpha2->Fill(log10(lambda.getVal()));
    //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl;
    log_beta1 ->Fill(log10(1/beta.getVal()*beta_gflash_factor));
    log_beta2 ->Fill(log10(1/theta.getVal()*theta_gflash_factor));
    log_corr1 ->Fill(log10(alpha.getVal()),log10(1/beta.getVal()*beta_gflash_factor));
    log_corr2 ->Fill(log10(lambda.getVal()),log10(1/theta.getVal()*theta_gflash_factor));
    */
    
    if(fsig.getVal()>0.1)log_alpha1->Fill(log(alpha.getVal()));
    if(fsig.getVal()<0.9)log_alpha2->Fill(log(lambda.getVal()));
    //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl;
    if(fsig.getVal()>0.1)log_beta1 ->Fill(log(1/beta.getVal()*beta_gflash_factor));
    if(fsig.getVal()<0.9)log_beta2 ->Fill(log(1/theta.getVal()*theta_gflash_factor));
    if(fsig.getVal()>0.1)log_corr1 ->Fill(log(alpha.getVal()),log(1/beta.getVal()*beta_gflash_factor));
    if(fsig.getVal()<0.9)log_corr2 ->Fill(log(lambda.getVal()),log(1/theta.getVal()*theta_gflash_factor));
    

    //prepare to dump all the plots in the ps file
    
    
    // one data sample and its fit is drawn
    /*
    datahisto->Draw();
    datahisto0->SetLineColor(kRed);
    datahisto0->Draw("same");
    datahisto1->SetLineColor(kGreen);
    datahisto1->Draw("same");
    datahisto2->SetLineColor(kBlue);
    datahisto2->Draw("same");
    can->Print(epsname);
    */
    //if(depthFrame->chiSquare()>5) continue;
    depthFrame->Draw("HIST p");
    legend->Draw();

    stringstream  particle_number; 
    particle_number.precision(1);
    particle_number << p <<endl;
    
    can->Print((epsname+"_"+particle_number.str()+".pdf").c_str());
  }

  RooDataHist roomeandatahist("roomeandatahist","roomeandatahist",depth,Import(*mean_fithist)) ;


  fsig.setVal(c_tot);
  alpha.removeMax(); // set infinite range
  beta.removeMax(); // set infinite range
  lambda.removeMax(); // set infinite range
  theta.removeMax(); // set infinite range

  //model.fitTo(roomeandatahist);
  //model.fitTo(mean,SumW2Error(kTRUE));

  TLegend * mean_legend = new TLegend(0.5,0.65,.9,0.9);
  mean_legend->SetTextFont(72);
  mean_legend->SetTextSize(0.04);
  mean_legend->SetFillColor(kWhite);
  mean_legend->SetBorderSize(0);

  stringstream  mean_gamma_one_text;
  mean_gamma_one_text.precision(3);
  mean_gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl;
  stringstream mean_gamma_two_text; 
  mean_gamma_two_text.precision(3);
  mean_gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl;
  
  stringstream  mean_gamma_text; 
  mean_gamma_text.precision(2);
  mean_gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<< c_tot<<")"<<endl;
  
  stringstream  mean_chi2; 
  mean_chi2.precision(2);
  //mean_chi2 << "#chi^{2} " <<depthFrame->chiSquare() <<endl;
  
  RooPlot * meanFrame = depth.frame(0,120,200);
  //meanFrame->SetMaximum(1);
  meanFrame->SetTitle("Mean Fit");
  meanFrame->SetYTitle("1/E dE/dr");
  model.plotOn(meanFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one"));
  model.plotOn(meanFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two"));
  model.plotOn(meanFrame,Name("model"));
  //mean.plotOn(meanFrame);
  //roomeandatahist.plotOn(meanFrame);

  mean_legend->AddEntry(meanFrame->findObject("gamma_one"),mean_gamma_one_text.str().c_str(),"L");
  mean_legend->AddEntry(meanFrame->findObject("gamma_two"),mean_gamma_two_text.str().c_str(),"L");
  mean_legend->AddEntry(meanFrame->findObject("model"),mean_gamma_text.str().c_str(),"L");
  
  meanFrame->Draw();
  mean_legend->Draw();
  //datahisto->Draw();
  //can->Print(epsname);

  //mean_hist->Draw("box");
  //can->Print(epsname);
 
  can->Print((epsname+"_mean.pdf").c_str());
  log_alpha1->Draw();
  can->Print((epsname+"_alpha1_log.pdf").c_str());
  log_beta1->Draw();
  can->Print((epsname+"_beta1_log.pdf").c_str());
  log_corr1->Draw("colz");
  can->Print((epsname+"corr1_log.pdf").c_str());
  log_alpha2->Draw();
  can->Print((epsname+"apha2_log.pdf").c_str());
  log_beta2->Draw();
  can->Print((epsname+"beta2_log.pdf").c_str());
  log_corr2->Draw("colz");
  can->Print((epsname+"corr2_log.pdf").c_str());

  ///can->Print(epsname+"]");
  return 0;
}
void AddModels(RooWorkspace *ws, const string inputfilePho, Int_t plotOption, Int_t constbkg) {

  gStyle->SetOptFit(0111);
  
  //Import the sample histograms
  TFile *filePho = new TFile(inputfilePho.c_str(), "READ");
  TH1F *sigPhoMass = (TH1F*)filePho->Get("sigPhoMassBJetWin");
  TH1F *nonresPhoMass = (TH1F*)filePho->Get("nonresPhoMassBJetWin");
  
  //-------------------------------------------------------------
  //Make Variables for Fit
  //=============================================================
    
  //Variables for diPhoton
  RooRealVar massPho("massPho","M_{#gamma#gamma}",100.,150.,"GeV/c^{2}");
  RooRealVar massPhoCut("massPhoCut","M_{#gamma#gamma} (Cut)",115.,130.,"GeV/c^{2}");
  //Signal diPhoton
  RooRealVar sigMeanPho("sigMeanPho", "#bar{M}_{#gamma#gamma}", 125., 120., 130., "GeV/c^{2}");
  RooRealVar sigSigmaPho("sigSigmaPho", "#sigma_{#gamma#gamma}", 1.5, 1., 2., "GeV/c^{2}");
  RooRealVar sigAlphaPho("sigAlphaPho","#alpha_{#gamma#gamma} (cut)", 1., 0.1, 2.);
  RooRealVar sigPowerPho("sigPowerPho", "n_{#gamma#gamma} (power)", 3., 1., 5.);
  //Non-Resonant Background diPhoton
  RooRealVar expRatePho("expRatePho", "#lambda_{#gamma#gamma}", -.027, -.1, 0.);
  
  //Weights for the fit
  RooRealVar nsig("N (Sig)", "# signal events", 18.5, -50,100); //(12.7 + 5.8)
  RooRealVar nnonres("N (NonResBkg)", "# non-resonant background events", 99.7, 0,1000);
  
  //-------------------------------------------------------------
  //Make PDFs for Signal + Background
  //=============================================================
  //PDFs for diPhoton
  //Preliminary Fit for Cut Signal
  RooCBShape sigPDFPhoCut("sigPDFPhoCut", "Signal PDF #gamma#gamma", massPhoCut, sigMeanPho, sigSigmaPho, sigAlphaPho, sigPowerPho);
  RooDataHist sigPhoData("sigPhoData", "sigPhoData", massPhoCut, sigPhoMass);
  RooFitResult *sigPhoCBResult = sigPDFPhoCut.fitTo(sigPhoData, RooFit::Strategy(2));
  //Signal
  RooCBShape sigPDFPho("sigPDFPho", "Signal PDF #gamma#gamma", massPho, sigMeanPho, sigSigmaPho, sigAlphaPho, sigPowerPho);

  //Non-Resonant Background
  RooDataHist nonresPhoData("nonresPhoData", "nonresPhoData", massPho, nonresPhoMass);
  RooExponential nonresPDFPho("nonresPDFPho", "Non-Resonant Background PDF #gamma#gamma", massPho, expRatePho);
  RooFitResult *nonresPhoResult = nonresPDFPho.fitTo(nonresPhoData, RooFit::Strategy(2));
  
  RooAddPdf modelpdf("modelpdf", "Signal+Background PDF", RooArgList(sigPDFPho, nonresPDFPho), RooArgList(nsig, nnonres));
  
  //Variables to set constant
  sigMeanPho.setConstant();
  sigSigmaPho.setConstant();
  sigAlphaPho.setConstant();
  sigPowerPho.setConstant();
  expRatePho.setConstant(); 
  
  //Add all stuff to workspace
  modelpdf.graphVizTree("fullModel.dot");
  ws->import(sigPhoData, Rename("sigPhoData"));
  ws->import(nonresPhoData, Rename("nonresPhoData"));
  ws->import(sigPDFPhoCut);
  
  ws->import(modelpdf);
  
  //-------------------------------------------------------------
  //Plot the fitting functions for signal+background
  //=============================================================
  if (plotOption == 1) {
    RooPlot *framex = 0;
    
    //Plot the Crystal Ball Fit for Signal Photon
    cv = new TCanvas("cv","cv",800,600);
    framex = massPhoCut.frame(Bins(50));
    sigPhoData.plotOn(framex, DrawOption("B"), DataError(RooAbsData::None), FillColor(kRed));
    sigPDFPhoCut.plotOn(framex);
    framex->SetTitle(""); framex->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
    framex->Draw();
    tex = new TLatex();
    tex->SetNDC();
    tex->SetTextSize(0.048);
    tex->SetTextFont(42);
    tex->DrawLatex(0.64, 0.84, Form("#bar{M}_{#gamma#gamma} = %.2f", sigMeanPho.getVal()));
    tex->DrawLatex(0.64, 0.79, Form("#sigma_{#gamma#gamma} = %.2f", sigSigmaPho.getVal()));
    //tex->DrawLatex(0.64, 0.74, Form("#alpha_{#gamma#gamma} = %.2f", sigAlpha.getVal()));
    //tex->DrawLatex(0.64, 0.69, Form("n_{#gamma#gamma} = %.2f", sigPower.getVal()));
    tex->Draw();
    cv->Update();
    cv->SaveAs("Plots/AllSignalBkgd/Fits/InitialFits/sigPhoCutCB.gif");
    
   
    //Plot Exponential Fit to Non-Resonant Background Bjet 
    cv = new TCanvas("cv","cv",800,600);
    framex = massPho.frame(Bins(50));
    nonresPhoData.plotOn(framex, DrawOption("B"), DataError(RooAbsData::None), FillColor(kGreen));
    nonresPDFPho.plotOn(framex);
    framex->SetTitle(""); framex->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
    framex->Draw();
    tex = new TLatex();
    tex->SetNDC();
    tex->SetTextSize(0.048);
    tex->SetTextFont(42);
    tex->DrawLatex(0.64, 0.84, Form("#lambda_{#gamma#gamma} = %.3f", expRatePho.getVal()));
    tex->Draw();
    cv->Update();
    cv->SaveAs("Plots/AllSignalBkgd/Fits/InitialFits/nonresPhoExpo.gif");
    
    
  }//end of plotting
}
Esempio n. 5
0
void fitDilMass(){
  
  using namespace RooFit;
  gROOT->SetStyle("Plain");

  //declare variables
  RooRealVar mll("mll",      "dilepton mass",              0,100 ,"GeV");
  RooRealVar edge("edge",    "dilepton mass edge",         0,100 ,"GeV");
  RooRealVar min("min",      "min dilepton mass",          0,100 ,"GeV");
  RooRealVar k("k",          "constant",                   0,100 ,"GeV");
  RooRealVar mean("mean",    "mean of mll resolution",     0,100 ,"GeV");
  RooRealVar sigma("sigma",  "sigma of mll resolution",    0,10  ,"GeV");

  //set variables
  mll.setBins(100);
  edge.setVal(50.);
  mean.setVal(0.);
  sigma.setVal(2.);
  min.setVal(10.);
  min.setConstant();
  k.setVal(1.);
  mean.setConstant();
  sigma.setConstant();
  mll.setMin(0);
  mll.setMax(100);

  //get data
  TFile* file = TFile::Open("LM0_dilmass.root");
  TH1D*  hist = static_cast<TH1D *>((file)->Get("dilmass"));
  RooDataHist data("data","data histogram",RooArgSet(mll),hist);

  //declare and make PDFs
  RooGenericPdf tri("tri","( (mll < min && mll > 0) * k + (mll > min && mll < edge ) * (mll - min) + (mll > edge && mll < 200) * k)", RooArgList(mll , edge, min, k) );
  RooGaussian gaus("gaus","Detector Gaussian",mll,mean,sigma); 
  RooNumConvPdf trigaus("trigaus","triangle + gaussian function",mll,tri,gaus); 
  trigaus.setConvolutionWindow(mean,sigma,25);

  //do fit
  RooFitResult *result = trigaus.fitTo( data , Save() , Minos(kFALSE) , SumW2Error(kFALSE));

  //make plot
  TCanvas *c1=new TCanvas("c1","",800,600);
  c1->cd();

  RooPlot* frame = mll.frame();
  frame->SetXTitle("dilepton mass (GeV)");
  frame->SetYTitle("");
  frame->SetTitle("");
  data.plotOn(frame);
  tri.plotOn(frame , LineStyle(kDashed));
  trigaus.plotOn( frame );
  trigaus.paramOn( frame );
  frame->Draw();
  //frame->SetMinimum(-10);
  //frame->SetMaximum(100);

 
  int nfloatpars = result->floatParsFinal().getSize();
  int ndf        = 20 - nfloatpars;
  float chi2     = frame->chiSquare(nfloatpars)*ndf;
  float prob     = TMath::Prob(chi2,ndf);
 
  cout << endl << endl;
  cout << "Fit Results-------------------------------------------"     << endl;
  cout << "chi2/ndf = " << chi2 << " / " << ndf                        << endl;
  cout << "prob     = " << prob                                        << endl;  
  cout << "edge     = " << edge.getVal() << " +/- " << edge.getError() << endl;
  cout << "k        = " << k.getVal()    << " +/- " << k.getError()    << endl;
  cout << "------------------------------------------------------"     << endl;
  cout << endl << endl;
}
void StandardHistFactoryPlotsWithCategories(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData"){


   double nSigmaToVary=5.;
   double muVal=0;
   bool doFit=false;

   // -------------------------------------------------------
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
                                                           // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }

   // -------------------------------------------------------
   // Tutorial starts here
   // -------------------------------------------------------

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if(!w){
      cout <<"workspace not found" << endl;
      return;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

   // get the modelConfig out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if(!data || !mc){
      w->Print();
      cout << "data or ModelConfig was not found" <<endl;
      return;
   }

   // -------------------------------------------------------
   // now use the profile inspector

   RooRealVar* obs = (RooRealVar*)mc->GetObservables()->first();
   TList* list = new TList();


   RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());

   firstPOI->setVal(muVal);
   //  firstPOI->setConstant();
   if(doFit){
      mc->GetPdf()->fitTo(*data);
   }

   // -------------------------------------------------------


   mc->GetNuisanceParameters()->Print("v");
   int  nPlotsMax = 1000;
   cout <<" check expectedData by category"<<endl;
   RooDataSet* simData=NULL;
   RooSimultaneous* simPdf = NULL;
   if(strcmp(mc->GetPdf()->ClassName(),"RooSimultaneous")==0){
      cout <<"Is a simultaneous PDF"<<endl;
      simPdf = (RooSimultaneous *)(mc->GetPdf());
   } else {
      cout <<"Is not a simultaneous PDF"<<endl;
   }



   if(doFit) {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      tt=(RooCatType*) iter->Next();
      RooAbsPdf* pdftmp = ((RooSimultaneous*)mc->GetPdf())->getPdf(tt->GetName()) ;
      RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
      obs = ((RooRealVar*)obstmp->first());
      RooPlot* frame = obs->frame();
      cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
      cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
      data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

      Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

      pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;
      frame->Draw();
      cout <<"expected events = " << mc->GetPdf()->expectedEvents(*data->get()) <<endl;
      return;
   }



   int nPlots=0;
   if(!simPdf){

      TIterator* it = mc->GetNuisanceParameters()->createIterator();
      RooRealVar* var = NULL;
      while( (var = (RooRealVar*) it->Next()) != NULL){
         RooPlot* frame = obs->frame();
         frame->SetYTitle(var->GetName());
         data->plotOn(frame,MarkerSize(1));
         var->setVal(0);
         mc->GetPdf()->plotOn(frame,LineWidth(1.));
         var->setVal(1);
         mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(1));
         var->setVal(-1);
         mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(1));
         list->Add(frame);
         var->setVal(0);
      }


   } else {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      //    TIterator* iter = simPdf->indexCat().typeIterator() ;
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      while(nPlots<nPlotsMax && (tt=(RooCatType*) iter->Next())) {

         cout << "on type " << tt->GetName() << " " << endl;
         // Get pdf associated with state from simpdf
         RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

         // Generate observables defined by the pdf associated with this state
         RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
         //      obstmp->Print();


         obs = ((RooRealVar*)obstmp->first());

         TIterator* it = mc->GetNuisanceParameters()->createIterator();
         RooRealVar* var = NULL;
         while(nPlots<nPlotsMax && (var = (RooRealVar*) it->Next())){
            TCanvas* c2 = new TCanvas("c2");
            RooPlot* frame = obs->frame();
            frame->SetName(Form("frame%d",nPlots));
            frame->SetYTitle(var->GetName());

            cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
            cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
            data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

            Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }
            // w->allVars().Print("v");
            // mc->GetNuisanceParameters()->Print("v");
            // pdftmp->plotOn(frame,LineWidth(2.));
            // mc->GetPdf()->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()+0.05);
               var->Print();
            } else{
               var->setVal(nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kRed),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()-0.05);
               var->Print();
            } else{
               var->setVal(-nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kGreen),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;



            // set them back to normal
            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }

            list->Add(frame);

            // quit making plots
            ++nPlots;

            frame->Draw();
            c2->SaveAs(Form("%s_%s_%s.pdf",tt->GetName(),obs->GetName(),var->GetName()));
            delete c2;
         }
      }
   }



   // -------------------------------------------------------


   // now make plots
   TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
   if(list->GetSize()>4){
      double n = list->GetSize();
      int nx = (int)sqrt(n) ;
      int ny = TMath::CeilNint(n/nx);
      nx = TMath::CeilNint( sqrt(n) );
      c1->Divide(ny,nx);
   } else
      c1->Divide(list->GetSize());
   for(int i=0; i<list->GetSize(); ++i){
      c1->cd(i+1);
      list->At(i)->Draw();
   }





}
Esempio n. 7
0
void MakePlots(RooWorkspace* ws){

  std::cout << "make plots" << std::endl;

  RooAbsPdf* model = ws->pdf("model");
  RooAbsPdf* model_dY = ws->pdf("model_dY");
  RooRealVar* nsig = ws->var("nsig");
  RooRealVar* nsigDPS = ws->var("nsigDPS");
  RooRealVar* nsigSPS = ws->var("nsigSPS");
  RooRealVar* nBbkg = ws->var("nBbkg");
  RooRealVar* nbkg = ws->var("nbkg");
  RooRealVar* nbkg2 = ws->var("nbkg2");
  RooRealVar* FourMu_Mass = ws->var("FourMu_Mass");
  RooRealVar* Psi1_Mass = ws->var("Psi1_Mass");
  RooRealVar* Psi2_Mass = ws->var("Psi2_Mass");
  RooRealVar* Psi1_CTxy = ws->var("Psi1_CTxy");
  RooRealVar* Psi2_CTxy = ws->var("Psi2_CTxy");
  RooRealVar* Psi1To2_dY = ws->var("Psi1To2_dY");
  RooRealVar* Psi1To2Significance = ws->var("Psi1To2Significance");

  // note, we get the dataset with sWeights
  RooDataSet* data = (RooDataSet*) ws->data("dataWithSWeights");
  model->fitTo(*data, Extended() );

  // make TTree with efficiency variation info
  //TFile *fFile = new TFile("Fit_Results_Eff_Cut.root","recreate");
  setTDRStyle();
  // make our canvas
  TCanvas* cmass1 = new TCanvas("sPlotMass1","sPlotMass1", 600, 600);
  cmass1->cd();
  cmass1->SetFillColor(kWhite);

  RooPlot* Mass1Plot = Psi1_Mass->frame(20);
  data->plotOn(Mass1Plot,Name("data"), DataError(RooAbsData::SumW2));
  model->plotOn(Mass1Plot,Name("all"));
  model->plotOn(Mass1Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(Mass1Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(Mass1Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(Mass1Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  Mass1Plot->SetTitle("");
  Mass1Plot->SetXTitle("#mu^{+}#mu^{-} 1 Invariant Mass (GeV/c^{2})");
  Mass1Plot->SetYTitle("Events / 0.025 GeV/c^{2}");
  Mass1Plot->SetLabelOffset(0.012);
  //Mass1Plot->SetTitleOffset(0.95);
  Mass1Plot->Draw();
  //cmass1->SaveAs("pic/Psi1_mass.pdf");
  //cmass1->Close();

  TCanvas* cmass2 = new TCanvas("sPlotMass2","sPlotMass2", 600, 600);
  cmass2->cd();
  cmass2->SetFillColor(kWhite);
  RooPlot* Mass2Plot = Psi2_Mass->frame(20); 
  data->plotOn(Mass2Plot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(Mass2Plot,Name("all"));   
  model->plotOn(Mass2Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(Mass2Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(Mass2Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(Mass2Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  Mass2Plot->SetTitle("");
  Mass2Plot->SetXTitle("#mu^{+}#mu^{-} 2 Invariant Mass (GeV/c^{2})");
  Mass2Plot->SetYTitle("Events / 0.025 GeV/c^{2}");
  Mass2Plot->SetLabelOffset(0.012);
  //Mass2Plot->SetTitleOffset(0.95);
  Mass2Plot->Draw();
  //cmass2->SaveAs("pic/Psi2_mass.pdf");
  //cmass2->Close();

  TCanvas* cctxy1 = new TCanvas("sPlotCTxy1","sPlotCTxy1", 600, 600);
  cctxy1->cd();
  cctxy1->SetFillColor(kWhite);
  RooPlot* CTxy1Plot = Psi1_CTxy->frame(30); 
  data->plotOn(CTxy1Plot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(CTxy1Plot,Name("all"));   
  model->plotOn(CTxy1Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(CTxy1Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(CTxy1Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(CTxy1Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  CTxy1Plot->SetTitle("");
  CTxy1Plot->SetXTitle("J/#psi^{1} ct_{xy} (cm)");
  CTxy1Plot->SetYTitle("Events / 0.005 cm");
  CTxy1Plot->SetMaximum(2000);
  CTxy1Plot->SetMinimum(0.1);
  CTxy1Plot->Draw();
  cctxy1->SetLogy();
  //cctxy1->SaveAs("pic/Psi1_CTxy.pdf");
  //cctxy1->Close();

  TCanvas* csig = new TCanvas("sPlotSig","sPlotSig", 600, 600);
  csig->cd();
  RooPlot* SigPlot = Psi1To2Significance->frame(20); 
  data->plotOn(SigPlot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(SigPlot,Name("all"));   
  model->plotOn(SigPlot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(SigPlot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(SigPlot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(SigPlot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  SigPlot->SetTitle("");
  SigPlot->SetYTitle("Events / 0.4");
  SigPlot->SetXTitle("J/#psi Distance Significance");
  SigPlot->Draw();
  //csig->SaveAs("pic/Psi1To2Significance.pdf");
  //csig->Close();

  // create weighted data set (signal-weighted)
  //RooDataSet * dataw_sig = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"nsig_sw");
  //  model_dY->fitTo(*data);
  //TCanvas* cdata2 = new TCanvas("sPlot2","sPlots2", 700, 500);
  //cdata2->cd();
  //RooPlot* frame2 = Psi1To2_dY->frame(20); 
  //dataw_sig->plotOn(frame2, DataError(RooAbsData::SumW2) ); 
  /*
  model_dY->fitTo(*dataw_sig, SumW2Error(kTRUE), Extended());
  model_dY->plotOn(frame2);
  model_dY->plotOn(frame2,RooFit::Components("*DPS"),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed));
  model_dY->plotOn(frame2,RooFit::Components("*SPS"),RooFit::LineColor(kGreen), RooFit::LineStyle(kDashed));
  */
  //frame2->SetTitle("DeltaY distribution for sig");
  //frame2->SetMinimum(1e-03);
  //frame2->Draw();

  //TCanvas* cdata3 = new TCanvas("sPlot3","sPlots3", 700, 500);
  //cdata3->cd();
  //RooPlot* frame3 = FourMu_Mass->frame(Bins(14),Range(6.,20.)); 
  //dataw_sig->plotOn(frame3, DataError(RooAbsData::SumW2));
  //frame3->SetTitle("FourMu_Mass distribution for sig");
  //frame3->SetMinimum(1e-03);
  //frame3->Draw();

  //fFile->Write();
  //fFile->Close();
  //delete fFile;

}
Esempio n. 8
0
double final4_D0::doFit(bool usePixel, bool isMC)
{
  gROOT->SetBatch(kTRUE);
  gROOT->SetStyle("Plain");

  //setTDRStyle();

  RooRealVar x("","",1.7,2.05);
  x.SetTitle("M(K#pi) [GeV/c^{ 2}]");

  RooRealVar mean("mean", "mean", 1.86484,1.5, 2.2);
  //RooRealVar mean("mean", "mean", 1.865116);
  RooRealVar sigma("sigma", "sigma", 0.017, 0.0002, 0.02);
  //RooRealVar sigma("sigma", "sigma", 0.015332);
  RooGaussian gauss("gauss","gaussian PDF", x, mean, sigma);

  RooRealVar alpha("alpha", "alpha", -1.0, -10.0, 10.0);
  RooRealVar power("power", "power", 3.0, 0.0, 50.0);
  RooCBShape cball("cball", "crystal ball PDF", x, mean, sigma, alpha, power);

  RooRealVar dm0("dm0", "dm0", 0.13957);
  dm0.setConstant(kTRUE);  
  RooRealVar shape("shape","shape",0.,-100.,100.);
  RooRealVar dstp1("p1","p1",0.,-500.,500.);
  RooRealVar dstp2("p2","p2",0.,-500.,500.);

  shape.setRange(0.000001,10.0);//was 0.02
  shape.setVal(0.0017);
  dstp1.setVal(0.45);
  dstp2.setVal(13.0);

  RooDstD0BG bkg("bkg","bkg",x,dm0,shape,dstp1,dstp2);

  RooRealVar c0("c0","c0",10.0,-10.0,11.0);
  RooRealVar c1("c1","c1",10.0,-10.0,11.0);
  RooRealVar c2("c2","c2",10.0,-10.0,11.0);
  RooRealVar c3("c3","c3",10.0,-10.0,11.0);
  RooRealVar c4("c4","c4",10.0,-10.0,11.0);
  RooRealVar c5("c5","c5",10.0,-10.0,11.0);
  RooRealVar c6("c6","c6",10.0,-10.0,11.0);
  RooRealVar c7("c7","c7",10.0,-10.0,11.0);
  RooRealVar c8("c8","c8",10.0,-10.0,11.0);
  RooGenericPdf cutoff("cutoff","cutoff","(@0 > @1)*(@2*abs(@0-@1) + @3*pow(abs(@0-@1),2) + @4*pow(abs(@0-@1),3) + @5*pow(abs(@0-@1),4) + @6*pow(abs(@0-@1),5) + @7*pow(abs(@0-@1),6) + @8*pow(abs(@0-@1),7))",RooArgSet(x,dm0,c0,c1,c2,c3,c4,c5,c6));

  RooRealVar poly1("poly1","poly1",0.,-5000.0,5000.0);
  RooRealVar poly2("poly2","poly2",1.0,-5000.0,5000.0);
  RooRealVar poly3("poly3","poly3",1.0,-5000.0,5000.0);
  RooRealVar poly4("poly4","poly4",1.0,-5000.0,5000.0);

  RooPolynomial polybkg("polybkg","polybkg",x,RooArgSet(poly1));


  RooRealVar cheby0("cheby0","cheby0",1.0,-500.0,500.0);
  RooRealVar cheby1("cheby1","cheby1",1.0,-500.0,500.0);
  RooRealVar cheby2("cheby2","cheby2",1.0,-500.0,500.0);
  RooRealVar cheby3("cheby3","cheby3",1.0,-500.0,500.0);

  RooChebychev chebybkg("chebybkg","chebybkg",x,RooArgSet(cheby0,cheby1,cheby2,cheby3));

  RooRealVar mean2("mean2", "mean2", 0.14548,0.144, 0.147);
  RooRealVar sigma2("sigma2", "sigma2", 0.00065, 0.0002, 0.005);
  RooGaussian gauss2("gauss2","gaussian PDF 2", x, mean2, sigma2);

  RooRealVar S("S", "Signal Yield", 1100, 0, 300000);
  //RooRealVar S("S", "Signal Yield", 0, 0, 300000);
  RooRealVar SS("SS", "Signal Yield #2", 100, 0, 100000);
  RooRealVar S2("S2", "Signal2 Yield (MC only)", 0, 0, 200);
  RooRealVar B("B", "Background Yield", 4000, 0, 30000000);
  //RooRealVar B("B", "Background Yield", 0, 0, 30000000);

  //RooAddPdf sum("sum", "gaussian plus threshold PDF",RooArgList(gauss, bkg), RooArgList(S, B));
  RooAddPdf sum("sum", "gaussian plus linear PDF", RooArgList(gauss, polybkg), RooArgList(S,B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(polybkg), RooArgList(B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(chebybkg), RooArgList(B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(cutoff), RooArgList(B));
  // RooAddPdf sum("sum", "gaussians plus threshold PDF",RooArgList(gauss, gauss2, bkg), RooArgList(S, SS, B));
  //RooAddPdf sum("sum", "crystal ball plus threshold PDF",RooArgList(cball, bkg), RooArgList(S, B));
  RooAddPdf sumMC("sumMC","double gaussian",RooArgList(gauss, gauss2), RooArgList(S, S2));

  fstream file;

  char filename[50];
  double cut=5.5;
  sprintf(filename,"D0Mass.dat");
  
  RooDataSet* data = RooDataSet::read(filename,RooArgList(x));
  RooFitResult* fit = 0;
  if (isMC == 0)
  {
    fit = sum.fitTo(*data,RooFit::Extended(),PrintLevel(1),Save(true),RooFit::NumCPU(8),RooFit::Strategy(2));
    file << "cut: " << cut << "GeV" << endl;
    file << "status: " << fit->status() << endl;
    file << "covQual: " << fit->covQual() << endl;
    file << "edm: " << fit->edm() <<  endl;
    file << "Yield: " <<  S.getVal() << " " << S.getError() << endl;
    file << "Bkg: " << B.getVal() << " " << B.getError() << endl; 
    file << "sigma: " << sigma.getVal() <<  " " << sigma.getError() << endl;
    file << "mean: " << mean.getVal() << " " << mean.getError() << endl;
    file << "shape: " << shape.getVal() << " " << shape.getError() << endl;
    file << "dstp1: " << dstp1.getVal() << " " << dstp1.getError() << endl;
    file << "dstp2: " << dstp2.getVal() << " " << dstp2.getError() << endl;
    file << endl;
  }
  else
  {
    fit = sumMC.fitTo(*data,RooFit::Extended(),PrintLevel(1),Save(true),RooFit::NumCPU(8),RooFit::Strategy(2),Range(0.142,0.15));
    file << "cut: " << cut << "GeV" << endl;
    file << "status: " << fit->status() << endl;
    file << "covQual: " << fit->covQual() << endl;
    file << "edm: " << fit->edm() <<  endl;
    file << "Yield: " <<  S.getVal() << " " << S.getError() << endl;
    file << "Yield2: " << S2.getVal() << " " << S2.getError() << endl; 
    file << "sigma: " << sigma.getVal() <<  " " << sigma.getError() << endl;
    file << "mean: " << mean.getVal() << " " << mean.getError() << endl;
    file << "sigma2: " << sigma2.getVal() << " " << sigma2.getError() << endl;
    file << "mean2: " << mean2.getVal() << " " << mean2.getError() << endl;
    file << endl; 
  }
  
  RooPlot* xFrame = x.frame(Bins(35));
  xFrame->SetTitle("D* #rightarrow D^{0}(K#pi)#pi");
  data->plotOn(xFrame);
  if(isMC == 0)
  {
    sum.plotOn(xFrame);
    sum.plotOn(xFrame,RooFit::Components(bkg),RooFit::LineStyle(kDashed));
  }
  else
  {
    sumMC.plotOn(xFrame, Range(0.139,0.159));
    //      sumMC.plotOn(xFrame,RooFit::Components(gauss2),RooFit::LineStyle(kDashed),Range(0.139,0.159));
  }
  data->plotOn(xFrame);
  file << xFrame->chiSquare() << endl;
  TCanvas c;
  TPaveText* ptext = 0;
  TPaveText* ptex = 0;
  
  if(usePixel == 0)
  {
    ptext = new TPaveText(0.47,0.33,0.9,0.43,"TRNDC");
    ptex = new TPaveText(0.47,0.18,0.9,0.28,"NDC"); 
  }
  else
  {
    if(isMC == 0)
    {
      ptext = new TPaveText(0.47,0.8,0.9,0.9,"TRNDC");
      ptex = new TPaveText(0.47,0.8,0.9,0.9,"NDC"); 
    }
    else
    {
      ptext = new TPaveText(0.47,0.78,0.9,0.88,"TRNDC");
      ptex = new TPaveText(0.47,0.63,0.9,0.73,"NDC"); 
    }
  }
  
  ptext->SetFillColor(0);
  ptext->SetTextSize(0.04);
  ptext->SetTextAlign(13);
  ptext->AddText("CMS Preliminary");
  //ptext->AddText("#sqrt{s} = 13 TeV, 40.0 pb^{-1}");
  ptext->AddText("#sqrt{s} = 13 TeV, Spring15 MinBias MC");
  xFrame->SetYTitle("Events / 10 MeV/c^{ 2}");
  xFrame->GetYaxis()->SetTitleOffset(1.3);
  xFrame->GetYaxis()->SetLabelSize(0.03);
  xFrame->GetXaxis()->SetLabelSize(0.03);
  
  ptex->SetFillColor(0);
  ptex->SetTextSize(0.033);
  ptex->SetTextAlign(13);
  char theyield[50];
  char themean[50];
  char thesigma[50];
  if(isMC == 0)
  {
    sprintf(theyield,"Yield = %u #pm %u",(unsigned)S.getVal(),(unsigned)S.getError());
    sprintf(themean,"Mean = (%.3f #pm %.3f) MeV/c^{2}",mean.getVal()*1000.0,mean.getError()*1000.0);
    sprintf(thesigma,"Sigma = (%.3f #pm %.3f) MeV/c^{2}",sigma.getVal()*1000.0,sigma.getError()*1000.0);
  }
  else
  {
    sprintf(theyield,"Yield = %u #pm %u",(unsigned)(S.getVal()+S2.getVal()),(unsigned)(sqrt(pow(S.getError(),2)+pow(S2.getError(),2))));
    sprintf(themean,"Mean = (%.3f #pm %.3f) MeV/c^{2}",mean.getVal()*1000.0,mean.getError()*1000.0);
    sprintf(thesigma,"Sigma = (%.3f #pm %.3f) MeV/c^{2}",sigma.getVal()*1000.0,sigma.getError()*1000.0);
  } 
  ptex->AddText(theyield);
  ptex->AddText(themean);
  ptex->AddText(thesigma);
  
  xFrame->Draw();
  ptext->Draw("same");
  ptex->Draw("same");
  
  c.SaveAs("D0Mass.png");
  c.SaveAs("D0Mass.pdf");

  S.Print();

  // compute integrals
  double sfactor;
  if(isMC)
    sfactor = 0.0;
  else
  {
    double sigbkg, bkg1, bkg2;
    double base = 0.145421;
    
    x.setRange("signal",base-0.0013,base+0.0013);
    x.setRange("background1",base-0.0051,base-0.0025);
    x.setRange("background2",base+0.0025,base+0.0051);    

    RooAbsReal* iSB = B.createIntegral(x,Range("signal"));
    RooAbsReal* iB1 = B.createIntegral(x,Range("background1"));
    RooAbsReal* iB2 = B.createIntegral(x,Range("background2"));

    sigbkg = iSB->getVal();
    bkg1 = iB1->getVal();
    bkg2 = iB2->getVal();
 
    sfactor = -1.0 * (sigbkg / (bkg1 + bkg2));
  }

  return sfactor;
}