Example #1
0
//2d reweighting of rho and its sigma
void reweight_rhosigma(TH1F* weight_rho, TH1F* weight_rhoo,TH2F*weight_rhon,TH2F*weight_rho2o,TH2F* weight_rhonr, TH2F* weight_rho2,TH2F*weight_sigman,TH2F*weight_sigma2o,TH2F* weight_sigmanr, TH2F* weight_sigma2,RooDataSet **dset, RooDataSet *dsetdestination, bool deleteold){
  if (!(*dset)) return;
//  TH2F *hnum = new TH2F("hnum","hnum",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
//  TH2F *hden = new TH2F("hden","hden",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
  TH2F *hnum = new TH2F("hnum","hnum",100,0,100,20,0,20);
  TH2F *hden = new TH2F("hden","hden",100,0,100,20,0,20);
  hnum->Sumw2();
  hden->Sumw2();
  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue("roorho")),fabs((*dset)->get(i)->getRealValue("roosigma")),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue("roorho")),fabs(dsetdestination->get(i)->getRealValue("roosigma")),dsetdestination->store()->weight(i));
  }

  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
//data/MC
  hnum->Divide(hden);
  TH2F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_rhosigmarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float rho = args.getRealValue("roorho");
    float sigma = args.getRealValue("roosigma");
    float neww = oldw*h->GetBinContent(h->FindBin(rho,sigma));
	if(debug){
		weight_rho->Fill(neww);
		weight_rhoo->Fill(oldw);
		weight_rho2o->Fill(h->GetXaxis()->FindBin(rho),oldw);	
		weight_rhon->Fill(h->GetXaxis()->FindBin(rho),neww);	
		if(oldw!=0)weight_rhonr->Fill(h->GetXaxis()->FindBin(rho),oldw/neww);
		else {weight_rhonr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_rho2->Fill(rho,oldw/neww);
		weight_sigma2o->Fill(h->GetYaxis()->FindBin(sigma),oldw);	
		weight_sigman->Fill(h->GetYaxis()->FindBin(sigma),neww);	
		if(oldw!=0)weight_sigmanr->Fill(h->GetYaxis()->FindBin(sigma),oldw/neww);
		else {weight_sigmanr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_sigma2->Fill(sigma,oldw/neww);
	}
		newdset->add(args,neww);
	  }
	  newdset->SetName((*dset)->GetName());
	  newdset->SetTitle((*dset)->GetTitle());
	  delete hnum; delete hden;
	  RooDataSet *old_dset = *dset;
	  *dset=newdset;
	  std::cout << "RhoSigma2D rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;
	  if (deleteold) delete old_dset;
	};
Example #2
0
TCanvas *PlotDataMC2D(TChain *data, TChain *mc, TString branchname, TString binning, 
		      TCut selection, 
		      TString dataLabel, TString mcLabel, 
		      TString xLabel, TString yLabel, 
		      int type=2, TString opt="colz", bool usePU=true, bool smear=false, bool scale=false){
  //type == 0: data only
  //type == 1: MC only
  //type == 2: data/MC
   
  TCanvas *c = new TCanvas("c","");
  TString weightVar;
  if(branchname.Contains("map")){
    weightVar=branchname.ReplaceAll("_map","").ReplaceAll("map","");
    branchname="seedXSCEle:seedYSCEle";
    binning="(361,-0.5,360.5,171,-85.5,85.5)";
    yLabel="iEta";
    xLabel="iPhi";
    c->SetGridx();
  }
  if(weightVar!="") selection+="*"+weightVar;
  data->Draw(branchname+">>data_hist"+binning, selection,opt);
  if(usePU)  mc->Draw(branchname+">>mc_hist"+binning, selection *"puWeight",opt);
  else  mc->Draw(branchname+">>mc_hist"+binning, selection,opt);

  c->Clear();
  
  TH2F *d = (TH2F *) gROOT->FindObject("data_hist");
  TH2F *s = (TH2F *) gROOT->FindObject("mc_hist");

  if(type==0) d->Draw(opt);
  else if(type==1) s->Draw(opt);
  else if(type==3){
    s->Scale(d->Integral()/s->Integral());
    d->Divide(s);
    d->Draw(opt);
  }

  d->GetXaxis()->SetTitle(xLabel);
  s->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  s->GetYaxis()->SetTitle(yLabel);
  c->SetRightMargin(0.2);
  return c;
  
}
void makeValidationPlots(TTree* tree, sel_t type,bool isMC) {

  SelectionStrings strings;

  TString tag="";

  TString lowString="",midString="",highString="";

  switch(type) {
  case kReal:
    tag = "_realselection";
    break;
  case kShift:
    tag = "_side";
    break;
  case kSingleIso:
    tag = "_singleIso";
    break;
  }
  if(isMC) {
    tag+="__DiPhotonJets";
  }
  Double_t Red[] = {0.00, 0.70, 0.90, 1.00, 1.00, 1.00, 1.00};
  Double_t Green[] ={0.00, 0.70, 0.90, 1.00, 0.90, 0.70, 0.00};
  Double_t Blue[] = {1.00, 1.00, 1.00, 1.00, 0.90, 0.70, 0.00};
  Double_t Length[] =  {0.00, 0.20, 0.35, 0.50, 0.65, 0.8, 1.00};

  TCanvas cv;

  std::vector<TH2F*> nSigs;
  std::vector<TH2F*> nSigs_gauss;

  cv.SetLogx();
  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    switch(type) {
    case kReal:
      lowString = strings.baseSelection+" && mgg>103 && mgg<120";
      midString = strings.baseSelection+" && "+strings.mggSigRegion[iBox];
      highString = strings.baseSelection+" && mgg>131 && mgg<160";
      break;
    case kShift:
      lowString = strings.baseSelection+" && mgg>130 && mgg<140";
      midString = strings.baseSelection+" && mgg>140 && mgg<150";
      highString = strings.baseSelection+" && mgg>150 && mgg<160";
      break;
    case kSingleIso:
      lowString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>103 && mgg<120";
      midString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && "+strings.mggSigRegion[iBox];
      highString = TString("(pho1_pt>40 && pho2_pt>25 && abs(pho1_eta)<1.48 && abs(pho2_eta)<1.48 && (pho1_pass_iso || pho2_pass_iso) && !(pho1_pass_iso && pho2_pass_iso))")+" && mgg>131 && mgg<160";      
      break;
    }


    TH2F* low = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"low");
    TH2F* mid = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"mid");
    TH2F* high = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"high");
  
    TH2F* nsig = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_"+boxName);
    TH2F* nsig_gauss = SigRegionBinning::makeHistogram(static_cast<SigRegionBinning::BinningRegion>(iBox),"nsig_gauss_"+boxName);

    low->SetMinimum(0.1);
    mid->SetMinimum(0.1);
    high->SetMinimum(0.1);

    tree->Project("low","Rsq:MR",lowString+" && "+strings.boxDefs[iBox]);
    tree->Project("mid","Rsq:MR",midString+" && "+strings.boxDefs[iBox]);
    tree->Project("high","Rsq:MR",highString+" && "+strings.boxDefs[iBox]);

    //SigRegionBinning::formatSigRegionPlot(low);
    //SigRegionBinning::formatSigRegionPlot(mid);
    //SigRegionBinning::formatSigRegionPlot(high);

    //get the difference in the prediction
    TH2F* low_norm = (TH2F*)low->Clone("low_norm");
    TH2F* high_norm = (TH2F*)high->Clone("high_norm");

    low_norm->Scale(1./low_norm->Integral());
    high_norm->Scale(1./high_norm->Integral());

    TH2F* pred_diff = (TH2F*)high_norm->Clone("pred_diff");
    pred_diff->Add(low_norm,-1);

    TH2F* norm_av = (TH2F*)low_norm->Clone("norm_av");
    norm_av->Add(high_norm);
    norm_av->Scale(0.5);

    TH2F* pred_per_diff = (TH2F*)pred_diff->Clone("pred_per_diff");
    pred_per_diff->Divide(norm_av);
    cv.SetLogx(1);
    cv.SetLogy(0);
    pred_per_diff->Draw("COLZ TEXT");
    cv.SaveAs("RsqMR_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);

    TH1D* low_1D = SigRegionBinning::make1DProj(low);
    TH1D* high_1D = SigRegionBinning::make1DProj(high);
    
    pred_per_diff->SetYTitle("high - low / (high+low/2)");
    TH1D* pred_per_diff_1D = SigRegionBinning::make1DProj(pred_per_diff);
    cv.SetLogx(0);
    cv.SetLogy(0);
    pred_per_diff_1D->Draw();
    cv.SaveAs("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".png");
    cv.SetLogx(1);
    cv.SetLogy(0);
    
    TFile out("RsqMR_1D_high_minus_low_div_av_"+boxName+tag+".root","RECREATE");
    low->Write();
    high->Write();
    low_1D->Write();
    high_1D->Write();
    pred_per_diff_1D->Write();
    pred_per_diff->Write();
    out.Close();



    TH2F* sideband_tot = (TH2F*)low->Clone("sideband_tot");
    sideband_tot->Add(high);


    sideband_tot->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_low_plus_high_"+boxName+tag+".png");
    cv.SetLogz(0);

    float sf = mid->Integral()/sideband_tot->Integral();
    std::cout << "sf: " << sf << std::endl;
    TH2F* sideband_pred = (TH2F*)sideband_tot->Clone("sideband_pred");

    sideband_pred->Scale(sf);

    sideband_pred->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_sideband_pred_"+boxName+tag+".png");
    cv.SetLogz(0);

    mid->Draw("COLZ TEXT");
    cv.SetLogz();
    cv.SaveAs("RsqMR_mid_"+boxName+tag+".png");
    cv.SetLogz(0);

    TH1D* pred_1D = SigRegionBinning::make1DProj(sideband_pred,true,sf);
    TH1D* mid_1D  = SigRegionBinning::make1DProj(mid);
    cv.SetLogx(0);
    cv.SetLogy();
    mid_1D->SetMarkerStyle(20);
    mid_1D->SetMarkerColor(kBlack);
    mid_1D->SetMarkerSize(1.4);

    pred_1D->SetFillColor(kRed);
    pred_1D->SetFillStyle(3001);
    pred_1D->SetLineColor(kRed);
    pred_1D->SetLineWidth(2);
    pred_1D->SetMarkerSize(0);
    pred_1D->Draw("L E2");
    pred_1D->Draw("LSAME");
    mid_1D->Draw("PSAME");
    cv.SaveAs("RsqMR_1D_obs_sideband_pred_"+boxName+tag+".png");    
    cv.SetLogx(1);
    cv.SetLogy(0);


    TH2F* perdiff = (TH2F*)mid->Clone("perdiff");
    perdiff->Add(sideband_pred,-1);
    perdiff->Divide(perdiff);
    perdiff->Draw("COLZ TEXT");

    cv.SaveAs("RsqMR_percentDiff_"+boxName+tag+".png");
    

    for(int iXbin=1; iXbin<=sideband_pred->GetNbinsX(); iXbin++) {
      for(int iYbin=1; iYbin<=sideband_pred->GetNbinsY(); iYbin++) {
	float obs = mid->GetBinContent(iXbin,iYbin);
	float exp = sideband_pred->GetBinContent(iXbin,iYbin);
	float err = TMath::Sqrt(sideband_tot->GetBinContent(iXbin,iYbin))*sf;
	float ns = fabs(TMath::NormQuantile(SigRegionBinning::pValue(obs,exp,err/exp)/2));
	if(obs<exp) ns*=-1;

	nsig->SetBinContent(iXbin,iYbin,ns);
	std::cout << "\t" << iXbin << "  " << iYbin << "  " << nsig->GetBinContent(iXbin,iYbin) << std::endl;

	float gauss_err = TMath::Sqrt(TMath::Power(err,2)+exp);
	if(gauss_err==0) gauss_err=1;
	nsig_gauss->SetBinContent(iXbin,iYbin,(obs-exp)/gauss_err);

      }
    }
    
    SigRegionBinning::formatSigRegionPlot(nsig); 
    SigRegionBinning::formatSigRegionPlot(nsig_gauss); 
    //cv.SetLogx();

    nSigs.push_back(nsig);
    nSigs_gauss.push_back(nsig_gauss);
    

    delete low;
    delete mid;
    delete high;
    delete sideband_tot;
    delete sideband_pred;

  }

  for(int iBox=0; iBox<SigRegionBinning::nBoxes; iBox++) {
    TString boxName = SigRegionBinning::getRegionName(static_cast<SigRegionBinning::BinningRegion>(iBox));
    TColor::CreateGradientColorTable(7,Length,Red,Green,Blue,999);
    TH2F* nsig = nSigs.at(iBox);

    nsig->SetMaximum(5.1);
    nsig->SetMinimum(-5.1);
    nsig->SetContour(999);


    nsig->Draw("COLZ TEXT0");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMA_"+boxName+tag+".png");
    
    TH2F* nsig_gauss = nSigs_gauss.at(iBox);
    nsig_gauss->SetMaximum(5.1);
    nsig_gauss->SetMinimum(-5.1);
    nsig_gauss->SetContour(999);

    nsig_gauss->Draw("COLZ");
    cv.SaveAs("RsqMR_low_plus_high_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    

    TH1D* nsig_gauss_1D = SigRegionBinning::make1DProj(nsig_gauss);

    nsig_gauss_1D->SetLineColor(kBlack);
    nsig_gauss_1D->SetLineWidth(1.5);
    nsig_gauss_1D->SetMinimum(-5.1);
    nsig_gauss_1D->SetMaximum(5.1);
    nsig_gauss_1D->SetYTitle("Number of Sigma");
    cv.SetLogx(0);
    cv.SetLogy(0);
    nsig_gauss_1D->Draw();
    cv.SaveAs("RsqMR_low_plus_high_1D_RAWSUM_NSIGMAGAUSS_"+boxName+tag+".png");
    cv.SetLogx(1);
  }
}
void combineBins(int mass, double scale_factor = 1.0){ //mass = mass of tprime quark

  //define some parameters
  //char fname[100]={"data/mujets_821/tprime_mujets_2D_821ipb.root"}; //input file name
  char fname[100]={"data/ejets_3560/tprime_ejets_2D_3560ipb.root"}; //input file name
  char oname[256]; //output file name
  char sname[100]; //name of signal histogram
  //sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_15jul2011test.root",mass);
  sprintf(oname,"data/mujets_821/tprime_%i_mujets_2D_821ipb_merged_test.root",mass);
  sprintf(sname,"TPrime%i_HtvsMfit",mass);
  char bname[20][100]={ //array of data and background histograms
    "Data_HtvsMfit", //data histogram must be first in this list
    "TTjets_HtvsMfit",
    "Ewk_HtvsMfit",
    "TPrime%i_HtvsMfit_JESup",
    "TPrime%i_HtvsMfit_JESdown",
    "TTjets_HtvsMfit_JESup",
    "TTjets_HtvsMfit_JESdown",
    "Ewk_HtvsMfit_JESup",
    "Ewk_HtvsMfit_JESdown"
  };
  
  int nb=9; //number of histograms in list
  int n_skip=3; // starting with this index, do not consider for background normalization
  float femax=0.20; //max fractional error in each bin of background histogram

  TFile *f = TFile::Open(fname);
  if (f==NULL) {
    printf("Cannot open file '%s'\n",fname);
    return;
  }

  TH2F* hs; f->GetObject(sname,hs); 
  // Gena: scale signal template to proper cross section
  hs->Scale(scale_factor);
  if (hs==NULL) {
    printf("Cannot find histogram '%s' in '%s'\n",sname,fname);
    return;
  }

  //figure out the binning
  int nx = hs->GetNbinsX()+2;
  int ny = hs->GetNbinsY()+2;

  // cross check printout
  std::cout << "2D hist name: " << hs->GetName() << std::endl;
  std::cout << "Integral with overflow: " << hs->Integral(0,nx-1,0,ny-1) << std::endl;
  std::cout << "Integral no overflow: " << hs->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;

  TH2F *hb = (TH2F*)hs->Clone(); 
  hb->SetName("hb");
  hb->Reset();
  TH2F *hX[20];
  for (int i=0;i<nb;i++){
    std::string sBName(bname[i]);
    // GENA: get names for signal JES histos
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){

      sprintf(bname[i],sBName.c_str(),mass);
      std::cout << bname[i] << std::endl;
    }

    f->GetObject(bname[i],hX[i]); 

    // GENA: scale JES signal templates to proper cross section
    if (sBName.find("TPrime")!=std::string::npos ||
	sBName.find("Tprime")!=std::string::npos ||
	sBName.find("tprime")!=std::string::npos){
      hX[i]->Scale(scale_factor);      
    }
    if (hX[i]==NULL) {
      printf("Cannot find histogram '%s' in '%s'\n",bname[i],fname);
      return;
    }
    //hX[i]->Print("base");
    std::cout << "2D hist name: " << hX[i]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << hX[i]->Integral(0,nx-1,0,ny-1) << std::endl;
    std::cout << "Integral no overflow: " << hX[i]->Integral(1,nx-2,1,ny-2) << std::endl << std::endl;
    //sum all background histograms into hb; do not add the data histogram
    if (i>0 && i<n_skip) hb->Add(hX[i]); 
  }

  //figure out the binning
  //int nx = hs->GetNbinsX()+2;
  //int ny = hs->GetNbinsY()+2;
  int nbin=nx*ny;
  std::cout << "number of bins: x="<<nx<<", y="<<ny<<std::endl;
  
  //book some 1d histograms with the same number of bins for diagnostics
  TH1F *h1sb = new TH1F("h1sb","h1sb",nbin,0,nbin);
  TH1F *h1s = new TH1F("h1s","h1s",nbin,0,nbin);
  TH1F *h1b = new TH1F("h1b","h1b",nbin,0,nbin);
  // GENA: vector to create 2D->1D bin map
  std::vector<std::vector<int> > vMap(nbin);

  float xs,xb;
  //xsb holds the s/b values for each bin
  //xx are the histogram contents 
  //(0=signal, 1=total background, 2=data, 3...nb-1=individual backgrounds) GENA: nb+1 ?
  float xsb[30000],xx[30000][20],xe[30000][20];
  int ibin; 
  double _sum = 0.0;
  for (int i=0;i<nx;i++){
    for (int j=0;j<ny;j++){

      ibin=hs->GetBin(i,j);

      // GENA: Will fill each bin with its original index
      vMap[ibin].push_back(ibin);

      xs=hs->GetBinContent(ibin);
      xb=hb->GetBinContent(ibin);
      //compute signal/background
      if (xb>0) {
	xsb[ibin]=xs/xb;
      }else{
	if (xs>0){
	  xsb[ibin]=999;
	}else{
	  xsb[ibin]=0;
	}
      }
      xx[ibin][0]=xs;
      xe[ibin][0]=hs->GetBinError(ibin);
      xx[ibin][1]=xb;
      xe[ibin][1]=hb->GetBinError(ibin);
      for (int k=0;k<nb;k++){
	xx[ibin][k+2]=hX[k]->GetBinContent(ibin);
	xe[ibin][k+2]=hX[k]->GetBinError(ibin);
      }
      if (xb>0) h1sb->SetBinContent(ibin,xs/xb);
      h1s->SetBinContent(ibin,xx[ibin][0]);
      h1s->SetBinError(ibin,xe[ibin][0]);
      h1b->SetBinContent(ibin,xx[ibin][1]);
      h1b->SetBinError(ibin,xe[ibin][1]);
      
      _sum += xx[ibin][0];
    }
  }

  std::cout << "SUM: " << _sum << std::endl;

  //sort all histogram bins in decreasing s/b
  int nswap=1;
  float xtmp;

  // GENA: for bin map
  int ibin_tmp;

  while (nswap>0) {
    nswap=0;
    for (int i=0;i<nbin-1;i++) {
      if (xsb[i]<xsb[i+1]){
	xtmp=xsb[i];
	xsb[i]=xsb[i+1];
	xsb[i+1]=xtmp;

	// GENA: for bin map
	ibin_tmp = vMap[i][0];
	vMap[i][0] = vMap[i+1][0];
	vMap[i+1][0] = ibin_tmp;

	for (int j=0;j<nb+2;j++){
	  xtmp=xx[i][j];
	  xx[i][j]=xx[i+1][j];
	  xx[i+1][j]=xtmp;

	  xtmp=xe[i][j];
	  xe[i][j]=xe[i+1][j];
	  xe[i+1][j]=xtmp;
	}
	nswap=nswap+1;
      }
    }
  }

  //these histograms have the bins ordered in decrerasing s/b for diagnostics
  TH1F *h1sb1 = new TH1F("h1sb1","h1sb1",nbin,0,nbin);
  TH1F *h1fe1 = new TH1F("h1fe1","h1fe1",nbin,0,nbin);
  TH1F *h1s1 = new TH1F("h1s1","h1s1",nbin,0,nbin);
  TH1F *h1b1 = new TH1F("h1b1","h1b1",nbin,0,nbin);
  for (int i=0;i<nbin;i++){
    h1sb1->SetBinContent(i+1,xsb[i]);
    if (xx[i][1]>0) h1fe1->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s1->SetBinContent(i+1,xx[i][0]);
    h1s1->SetBinError(i+1,xe[i][0]);
    h1b1->SetBinContent(i+1,xx[i][1]);
    h1b1->SetBinError(i+1,xe[i][1]);
  }


  //combine bins starting with the highest s/b until the fractional error in
  //the total backround in every bin is smaller than femax
  int ncomb=1;
  //float xtmp;
  float fe=0;
  while (ncomb>0) {
    ncomb=0;
    for (int i=0;i<nbin-1;i++){

      if (xx[i][1]>0){
	fe=xe[i][1]/xx[i][1]; //fractional error in background
      }else{
	fe=1;
      }
      if (fe>femax){

	// GENA: write down bin
	for (std::vector<int>::const_iterator vi=vMap[i+1].begin();
	     vi != vMap[i+1].end(); ++vi){
	  vMap[i].push_back(*vi);
	}
	//move all successive bins up
	vMap.erase(vMap.begin()+i+1);

	for (int k=0;k<nb+2;k++){ //add the next bin
	  xx[i][k]=xx[i][k]+xx[i+1][k];
	  xe[i][k]=sqrt(xe[i][k]*xe[i][k]+xe[i+1][k]*xe[i+1][k]);
	  for (int j=i+1;j<nbin-1;j++){ //move all successive bins up
	    xx[j][k]=xx[j+1][k];
	    xe[j][k]=xe[j+1][k];
	  }
	}
	ncomb++;
	nbin=nbin-1; //decrease the total number of bins

      }
    }
  }


  //GENA: open the map file
  std::ofstream mapFile;
  mapFile.open("bin.map");
  int bin_count = 0;
  for (std::vector<std::vector<int> >::const_iterator i=vMap.begin();
       i != vMap.end(); ++i){

    mapFile << " " << i-vMap.begin()+1 << ":";

    for(std::vector<int>::const_iterator j=i->begin();
	j != i->end(); ++j){
      mapFile << " " << *j;
      ++bin_count;
    }

    mapFile << std::endl;

  }
  //GENA: close the map file
  mapFile.close();

  //these are the output histograms
  TFile *f2 = TFile::Open(oname,"recreate");
  TH1F *h1feb2 = new TH1F("h1fe2","h1fe2",nbin,0,nbin);
  TH1F *h1s2 = new TH1F(sname,sname,nbin,0,nbin);
  TH1F *h1b2 = new TH1F("h1b2","h1b2",nbin,0,nbin);
  TH1F *h1X2[20];
  for (int i=0;i<nb;i++){
    h1X2[i] = new TH1F(bname[i],bname[i],nbin,0,nbin);
  }
  for (int i=0;i<nbin;i++){
    h1feb2->SetBinContent(i+1,xe[i][1]/xx[i][1]);
    h1s2->SetBinContent(i+1,xx[i][0]);
    h1s2->SetBinError(i+1,xe[i][0]);
    h1b2->SetBinContent(i+1,xx[i][1]);
    h1b2->SetBinError(i+1,xe[i][1]);
    for (int j=0;j<nb;j++){
      h1X2[j]->SetBinContent(i+1,xx[i][j+2]);
      h1X2[j]->SetBinError(i+1,xe[i][j+2]);
    }
  }
  
  std::cout << "Merged 1D hist name: " << h1s2->GetName() << std::endl;
  std::cout << "Integral with overflow: " << h1s2->Integral(0,nbin+1) << std::endl;
  std::cout << "Integral no overflow: " << h1s2->Integral(1,nbin) << std::endl << std::endl;
  h1s2->Write();
  for (int j=0;j<nb;j++){
    std::cout << "Merged 1D hist name: " << h1X2[j]->GetName() << std::endl;
    std::cout << "Integral with overflow: " << h1X2[j]->Integral(0,nbin+1) << std::endl;
    std::cout << "Integral no overflow: " << h1X2[j]->Integral(1,nbin) << std::endl << std::endl;
    h1X2[j]->Write();
  }
  
  h1s2->Print("base");

  f2->Close();
  f->Close();

  std::cout << "map size: " << vMap.size() << " combined bins" << std::endl;
  std::cout << "total bins merged: " << bin_count << std::endl;
}
Example #5
0
int cleanData(TString rawdatafiles="files.txt",TString keyfilename = "keys.txt", TString cleandir="./clean/")
{

   TString key = "clean";

   const int nreqmod = 0;
   TString reqmod[nreqmod];
   
   bool pass;
   DmtpcKeys k(keyfilename,rawdatafiles,key,cleandir,nreqmod,reqmod,pass);
   if(!pass) return -1;

   TCanvas* c = new TCanvas("c","c",0,0,1000,1000);
   c->Divide(2,2);
   c->cd(1);

   TFile* routfile;
   TTree* cleantree;
   TClonesArray* cleanimage;
   TH2F* tempimg;

   for(int f=0; f<k.getNFiles(); f++)
   {
      cout << k.getFile(f) << endl;
      
      //Create DMPTC Database and draw out tree
      DmtpcDataset d;
      d.openRootFile(k.getRootDirName()+k.getFile(f));
      TTree* rawtree = d.tree();

      //Add friends
      k.addFriends(rawtree,f);

      //name outputfile, open up outputfile
      TString routfilename = k.getFile(f);
      routfilename.ReplaceAll(".root",key+".root");
      routfile = new TFile(cleandir+routfilename,"CREATE");
      
      if(routfile->IsOpen())
      {
	 routfile->cd();
      }
      else
      {
	 cout << "Output file already exists; Aborting!" << endl;
	 return -1;
      }

      d.getEvent(0);
      const int ncamera = d.event()->ccdData()->GetEntries();
      const int nbinsx = d.event()->ccdData(0)->GetNbinsX();
      const int nbinsy = d.event()->ccdData(0)->GetNbinsY();

      //create tree to store clean images and sparking data
      cleantree = new TTree(key,"Cleaned Images");
      cleanimage = new TClonesArray("TH2F",ncamera);
      Bool_t spark[ncamera];
      double integral[ncamera];

      //Add branches
      cleantree->Branch("cleanimage","TClonesArray",&cleanimage,128000,0);
      cleantree->Branch("spark",&spark,"spark[2]/O");
      cleantree->Branch("integral",&integral,"integral[2]/D");
      gROOT->cd();

      //open up file for bias frame saving
      TString biasoutfilename = routfilename;
      biasoutfilename.ReplaceAll(key+".root","bias.root");

      TFile* biasoutfile = new TFile(cleandir+biasoutfilename,"RECREATE");

      TH2F* biasframe = d.event()->ccdData(0);
      TTree* biastree = new TTree("bias","Bias Information");

      biastree->Branch("biasframe","TH2F",&biasframe,128000,0);

      gROOT->cd();

      double threshhold[ncamera];
      int nframes[ncamera];
      for(int i=0; i<ncamera; i++){threshhold[i]=200; nframes[i]=0;}

      TH2F* secondarybias[ncamera];

      //find the spark cut
      const int nev = rawtree->GetEntries();
      double countthresh[nev];
      double sparkcut[ncamera];


      for(int j=0; j<ncamera; j++)
      {
	 cout << j << ":" << endl;
	 countthresh[j] =d.getBiasFrame(j+1)->Integral()/(65536);
	 sparkcut[j] =  MaxCamImageTools::countPixelsAboveThreshold(d.getBiasFrame(j+1),countthresh[j])-2000;

	 cout << "count: " << countthresh[j] << "\t cut: " << sparkcut[j] << endl;

	 
      }
      
      //Grab every 100th image to make bias frame; must check for sparks
      for(int i=0; i<nev; i=i+100)
      {
	 cout << i << endl;
	 d.getEvent(i);
	 for(int u=0; u<ncamera; u++)
	 {
	    tempimg = (TH2F*)d.event()->ccdData(u)->Clone("backimg");
//	    MaxCamImageTools::killLonePixels2(tempimg,1300);
	    int nabove = MaxCamImageTools::countPixelsAboveThreshold(tempimg,countthresh[u]);
	    if(nabove<sparkcut[u])
	    {
	       if(nframes[u]==0) 
	       {
		  secondarybias[u]=(TH2F*)tempimg->Clone("average");
	       }
	       else
	       {
		  secondarybias[u]->Add(tempimg,1);
	       }
	       nframes[u]++;
	    }
	    
	 }
	 
      }

      gROOT->Delete("backimg;*");

      for(int i=0; i<ncamera; i++)
      {
	 secondarybias[i]->Scale(1/double(nframes[i]));
 	 biasframe = secondarybias[i];
 	 biasoutfile->cd();
 	 biastree->Fill();
 	 gROOT->cd();
	 
      }

      cout << "All preclean activities done" << endl;
      c->Update();

      //cleaning should go here
      for(int i = 0; i<nev; i++)
//      for(int i = 0; i<100; i++) //For testing
      {
	 cout << i << endl;
	 d.getEvent(i);
	 for(int u=0; u<ncamera; u++)
	 {
//	    c->cd(u+1);

	    
	    //create cloned image
	    tempimg = (TH2F*)d.event()->ccdData(u);

	    //check for sparking
	    int nabove = MaxCamImageTools::countPixelsAboveThreshold(tempimg,countthresh[u]);

	    if(nabove < sparkcut[u])
	       spark[u]=0;
	    else
	       spark[u]=1;

	    if(spark[u] == 1) cout << "SPARK!" << endl;


	    //subtract of temp bias
	    tempimg->Add(secondarybias[u],-1);
	    //kill lone pixels
	    MaxCamImageTools::killLonePixels2(tempimg,threshhold[u]);
   
	    
	    //additionally correct
	    double perpx = tempimg->Integral()/(nbinsx*nbinsy);

	    if(spark[u]==0)
	       MaxCamImageTools::subtractPedestal(tempimg,perpx);

	    integral[u] = tempimg->Integral();
	    
	    //add to TClonesArray
	    new((*cleanimage)[u]) TH2F(*tempimg);
	    


	 }
	 routfile->cd();
	 cleantree->Fill();
	 gROOT->cd();

      }

      routfile->cd();
      cleantree->Write();

      delete cleantree;

      routfile->Close();

      biasoutfile->cd();
      biastree->Write();
      
      delete biastree;
      
      biasoutfile->Close();

   }

      
   return 0;
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################
 
     string signalCategory = "T2bw-025";

     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

  // ##########################
  // ##   Create Variables   ##
  // ##########################

     screwdriver.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,         &(myEvent.METoverSqrtHT),       "");
     screwdriver.AddVariable("MET",            "MET",                     "GeV",    15,50,500,       &(myEvent.MET),                 "logY=true");
     screwdriver.AddVariable("MT",             "MT",                      "GeV",    20,0,400,        &(myEvent.MT),                  "logY=true");
     screwdriver.AddVariable("leadingBPt",     "p_{T}(leading b jet)",    "GeV",    20,0,200,        &(myEvent.leadingBPt),          "logY=true");
     
     screwdriver.AddVariable("mStop",          "m_{#tilde{t}}",           "GeV",    28,112.5,812.5,  &(myEvent.mStop),               "");
     screwdriver.AddVariable("mNeutralino",    "m_{#chi^{0}}",            "GeV",    16,-12.5,387.5,  &(myEvent.mNeutralino),         "noOverflowInLastBin");
     
     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

     screwdriver.AddProcessClass("1ltop",                        "1l top", "background",kRed-7);
         #ifdef USING_TTBAR_POWHEG
             screwdriver.AddDataset("ttbar_powheg",              "1ltop",  0, 0);
         #endif
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_1l",         "1ltop",  0, 0);
         #endif
         screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
         #endif

     screwdriver.AddProcessClass("W+jets",         "W+jets",                    "background", kOrange-2);
             screwdriver.AddDataset("W+jets",      "W+jets", 0, 0);
                                                   
     screwdriver.AddProcessClass("rare",           "rare",                      "background", kMagenta-5);
             screwdriver.AddDataset("rare",        "rare", 0, 0);
                                                   
     screwdriver.AddProcessClass(signalCategory,    signalCategory,             "signal",     kViolet-1);
             screwdriver.AddDataset(signalCategory, signalCategory,   0, 0);

     screwdriver.AddProcessClass("signal_250_100",  signalCategory+" (250/100)",      "signal",COLORPLOT_BLUE   );
     screwdriver.AddProcessClass("signal_450_100",  signalCategory+" (450/100)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_400_175",  signalCategory+" (400/175)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_650_100",  signalCategory+" (650/100)",      "signal",COLORPLOT_GREEN  );

  // ##########################
  // ##    Create Regions    ##
  // ##########################

     screwdriver.AddRegion("presel",             "Preselection",                          &goesInPreselectionMTtail);
/*
     screwdriver.AddRegion("veryOffShell_loose", "Cut-and-count;Very off-shell (loose)",  &Selector_veryOffShell_loose);
     screwdriver.AddRegion("offShell_loose",     "Cut-and-count;Off-shell (loose)",       &Selector_offShell_loose );
     screwdriver.AddRegion("lowDeltaM_tight",    "Cut-and-count;Low #DeltaM (tight)",     &Selector_lowDeltaM_tight );
     screwdriver.AddRegion("highDeltaM",         "Cut-and-count;High #DeltaM",            &Selector_highDeltaM );
*/
     
     screwdriver.AddRegion("offshell",           "Cut-and-count;Off-shell",              &Selector_offShell);
     screwdriver.AddRegion("lowMasses",          "Cut-and-count;Low masses",             &Selector_lowMasses);
     screwdriver.AddRegion("highMasses",         "Cut-and-count;High masses",            &Selector_highMasses);
     

  // ##########################
  // ##   Create Channels    ##
  // ##########################
      
     screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     screwdriver.SetLumi(20000);

     // Create histograms
     screwdriver.Create1DHistos();
     screwdriver.Add2DHisto("mStop","mNeutralino");

     screwdriver.SetGlobalBoolOption  ("1DSuperimposed",   "includeSignal",                   true   );

     screwdriver.SetGlobalStringOption("1DStack",          "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("1DStack",          "factorSignal",                    1.0    );

     screwdriver.SetGlobalStringOption("DataMCComparison", "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison", "factorSignal",                    1.0    );

     // Schedule plots
     screwdriver.SchedulePlots("1DSuperimposed");
     screwdriver.SchedulePlots("1DStack");
     screwdriver.SchedulePlots("2D");
     screwdriver.SchedulePlots("2DSuperimposed");

     // Config plots

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 20 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset); 
     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple"); 

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     sampleName = currentDataset;
     sampleType = screwdriver.GetProcessClassType(currentProcessClass);
    
     if (currentDataset == signalCategory)
     {
         theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
         theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      //for (int i = 0 ; i < min(200000, (int) theTree->GetEntries()); i++)
      {
          if (i % (theTree->GetEntries() / 50) == 0) 
              printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if ((currentDataset == "ttbar_powheg") && (myEvent.numberOfGenLepton == 2)) 
              currentProcessClass_ = "ttbar_2l";

          screwdriver.AutoFillProcessClass(currentProcessClass_,getWeight());

          if ((myEvent.mStop == 250) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_250_100",getWeight());
          if ((myEvent.mStop == 450) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_450_100",getWeight());
          if ((myEvent.mStop == 400) && (myEvent.mNeutralino == 175))
              screwdriver.AutoFillProcessClass("signal_400_175",getWeight());
          if ((myEvent.mStop == 650) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_650_100",getWeight());
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################
 
  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("../plots/cutAndCount_performances/"+signalCategory+"/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
  
  printBoxedMessage("Now computing misc tests ... ");
  
  /*
  vector<string> cutAndCountRegions =
  {
      "veryOffShell_loose",
      "offShell_loose",    
      "lowDeltaM_tight",   
      "highDeltaM"     
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2,
      0.4
  };
  */
  
  vector<string> cutAndCountRegions =
  {
    "presel",
    "offshell",
    "lowMasses",
    "highMasses"
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2
  };
  
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").Print();
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").PrintLatex();

  // ##########################
  // ##   Compute FOM maps   ##
  // ##########################

  vector<TH2F*> signalMaps;
  vector<TH2F*> FOMdiscoveryMaps;
  vector<TH2F*> FOMexclusionMaps;
  vector<TH2F*> efficiencies;

  int nBinsX = -1;
  int nBinsY = -1;

  TH2F* signalMapPresel  = screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,"presel","singleLepton");
  TH2F* backgroundPresel = screwdriver.get2DCompositeHistoClone("mStop","mNeutralino","2DSumBackground","presel","singleLepton","");

  if (nBinsX == -1) nBinsX = signalMapPresel->GetNbinsX();
  if (nBinsY == -1) nBinsY = signalMapPresel->GetNbinsY();

  // Store background eff in (mStop,mLSP) = (200,300)
  int backgroundBin = signalMapPresel->FindBin(200,300);
  float backgroundYieldPresel = backgroundPresel->Integral(0,nBinsX+1,0,nBinsY+1);

  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      signalMaps.push_back(screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,cutAndCountRegions[i],"singleLepton"));
      signalMaps[i]->SetName((string("signalMap_")+cutAndCountRegions[i]).c_str());

      float B =   screwdriver.GetYieldAndError("1ltop",    cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("ttbar_2l", cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers
                + screwdriver.GetYieldAndError("W+jets",   cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("rare",     cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers;

      // Apply scale factor from background prediction
      float f_B = globalBackgroundUncertainty[i];
      //float f_B = 0.15;

      if (B < 1.0) B = 1.0;
 
      efficiencies.push_back((TH2F*) signalMaps[i]->Clone());
      efficiencies[i]->SetName((string("eff_")+cutAndCountRegions[i]).c_str());
      efficiencies[i]->Divide(signalMapPresel);
      efficiencies[i]->SetBinContent(backgroundBin,B/backgroundYieldPresel);
      
      FOMdiscoveryMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMdiscoveryMaps[i]->SetName((string("FOMdisco_")+cutAndCountRegions[i]).c_str());

      FOMexclusionMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMexclusionMaps[i]->SetName((string("FOMexclu_")+cutAndCountRegions[i]).c_str());

      for (int x = 1 ; x <= nBinsX ; x++)
      for (int y = 1 ; y <= nBinsY ; y++)
      {
          float S = signalMaps[i]->GetBinContent(x,y);

          float FOMdiscovery = figureOfMerit(S,B,"discovery",false,f_B);
          FOMdiscoveryMaps[i]->SetBinContent(x,y,FOMdiscovery);
          
          float FOMexclusion = figureOfMerit(S,B,"exclusion",false,f_B);
          FOMexclusionMaps[i]->SetBinContent(x,y,FOMexclusion);
      }

  }

  // ################################
  // ##   Compute "best" FOM map   ##
  // ################################

  TH2F* bestDiscoFOMMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoFOMMap->SetName("bestDiscoFOM");
  TH2F* bestDiscoSetMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoSetMap->SetName("bestDiscoSet");
  TH2F* bestDiscoSigEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoSigEff->SetName("bestDiscoSigEff");
  TH2F* bestDiscoBkgEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoBkgEff->SetName("bestDiscoBkgEff");
  
  TH2F* bestExcluFOMMap = (TH2F*) signalMaps[0]->Clone();  bestExcluFOMMap->SetName("bestExcluFOM");
  TH2F* bestExcluSetMap = (TH2F*) signalMaps[0]->Clone();  bestExcluSetMap->SetName("bestExcluSet");
  TH2F* bestExcluSigEff = (TH2F*) signalMaps[0]->Clone();  bestExcluSigEff->SetName("bestExcluSigEff");
  TH2F* bestExcluBkgEff = (TH2F*) signalMaps[0]->Clone();  bestExcluBkgEff->SetName("bestExcluBkgEff");
  
  for (int x = 1 ; x <= nBinsX ; x++)
  for (int y = 1 ; y <= nBinsY ; y++)
  {
      float bestDiscoFOM = -1.0;
      int   bestDiscoSet = 0;
      float bestDiscoSigEff_ = -1.0;
      float bestDiscoBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float DiscoFOM = FOMdiscoveryMaps[i]->GetBinContent(x,y);
          if (bestDiscoFOM < DiscoFOM)
          {
              bestDiscoFOM = DiscoFOM;
              if (bestDiscoFOM > 0) bestDiscoSet = i+1;
              bestDiscoSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestDiscoBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestDiscoFOMMap->SetBinContent(x,y,bestDiscoFOM);
      bestDiscoSetMap->SetBinContent(x,y,bestDiscoSet);
      bestDiscoSigEff->SetBinContent(x,y,bestDiscoSigEff_);
      bestDiscoBkgEff->SetBinContent(x,y,bestDiscoBkgEff_);

      float bestExcluFOM = -1.0;
      int   bestExcluSet = 0;
      float bestExcluSigEff_ = -1.0;
      float bestExcluBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float ExcluFOM = FOMexclusionMaps[i]->GetBinContent(x,y);
          if (bestExcluFOM < ExcluFOM)
          {
              bestExcluFOM = ExcluFOM;
              if (bestExcluFOM > 0) bestExcluSet = i+1;
              bestExcluSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestExcluBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestExcluFOMMap->SetBinContent(x,y,bestExcluFOM);
      bestExcluSetMap->SetBinContent(x,y,bestExcluSet);
      bestExcluSigEff->SetBinContent(x,y,bestExcluSigEff_);
      bestExcluBkgEff->SetBinContent(x,y,bestExcluBkgEff_);

  }

  // #########################
  // ##   Save those maps   ##
  // #########################

  float lineOffset = 0.0;
  string label;
  if (signalCategory == "T2tt"    ) { lineOffset = 172; label = "T2tt;";            }
  if (signalCategory == "T2bw-025") { lineOffset = 320; label = "T2bw (x = 0.25);"; }
  if (signalCategory == "T2bw-050") { lineOffset = 160; label = "T2bw (x = 0.50);"; }
  if (signalCategory == "T2bw-075") { lineOffset = 105; label = "T2bw (x = 0.75);"; }

  TFile fOutput(("../plots/cutAndCount_performances/"+signalCategory+"/custom.root").c_str(),"RECREATE");
  string pathExport = "../plots/cutAndCount_performances/"+signalCategory+"/";
  gStyle->SetPaintTextFormat("4.0f");
  formatAndWriteMapPlot(&screwdriver,bestDiscoSetMap,bestDiscoSetMap->GetName(),label+"Best set of cuts;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSetMap,bestExcluSetMap->GetName(),label+"Best set of cuts;(for exclusion)",pathExport,lineOffset);
  gStyle->SetPaintTextFormat("4.1f");
  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      FOMdiscoveryMaps[i]->SetMaximum(5.0);
      formatAndWriteMapPlot(&screwdriver,FOMdiscoveryMaps[i],FOMdiscoveryMaps[i]->GetName(),string("Discovery FOM for ")+cutAndCountRegions[i], pathExport,lineOffset);
      formatAndWriteMapPlot(&screwdriver,    efficiencies[i],    efficiencies[i]->GetName(),string("Efficiencies for " )+cutAndCountRegions[i], pathExport,lineOffset);
  }
  bestDiscoFOMMap->SetMaximum(5.0);
  bestExcluFOMMap->SetMaximum(5.0);
  formatAndWriteMapPlot(&screwdriver,bestDiscoFOMMap,bestDiscoFOMMap->GetName(),label+"Best FOM;(for discovery)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoSigEff,bestDiscoSigEff->GetName(),label+"Best signal efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoBkgEff,bestDiscoBkgEff->GetName(),label+"Best backgr efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluFOMMap,bestExcluFOMMap->GetName(),label+"Best FOM;(for exclusion)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSigEff,bestExcluSigEff->GetName(),label+"Best signal efficiency;(for exclusion)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluBkgEff,bestExcluBkgEff->GetName(),label+"Best backgr efficiency;(for exclusion)",pathExport,lineOffset);
  fOutput.Close();

  printBoxedMessage("Program done.");
  return (0);
}
Example #7
0
/**
 * Loads a histogram from a ROOT-file, scales it, and either returns it as \c
 * returnedHistogram or adds it to \c returnedHistogram . The first if
 * \c returnedHistogram is \c NULL otherwise the latter.
 *
 * @param histogramName
 *                              name of the histogram.
 * @param inputFilename
 *                              name of the ROOT-file.
 * @param scale
 *                              scale factor for histogram.
 * @param returnedHistogram
 *                              the returned histogram (input, pass-by-reference does not work).
 * @param debug
 *                              switch on debug output, defaults to \c false
 *
 * @return
 *                              the returned histogram (output, pass-by-reference does not work).
 */
void
LoadHistogramTH2F(const TString& histogramName, const TString& inputFilename, double scale, TH2F*& returnedHistogram, bool debug = false)
{
// {{{
    TFile inputFile(inputFilename);
    if (!inputFile.IsOpen())
    {
        cerr << "Could not open '" << inputFilename << "' for reading." << endl;
    }
    else
    {
        TH2F* histogram = dynamic_cast<TH2F*>( inputFile.Get(histogramName) );
        if (!histogram)
        {
            cerr << "No histogram named '" << histogramName << "' in file '" << inputFilename << "'" << endl;
        }
        else
        {
            if (debug) cerr << inputFilename << " " << histogramName << " entries=" << histogram->GetEntries() << " integral=" << histogram->Integral() << " scale*integral=" << scale*histogram->Integral() << endl;
            histogram->Scale(scale);
            if (!returnedHistogram)
            {
                returnedHistogram = new TH2F(*histogram);
                returnedHistogram->SetDirectory(0); // otherwise "TFile inputFile" owns this returnedHistogram and deletes it when "TFile inputFile" goes out of scope
            }
            else
            {
                returnedHistogram->Add(histogram);
            }
        }
        inputFile.Close();
    }
// }}}
};
Example #8
0
int main(){

  BaBarStyle p;
  p.SetBaBarStyle();
  //gROOT->SetStyle("Plain");

  Bool_t doNorm = kTRUE;
  Bool_t doComparison = kFALSE;
  Bool_t doFract = kFALSE;
  Bool_t doFit = kFALSE;
  Bool_t doPlots = kFALSE;

  //define DalitzSpace for generation
  EvtPDL pdl;
  pdl.readPDT("evt.pdl");
  EvtDecayMode mode("D0 -> K- pi+ pi0");
  EvtDalitzPlot dalitzSpace(mode);

  RooRealVar m2Kpi_d0mass("m2Kpi_d0mass","m2Kpi_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AB),dalitzSpace.qAbsMax(EvtCyclic3::AB));
  RooRealVar m2Kpi0_d0mass("m2Kpi0_d0mass","m2Kpi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AC),dalitzSpace.qAbsMax(EvtCyclic3::AC));
  RooRealVar m2pipi0_d0mass("m2pipi0_d0mass","m2pipi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::BC),dalitzSpace.qAbsMax(EvtCyclic3::BC));
  RooCategory D0flav("D0flav","D0flav");
  D0flav.defineType("D0",-1);
  D0flav.defineType("antiD0",1);

  //this is just to plot the m23 pdf
  Float_t total = pow(dalitzSpace.bigM(),2) + pow(dalitzSpace.mA(),2) + pow(dalitzSpace.mB(),2) + pow(dalitzSpace.mC(),2);
  RooRealVar totalm("totalm","totalm",total);
  RooFormulaVar mass13a("mass13a","@0-@1-@2",RooArgSet(totalm,m2Kpi_d0mass,m2pipi0_d0mass));

  cout << "read the dataset" << endl;

  TFile hello("DataSet_out_tmp.root");
  gROOT->cd();
  RooDataSet *data = (RooDataSet*)hello.Get("fulldata");
  RooDataSet *data_1 = (RooDataSet*)data->reduce("D0flav ==  1 && isWS == 0 && d0LifetimeErr < 0.5 && d0Lifetime > -2. && d0Lifetime < 4.");
  RooDataSet *finaldata = (RooDataSet*)data_1->reduce("deltaMass > 0.1449 && deltaMass < 0.1459 && d0Mass > 1.8495 && d0Mass < 1.8795");
  RooDataSet *leftdata = (RooDataSet*)(RooDataSet*)data_1->reduce("d0Mass > 1.74 && d0Mass < 1.79");
  RooDataSet *rightdata = (RooDataSet*)data_1->reduce("d0Mass > 1.94 && d0Mass < 1.99");

  //here we set the weights for the dataset
  finaldata->setWeightVar(0);
  leftdata->setWeightVar(0);
  rightdata->setWeightVar(0);

  //if you want to have a little dataset to test, uncomment next line and rename finaldata above
  //RooDataSet *finaldata = finaldata_1->reduce(EventRange(1,1000));
  cout << "*************************************************************" << endl;
  cout << "The final data entry    " << finaldata->numEntries() << endl;
  cout << "*************************************************************" << endl;

  //Construct signal pdf
  string dirname = "configmaps/effmapping_RS_CP/";

  RooKpipi0pdf *D0pdf = new RooKpipi0pdf("D0pdf","D0pdf",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace,dirname,1);
  RooKpipi0pdf *D0pdf23 = new RooKpipi0pdf("D0pdf23","D0pdf23",m2Kpi_d0mass,mass13a,&dalitzSpace,dirname,1);

  if(doNorm) D0pdf->getManager()->calNorm();

  //When we plot the 1D projection, need to calculate the 1D integral
  //set the precision here
  //cout << "config integrator " << endl;
  RooNumIntConfig *cfg = RooAbsReal::defaultIntegratorConfig();
  cfg->setEpsAbs(1E-3);
  cfg->setEpsRel(1E-3);
  cfg->method1D().setLabel("RooSegmentedIntegrator1D");
  //cfg.getConfigSection("RooSegmentedIntegrator1D").setRealValue("numSeg",3);
  //cfg->method1D()->Print("v");
  D0pdf->setIntegratorConfig(*cfg);
  D0pdf23->setIntegratorConfig(*cfg);

  cout << "about to init" << endl;

  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  m2pipi0_d0mass.setBins(150);

  //background description
  //RooBkg combdalitz("combdalitz","combdalitz",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace);
  //RooBkg combdalitz23("combdalitz23","combdalitz23",m2Kpi_d0mass,mass13a,&dalitzSpace);

  RooRealVar Nsig("Nsig","Nsig", 653962. + 2218.);
  RooRealVar Nbkg("Nbkg","Nbkg", 2255. + 551.);

  RooDataHist* dbdalitz = new RooDataHist("dbdalitz","dbdalitz",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*finaldata);
  RooDataHist* dbdalitz23 = new RooDataHist("dbdalitz23","dbdalitz23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*finaldata);

  ////////////////////////////////////////
  //background parametrization using sidebands histograms
  ////////////////////////////////////////
  TH2F *lefth = m2Kpi_d0mass.createHistogram("lefth",m2Kpi0_d0mass);
  leftdata->fillHistogram(lefth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
  TH2F *righth = m2Kpi_d0mass.createHistogram("righth",m2Kpi0_d0mass);
  rightdata->fillHistogram(righth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));

  TH2F *lefth23 = m2Kpi_d0mass.createHistogram("lefth23",m2pipi0_d0mass);
  leftdata->fillHistogram(lefth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));
  TH2F *righth23 = m2Kpi_d0mass.createHistogram("righth23",m2pipi0_d0mass);
  rightdata->fillHistogram(righth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));

  righth->Scale(lefth->Integral()/righth->Integral());
  lefth->Sumw2();
  righth->Sumw2();
  righth23->Scale(lefth23->Integral()/righth23->Integral());
  lefth23->Sumw2();
  righth23->Sumw2();

  RooDataHist *lefthist = new RooDataHist("lefthist","lefthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),lefth);
  RooDataHist *righthist = new RooDataHist("righthist","righthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),righth);
  RooDataHist *lefthist23 = new RooDataHist("lefthist23","lefthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),lefth23);
  RooDataHist *righthist23 = new RooDataHist("righthist23","righthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),righth23);

  RooHistPdf leftpdf("leftpdf","leftpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*lefthist,4);
  RooHistPdf rightpdf("rightpdf","rightpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*righthist,4);
  RooHistPdf leftpdf23("leftpdf23","leftpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*lefthist23,4);
  RooHistPdf rightpdf23("rightpdf23","rightpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*righthist23,4);

  RooRealVar fcomb("fcomb","fcomb",0.738);
  RooAddPdf combdalitz("combdalitz","combdalitz",RooArgList(leftpdf,rightpdf),RooArgList(fcomb));
  RooAddPdf combdalitz23("combdalitz23","combdalitz23",RooArgList(leftpdf23,rightpdf23),RooArgList(fcomb));
  ///////////////////////////////////////

  RooAddPdf totpdf("totpdf","totpdf",RooArgList(*D0pdf,combdalitz),RooArgList(Nsig,Nbkg));
  RooAddPdf totpdf23("totpdf23","totpdf23",RooArgList(*D0pdf23,combdalitz23),RooArgList(Nsig,Nbkg));

  if(doFit){
    // Start Minuit session on Chi2
    RooChi2Var chi2("chi2","chi2",totpdf,*dbdalitz);
    RooMinuit m2(chi2);
    m2.migrad();
    m2.hesse();
    RooFitResult* fitRes = m2.save();
    fitRes->Print("v");
    RooArgSet results(fitRes->floatParsFinal());
    RooArgSet conresults(fitRes->constPars());
    results.add(conresults);
    results.writeToFile("fit_isobar_RS.txt");

    //save the stupid result
    TFile f("fit_RSDalitz_result.root","RECREATE");
    fitRes->Write();
    f.Close();
  }

  if(doFract) {

    cout << "Calculating fit fractions" << endl;
    TFile f("fit_RSDalitz_result.root");
    RooFitResult* fitRes = (RooFitResult*)f.Get("chi2");

    //now calculate the fit fractions
    const Int_t nRes = D0pdf->getManager()->getnRes();

    //recalculate the normalization if necessary
    D0pdf->getManager()->calNorm();

    EvtComplex normarray[nRes][nRes];

    const Int_t myRes = 12;
    TH1F fitty[myRes];

    //read the integral value from the cache file.
    //In this way we don't need to compute the normalization everytime during MIGRAD
    char int_name[50];
    D0pdf->getManager()->getFileName(int_name);

    ifstream f1;
    f1.open(int_name);
    if (!f1){
      cout << "Error opening file " << endl;
      assert(0);
    }
  
    Double_t re=0.,im=0.;
    //Read in the cache file and store back to array
    for(Int_t j=0;j<nRes;j++) {
      char thname[100];
      sprintf(thname,"thname_%d",j);
      if(j < myRes) fitty[j] = TH1F(thname,thname,30,0.,1.);
      for(Int_t k=0;k<nRes;k++){
	f1 >> re >> im;       
	normarray[j][k] = EvtComplex(re,im);
      }
    }   

    EvtComplex mynorm[myRes][myRes];
    Int_t m = 0, l = 0;
    for(Int_t i=0;i<myRes;i++){
      for(Int_t j=0;j<myRes;j++){
	if(i==0) l = 7;
	else if(i==1) l = 6;
	else if(i==2) l = 11;
	else if(i==3) l = 4;
	else if(i==4) l = 5;
	else if(i==5) l = 3;
	else if(i==6) l = 9;
	else if(i==7) l = 10;
	else if(i==8) l = 12;
	else if(i==9) l = 8;
	else if(i==10) l = 2;
	else if(i==11) l = 0;

	if(j==0) m = 7;
	else if(j==1) m = 6;
	else if(j==2) m = 11;
	else if(j==3) m = 4;
	else if(j==4) m = 5;
	else if(j==5) m = 3;
	else if(j==6) m = 9;
	else if(j==7) m = 10;
	else if(j==8) m = 12;
	else if(j==9) m = 8;
	else if(j==10) m = 2;
	else if(j==11) m = 0;

	mynorm[i][j] = normarray[l][m];
      }
    }

    //do 100 experiments and extract parameters using covariance matrix
    for(Int_t l=0;l<300;l++){
      RooArgList listpar = fitRes->randomizePars();
      if(l==0) listpar.Print();

      Double_t mynormD0 = 0.;
      EvtComplex coeff_i(0.,0.), coeff_j(0.,0.);
      for(Int_t i=0;i<2*myRes;i++){
	for(Int_t j=0;j<2*myRes;j++){
	  if(i==(2*myRes - 2)) coeff_i = EvtComplex(1.,0.);
	  else coeff_i = EvtComplex(((RooAbsReal*)listpar.at(i))->getVal()*cos(((RooAbsReal*)listpar.at(i+1))->getVal()),
				    ((RooAbsReal*)listpar.at(i))->getVal()*sin(((RooAbsReal*)listpar.at(i+1))->getVal()));

	  if(j==(2*myRes - 2)) coeff_j = EvtComplex(1.,0.);
	  else coeff_j = EvtComplex(((RooAbsReal*)listpar.at(j))->getVal()*cos(((RooAbsReal*)listpar.at(j+1))->getVal()),
				    ((RooAbsReal*)listpar.at(j))->getVal()*sin(((RooAbsReal*)listpar.at(j+1))->getVal()));

	  mynormD0 += real(coeff_i*conj(coeff_j)*(mynorm[i/2][j/2]));
	  j++;
	}
	i++;
      }

      //now calculate the fit fractions
      for(Int_t i=0;i<2*myRes;i++){
	Double_t fitfrac = 0.;
	if(i==(2*myRes - 2)) fitfrac = abs(mynorm[i/2][i/2])/mynormD0;
	else fitfrac = abs2( ((RooAbsReal*)listpar.at(i))->getVal())*abs(mynorm[i/2][i/2])/mynormD0;
	fitty[i/2].Fill(fitfrac);
	i++;
      }
    }// nexperiments

    Double_t tot_frac = 0.;
    for(Int_t i=0;i<myRes;i++){
      tot_frac += fitty[i].GetMean();
      cout << "Resonance " << i << ": fit fraction = " << fitty[i].GetMean() << " +/- " << fitty[i].GetRMS() << endl;
    }

    cout << "Total fit fraction = " << tot_frac << endl;
    cout << "///////////////////////////" << endl;
  }

  if(doPlots){
    //Make the plots
    // REMEBER: if you want roofit to consider the reweighted errors, you must put DataError(RooAbsData::SumW2))
    //******************************************************
    RooPlot* xframe = m2Kpi_d0mass.frame();
    dbdalitz->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(xframe);
    xframe->getAttLine()->SetLineWidth(1);
    xframe->getAttLine()->SetLineStyle(1);
    xframe->SetTitle("");
    xframe->GetXaxis()->SetTitle("s_{12} [GeV^{2}/c^{4}]");
    xframe->GetYaxis()->SetTitle("Events/4 MeV^{2}/c^{4}");
    Double_t chi2Kpi = xframe->chiSquare();

    RooPlot* yframe = m2Kpi0_d0mass.frame();
    dbdalitz->plotOn(yframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(yframe);
    yframe->getAttLine()->SetLineWidth(1);
    yframe->getAttLine()->SetLineStyle(1);
    yframe->SetTitle("");
    yframe->GetXaxis()->SetTitle("s_{13} [GeV^{2}/c^{4}]");
    yframe->GetYaxis()->SetTitle("Events/5 MeV^{2}/c^{4}");
    Double_t chi2Kpi0 = yframe->chiSquare();
    /*
    RooPlot* zframe = m2pipi0_d0mass.frame(0.,2.3);
    dbdalitz23->plotOn(zframe,MarkerSize(0.1),DrawOption("z"));
    totpdf23.plotOn(zframe);
    zframe->getAttLine()->SetLineWidth(1);
    zframe->getAttLine()->SetLineStyle(1);
    zframe->SetTitle("");
    zframe->GetXaxis()->SetTitle("m^{2}_{#pi^{+}#pi^{0}}");
    Double_t chi2pipi0 = zframe->chiSquare();

    cout << "Chi2 for Kpi = " << chi2Kpi << endl;
    cout << "Chi2 for Kpi0 = " << chi2Kpi0 << endl;
    cout << "Chi2 for pipi0 = " << chi2pipi0 << endl;

    RooPlot* pullFramem12 = m2Kpi_d0mass.frame() ;
    pullFramem12->SetTitle("");
    pullFramem12->GetXaxis()->SetTitle("");
    pullFramem12->addPlotable(xframe->pullHist()) ;
    pullFramem12->SetMaximum(5.);
    pullFramem12->SetMinimum(-5.);

    RooPlot* pullFramem13 = m2Kpi0_d0mass.frame() ;
    pullFramem13->SetTitle("");
    pullFramem13->GetXaxis()->SetTitle("");
    pullFramem13->addPlotable(yframe->pullHist()) ;
    pullFramem13->SetMaximum(5.);
    pullFramem13->SetMinimum(-5.);

    RooPlot* pullFramem23 = m2pipi0_d0mass.frame() ;
    pullFramem23->SetTitle("");        
    pullFramem23->GetXaxis()->SetTitle("");
    pullFramem23->addPlotable(zframe->pullHist()) ;
    pullFramem23->SetMaximum(5.);
    pullFramem23->SetMinimum(-5.);

    TCanvas *c2 = new TCanvas("c2","residuals",1200,200);
    c2->Divide(3,1);
    c2->cd(1);pullFramem12->Draw();
    c2->cd(2);pullFramem13->Draw();
    c2->cd(3);pullFramem23->Draw();
    c2->SaveAs("RSresiduals.eps");
    */
    totpdf.plotOn(xframe,Project(m2Kpi0_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    totpdf.plotOn(yframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    //totpdf23.plotOn(zframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz23)),DrawOption("F"),FillColor(kRed));

    TPaveText *box_m12 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m12->AddText("(b)");
    box_m12->SetFillColor(10);

    TPaveText *box_m13 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m13->AddText("(c)");
    box_m13->SetFillColor(10);

    TCanvas c1("c1","c1",600,600);
    c1.cd();
    xframe->Draw();box_m12->Draw("SAME");
    c1.SaveAs("RSfit_m2Kpi.eps");

    TCanvas c2("c2","c2",600,600);
    c2.cd();
    yframe->Draw();box_m13->Draw("SAME");
    c2.SaveAs("RSfit_m2Kpi0.eps");
    /*
    TCanvas *c1 = new TCanvas("c1","allevents",1200,400);
    c1->Divide(3,1);
    c1->cd(1);xframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(2);yframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(3);zframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->SaveAs("RSsigfit.eps");
    */
  }

  if(doComparison){
    RooDataSet *littledata = (RooDataSet*)finaldata->reduce(EventRange(1,70000));
    RooArgSet VarList1(m2Kpi_d0mass,m2Kpi0_d0mass);
    Int_t num_entries = littledata->numEntries();
    RooDataSet* genpdf = D0pdf->generate(VarList1,num_entries);

    Int_t nbinx = 20;
    Int_t nbiny = 20;
    m2Kpi_d0mass.setBins(nbinx);
    m2Kpi0_d0mass.setBins(nbiny);

    TH2F* pdfhist = new TH2F("pdfhist","pdfhist",nbinx,0.39,3.,nbiny,0.39,3.);
    TH2F* datahist = new TH2F("datahist","datahist",nbinx,0.39,3.,nbiny,0.39,3.);
    pdfhist = genpdf->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    datahist = finaldata->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    pdfhist->GetXaxis()->SetTitle("m_{K#pi}^{2}");
    pdfhist->GetYaxis()->SetTitle("m_{K#pi^{0}}^{2}");

    pdfhist->Scale(datahist->Integral()/pdfhist->Integral());

    pdfhist->Add(datahist,-1.);

    TCanvas c2;
    c2.cd();pdfhist->Draw("LEGO2Z");
    c2.SaveAs("RSsigdiff.eps");

    TFile ftmp("prova.root","RECREATE");
    ftmp.cd();pdfhist->Write();
    ftmp.Close();

  }

  return 0;
}//end of the macro
Example #9
0
File: toffit.C Project: XuQiao/HI
void toffit(){
	gStyle->SetErrorX(0);
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(1);
	TFile *f = TFile::Open("mergedFull.root");
	TString charge;
	ofstream fout("Run15tofdphidzcalib.dat");
	ofstream fouttmp("Run15tofdphidzcalibtmp.dat");
	for(int iarm=0; iarm<2; iarm++){
	for(int ich=0; ich<2; ich++){
	if(iarm==0)
	TH2F *tofdphidz = (TH2F*)f->Get(Form("tofdphidz_%d",ich));
	else
	TH2F *tofdphidz = (TH2F*)f->Get(Form("tofwdphidz_%d",ich));
	if(tofdphidz->Integral()==0) continue;
	TH1F* tofdphi = (TH1F*)tofdphidz->ProjectionX(Form("tofdphi_%d_%d",iarm,ich),0,-1);
	TH1F* tofdz = (TH1F*)tofdphidz->ProjectionY(Form("tofdz_%d_%d",iarm,ich),0,-1);
	//tofdphi->Rebin(4);
	tofdz->Rebin(5);
	tofdphi->Scale(1./tofdphi->Integral());
	tofdz->Scale(1./tofdz->Integral());
	TF1 *fphi = new TF1("fphi","gaus(0)+gaus(3)",-0.1,0.1);
	fphi->SetNpx(10000);
	//TF1 *fphi = new TF1("fphi","[0]*([1]*exp(-(x-[2])**2/[3]/[3])+(1-[1])*exp(-(x-[4])**2/[5]/[5]))",-0.1,0.1);
	fphi->SetParameters(1e-1,0,1e-3,1e-3,0,1e-2);
	//fphi->SetParameters(4.79253e-02,9.25529e-01,-8.56488e-05,-7.46701e-03,-5.37828e-04,5.99178e-0);
	SetStyle(*tofdphi,1.2,1,20,0,0);
	tofdphi->Fit("fphi","RQ");
	double par[6];
	fphi->GetParameters(par);
	TF1 *fphi1 = new TF1("fphi1","gaus",-0.1,0.1);
	fphi1->SetNpx(10000);
	fphi1->SetParameters(par);
	TF1 *fphi2 = new TF1("fphi2","gaus",-0.1,0.1);
	fphi2->SetNpx(10000);
	fphi2->SetParameters(&par[3]);
	fphi1->SetLineColor(4);
	//fphi1->Draw("same");
	fphi2->SetLineColor(6);
	//fphi2->Draw("same");
	fout<<par[1]<<",";
	if(par[1]>1) cout<<"dphi "<<iarm<<"\t"<<ich<<"\t"<<ipt<<endl;

	TF1 *fz = new TF1("fz","gaus(0)+gaus(3)",-10,10);
	//fz->SetParameters(3.02349e+07,8.32462e-01,2.39187e+00,2.17631e+07,6.35460e-01,8.09821e+00);
	fz->SetParameters(1e-1,0,2,1e-3,0,8);
	SetStyle(*tofdz,1.2,1,20,0,0);
	tofdz->Fit("fz","RQ");
	fz->GetParameters(par);
	TF1 *fz1 = new TF1("fz1","gaus",-10,10);
	fz1->SetNpx(10000);
	fz1->SetParameters(par);
	TF1 *fz2 = new TF1("fz2","gaus",-10,10);
	fz2->SetNpx(10000);
	fz2->SetParameters(&par[3]);
	fz1->SetLineColor(4);
	//fz1->Draw("same");
	fz2->SetLineColor(6);
	//fz2->Draw("same");
	if(par[1]>10) cout<<"dz"<<iarm<<"\t"<<ich<<"\t"<<ipt<<endl;
	fouttmp<<par[1]<<",";
	}
	fout<<endl;
	fouttmp<<endl;
}

}
Example #10
0
void
CalcFakeRate(string infile, bool useData=true, bool doSystematics=false){  
  cout<<" UseData="<<useData<<" dosystematics="<<doSystematics<<endl;

  TFile *f = TFile::Open(infile.c_str(), "read"); assert(f);
  TH2F* hFakeRateNum = NULL;
  TH2F* hFakeRateAll = NULL;
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  gStyle->SetTextFont(132);
  gStyle->SetTextSize(1.2);
  //gROOT->ForceStyle();

  bool useElectrons = infile.find("Muon") == string::npos;
  bool doWLep = infile.find("-TT") == string::npos;

  vector<string> allsamples;
  if(!useData){
    allsamples.push_back("WJetsToLNu");
    if(!doSystematics){
    allsamples.push_back("TTJets");
    allsamples.push_back("ZZ");
    allsamples.push_back("GVJets");
    allsamples.push_back("WWTo2L2Nu");
    allsamples.push_back("WZJetsTo3LNu");
    allsamples.push_back("DYJetsToLL");
    }
  }else{
    allsamples.push_back("data");
  }
  
  float offset = 0.01;
  float eta[] = {0., 1.5, 2.5}; int neta = 3;
  if(!useElectrons){
    eta[1] = 2.4;
    neta = 2;//eta[2] = 2.4;
  }

  //float pt [] = {0., 20., 40., 1000}; const int npt  = 4;
  //float pt [] = {0., 10., 20., 30., 1000}; const int npt  = 5;

  //float pt [] = {0., 10., 15., 25., 1000}; const int npt  = 5;
  //float pt [] = {0., 10., 15., 20., 30., 1000}; const int npt  = 6;
  float pt [] = {10., 15., 20., 30., 40., 100}; const int npt  = 6;

  //float pt [] = {0., 20., 25., 30., 50., 1000}; const int npt  = 6;
  hFakeRateNum = new TH2F("hFakeRateNum", "hFakeRateNum;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  hFakeRateAll = new TH2F("hFakeRateAll", "hFakeRateAll;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta);
  string title = useElectrons ? "Electron Fake Rate" : "Muon Fake Rate";
  title += useData ? " from Data" : " from MC";
  title += !useData && doSystematics ? " Systematics" : "";
  title += " using W+Jets method";
  title += doWLep ? " on W lepton" : " on Z lepton";
  hFakeRateNum->SetTitle(title.c_str());

/////////This is for eta, pt agnotistic Fake Rate Calc
  float in_tot(0), out_tot(0);
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);

    in  = hist->GetBinContent(lastbin);
    out = hist->GetBinContent(lastbin-1);

    in_tot += in;
    out_tot += out;

    //cout<<"Sample: "<<allsamples[i]<<" = "<<in/out<<" = pass/total = "<<in<<"/"<<out<<endl;
    printf("  Sample: %s = %.2f%% : pass/total = %.2f / %.2f \n",allsamples[i].c_str(), in/out*100, in, out);
  }
  float  eff = in_tot/out_tot;
  float deff = TMath::Sqrt(eff * (1-eff)/out_tot);
  //cout<<"Total: "<<eff*100<<"% +/- "<<deff*100<<"% = in_tot/out_tot*100% = "<<in_tot<<"/"<<out_tot<<"*100%\n";
  printf("Total: %.2f%% +/- %.2f%% = in_tot/out_tot*100%% = %.2f/%.2f\n", eff*100, deff*100, in_tot, out_tot);


/////////This is for 2D Fake Rate Calc
  for(unsigned i=0; i<allsamples.size(); ++i){
    string hist_name = allsamples[i] + "/hNumEvts";
    TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist);
    int lastbin = hist->GetNbinsX();
    float in(0), out(0);
    string binNameNum   = hist->GetXaxis()->GetBinLabel(lastbin);
    string binNameDenom = hist->GetXaxis()->GetBinLabel(lastbin-1);
      
    string hist_nameNum = allsamples[i] + "/hEtaVsPt_" + binNameNum;
    TH2F* histNum = (TH2F*) f->Get(hist_nameNum.c_str()); assert(histNum);
      
    string hist_nameDenom = allsamples[i] + "/hEtaVsPt_" + binNameDenom;
    TH2F* histDenom = (TH2F*) f->Get(hist_nameDenom.c_str()); assert(histDenom);
/*
    cout<<" Total from 2D Plot is "<<histNum->Integral()<<" / "<<histDenom->Integral()<<endl; //By default, integral doesn't count over/underflow
    cout<<" Total from 2D Plot is "<<histNum->GetEntries()<<" / "<<histDenom->GetEntries()<<endl;

    float sUnder(0), sOver(0);
    for(int ybin = 0; ybin<= histDenom->GetYaxis()->GetNbins() + 1; ++ybin){
      for(int xbin = 0; xbin<= histDenom->GetXaxis()->GetNbins() +1; ++xbin){
        int bin = histDenom->GetBin(xbin, ybin);
        if(histDenom->IsBinOverflow(bin)) sOver += histDenom->GetBinContent(bin);
        if(histDenom->IsBinUnderflow(bin)) sUnder += histDenom->GetBinContent(bin);
      }
    }
    printf("Total overflow, underflow in denom histo is %.2f , %.2f\n", sOver, sUnder);
*/
    for(int ieta=0; ieta<neta-1; ++ieta){
      float ymin = eta[ieta]; 
      float ymax = eta[ieta+1]-offset;
      for(int ipt=0; ipt<npt-1; ++ipt){
        float xmin = pt[ipt]; 
        float xmax = pt[ipt+1];
          
        int xminbin,xmaxbin,yminbin,ymaxbin;
        xminbin = histNum->GetXaxis()->FindBin(xmin); //+ (ipt!=0);//Avoid overlap except for first bin
        xmaxbin = histNum->GetXaxis()->FindBin(xmax)-1 + (ipt == npt-1-1);
        yminbin = histNum->GetYaxis()->FindBin(ymin);
        ymaxbin = histNum->GetYaxis()->FindBin(ymax);
        
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */      
        in  = histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out = histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
          
        //Cory: Deal with negative eta (Y axis)
        yminbin = histNum->GetYaxis()->FindBin(-1*ymax);
        ymaxbin = histNum->GetYaxis()->FindBin(-1*ymin)-1;//avoid overlap
        /*
        cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t"
            <<xmin<<"-"<<xmax<<":"
            <<ymin<<"-"<<ymax<<":"
            <<"\t";
        cout<<"("<<ipt<<", "<<ieta<<")\t"
            <<xminbin<<"-"<<xmaxbin<<":"
            <<yminbin<<"-"<<ymaxbin
            <<endl;
        */
        in  += histNum  ->Integral(xminbin, xmaxbin, yminbin, ymaxbin);
        out += histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin);

        //cout<<"("<<pt[ipt]<<","<<eta[ieta]<<") "<<in<<"/"<<out<<endl;
        //cout<<"("<<(pt[ipt]+pt[ipt+1])/2<<","<<(eta[ieta]+eta[ieta+1])/2<<") "<<in<<"/"<<out<<endl;
        hFakeRateNum   ->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, in);
        hFakeRateAll->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, out);

      }
    }

  }

  if(hFakeRateNum){
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum->GetArray(), hFakeRateAll->GetArray(), "");
    //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum, hFakeRateAll, "");
    TH2F* hFakeRate = (TH2F*) hFakeRateNum->Clone("hFakeRate");
    //hFakeRate->Divide(hFakeRateAll);
    //hFakeRate->Scale(100.); //make is a percent
    TCanvas c1;
    c1.SetLogx(1);


    //gStyle->SetTextFont(132);
    //gStyle->SetTextSize(1.2);
    hFakeRate->SetMarkerSize(3);
    //gStyle->SetPaintTextFormat("3.0f m");
    gStyle->SetPaintTextFormat("4.0f");
    hFakeRate->Draw("colz");

    TLatex latexLabel;
    latexLabel.SetNDC();
    latexLabel.SetTextSize(0.04);
    latexLabel.SetTextFont(42);
    latexLabel.SetTextAngle(90);
    latexLabel.SetTextAlign(22);
    for(int ybin = 1; ybin<= hFakeRate->GetYaxis()->GetNbins(); ++ybin){
      int nx = hFakeRate->GetXaxis()->GetNbins();
      TGraphAsymmErrors* gFakeRatePt = new TGraphAsymmErrors(nx);
      gFakeRatePt->SetMaximum(1.1);
      gFakeRatePt->SetMinimum(0.);
      gFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());
      for(int xbin = nx; xbin >= 1; --xbin){
        float xcen = hFakeRate->GetXaxis()->GetBinCenter(xbin);
        float ycen = hFakeRate->GetYaxis()->GetBinCenter(ybin);
        
        double xpos, ypos;
        GetNDC(c1, xcen, ycen, xpos, ypos);
        int bin = hFakeRate->GetBin(xbin, ybin);
        float pass = hFakeRateNum->GetBinContent(bin);
        float tot  = hFakeRateAll->GetBinContent(bin);
        float mean    = tot>0 ? pass / tot : 0.;
        float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
        float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
        errDown = max(errDown, (float) 0.);
        hFakeRate->SetBinContent(bin, mean);
        //hFakeRate->SetBinError(bin, err);
        float err = (errUp + errDown)/2;
        printf("if(pt > %.0f) return Value(%.4f, %.4f); //pt %3.0f eta %.1f, bin %2i, (mean, err)= (%.4f, %.4f) (%.2f / %.2f) +%.4f -%.4f\n", 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), mean, err, 
               hFakeRate->GetXaxis()->GetBinLowEdge(xbin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin), bin, mean, err, pass, tot, errUp, errDown);
        if(xbin != 1) latexLabel.DrawLatex(xpos, ypos, Form("%.0f^{+%.0f}_{-%.0f}%% (%.0f/%.0f)(%.f-%.f)GeV",mean*100, errUp*100, errDown*100, pass, tot, pt[xbin-1],pt[xbin]));
        

        gFakeRatePt->SetPoint      (xbin-1, xcen, mean);
        gFakeRatePt->SetPointEYhigh(xbin-1, errUp);
        gFakeRatePt->SetPointEYlow (xbin-1, errDown);
        gFakeRatePt->SetPointEXhigh(xbin-1, hFakeRate->GetXaxis()->GetBinLowEdge(xbin+1) - xcen);
        gFakeRatePt->SetPointEXlow (xbin-1, xcen - hFakeRate->GetXaxis()->GetBinLowEdge(xbin));

      }//pt loop
      c1.Clear();
      c1.SetLogx(1);
      //c1.SetGrid();
      gFakeRatePt->Draw("ap*");
      string outName = Form("WJetsFakeRatePt-Eta%.1fto%.1f-", hFakeRate->GetYaxis()->GetBinLowEdge(ybin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin+1));
      replace(outName.begin(), outName.end(), '.', 'p');
      outName += useElectrons ? "Elec" : "Muon";
      outName += useData ? "Data" : "MC";
      outName += !useData && doSystematics ? "Sys" : "";
      outName += doWLep ? "WLep" : "ZLep";
      outName += ".pdf";
      c1.Print(outName.c_str());
      
    }//eta loop
    
    c1.Clear();
    c1.SetLogx(1);
    string outName = "FakeRate";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Now make profiles
    c1.Clear();
    c1.SetLogx(0);
    //c1.SetGrid();

    TH1D* hFakeRateNumEta = hFakeRateNum->ProjectionY("hFakeRateNumEta", 0, -1, "e");
    TH1D* hFakeRateAllEta = hFakeRateAll->ProjectionY("hFakeRateAllEta", 0, -1, "e");
    //TH1D* hFakeRateEta = (TH1D*) hFakeRateNumEta->Clone("hFakeRateEta");

    int n = hFakeRateAllEta->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRateEta = new TGraphAsymmErrors(n);//hFakeRateNumEta, hFakeRateAllEta);
    hFakeRateEta->SetMaximum(1.);
    hFakeRateEta->SetMinimum(0.);
    hFakeRateEta->SetTitle((title + ";#eta;Rate").c_str());

    //hFakeRateEta->SetMarkerStyle(21);    
    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllEta->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumEta->GetBinContent(xbin);
      float tot  = hFakeRateAllEta->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRateEta->SetPoint      (xbin, x, mean);
      hFakeRateEta->SetPointEYhigh(xbin, errUp);
      hFakeRateEta->SetPointEYlow (xbin, errDown);
      //printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    
    //hFakeRateEta->Divide(hFakeRateAllEta);
    //hFakeRateEta->Scale(100.);
    hFakeRateEta->Draw("ap*");
    outName = "FakeRateEta";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    //Pt projections (split these by eta?)
    c1.Clear();
    c1.SetLogx(1);
    //c1.SetGrid();

    TH1D* hFakeRateNumPt = hFakeRateNum->ProjectionX("hFakeRateNumPt", 0, -1, "e");
    TH1D* hFakeRateAllPt = hFakeRateAll->ProjectionX("hFakeRateAllPt", 0, -1, "e");
    //TH1D* hFakeRatePt = (TH1D*) hFakeRateNumPt->Clone("hFakeRatePt");

    n = hFakeRateAllPt->GetXaxis()->GetNbins();
    TGraphAsymmErrors* hFakeRatePt = new TGraphAsymmErrors(n);//hFakeRateNumPt, hFakeRateAllPt);
    hFakeRatePt->SetMaximum(1.);
    hFakeRatePt->SetMinimum(0.);
    hFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str());

    for(int xbin = 1; xbin <= n; ++xbin){
      float x = hFakeRateAllPt->GetXaxis()->GetBinCenter(xbin);
      float pass = hFakeRateNumPt->GetBinContent(xbin);
      float tot  = hFakeRateAllPt->GetBinContent(xbin);
      float mean    = tot>0 ? pass / tot : 0.;
      float errUp   = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1);
      float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1);
      errDown = max(errDown, (float) 0.);
      hFakeRatePt->SetPoint      (xbin, x, mean);
      hFakeRatePt->SetPointEYhigh(xbin, errUp);
      hFakeRatePt->SetPointEYlow (xbin, errDown);
      //cout<<"low edge is "<<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin)<<" up edge is "
      //    <<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1)<<endl;
      hFakeRatePt->SetPointEXhigh(xbin, hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1) - x);
      hFakeRatePt->SetPointEXlow (xbin, x - hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin));
      printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100);
    }
    


    //hFakeRatePt->Divide(hFakeRateAllPt);
    //hFakeRatePt->Scale(100.);
    hFakeRatePt->Draw("ap*");
    outName = "FakeRatePt";
    outName += useElectrons ? "Elec" : "Muon";
    outName += useData ? "Data" : "MC";
    outName += !useData && doSystematics ? "Sys" : "";
    outName += doWLep ? "WLep" : "ZLep";
    outName += ".pdf";
    c1.Print(outName.c_str());

    
  }


}
Example #11
0
void Optimize2D(TString signal, TString background, TString histname,
		int minxwidth = 2, int minywidth = 2, float minsigeff=0.5){

  TFile *sigfile = TFile::Open(signal);
  TFile *bkgfile = TFile::Open(background);

  TH2F *sighist = (TH2F*)sigfile->Get(histname);
  TH2F *bkghist = (TH2F*)bkgfile->Get(histname);

  int nxbins = sighist->GetNbinsX();
  int nybins = sighist->GetNbinsY();
  if ( nxbins != bkghist->GetNbinsX() || nybins != bkghist->GetNbinsY() ) {
    cout << "Error! The two input histograms do not have the same number of bins!" << endl;
    return; }

  int nsigtot = sighist->Integral(1,nxbins,1,nybins);
  int nbkgtot = bkghist->Integral(1,nxbins,1,nybins);
  
  cout << "Total number of entries in the signal histogram: " << nsigtot << endl;
  cout << "Total number of entries in the bkgrnd histogram: " << nbkgtot << endl;

  if ( nsigtot==0 || nbkgtot==0 ) {
    cout << "Error! At least one of the input histograms is empty!" << endl;
    return; }

  TH1D *projx = sighist->ProjectionX("projx");
  TH1D *projy = sighist->ProjectionY("projy");

  float bestsob = (float)nsigtot / nbkgtot;
  cout << "Starting with a \"no-cuts\" s/b of " << bestsob << endl;

  float x1=0, y1=0, x2=0, y2=0; // corner coordinates for the window

  for (int i=1; i<=nxbins; ++i)
    for (int j=minxwidth-1; i+j<=nxbins; ++j) 
      for (int k=1; k<=nybins; ++k)
	for (int l=minywidth-1; k+l<=nybins; ++l) {

	  int nsig = sighist->Integral(i, i+j, k, k+l);
	  if ( nsig == 0 ) continue;
	  if ( nsig < nsigtot*minsigeff ) continue;

	  int nbkg = bkghist->Integral(i, i+j, k, k+l);
	  if ( nbkg == 0 ) continue;

	  float sob = (float)nsig / nbkg;

	  if ( (float)nsig / nbkg > bestsob ) {
	    bestsob = sob;
	    x1 = projx->GetBinLowEdge(i);
	    x2 = projx->GetBinLowEdge(i+j+1);
	    y1 = projy->GetBinLowEdge(k);
	    y2 = projy->GetBinLowEdge(k+l+1);
	    cout << "x-range " << i << " (" << x1
		 << ") to " << i+j << " (" << x2
		 << ") ; \t y-range " << k << " (" << y1
		 <<") to " << k+l << " (" << y2
		 << ") ; \t signal= " << nsig
		 << " bkgrnd= " << nbkg << " s/b= " << sob << endl;
	  }
	  
	}

  TCanvas *cnv = TCanvas::MakeDefCanvas();
  cnv->Divide(2);
  TBox *box = new TBox(x1, y1, x2, y2);
  box->SetFillStyle(0);
  box->SetLineColor(2);
  box->SetLineWidth(2);
  cnv->cd(1); sighist->Draw("colbox"); box->Draw();
  cnv->cd(2); bkghist->Draw("colbox"); box->Draw();
  cnv->SaveAs("Optimize2D"+histname+".eps");

}
Example #12
0
int main(int argc, char* argv[])
{
  string name;

  for(Int_t i=1;i<argc;i++){
    char *pchar = argv[i];

    switch(pchar[0]){

    case '-':{

      switch(pchar[1]){
      case 'n':
        name = argv[i+1];
        cout << "Name of the configuration key " << name << endl;
        break;
      }
    }
    }
  }

  Bool_t doFit = kFALSE;
  Bool_t extract = kFALSE;
  Bool_t doFrac = kFALSE;
  Bool_t doPlots = kTRUE;
  Bool_t doChi2 = kFALSE;

  BaBarStyle p;
  p.SetBaBarStyle();
  gROOT->GetStyle("BABAR")->SetPalette(1);
  gROOT->GetStyle("BABAR")->SetPadTopMargin(0.04);
  gROOT->GetStyle("BABAR")->SetPadLeftMargin(0.17);
  gROOT->GetStyle("BABAR")->SetPadBottomMargin(0.19);
  gROOT->GetStyle("BABAR")->SetTitleSize(0.08,"xyz"); // set the 3 axes title size 

  //define DalitzSpace for generation
  EvtPDL pdl;
  pdl.readPDT("evt.pdl");
  EvtDecayMode mode("D0 -> K- pi+ pi0");
  EvtDalitzPlot dalitzSpace(mode);

  RooRealVar tau("tau","tau",0.4099);
  RooRealVar m2Kpi_d0mass("m2Kpi_d0mass","m2Kpi_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AB),dalitzSpace.qAbsMax(EvtCyclic3::AB));
  RooRealVar m2Kpi0_d0mass("m2Kpi0_d0mass","m2Kpi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AC),dalitzSpace.qAbsMax(EvtCyclic3::AC));
  RooRealVar m2pipi0_d0mass("m2pipi0_d0mass","m2pipi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::BC),dalitzSpace.qAbsMax(EvtCyclic3::BC));
  RooRealVar d0Lifetime("d0Lifetime","d0Lifetime",-2.,4.);
  RooRealVar d0LifetimeErr("d0LifetimeErr","d0LifetimeErr",0.0000001,0.5);
  RooCategory D0flav("D0flav","D0flav");
  D0flav.defineType("D0",-1);
  D0flav.defineType("antiD0",1);

  RooRealVar scalefact1("scalefact1","scalefact1",3.20);
  RooRealVar scalefact2("scalefact2","scalefact2",1.42);
  RooRealVar scalefact3("scalefact3","scalefact3",0.94);

  RooRealVar c1("c1","c1",-2.,2.);
  RooRealVar c2("c2","c2",-2.,2.);
  RooUnblindOffset c1_unblind("c1_unblind","c1 (unblind)","VaffanculoS",1.,c1) ;
  RooUnblindOffset c2_unblind("c2_unblind","c2 (unblind)","VaffanculoS",1.,c2) ;

  TFile fWS("DataSet_out_tmp.root");
  gROOT->cd();
  RooDataSet *data = (RooDataSet*)fWS.Get("fulldata");
  RooDataSet *data_clean = (RooDataSet*)data->reduce("d0LifetimeErr < 0.5 && d0Lifetime > -2. && d0Lifetime < 4. && deltaMass > 0.1449 && deltaMass < 0.1459");
  RooDataSet *dataWS_2 = (RooDataSet*)data_clean->reduce("isWS == 1");
  RooDataSet *dataWS = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.8495 && d0Mass < 1.8795");
  RooDataSet *RSdata = (RooDataSet*)data_clean->reduce("isWS == 0 && d0Mass > 1.8495 && d0Mass < 1.8795");

  Double_t low12,hig12,low13,hig13,low23,hig23;
  Bool_t m12bool = dataWS->getRange(m2Kpi_d0mass,low12,hig12);
  Bool_t m13bool = dataWS->getRange(m2Kpi0_d0mass,low13,hig13);
  Bool_t m23bool = dataWS->getRange(m2pipi0_d0mass,low23,hig23);
  m2Kpi_d0mass.setRange(low12,hig12);
  m2Kpi0_d0mass.setRange(low13,hig13);
  m2pipi0_d0mass.setRange(low23,hig23);

  m2Kpi_d0mass.setBins(10);
  m2Kpi0_d0mass.setBins(10);
  d0Lifetime.setBins(8);
  d0LifetimeErr.setBins(10);
  m2pipi0_d0mass.setBins(10);

  Float_t total = pow(dalitzSpace.bigM(),2) + pow(dalitzSpace.mA(),2) + pow(dalitzSpace.mB(),2) + pow(dalitzSpace.mC(),2);
  RooRealVar totalm("totalm","totalm",total);
  RooFormulaVar mass13a("mass13a","@0-@1-@2",RooArgSet(totalm,m2Kpi_d0mass,m2pipi0_d0mass));

  //Construct signal pdf
  RooRealVar bias("bias","bias",0.0047) ;
  RooRealVar one("one","one",1.);

  //consider the resolution or the truth model
  RooGaussModel gm1("gm1","gauss model 1",d0Lifetime,bias,d0LifetimeErr,one,scalefact1) ;
  RooGaussModel gm2("gm2","gauss model 2",d0Lifetime,bias,d0LifetimeErr,one,scalefact2) ;
  RooGaussModel gm3("gm3","gauss model 3",d0Lifetime,bias,d0LifetimeErr,one,scalefact3) ;

  RooRealVar N1("N1","N1",0.0052);
  RooRealVar N2("N2","N2",0.179);

  RooFormulaVar f2("f2","f2","(1-@0)*@1",RooArgList(N1,N2));
  RooFormulaVar f3("f3","f3","(1-@0)*(1-@1)",RooArgList(N1,N2));
  RooAddModel gm("gm","gm",RooArgList(gm2,gm3,gm1),RooArgList(f2,f3));

  string dirname = "configmaps/effmapping_" + name + "/";

  RooTimepdf TOTsigD0("TOTsigD0","TOTsigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1,c2,-1,dirname);
  //RooTimepdf TOTsigantiD0("TOTsigantiD0","TOTsigantiD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1_unblind,c2_unblind,1);
 
  //RooSimultaneous TOTTime("TOTTime","TOTTime",D0flav);
  //TOTTime.addPdf(TOTsigD0,"D0");
  //TOTTime.addPdf(TOTsigantiD0,"antiD0");

  RooTimepdf TOTsigD023("TOTsigD023","TOTsigD023",d0Lifetime,m2Kpi_d0mass,mass13a,gm,&dalitzSpace,tau,c1,c2,-1,dirname);

  //////////////////////////
  // BACKGROUND
  /////////////////////////

  //Mistag parametrization
  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  m2pipi0_d0mass.setBins(150);
  d0Lifetime.setBins(70);

  TH3F *mis_h = m2Kpi_d0mass.createHistogram("mis_h",m2Kpi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_h,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  mis_h->Sumw2();
  RooDataHist *mis_hist = new RooDataHist("mis_hist","mis_hist",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),mis_h);
  RooHistPdf Tot_mis("Tot_mis","Tot_mis",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*mis_hist);

  TH3F *mis_h23 = m2Kpi_d0mass.createHistogram("mis_h",m2pipi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_h23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  mis_h23->Sumw2();
  RooDataHist *mis_hist23 = new RooDataHist("mis_hist23","mis_hist23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),mis_h23);
  RooHistPdf Tot_mis23("Tot_mis23","Tot_mis23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),*mis_hist23);

  m2Kpi_d0mass.setBins(10);
  m2Kpi0_d0mass.setBins(10);
  m2pipi0_d0mass.setBins(10);
  d0Lifetime.setBins(8);
  d0LifetimeErr.setBins(10);

  RooArgSet observ(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass);
  RooArgSet observ23(d0Lifetime,m2Kpi_d0mass,m2pipi0_d0mass);
  RooArgSet tot_var(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,d0LifetimeErr);

  //combinatoric
  RooDataSet *leftdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.75 && d0Mass < 1.77");
  RooDataSet *rightdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.95 && d0Mass < 1.97");
  RooDataSet *bkgdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.95 || d0Mass < 1.77");
  rightdata->setWeightVar(0);
  leftdata->setWeightVar(0);

  TH3F *lefth = m2Kpi_d0mass.createHistogram("lefth",m2Kpi0_d0mass,d0Lifetime,"");
  leftdata->fillHistogram(lefth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  TH3F *righth = m2Kpi_d0mass.createHistogram("righth",m2Kpi0_d0mass,d0Lifetime,"");
  rightdata->fillHistogram(righth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  righth->Scale(lefth->Integral()/righth->Integral());
  lefth->Sumw2();
  righth->Sumw2();
  lefth->Add(righth);
  lefth->Sumw2();
  RooDataHist *lefthist = new RooDataHist("lefthist","lefthist",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),lefth);
  RooHistPdf Tot_comb("Tot_comb","Tot_comb",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*lefthist);

  TH3F *lefth23 = m2Kpi_d0mass.createHistogram("lefth23",m2pipi0_d0mass,d0Lifetime,"");
  leftdata->fillHistogram(lefth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  TH3F *righth23 = m2Kpi_d0mass.createHistogram("righth23",m2pipi0_d0mass,d0Lifetime,"");
  rightdata->fillHistogram(righth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  righth23->Scale(lefth23->Integral()/righth23->Integral());
  lefth23->Sumw2();
  righth23->Sumw2();
  lefth23->Add(righth23);
  lefth23->Sumw2();
  RooDataHist *lefthist23 = new RooDataHist("lefthist23","lefthist23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),lefth23);
  RooHistPdf Tot_comb23("Tot_comb23","Tot_comb23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),*lefthist23);

  RooRealVar Nsig("Nsig","Nsig",1508.);
  RooRealVar Nmis("Nmis","Nmis",791.);
  RooRealVar Ncomb("Ncomb","Ncomb",(663. + 47.));

  d0LifetimeErr.setBins(100);
  RooDataSet *ProtoData_err = (RooDataSet*)RSdata->reduce(RooArgSet(d0LifetimeErr));
  TH1F *err_sig_h = (TH1F*)d0LifetimeErr.createHistogram("err_sig_h");
  ProtoData_err->fillHistogram(err_sig_h,RooArgSet(d0LifetimeErr));
  RooDataHist terr_sig("terr_sig","terr_sig",RooArgSet(d0LifetimeErr),err_sig_h);
  RooHistPdf terr_sig_pdf("terr_sig_pdf","terr_sig_pdf",RooArgSet(d0LifetimeErr),terr_sig,3);
  d0LifetimeErr.setBins(10);

  RooDataSet *ProtoData_bkg = (RooDataSet*)bkgdata->reduce(RooArgSet(d0LifetimeErr));
  TH1F *err_bkg_h = (TH1F*)d0LifetimeErr.createHistogram("err_bkg_h");
  ProtoData_bkg->fillHistogram(err_bkg_h,RooArgSet(d0LifetimeErr));
  err_bkg_h->Scale(err_sig_h->Integral()/err_bkg_h->Integral());
  RooDataHist terr_bkg("terr_bkg","terr_bkg",RooArgSet(d0LifetimeErr),err_bkg_h);
  RooHistPdf terr_bkg_pdf("terr_bkg_pdf","terr_bkg_pdf",RooArgSet(d0LifetimeErr),terr_bkg,3);

  RooProdPdf totsig_norm("totsig_norm","totsig_norm",RooArgSet(terr_sig_pdf),Conditional(TOTsigD0,observ));
  RooProdPdf totmis_norm("totmis_norm","totmis_norm",RooArgSet(terr_sig_pdf),Conditional(Tot_mis,observ));
  RooProdPdf totbkg_norm("totbkg_norm","totbkg_norm",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb,observ));

  RooProdPdf totsig_norm23("totsig_norm23","totsig_norm23",RooArgSet(terr_sig_pdf),Conditional(TOTsigD023,observ23));
  RooProdPdf totmis_norm23("totmis_norm23","totmis_norm23",RooArgSet(terr_sig_pdf),Conditional(Tot_mis23,observ23));
  RooProdPdf totbkg_norm23("totbkg_norm23","totbkg_norm23",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb23,observ23));

  //Signal + background
  RooAddPdf TOTpdf("TOTpdf","TOTpdf",RooArgList(totsig_norm,totmis_norm,totbkg_norm),RooArgList(Nsig,Nmis,Ncomb));
  RooAddPdf TOTpdf23("TOTpdf23","TOTpdf23",RooArgList(totsig_norm23,totmis_norm23,totbkg_norm23),RooArgList(Nsig,Nmis,Ncomb));

  if(doFit){

    RooFitResult *theRes = TOTpdf.fitTo(*dataWS,Save(1),Minos(0),Extended(0));

    string filename = "syst_root/fit_WS_" + name + ".root";
    TFile fout(filename.c_str(),"RECREATE");
    fout.cd();
    theRes->Write();
    fout.Close();
  }

  if(extract){
    TFile f("fitWS.root");
    RooFitResult* theRes = (RooFitResult*)f.Get("nll");
 
    RooRealVar myc1("myc1","myc1",-10.,10.);
    RooRealVar myc2("myc2","myc2",-10.,10.);
    RooRealVar myratio("myratio","myratio",0.,0.,1.);
    RooRealVar myx("myx","myx",0.,-1.,1.);
    RooRealVar myy("myy","myy",0.,-1.,1.);
 
    Double_t NrsNws = 2562./1132332.;
    Double_t ratioerr = sqrt(pow(89.,2.) + pow(NrsNws,2.)*pow(2862.,2.))/1132332.;
    RooDataSet *parFloat = new RooDataSet("parFloat","parFloat",RooArgList(myratio,myx,myy));
 
    for(Int_t j=0;j<400;j++){
      cout << "Performing step number " << j << endl;
      RooArgList floated = theRes->randomizePars();
      myc1.setVal(((RooAbsReal*)floated.find("c1"))->getVal());
      myc2.setVal(((RooAbsReal*)floated.find("c2"))->getVal());
 
      RooTimepdf mysigD0("mysigD0","mysigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,myc1,myc2,-1,dirname);
      Double_t myDenom = mysigD0.createIntegral(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime))->getVal();
      Double_t myNum = RooRandom::randomGenerator()->Gaus(NrsNws,ratioerr);
 
      myratio.setVal(myNum/myDenom);
      myx.setVal(myc2.getVal()*sqrt((myNum/myDenom)));
      myy.setVal(myc1.getVal()*sqrt((myNum/myDenom)));
 
      parFloat->add(RooArgSet(myratio,myx,myy));
    }
 
    TFile *f1 = new TFile("fitWS_float.root","RECREATE");
    f1->cd();
    parFloat->Write();
    f1->Close();
  }

  if(doChi2){
 
    m2Kpi_d0mass.setBins(40);
    m2Kpi0_d0mass.setBins(40);
 
    RooDataSet *dterr_ds = (RooDataSet*)dataWS->reduce(RooArgSet(d0LifetimeErr));
 
    TH2F *dphist_data = (TH2F*)m2Kpi_d0mass.createHistogram("dphist_data",m2Kpi0_d0mass);
    dataWS->fillHistogram(dphist_data,RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass));
 
    RooDataSet *pdf_ds = (RooDataSet*)TOTpdf.generate(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),dataWS->numEntries(),RooFit::ProtoData(*dterr_ds,1));
    TH2F *dphist = (TH2F*)m2Kpi_d0mass.createHistogram("dphist",m2Kpi0_d0mass);
    pdf_ds->fillHistogram(dphist,RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass));
 
    Int_t binx = m2Kpi_d0mass.getBinning().numBins();
    Int_t biny = m2Kpi0_d0mass.getBinning().numBins();
    Double_t chi2 = 0.;
    Int_t myBins = 0;
    Int_t nBin = 1;
 
    TH2F *pull_dal = (TH2F*)m2Kpi_d0mass.createHistogram("pull_dal",m2Kpi0_d0mass);
 
    dphist->Sumw2();
    dphist->Scale(dphist_data->Integral()/dphist->Integral());
    dphist->Sumw2();
 
    for(Int_t i=0;i<binx*biny;i++){
 
      Double_t chi_tmp = (dphist->GetBinContent(i)-dphist_data->GetBinContent(i))/dphist->GetBinError(i);
      Double_t nEv = dphist_data->GetBinContent(i);
      if(nEv == 0.) chi_tmp = 0.;
      pull_dal->SetBinContent(i,chi_tmp);
 
      if(nBin > 1){
	nBin--;
	//Double_t chi_tmp = (dphist->GetBinContent(i)-dphist_data->GetBinContent(i))/dphist->GetBinError(i);
	//pull_dal->SetBinContent(i,chi_tmp);
	continue;
      }
 
      if(nEv == 0.) continue;
      Double_t ndata = dphist_data->GetBinContent(i);
      Double_t npdf = dphist->GetBinContent(i);
      Double_t err = dphist->GetBinError(i);
      myBins++;
 
      while(nEv < 9.){
	if(dphist_data->GetBinContent(i+nBin) == 0. || dphist->GetBinError(i+nBin) == 0.){
	  nBin++;
	  continue;
	}
	ndata += dphist_data->GetBinContent(i+nBin);
	npdf += dphist->GetBinContent(i+nBin);
	err += sqrt(pow(err,2.) + pow(dphist->GetBinError(i+nBin),2.));
	nEv += dphist_data->GetBinContent(i+nBin);
	nBin++;
      }
 
      chi2 += pow((ndata-npdf)/err,2.);
    }
 
    Double_t chi2_root = dphist_data->Chi2Test(dphist,"UW");
 
    cout << "chi2 = " << chi2 << endl;
    cout << "chi2/ndof = " << chi2/(myBins -1.) << endl;
    cout << "mybins = " << myBins << endl;
    cout << "chi2 for root = " << chi2_root << endl;
 
    dphist_data->Sumw2();
    dphist->Sumw2();
    dphist_data->Add(dphist,-1.);
    dphist_data->SetMaximum(15.);

    dphist_data->SetMinimum(-15.);

    TCanvas c;
    c.Divide(1,2);
    c.cd(1);dphist_data->Draw("COLZ");
    c.cd(2);pull_dal->Draw("COLZ");
    c.SaveAs("WScomparison.eps");
    TFile fp("prova.root","RECREATE");
    dphist_data->Write();
    pull_dal->Write();
    fp.Close();
  }

  if(doPlots){
 
    m2Kpi_d0mass.setBins(20);
    m2Kpi0_d0mass.setBins(20);
    m2pipi0_d0mass.setBins(20);
    d0Lifetime.setBins(70);
 
    RooDataHist *dshist = new RooDataHist("dshist","dshist",RooArgSet(d0LifetimeErr),*dataWS);

    TH2F *lefth_t = m2Kpi_d0mass.createHistogram("lefth_t",m2Kpi0_d0mass);
    leftdata->fillHistogram(lefth_t,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
    TH2F *righth_t = m2Kpi_d0mass.createHistogram("righth_t",m2Kpi0_d0mass);
    rightdata->fillHistogram(righth_t,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
    righth_t->Scale(lefth_t->Integral()/righth_t->Integral());
    lefth_t->Sumw2();
    righth_t->Sumw2();
    lefth_t->Add(righth);
    lefth_t->Sumw2();
    TH1F *left_t = (TH1F*)d0Lifetime.createHistogram("left_t");
    leftdata->fillHistogram(left_t,RooArgList(d0Lifetime));
    TH1F *right_t = (TH1F*)d0Lifetime.createHistogram("right_t");
    rightdata->fillHistogram(right_t,RooArgList(d0Lifetime));
    right_t->Scale(left_t->Integral()/right_t->Integral());
    left_t->Sumw2();
    right_t->Sumw2();
    left_t->Add(right_t);
    left_t->Sumw2();
 
    RooDataHist *lefthist_d = new RooDataHist("lefthist_d","lefthist_d",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass),lefth_t);
    RooDataHist *lefthist_t = new RooDataHist("lefthist_t","lefthist_t",RooArgList(d0Lifetime),left_t);
    RooHistPdf left_plot("left_plot","left_plot",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*lefthist_d,6);
    RooHistPdf left_t_plot("left_t_plot","left_t_plot",RooArgSet(d0Lifetime),*lefthist_t,6);
 
    RooProdPdf tot_plot("tot_plot","tot_plot",left_plot,left_t_plot);
 
    RooProdPdf totbkg_norm_plot("totbkg_norm_plot","totbkg_norm_plot",RooArgSet(terr_bkg_pdf),Conditional(tot_plot,observ));
    RooAddPdf TOTpdf_plot("TOTpdf_plot","TOTpdf_plot",RooArgList(totsig_norm,totmis_norm,totbkg_norm_plot),RooArgList(Nsig,Nmis,Ncomb));

    RooPlot* tframe = d0Lifetime.frame();
    dataWS->plotOn(tframe,MarkerSize(0.1),DrawOption("z"));
    //TOTpdf.plotOn(tframe,Project(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0LifetimeErr)),ProjWData(*dshist));
    TOTpdf_plot.plotOn(tframe);
    Double_t chi2t = tframe->chiSquare();
    TOTpdf_plot.plotOn(tframe,Components(RooArgSet(totmis_norm,totbkg_norm_plot)),DrawOption("F"),FillColor(kBlue));       //FillColor(17));
    TOTpdf_plot.plotOn(tframe,Components(RooArgSet(totbkg_norm_plot)),DrawOption("F"),FillColor(kRed));                       //FillColor(14));
    tframe->getAttLine()->SetLineWidth(1);
    tframe->getAttLine()->SetLineStyle(1);
    tframe->SetTitle("");
    tframe->GetXaxis()->SetTitle("t_{K^{+}#pi^{-}#pi^{0}} [ps]");
    tframe->GetYaxis()->SetTitle("Events/0.08 ps");

    TPaveText *boxt = new TPaveText(2.5,2.5,2.7,2.7,"");
    boxt->AddText("(d)");
    boxt->SetFillColor(10);

    cout << "Chi2 for t = " << chi2t << endl;
    TCanvas ct("t","t",300,300);
    ct.cd();tframe->Draw();boxt->Draw("SAME");
    ct.SaveAs("WSfit_t.eps");

    //When we plot the 1D projection, need to calculate the 1D integral
    //set the precision here
    //cout << "config integrator " << endl;
    RooNumIntConfig *cfg = RooAbsReal::defaultIntegratorConfig();
    cfg->setEpsAbs(1E-5);
    cfg->setEpsRel(1E-5);
    cfg->method1D().setLabel("RooSegmentedIntegrator1D");
    //cfg.getConfigSection("RooSegmentedIntegrator1D").setRealValue("numSeg",3);
    //cfg->method1D()->Print("v");
    TOTsigD0.setIntegratorConfig(*cfg);
    //TOTsigantiD0.setIntegratorConfig(*cfg);
    TOTsigD023.setIntegratorConfig(*cfg);
    //TOTsigantiD023.setIntegratorConfig(*cfg);

    RooPlot* xframe = m2Kpi_d0mass.frame(53);  //was 19
    dataWS->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    xframe->getAttLine()->SetLineWidth(1);
    xframe->getAttLine()->SetLineStyle(1);
    xframe->SetTitle("");
    xframe->GetXaxis()->SetTitle("m^{2}_{K^{+}#pi^{-}}  [GeV^{2}/c^{4}]");
    xframe->GetYaxis()->SetTitle("Events/0.05 GeV^{2}/c^{4}");
    Double_t chi2Kpi = xframe->chiSquare();
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm,totbkg_norm)),DrawOption("F"),FillColor(kBlue)); //FillColor(17));
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm)),DrawOption("F"),FillColor(kRed)); //FillColor(14));
    dataWS->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));

    xframe->GetYaxis()->SetTitleOffset(1.3);

    TPaveText *box_m12 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m12->AddText("(b)");
    box_m12->SetFillColor(10);

    TCanvas c1("c1","c1",300,300);
    c1.cd();xframe->Draw();box_m12->Draw("SAME");
    c1.SaveAs("WSfit_m2Kpi.eps");

    m2Kpi0_d0mass.setBins(50);

    RooPlot* yframe = m2Kpi0_d0mass.frame(49);
    dataWS->plotOn(yframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    yframe->getAttLine()->SetLineWidth(1);
    yframe->getAttLine()->SetLineStyle(1);
    yframe->SetTitle("");
    yframe->GetYaxis()->SetTitle("Events/0.05 GeV^{2}/c^{4}");
    yframe->GetXaxis()->SetTitle("m^{2}_{K^{+}#pi^{0}}  [GeV^{2}/c^{4}]");
    Double_t chi2Kpi0 = yframe->chiSquare();
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm,totbkg_norm)),DrawOption("F"),FillColor(kBlue)); //FillColor(17));
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm)),DrawOption("F"),FillColor(kRed));  //FillColor(14));

    yframe->GetYaxis()->SetTitleOffset(1.3);

    TPaveText *box_m13 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m13->AddText("(c)");
    box_m13->SetFillColor(10);

    TCanvas c2("c2","c2",300,300);
    c2.cd();yframe->Draw();box_m13->Draw("SAME");
    c2.SaveAs("WSfit_m2Kpi0.eps");

    m2Kpi0_d0mass.setBins(20);

    RooPlot* zframe = m2pipi0_d0mass.frame(50);
    dataWS->plotOn(zframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    zframe->getAttLine()->SetLineWidth(1);
    zframe->getAttLine()->SetLineStyle(1);
    zframe->SetTitle("");
    zframe->GetYaxis()->SetTitle("Events/0.08 GeV^{2}/c^{4}");
    zframe->GetXaxis()->SetTitle("m^{2}_{#pi^{-}#pi^{0}} [GeV/c^{2}]");
    Double_t chi2pipi0 = zframe->chiSquare();
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm23,totbkg_norm23)),DrawOption("F"),FillColor(kBlue));
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm23)),DrawOption("F"),FillColor(kRed));

    cout << "Chi2 for Kpi = " << chi2Kpi << endl;
    cout << "Chi2 for Kpi0 = " << chi2Kpi0 << endl;
    cout << "Chi2 for pipi0 = " << chi2pipi0 << endl;

    TCanvas *c = new TCanvas("c","allevents",1200,400);
    c->Divide(3,1);
    c->cd(1);xframe->Draw();
    c->cd(2);yframe->Draw();
    c->cd(3);zframe->Draw();
    c->SaveAs("WSfit.eps");

  }

  if(doFrac){
    cout << "Calculating fit fractions" << endl;
    TFile f("fitWS.root");
    RooFitResult* fitRes = (RooFitResult*)f.Get("nll");
 
    //now calculate the fit fractions
    const Int_t nRes = TOTsigD0.getManager()->getnRes();
 
    //recalculate the normalization if necessary
    //TOTsigD0.getManager()->calNorm();
 
    EvtComplex normarray[nRes][nRes];
 
    const Int_t myRes = 7;
    TH1F fitty[myRes];
 
    //read the integral value from the cache file.
    //In this way we don't need to compute the normalization everytime during MIGRAD
    char int_name[50];
    TOTsigD0.getManager()->getFileName(int_name);
 
    ifstream f1;
    f1.open(int_name);
    if (!f1){
      cout << "Error opening file " << endl;
      assert(0);
    }
   
    Double_t re=0.,im=0.;
    //Read in the cache file and store back to array
    for(Int_t j=0;j<nRes;j++) {
      char thname[100];
      sprintf(thname,"thname_%d",j);
      if(j < myRes) fitty[j] = TH1F(thname,thname,30,0.,1.);
      for(Int_t k=0;k<nRes;k++){
	f1 >> re >> im;       
	normarray[j][k] = EvtComplex(re,im);
      }
    }   
    EvtComplex mynorm[myRes][myRes];
    Int_t m = 0, l = 0;
    for(Int_t i=0;i<myRes;i++){
      for(Int_t j=0;j<myRes;j++){
	if(i==0) l = 11;
	else if(i==1) l = 5;
	else if(i==2) l = 3;
	else if(i==3) l = 10;
	else if(i==4) l = 8;
	else if(i==5) l = 2;
	else if(i==6) l = 0;
 
	if(j==0) m = 11;
	else if(j==1) m = 5;
	else if(j==2) m = 3;
	else if(j==3) m = 10;
	else if(j==4) m = 8;
	else if(j==5) m = 2;
	else if(j==6) m = 0;
 
	mynorm[i][j] = normarray[l][m];
      }
    }
 
    //do 100 experiments and extract parameters using covariance matrix
    for(Int_t l=0;l<200;l++){
      RooArgList listpar = fitRes->randomizePars();
      if(l==0) listpar.Print();

      Double_t mynormD0 = 0.;
      EvtComplex coeff_i(0.,0.), coeff_j(0.,0.);
      for(Int_t i=0;i<2*myRes;i++){
        for(Int_t j=0;j<2*myRes;j++){
          if(i==(2*myRes - 2)) coeff_i = EvtComplex(1.,0.);
          else coeff_i = EvtComplex(((RooAbsReal*)listpar.at(i))->getVal()*cos(((RooAbsReal*)listpar.at(i+1))->getVal()),
                                    ((RooAbsReal*)listpar.at(i))->getVal()*sin(((RooAbsReal*)listpar.at(i+1))->getVal()));

          if(j==(2*myRes - 2)) coeff_j = EvtComplex(1.,0.);
          else coeff_j = EvtComplex(((RooAbsReal*)listpar.at(j))->getVal()*cos(((RooAbsReal*)listpar.at(j+1))->getVal()),
                                    ((RooAbsReal*)listpar.at(j))->getVal()*sin(((RooAbsReal*)listpar.at(j+1))->getVal()));
          mynormD0 += real(coeff_i*conj(coeff_j)*(mynorm[i/2][j/2]));
          j++;
        }
        i++;
      }

      //now calculate the fit fractions
      for(Int_t i=0;i<2*myRes;i++){
        Double_t fitfrac = 0.;
        if(i==(2*myRes - 2)) fitfrac = abs(mynorm[i/2][i/2])/mynormD0;
        else fitfrac = abs2( ((RooAbsReal*)listpar.at(i))->getVal())*abs(mynorm[i/2][i/2])/mynormD0;
        fitty[i/2].Fill(fitfrac);
        i++;
      }
    }// nexperiments

    Double_t tot_frac = 0.;
    for(Int_t i=0;i<myRes;i++){
      tot_frac += fitty[i].GetMean();
      cout << "Resonance " << i << ": fit fraction = " << fitty[i].GetMean() << " +/- " << fitty[i].GetRMS() << endl;
    }
    cout << "Total fit fraction = " << tot_frac << endl;
    cout << "///////////////////////////" << endl;
  }

  return 0;
}