Beispiel #1
0
void makeTable(TString rootfilename, 
	       TString histname, char* tablefilename)
{

  TFile myhistos(rootfilename); 
  TH2F* h = (TH2F*) myhistos.Get(histname);
  int nX = h->GetNbinsX();
  int nY = h->GetNbinsY();


  FILE *file = fopen(tablefilename,"w+");


  for(int i=1; i<=nX; ++i) {
  
    Double_t pT0 = h->GetXaxis()->GetBinLowEdge(i);
    Double_t pT1 = h->GetXaxis()->GetBinLowEdge(i+1);

    for(int j=1; j<=nY; ++j) {
      Double_t x = h->GetBinContent(i,j);
      Double_t dx = 8.0 * h->GetBinError(i,j);
      if( dx > 1.0 ) dx = 1.0;
      Double_t eta0 = h->GetYaxis()->GetBinLowEdge(j);
      Double_t eta1 = h->GetYaxis()->GetBinLowEdge(j+1);

      fprintf( file ,"%4.1f  %4.1f   %+6.4f   %+6.4f  %6.4f   %6.4f \n", 
	       pT0, pT1, eta0, eta1, x, dx);
    }
  }

  fclose(file);
}
Beispiel #2
0
void shakeErrors(TString inFileName, TString histName){
  TFile inFile(inFileName);
  TH2F* h = (TH2F*)gROOT->FindObject(histName);
  if(!h){
    std::cout<<"Could not access histogram!"<<std::endl;
    return;
  }

  TFile lowFile(TString("low_")+inFileName,"recreate");
  TH2F* hLow = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hLow->SetBinContent( i, h->GetBinContent(i)-h->GetBinError(i) );
  }
  hLow->Write();
  lowFile.Close();

  TFile hiFile(TString("hi_")+inFileName,"recreate");
  TH2F* hHi = (TH2F*)h->Clone(histName);
  for(int i=0; i<h->GetSize(); i++){
    hHi->SetBinContent( i, h->GetBinContent(i)+h->GetBinError(i) );
  }
  hHi->Write();
  hiFile.Close();
}
void cetaflatHFP12(int nIterN=1, double Ethr1=10, double Ethr2=150) {
  
  gStyle->SetOptLogz(0);
  gStyle->SetMarkerSize(0.7);
  gStyle->SetMarkerStyle(20);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);
  gStyle->SetTitleOffset(1.7,"Y");
  gStyle->SetTitleOffset(0.9,"X");
  //gStyle->SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  gStyle->SetPadLeftMargin(0.18);
  //gStyle->SetNdivisions(516);
  gStyle->SetStatH(0.025);
  gStyle->SetStatW(0.3);
  gStyle->SetTitleW(0.4);
  gStyle->SetTitleX(0.28);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();

  char ctit[245],ftit[245];
  float etaBounds[14] = {2.853,2.964,3.139,3.314,3.489,3.664,3.839,4.013,4.191,4.363,4.538,4.716,4.889,5.205};

  // ------Histos input: spectra of all channels-----------------------------------

  //sprintf(ftit,"%s","phi43val2012A");
  //sprintf(ftit,"%s","phi2012A_May");
  //sprintf(ftit,"%s","phiSym524_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012AB");
  //sprintf(ftit,"%s","phiSym524newGain_2012ABC");
  //sprintf(ftit,"%s","phisymNewCond2012Cval");
  //sprintf(ftit,"%s","phisymOldCond2012Cval");
  //sprintf(ftit,"%s","phiSym533Gain507_2012D");
  sprintf(ftit,"%s","phiSym533Corr45Gain507_2012D");

  sprintf(ctit,"/home/vodib/beam12/intercal/%s.root",ftit);
  TFile *fila = new TFile (ctit);
  cout<<"File= "<<ctit<<endl;

  TH1F *hcounter =   new TH1F(*((TH1F*)fila->Get("phaseHF/hcounter")));
  cout<<"Stat= "<<hcounter->GetBinContent(2)<<endl;
  cout<<"E within: "<<Ethr1<<" - "<<Ethr2<<endl;

  TH2F* hLmapP = new TH2F("hLmapP","E L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapP = new TH2F("hSmapP","E S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hLmapP0 = new TH2F("hLmapP0","E0 L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapP0 = new TH2F("hSmapP0","E0 S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hLmapPc = new TH2F("hLmapPc","corr L HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  TH2F* hSmapPc = new TH2F("hSmapPc","corr S HFP;i#eta;i#phi",13,28.5,41.5,36,0,72);
  hLmapPc->Sumw2(); hSmapPc->Sumw2();
  //TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",300,0.5,2);
  //TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",300,0.5,2);
  TH1F *hLcorr1D = new TH1F("hLcorr1D","Corr L",180,0.7,1.5);
  TH1F *hScorr1D = new TH1F("hScorr1D","Corr S",180,0.7,1.5);
  TH1F *hLdatP[13][36], *hSdatP[13][36], *hLdatPx[13][36], *hSdatPx[13][36];
  for (int ii=0;ii<13;ii++) for (int jj=0;jj<36;jj++) {
    sprintf(ctit,"hL%d_%d",ii+29,2*jj+1);
    hLdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
    sprintf(ctit,"hS%d_%d",ii+29,2*jj+1);
    hSdatP[ii][jj] = new TH1F(ctit,ctit,8000,0,250);
  }
  TH1F *htL = new TH1F("htL","htL",20000,0,7e8/3.);
  TH1F *htS = new TH1F("htS","htS",20000,0,5e8/3.);
  //TH1F *htL = new TH1F("htL","htL",20000,0,4e8/40);
  //TH1F *htS = new TH1F("htS","htS",20000,0,2e8/40);
  TH1F *hLdatPx[13][36], *hSdatPx[13][36];

  TCanvas *cLx[200],*cSx[200];
  TSpline5 *ttL,*ttS;

  Double_t x,y,rPL,rPS,drPL,drPS,mLE,mSE,ermean,rms;
  Double_t xxL[1000],yyL[1000];
  Double_t xxS[1000],yyS[1000];
  Int_t nELP, nESP, nIter=0;
  Double_t mcorrL,scorrL,mcorrS,scorrS,erLP,erSP,rLP,drLP,rSP,drSP,corrL,corrS,dcorrL,dcorrS;
  double mLEphi[13],mSEphi[13],dmLEphi[13],dmSEphi[13];

  TCanvas *ccxx = new TCanvas("ccxx","ccxx",100,300,900,500);
  ccxx->Divide(2,1);

  for (int ii=0;ii<13;ii++) {
  //for (int ii=1;ii<2;ii++) {
    int ieta=ii+29;

    mLE=mSE=0;   // ------------------for initial condition
    int nmLE=0, nmSE=0;
    htL->Reset(); htS->Reset();
    for (int ll=1;ll<=72;ll+=2) {
      int iphi=ll;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      hSmapPc->SetBinContent(ii+1,ll/2+1,1);
      hLmapPc->SetBinContent(ii+1,ll/2+1,1);
      hSmapPc->SetBinError(ii+1,ll/2+1,1.e-6);
      hLmapPc->SetBinError(ii+1,ll/2+1,1.e-6);
      sprintf(ctit,"phaseHF/espec/E_+%d_%d_1",ieta,iphi);
      hLdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
      hLdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rLP = hLdatPx[ii][ll/2]->Integral()*hLdatPx[ii][ll/2]->GetMean();
      hLmapP0->SetBinContent(ii+1,ll/2+1,rLP);
      sprintf(ctit,"phaseHF/espec/E_+%d_%d_2",ieta,iphi);
      hSdatPx[ii][ll/2]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
      hSdatPx[ii][ll/2]->SetAxisRange(Ethr1,Ethr2);
      rSP = hSdatPx[ii][ll/2]->Integral()*hSdatPx[ii][ll/2]->GetMean();
      hSmapP0->SetBinContent(ii+1,ll/2+1,rSP);
      if (ieta<=32 && iphi==67) continue;
      if (rLP>0) {
	htL->Fill(rLP);
	mLE += rLP;
	nmLE++;
      }
      if (rSP>0) {
	htS->Fill(rSP);
	mSE += rSP;
	nmSE++;
      }
    }
    if (nmLE>0) mLE /= nmLE; 
    else continue;
    if (nmSE>0) mSE /= nmSE; 
    else continue;
    ccxx->cd(1); htL->Draw("hist");
    ccxx->cd(2); htS->Draw("hist");
    ccxx->Update();
    //histspec(htL,mLE,ermean,rms,4,3);
    //histspec(htS,mSE,ermean,rms,4,3);
    mLEphi[ii]=mLE;
    mSEphi[ii]=mSE;
    dmLEphi[ii]=htL->GetRMS();
    dmSEphi[ii]=htS->GetRMS();
    printf("ieta %2d :  <E>L= %8.1f (%6.1f) x %d    <E>S= %8.1f (%6.1f) x %d \n",
	   ieta,mLE,dmLEphi[ii],nmLE,mSE,dmSEphi[ii],nmSE);
    
    for (int jj=1;jj<=72;jj+=2) {
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      if (ieta<=32 && iphi==67) {
	hLmapP->SetBinContent(ii+1,jj/2+1,hLmapP0->GetBinContent(ii+1,jj/2+1));
	hSmapP->SetBinContent(ii+1,jj/2+1,hSmapP0->GetBinContent(ii+1,jj/2+1));
	continue;
      }

      for (nIter=1;nIter<nIterN;nIter++) { //cout<<nIter<<" |  ";
	corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
	hLdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hLdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxL[kk-1]=hLdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyL[kk-1]=hLdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttL = new TSpline5("tt",xxL,yyL,1000,"",10,20);

	for (int kk=1;kk<=hLdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hLdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hLdatP[ii][jj/2]->GetBinContent(kk);
	  hLdatP[ii][jj/2]->Fill(x*corrL,ttL->Eval(x)/8.0);
	}
	ttL->Delete();

	hLdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rLP = hLdatP[ii][jj/2]->Integral()*hLdatP[ii][jj/2]->GetMean();
	dcorrL=(rLP-mLE)/mLE;
	if (rLP>0) drLP=
	      sqrt(pow(hLdatP[ii][jj/2]->GetMeanError()/hLdatP[ii][jj/2]->GetMean(),2)+
		   1.f/hLdatP[ii][jj/2]->Integral()+
		   pow(dcorrL/(1.0+sqrt((float) nIter)),2));
	else drLP=1.e-6;
	if (fabs(dcorrL)>0.001) { 
	  corrL*=1-dcorrL/(1.0+sqrt((float) nIter));
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrL,corrL);
	  hLmapPc->SetBinContent(ii+1,jj/2+1,corrL);
	  hLmapPc->SetBinError(ii+1,jj/2+1,corrL*drLP);
	  hLmapP->SetBinContent(ii+1,jj/2+1,rLP);
	}
	else {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	  hLmapP->SetBinContent(ii+1,jj/2+1,rLP);
	  hLmapPc->SetBinError(ii+1,jj/2+1,corrL*drLP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 1 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
	}
      }

      for (nIter=1;nIter<nIterN;nIter++) { //cout<<nIter<<" |  ";
	corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
	hSdatP[ii][jj/2]->Reset();

	for (int kk=1;kk<=hSdatPx[ii][jj/2]->GetNbinsX();kk++) {
	  xxS[kk-1]=hSdatPx[ii][jj/2]->GetBinCenter(kk);
	  yyS[kk-1]=hSdatPx[ii][jj/2]->GetBinContent(kk);
	}
	ttS = new TSpline5("tt",xxS,yyS,1000,"",10,20);

	for (int kk=1;kk<=hSdatP[ii][jj/2]->GetNbinsX();kk++) {
	  x=hSdatP[ii][jj/2]->GetBinCenter(kk);
	  y=hSdatP[ii][jj/2]->GetBinContent(kk);
	  hSdatP[ii][jj/2]->Fill(x*corrS,ttS->Eval(x)/8.0);
	}
	ttS->Delete();

	hSdatP[ii][jj/2]->SetAxisRange(Ethr1,Ethr2);
	rSP = hSdatP[ii][jj/2]->Integral()*hSdatP[ii][jj/2]->GetMean();
	dcorrS=(rSP-mSE)/mSE;
	if (rSP>0) drSP=sqrt(pow(hSdatP[ii][jj/2]->GetMeanError()/hSdatP[ii][jj/2]->GetMean(),2)+
			     1.f/hSdatP[ii][jj/2]->Integral()+
			     pow(dcorrS/(1.0+sqrt((float) nIter)),2));
	else drSP=1.e-6;
	if (fabs(dcorrS)>0.001) { 
	  corrS*=1-dcorrS/(1.0+sqrt((float) nIter));
	  //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrS,corrS);
	  hSmapPc->SetBinContent(ii+1,jj/2+1,corrS);
	  hSmapPc->SetBinError(ii+1,jj/2+1,corrS*drSP);
	  hSmapP->SetBinContent(ii+1,jj/2+1,rSP);
	}
	else {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	  hSmapP->SetBinContent(ii+1,jj/2+1,rSP);
	  hSmapPc->SetBinError(ii+1,jj/2+1,corrS*drSP);
	  break;
	}
	if (nIter==nIterN-1) {
	  printf("%2d : %2d / %2d / 2 %7.3f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrS,corrS,corrS*drSP);
	}
      }
    }
  }
  //fila->Close();

  cout<<endl<<"Rings :  "<<endl;
  cout<<"       E L        "<<"E S        "<<"eta     "<<"delta eta"<<endl;
  double xeta[13], weta[13], reta[13];
  for (int i=29;i<=41;i++) {
    xeta[i-29]=(etaBounds[i-28]+etaBounds[i-29])/2;
    weta[i-29]=(etaBounds[i-28]-etaBounds[i-29]);
    mLEphi[i-29]=mLEphi[i-29]*36/weta[i-29];
    mSEphi[i-29]=mSEphi[i-29]*36/weta[i-29];
    dmLEphi[i-29]=dmLEphi[i-29]*36/weta[i-29];
    dmSEphi[i-29]=dmSEphi[i-29]*36/weta[i-29];
    if (i>39) {  mLEphi[i-29]/=2; mSEphi[i-29]/=2; dmLEphi[i-29]/=2; dmSEphi[i-29]/=2; }
    reta[i-29] = mSEphi[i-29]/mLEphi[i-29];
    cout<<i<<" :  "<<mLEphi[i-29]<<"    "<<mSEphi[i-29]<<"    "<<xeta[i-29]<<"   "<<weta[i-29]<<endl;
  }
  TCanvas *cgL = new TCanvas("cgL","cgL",300,300,600,600);
  TGraphErrors *grL = new TGraphErrors(13,xeta,mLEphi,0,dmLEphi);
  grL->SetTitle("HFP L;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grL->SetMinimum(0);
  grL->SetMarkerStyle(20);
  grL->Draw("1+PAl");
  cgL->Print("pictHFplot/etaProfHFPL.gif");
  mSEphi[12]/=2; mSEphi[11]/=2;
  TCanvas *cgS = new TCanvas("cgS","cgS",300,300,600,600);
  TGraphErrors *grS = new TGraphErrors(13,xeta,mSEphi,0,dmSEphi);
  grS->SetTitle("HFP S;#eta;E_{Ring} / #Delta#eta_{Ring} ,  GeV");
  grS->SetMinimum(0);
  grS->SetMarkerStyle(20);
  grS->Draw("1+PAl");
  cgS->Print("pictHFplot/etaProfHFPS.gif");
  TCanvas *crg = new TCanvas("crg","crg",300,300,600,600);
  TGraphErrors *rg = new TGraphErrors(13,xeta,reta,0,0);
  rg->SetTitle("HFP;#eta;E(S) / E(L)");
  rg->SetMinimum(0);
  rg->Draw("1+PAl");
  crg->Print("pictHFplot/SoverLetaHFP.gif");

  TCanvas *cL0 = new TCanvas("cL0","cL0",0,0,650,600);
  hLmapP0->Draw("colz");
  cL0->Update();
  TCanvas *cS = new TCanvas("cS0","cS0",1000,0,650,600);
  hSmapP0->Draw("colz");
  cS0->Update();

  //TFile *histf = new TFile("HFPmc.root","RECREATE");

  FILE *ft1;
  //sprintf(ctit,"corrHFPmc_%d_%d.txt",((int) Ethr1),((int) Ethr2));
  sprintf(ctit,"corrHFP_%s_%d_%d.txt",ftit,((int) Ethr1),((int) Ethr2));
  if ((ft1 = fopen(ctit,"w"))==NULL){               // Open new file
    printf("\nNo file %s open => EXIT\n\n",file);
    return;
  }
  printf("\n\n File '%s' open \n\n",ctit);

  TH1D *hprL[13],*hprS[13],*hprL0[13],*hprS0[13];
  TH1D *hprcL[13],*hprcS[13];
  TCanvas *cpr[13],*ccc[13];
  TLine *lin1 = new TLine(0,1,71,1); lin1->SetLineWidth(1);

  int noff=0;
  for (int ii=0;ii<13;ii++) {

    sprintf(ctit,"HFPcorr_%d_L",ii+29);  // draw corrections
    hprcL[ii] = hLmapPc->ProjectionY(ctit,ii+1,ii+1);
    hprcL[ii]->SetTitle(ctit);
    sprintf(ctit,"HFPcorr_%d_S",ii+29);
    hprcS[ii] = hSmapPc->ProjectionY(ctit,ii+1,ii+1);
    hprcS[ii]->SetTitle(ctit);
    ccc[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    ccc[ii]->Divide(1,2);
    ccc[ii]->cd(1);
    if (ii+29>39) {
      hprcL[ii]->Rebin(2);
      hprcS[ii]->Rebin(2);
    }
    hprcL[ii]->SetMinimum(0);
    hprcL[ii]->SetTitleOffset(0.9,"X");
    hprcL[ii]->Draw("e");
    lin1->Draw();
    ccc[ii]->cd(2);
    hprcS[ii]->SetMinimum(0);
    hprcS[ii]->SetTitleOffset(0.9,"X");
    hprcS[ii]->Draw("e");
    lin1->Draw();
    sprintf(ctit,"pictHFplot/HFPcorr_%d.gif",ii+29);
    ccc[ii]->Update();
    ccc[ii]->Print(ctit);
    //hprcL[ii]->Write();
    //hprcS[ii]->Write();

    sprintf(ctit,"HFP_%d_L",ii+29);  //  draw E depositions
    hprL0[ii] = hLmapP0->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_L;i#phi;GeV;",29+ii);  //  draw E depositions
    hprL0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFP_L_%d",ii+29);
    hprL[ii] = hLmapP->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_S",ii+29);
    hprS0[ii] = hSmapP0->ProjectionY(ctit,ii+1,ii+1);
    sprintf(ctit,"HFP_%d_S;i#phi;GeV;",29+ii);  //  draw E depositions
    hprS0[ii]->SetTitle(ctit);
    sprintf(ctit,"HFP_S_%d",ii+29);
    hprS[ii] = hSmapP->ProjectionY(ctit,ii+1,ii+1);

    cpr[ii] = new TCanvas(ctit,ctit,800,100,500,900);
    cpr[ii]->Divide(1,2);
    cpr[ii]->cd(1);
    if (ii+29>39) {
      hprL0[ii]->Rebin(2);
      hprL[ii]->Rebin(2);
      hprS0[ii]->Rebin(2);
      hprS[ii]->Rebin(2);
    }
    hprL0[ii]->SetFillColor(3);hprL0[ii]->SetLineColor(3);hprL0[ii]->SetLineWidth(3);
    hprL0[ii]->SetMinimum(0);
    hprL0[ii]->SetTitleOffset(0.9,"X");
    hprL0[ii]->Draw("hist");
    hprL[ii]->Draw("samehist");
    cpr[ii]->cd(2);
    hprS0[ii]->SetMinimum(0);
    hprS0[ii]->SetTitleOffset(0.9,"X");
    hprS0[ii]->SetFillColor(3);hprS0[ii]->SetLineColor(3);hprS0[ii]->SetLineWidth(3);
    hprS0[ii]->Draw("hist");
    hprS[ii]->Draw("samehist");
    sprintf(ctit,"pictHFplot/HFP_%d.gif",ii+29);
    cpr[ii]->Print(ctit);
    //hprS0[ii]->Write();
    //hprL0[ii]->Write();

    cout<<"Results : "<<endl;
    for (int jj=1;jj<=72;jj+=2) {
      int ieta=ii+29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      //if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
      corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
      dcorrL=hLmapPc->GetBinError(ii+1,jj/2+1);
      dcorrS=hSmapPc->GetBinError(ii+1,jj/2+1);
      hLcorr1D->Fill(corrL); hScorr1D->Fill(corrS);
      noff++;
      //printf("%2d : %2d / %2d / 1 %9.4f %9.4f\n",noff,ieta,iphi,corrL,dcorrL);
      fprintf(ft1,"%2d   %2d   1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      noff++;
      //printf("%2d : %2d / %2d / 2 %9.4f %9.4f\n",noff,ieta,iphi,corrS,dcorrS);
      fprintf(ft1,"%2d   %2d   2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
    }
  }
  fclose(ft1);

  for (int ii=0;ii<13;ii++) for (int jj=1;jj<=72;jj+=2) {
      int ieta=ii+29;
      int iphi=jj;
      if (abs(ieta)>39 && (iphi-1)%4==0) continue;
      if (ieta==29 && iphi==67) continue;
      corrL=hLmapPc->GetBinContent(ii+1,jj/2+1);
      if (fabs(corrL-1)>0.16) printf("%2d / %2d / 1 %9.4f %9.4f\n",ieta,iphi,corrL,dcorrL);
      corrS=hSmapPc->GetBinContent(ii+1,jj/2+1);
      if (fabs(corrS-1)>0.16) printf("%2d / %2d / 2 %9.4f %9.4f\n",ieta,iphi,corrS,dcorrS);
  }

  TCanvas *cLcorr =new TCanvas("cLcorr","cLcorr",30,30,600,600);
  cLcorr->SetRightMargin(0.12);
  hLmapPc->SetAxisRange(0.6,1.6,"Z");
  hLmapPc->Draw("colz");
  TCanvas *cScorr =new TCanvas("cScorr","cScorr",30,300,600,600);
  cScorr->SetRightMargin(0.12);
  hSmapPc->SetAxisRange(0.6,1.6,"Z");
  hSmapPc->Draw("colz");

  TCanvas *cL = new TCanvas("cL","cL",0,0,650,600);
  hLmapP->Draw("colz");
  cL->Update();
  TCanvas *cS = new TCanvas("cS","cS",1000,0,650,600);
  hSmapP->Draw("colz");
  cS->Update();

  TCanvas *c1corr =new TCanvas("c1corr","c1corr",30,30,900,500);
  c1corr->Divide(2,1);
  c1corr->cd(1);  hLcorr1D->Draw("hist");  histStat(hLcorr1D,1);
  c1corr->cd(2);  hScorr1D->Draw("hist");  histStat(hScorr1D,1);
  //hLcorr1D->Write(); hScorr1D->Write();  

  c1corr->Print("pictHFplot/corrHFP.gif");
  //c1corr->Print("pictHFmc/corrHFP.gif");
  c1corr->Update();
  
  //fila->Close();
  //histf->Close();

  sprintf(ctit,"HFPo_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
  TFile *histf = new TFile(ctit,"RECREATE");
  hLcorr1D->Write(); 
  hScorr1D->Write();  
  hLmapP->Write(); 
  hLmapP0->Write(); 
  hLmapPc->Write(); 
  hSmapP->Write(); 
  hSmapP0->Write(); 
  hSmapPc->Write(); 
  grL->Write();
  grS->Write();
  histf->Close();
}
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;
}
Beispiel #5
0
void btag_eff_calc(const TString flavour="b", const TString tagger="CSVL",const bool rebin=false){

  const TString path = "/gpfs/cms/users/casarsa/analysis/Zc/work/output/v10/";
  const TString filename = "DYJetsToLL.root";


  f = new TFile(path+filename);


  // --- Read ee and mm histigrams:
  h_numL_b_0[1] = (TH2F*) f->Get("anaEle/hc_CSVL_eff_b");
  h_numL_c_0[1] = (TH2F*) f->Get("anaEle/hc_CSVL_eff_c");
  h_numL_l_0[1] = (TH2F*) f->Get("anaEle/hc_CSVL_eff_l");
  h_numL_b_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVL_eff_b");
  h_numL_c_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVL_eff_c");
  h_numL_l_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVL_eff_l");

  h_numT_b_0[1] = (TH2F*) f->Get("anaEle/hc_CSVT_eff_b");
  h_numT_c_0[1] = (TH2F*) f->Get("anaEle/hc_CSVT_eff_c");
  h_numT_l_0[1] = (TH2F*) f->Get("anaEle/hc_CSVT_eff_l");
  h_numT_b_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVT_eff_b");
  h_numT_c_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVT_eff_c");
  h_numT_l_0[2] = (TH2F*) f->Get("anaMuo/hc_CSVT_eff_l");

  h_den_b_0[1] = (TH2F*) f->Get("anaEle/h_eff_b");
  h_den_c_0[1] = (TH2F*) f->Get("anaEle/h_eff_c");
  h_den_l_0[1] = (TH2F*) f->Get("anaEle/h_eff_l");
  h_den_b_0[2] = (TH2F*) f->Get("anaMuo/h_eff_b");
  h_den_c_0[2] = (TH2F*) f->Get("anaMuo/h_eff_c");
  h_den_l_0[2] = (TH2F*) f->Get("anaMuo/h_eff_l");


  // --- Rebin the histograms
  
  if (rebin) {

    // original binning:
    // 20., 30., 40., 50., 60., 70., 80., 100., 120., 160., 210., 260., 320., 400., 500., 600., 800.

    // for b jets
    const Double_t xbins[] = {20, 30, 40, 50, 60, 70, 80, 100, 120, 800};
    const Double_t ybins[] = {-2.4, -1.5, -1.0, -0.5, 0., 0.5, 1.0, 1.5, 2.4};
    const int nx = 9;
    const int ny = 8;

    // for c jets
    //const Double_t xbins[] = {20, 30, 40, 50, 60, 70, 80, 100, 120, 800};
    //const Double_t ybins[] = {-2.4, -1., -0., 1., 2.4};
    //const int nx = 9;
    //const int ny = 4;

    
    // for light jets CSVL
    //const Double_t xbins[] = {20, 30, 40, 50, 60, 70, 80, 100, 120, 160, 210, 800};
    //const Double_t ybins[] = {-2.4, -1.5, -1.0, -0.5, 0., 0.5, 1.0, 1.5, 2.4};
    //const int nx = 11;
    //const int ny = 8;

    
    // for light jets CSVT
    //const Double_t xbins[] = {20, 30, 40, 50, 60, 70, 80, 100, 120, 160, 800};
    //const Double_t ybins[] = {-2.4, 2.4};
    //const int nx = 10;
    //const int ny = 1;


    for (int i=1;i<3; ++i) {
      h_numL_b[i] = histo_rebin( h_numL_b_0[i], nx, xbins, ny, ybins);
      h_numL_c[i] = histo_rebin( h_numL_c_0[i], nx, xbins, ny, ybins);
      h_numL_l[i] = histo_rebin( h_numL_l_0[i], nx, xbins, ny, ybins);
      h_numT_b[i] = histo_rebin( h_numT_b_0[i], nx, xbins, ny, ybins);
      h_numT_c[i] = histo_rebin( h_numT_c_0[i], nx, xbins, ny, ybins);
      h_numT_l[i] = histo_rebin( h_numT_l_0[i], nx, xbins, ny, ybins);
      h_den_b[i]  = histo_rebin( h_den_b_0[i],  nx, xbins, ny, ybins);
      h_den_c[i]  = histo_rebin( h_den_c_0[i],  nx, xbins, ny, ybins); 
      h_den_l[i]  = histo_rebin( h_den_l_0[i],  nx, xbins, ny, ybins); 
    }

  }
  else {

    for (int i=1;i<3; ++i) {
      h_numL_b[i] = h_numL_b_0[i];
      h_numL_c[i] = h_numL_c_0[i];
      h_numL_l[i] = h_numL_l_0[i];
      h_numT_b[i] = h_numT_b_0[i];
      h_numT_c[i] = h_numT_c_0[i];
      h_numT_l[i] = h_numT_l_0[i];
      h_den_b[i]  = h_den_b_0[i];
      h_den_c[i]  = h_den_c_0[i]; 
      h_den_l[i]  = h_den_l_0[i]; 
    }

  }

  
  // --- Sum ee and mm histograms:
  h_numL_b[0] = (TH2F*) h_numL_b[1]->Clone("h_numL_b");
  h_numL_b[0]->Add(h_numL_b[2]);
  h_numL_c[0] = (TH2F*) h_numL_c[1]->Clone("h_numL_c");
  h_numL_c[0]->Add(h_numL_c[2]);
  h_numL_l[0] = (TH2F*) h_numL_l[1]->Clone("h_numL_l");
  h_numL_l[0]->Add(h_numL_l[2]);

  h_numT_b[0] = (TH2F*) h_numT_b[1]->Clone("h_numT_b");
  h_numT_b[0]->Add(h_numT_b[2]);
  h_numT_c[0] = (TH2F*) h_numT_c[1]->Clone("h_numT_c");
  h_numT_c[0]->Add(h_numT_c[2]);
  h_numT_l[0] = (TH2F*) h_numT_l[1]->Clone("h_numT_l");
  h_numT_l[0]->Add(h_numT_l[2]);

  h_den_b[0] = (TH2F*) h_den_b[1]->Clone("h_den_b");
  h_den_b[0]->Add(h_den_b[2]);
  h_den_c[0] = (TH2F*) h_den_c[1]->Clone("h_den_c");
  h_den_c[0]->Add(h_den_c[2]);
  h_den_l[0] = (TH2F*) h_den_l[1]->Clone("h_den_l");
  h_den_l[0]->Add(h_den_l[2]);



  // --- Calculate ratios:
  for (int i=0; i<3; ++i) {

    h_effL_b[i] = (TH2F*) h_numL_b[i]->Clone("h_effL_b");
    h_effL_c[i] = (TH2F*) h_numL_c[i]->Clone("h_effL_c");
    h_effL_l[i] = (TH2F*) h_numL_l[i]->Clone("h_effL_l");
    h_effT_b[i] = (TH2F*) h_numT_b[i]->Clone("h_effT_b");
    h_effT_c[i] = (TH2F*) h_numT_c[i]->Clone("h_effT_c");
    h_effT_l[i] = (TH2F*) h_numT_l[i]->Clone("h_effT_l");

    h_effL_b[i]->Reset();
    h_effL_c[i]->Reset();
    h_effL_l[i]->Reset();
    h_effT_b[i]->Reset();
    h_effT_c[i]->Reset();
    h_effT_l[i]->Reset();

    h_effL_b[i]->Divide(h_numL_b[i],h_den_b[i],1.,1.,"B");
    h_effL_c[i]->Divide(h_numL_c[i],h_den_c[i],1.,1.,"B");
    h_effL_l[i]->Divide(h_numL_l[i],h_den_l[i],1.,1.,"B");
    h_effT_b[i]->Divide(h_numT_b[i],h_den_b[i],1.,1.,"B");
    h_effT_c[i]->Divide(h_numT_c[i],h_den_c[i],1.,1.,"B");
    h_effT_l[i]->Divide(h_numT_l[i],h_den_l[i],1.,1.,"B");

  }


  // --- Printout the CSV efficiencies: 

  TH2F * h;

  if ( flavour=="b" && tagger=="CSVL" )
    h = h_effL_b[0];
  else if ( flavour=="c" && tagger=="CSVL" )
    h = h_effL_c[0];
  else if ( flavour=="l" && tagger=="CSVL" )
    h = h_effL_l[0];
  else if ( flavour=="b" && tagger=="CSVT" )
    h = h_effT_b[0];
  else if ( flavour=="c" && tagger=="CSVT" )
    h = h_effT_c[0];
  else if ( flavour=="l" && tagger=="CSVT" )
    h = h_effT_l[0];
  else {
    cout << "*** Wrong arguments! ***" << endl;
    return;
  }
//  if ( flavour=="b" && tagger=="CSVL" )
//    h = h_numL_b[0];
//  else if ( flavour=="c" && tagger=="CSVL" )
//    h = h_numL_c[0];
//  else if ( flavour=="l" && tagger=="CSVL" )
//    h = h_numL_l[0];
//  else if ( flavour=="b" && tagger=="CSVT" )
//    h = h_numT_b[0];
//  else if ( flavour=="c" && tagger=="CSVT" )
//    h = h_numT_c[0];
//  else if ( flavour=="l" && tagger=="CSVT" )
//    h = h_numT_l[0];
//  else {
//    cout << "*** Wrong arguments! ***" << endl;
//    return;
//  }

  for (unsigned int ipt=1; ipt<=h_effL_b[0]->GetNbinsX(); ++ipt){
    for (unsigned int ieta=1; ieta<=h_effL_b[0]->GetNbinsY(); ++ieta){

      cout << h->GetXaxis()->GetBinLowEdge(ipt) << "\t"
	   << h->GetXaxis()->GetBinLowEdge(ipt) + h->GetXaxis()->GetBinWidth(ipt) << "\t"
	   << h->GetYaxis()->GetBinLowEdge(ieta) << "\t"
	   << h->GetYaxis()->GetBinLowEdge(ieta) + h->GetYaxis()->GetBinWidth(ieta) << "\t"
	   << h->GetBinContent(ipt,ieta) << "\t"
	   << h->GetBinError(ipt,ieta) << "\t"
	   << h->GetBinError(ipt,ieta) 
	   << endl;
    }
  }

  
}
Beispiel #6
0
TH2F* fixrange(TH2F* old, int numB) {

  float x1, x2;
  string name = old->GetName();

  if (name.find("Ht")!=string::npos) {
    x1 = 30.;
    x2 = 500.;
    if (numB==2) x2 = 400.;
  } else if (name.find("jet_pt")!=string::npos) {
    x1 = 30.;
    x2 = 300.;
    if (numB==2) {
      if (name.find("first")!=string::npos) x2 = 200.;
      if (name.find("second")!=string::npos) x2 = 120.;
    }
  } else if (name.find("pt_Z")!=string::npos) {
    x1 = 0.;
    x2 = 300.;
    if (numB==2) x2 = 230.;
  } else {
    x1 = old->GetXaxis()->GetBinCenter(1);
    x2 = old->GetXaxis()->GetBinCenter(old->GetNbinsX());
  }

  float y1=x1;
  float y2=x2;

  int nx = old->GetXaxis()->FindBin(x2)-old->GetXaxis()->FindBin(x1)+1;
  int ny = old->GetYaxis()->FindBin(y2)-old->GetYaxis()->FindBin(y1)+1;

  x1 = old->GetXaxis()->GetBinLowEdge(old->GetXaxis()->FindBin(x1));
  x2 = old->GetXaxis()->GetBinUpEdge(old->GetXaxis()->FindBin(x2));
  y1 = old->GetYaxis()->GetBinLowEdge(old->GetYaxis()->FindBin(y1));
  y2 = old->GetYaxis()->GetBinUpEdge(old->GetYaxis()->FindBin(y2));

  TH2F* tmp = new TH2F("tmp",old->GetTitle(),nx,x1,x2,ny,y1,y2);
  tmp->Sumw2();

  tmp->GetXaxis()->SetTitle(old->GetXaxis()->GetTitle());
  tmp->GetYaxis()->SetTitle(old->GetYaxis()->GetTitle());

  for (int i=0;i<=old->GetNbinsX()+1;i++) {
    for (int j=0;j<=old->GetNbinsY()+1;j++) {
      int ii = tmp->GetXaxis()->FindBin(old->GetXaxis()->GetBinCenter(i));
      int jj = tmp->GetYaxis()->FindBin(old->GetYaxis()->GetBinCenter(j));
      float c1 = tmp->GetBinContent(ii,jj);
      float e1 = tmp->GetBinError(ii,jj);
      float c2 = old->GetBinContent(i,j);
      float e2 = old->GetBinError(i,j);
//
// underflows and overflows *must* be discarded before the unfolding:
// inefficiencies and fakes/background are taken from the additional entries
// in the 'reco' and 'truth' histograms, respectively
//
      if (ii==0) continue;
      if (ii==tmp->GetNbinsX()+1) continue;
      if (jj==0) continue;
      if (jj==tmp->GetNbinsY()+1) continue;

      tmp->SetBinContent(ii,jj,c1+c2);
      tmp->SetBinError(ii,jj,TMath::Sqrt(e1*e1+e2*e2));
    }
  }

  tmp->SetEntries(old->GetEntries());

  old->Delete();
  tmp->SetName(name.c_str());

  return tmp;
}
void makeErrorTemplatesPtSyst(TString channel="2e2mu") { 
    
  systSources[0][0] = "Resummation";
  systSources[0][1] = "TopMass";
  systSources[0][2] = "Mela";
  
  systSources[1][0] = "PDF-VBF";
  systSources[1][1] = "scale-VBF";
  systSources[1][2] = "Mela";
  
  systSources[5][0] = "SingleZ";
  systSources[5][1] = "PDF-ZZ";
  systSources[5][2] = "scale-ZZ";
  systSources[5][3] = "Mela"; 
 
  systSources[2][0] = "NLOLO_WH";
  systSources[3][0] = "NLOLO_ZH";

  TString aLongString;
  char fileName[200];
  char fileName2[200];

  //  for (Int_t lhc=8; lhc<9; lhc++) {
  for (Int_t lhc=7; lhc<9; lhc++) {
    for (Int_t k=0; k<nsamp; k++) {

      TString lhcs = "7";
      if (lhc==8) lhcs="8";
 
      aLongString = destDir + "/" + whichVar + "_" + dataFileNames[k] + /* "_" + channel*/ + "_TEMPL_"+ lhcs + "TeV.root";  
      TFile* ftemp = new TFile(aLongString,"UPDATE");
      
      TString whichVar2 = whichVar;
      whichVar2.ToLower();
      sprintf(fileName,"%sH_Default",whichVar2.Data());
      cout << aLongString << " " << fileName << endl;
      TH2F* baseHist = (TH2F*)ftemp->Get(fileName);
      cout << "Histo found OK " << ftemp << " " << baseHist << endl;

      TH2F* upHist = (TH2F*)baseHist->Clone();
      TH2F* downHist = (TH2F*)baseHist->Clone();

      //MC stats
      for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	  upHist->SetBinContent(i,j,(baseHist->GetBinError(i,j))*(baseHist->GetBinError(i,j)));
	  downHist->SetBinContent(i,j,(baseHist->GetBinError(i,j))*(baseHist->GetBinError(i,j)));
	}
      }
      cout << "Errors filled OK" << endl;
      cout << dataFileNames[k] << " entries " << baseHist->GetBinContent(100,10) << " "  << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl ;

      //Other systs
      for (int ss = 0; ss < 5; ss++) {
	if (systSources[k][ss] != "") {

	  TH2F* thisHistUp;
	  TH2F* thisHistDown;

	  if (systSources[k][ss] == "Resummation") {
	    sprintf(fileName,"%sH_ResummationUp",whichVar2.Data());
            sprintf(fileName2,"%sH_ResummationDown",whichVar2.Data());
	  } else if (systSources[k][ss] == "Mela") {
            sprintf(fileName2,"%sH_Mela00-03",whichVar2.Data());
            sprintf(fileName,"%sH_Mela06-10",whichVar2.Data());
          } else {
	    sprintf(fileName,"%sH_%s",whichVar2.Data(),systSources[k][ss].Data());
	    sprintf(fileName2,"%sH_%s",whichVar2.Data(),systSources[k][ss].Data());  
	  }
	  thisHistUp = (TH2F*)((TH2F*)ftemp->Get(fileName))->Clone();
          cout << "Histo up found OK" << endl;
          thisHistDown = (TH2F*)((TH2F*)ftemp->Get(fileName2))->Clone();
          cout << "Histo down found OK" << endl;

	  for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	    for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	      float upval = upHist->GetBinContent(i,j) + pow(thisHistUp->GetBinContent(i,j)-baseHist->GetBinContent(i,j),2);
	      float downval = upHist->GetBinContent(i,j) + pow(thisHistDown->GetBinContent(i,j)-baseHist->GetBinContent(i,j),2);
	      upHist->SetBinContent(i,j,upval);
	      downHist->SetBinContent(i,j,downval);
	    }
	  }

          if (k == 6) cout << "zx entries after syst " << systSources[k][ss] << " " << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl;
	}
      }

      // Subtract or add
      for (int i=1; i<=baseHist->GetNbinsX(); i++) { 
	for (int j=1; j<=baseHist->GetNbinsY(); j++) {
	  float upval = baseHist->GetBinContent(i,j) + sqrt(upHist->GetBinContent(i,j));
          float downval = baseHist->GetBinContent(i,j) - sqrt(downHist->GetBinContent(i,j));
	  upHist->SetBinContent(i,j,upval);
	  downHist->SetBinContent(i,j,downval);
	}
      }

      if (k == 6 && lhc == 8) cout << "zx entries after sqrt " << baseHist->GetBinContent(100,10) << " " << upHist->GetBinContent(100,10) << " " << downHist->GetBinContent(100,10) << endl;

      ftemp->cd();
      upHist->SetName(whichVar2 + "H_TotalUp");
      adjustHistogram(upHist);
      upHist->Write();
      downHist->SetName(whichVar2 + "H_TotalDown");
      adjustHistogram(downHist); 
      downHist->Write();
    }      
  }
  return;
}
Beispiel #8
0
int InputForLimits(){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;

  Int_t NBR = 3;
  Float_t BR[] = { 1., 0.75, 0.5};

  TFile* bkgFile = new TFile( "../../BkgPrediction/BkgPrediction.root", "READ"); 
  TTree* bkgTree;
  bkgFile->GetObject( "ElAndMu", bkgTree);
  
  Float_t bkg = 0.;
  Float_t bkgTotUnc = 0.;

  Float_t obs = 0.;

  bkgTree->SetBranchAddress( "srData", &obs);
  bkgTree->SetBranchAddress( "srAllBkgCorr", &bkg);
  bkgTree->SetBranchAddress( "TotUnc", &bkgTotUnc);

  TFile* sigFile = new TFile( "../../SignalSystematics/SignalSys.root", "READ"); 

  std::vector<std::vector<TString> > sysColl;
  std::vector<TString> sys;
  sys.push_back(TString("JES_Up"));
  sys.push_back(TString("JES_Down"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpBC"));
  sys.push_back(TString("BTagReweight_DownBC"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpLight"));
  sys.push_back(TString("BTagReweight_DownLight"));
  sysColl.push_back(sys);

  std::vector<TString> decayMode;
  decayMode.push_back(TString("tt"));
  decayMode.push_back(TString("tb"));
  decayMode.push_back(TString("bb"));
		      
  Systematics* systematics[3];
  TString dirname;
  TString histoname;

  TDirectory* srDir;
  TDirectory* histoDir;

  TFile* outFile = new TFile( "InputForLimits.root", "RECREATE");
  TDirectory* outBRDir;
  TDirectory* outSRDir;

  TH1F* datah = new TH1F( "data", "data", 1, 0., 1.);
  TH1F* bkgh = new TH1F( "bkg", "bkg", 1, 0., 1.);

  TH2F* sigh;
  TH2F* sig_toth;
  TH2F* effh;
  
  TH2F* sigLh;
  TH2F* effLh;

  TH2F* sigRh;
  TH2F* effRh;
  
  TH2F* jesh;
  TH2F* btagBCh;
  TH2F* btagLighth;
  TH2F* btagh;
  
  TH2F* sysh;

  TH2F* unch;

  TH2F* jesPercenth;
  TH2F* btagBCPercenth;
  TH2F* btagLightPercenth;
  TH2F* btagPercenth;
  
  TH2F* sysPercenth;

  TH2F* uncPercenth;

  Float_t sig = 0.;
  Float_t stat = 0.;

  Float_t jes = 0.;
  Float_t bc = 0.;
  Float_t light = 0.;
  
  Float_t unc = 0.;

  int N = bkgTree->GetEntries();

  for ( int ibr = 0; ibr < NBR; ibr++){
    dirname = ""; dirname += BR[ibr];
    outFile->mkdir(dirname);
    outBRDir = outFile->GetDirectory(dirname);

    for ( int iSR = 0; iSR < 9; iSR++){
      bkgTree->GetEntry(iSR);      
      datah->SetBinContent( 1, obs);
      bkgh->SetBinContent( 1, bkg);
      bkgh->SetBinError( 1, bkgTotUnc);

      dirname = ""; dirname += iSR;
      outBRDir->mkdir(dirname);
      outSRDir = outBRDir->GetDirectory(dirname);
      
      dirname = ""; dirname += iSR; dirname += ".root";      
      srDir = sigFile->GetDirectory( dirname);
      for ( int isys = 0; isys < (int) sysColl.size(); isys++){
	systematics[isys] = new Systematics();
	systematics[isys]->BR = BR[ibr];

	histoDir = srDir->GetDirectory( "NoSystematic");
	for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	  histoDir->GetObject( decayMode.at(idecay), systematics[isys]->h[idecay]);
	  histoDir->GetObject( decayMode.at(idecay) + "l", systematics[isys]->Lh);
	  histoDir->GetObject( decayMode.at(idecay) + "r", systematics[isys]->Rh);
	}
	histoDir->GetObject( decayMode.at(0) + "l", systematics[isys]->Lh);
	histoDir->GetObject( decayMode.at(0) + "r", systematics[isys]->Rh);
	histoDir->GetObject( "sig_tot", systematics[isys]->sig_toth);

	for ( int ishift = 0; ishift < 2; ishift++){
	  histoDir = srDir->GetDirectory(sysColl.at(isys).at(ishift));
	  for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	    histoDir->GetObject( decayMode.at(idecay), systematics[isys]->shifth[ishift][idecay]);
	  }
	}
	systematics[isys]->Calc();
      }
      sig_toth = new TH2F( *systematics[0]->sig_toth);
      sig_toth->SetName("sig_tot");
      sig_toth->SetTitle("sig_tot");    

      sigh = new TH2F( *systematics[0]->sigh);
      sigh->SetName("sig");
      sigh->SetTitle("sig");

      effh = new TH2F( *systematics[0]->effh);
      effh->SetName("eff");
      effh->SetTitle("eff");

      sigLh = new TH2F( *systematics[0]->sigRh);
      sigLh->SetName("sigL");
      sigLh->SetTitle("sigL");

      effLh = new TH2F( *systematics[0]->effLh);
      effLh->SetName("effL");
      effLh->SetTitle("effL");

      sigRh = new TH2F( *systematics[0]->sigRh);
      sigRh->SetName("sigR");
      sigRh->SetTitle("sigR");

      effRh = new TH2F( *systematics[0]->effRh);
      effRh->SetName("effR");
      effRh->SetTitle("effR");

      jesh = new TH2F( *systematics[0]->sysh);
      jesh->SetName("jes");
      jesh->SetTitle("jes");

      btagBCh = new TH2F( *systematics[1]->sysh);
      btagBCh->SetName("btagBC");
      btagBCh->SetTitle("btagBC");
      
      btagLighth = new TH2F( *systematics[2]->sysh);
      btagLighth->SetName("btagLight");
      btagLighth->SetTitle("btagLight");
      
      btagh = new TH2F( *btagBCh);
      btagh->Reset();
      btagh->SetName("btag");
      btagh->SetTitle("btag");
 
      sysh = new TH2F( *jesh);
      sysh->Reset();
      sysh->SetName("sys");
      sysh->SetTitle("sys");

      unch = new TH2F( *jesh);
      unch->Reset();
      unch->SetName("unc");
      unch->SetTitle("unc");


      jesPercenth = new TH2F( *systematics[0]->sysh);
      jesPercenth->SetName("jesPercent");
      jesPercenth->SetTitle("jesPercent");
      jesPercenth->Divide( sigh);
      jesPercenth->Scale( 100.);      

      btagBCPercenth = new TH2F( *systematics[1]->sysh);
      btagBCPercenth->SetName("btagBCPercent");
      btagBCPercenth->SetTitle("btagBCPercent");
      btagBCPercenth->Divide( sigh);
      btagBCPercenth->Scale( 100.);   

      btagLightPercenth = new TH2F( *systematics[2]->sysh);
      btagLightPercenth->SetName("btagLightPercent");
      btagLightPercenth->SetTitle("btagLightPercent");
      btagLightPercenth->Divide( sigh);
      btagLightPercenth->Scale( 100.);   

      btagPercenth = new TH2F( *btagBCh);
      btagPercenth->Reset();
      btagPercenth->SetName("btagPercent");
      btagPercenth->SetTitle("btagPercent");
 
      sysPercenth = new TH2F( *jesh);
      sysPercenth->Reset();
      sysPercenth->SetName("sysPercent");
      sysPercenth->SetTitle("sysPercent");

      uncPercenth = new TH2F( *jesh);
      uncPercenth->Reset();
      uncPercenth->SetName("uncPercent");
      uncPercenth->SetTitle("uncPercent");

      for (int ibin = 0; ibin < sigh->GetSize(); ibin++){	
	sig = sigh->GetBinContent( ibin);
	stat = sigh->GetBinError( ibin);

	jes = jesh->GetBinContent(ibin);
	bc = btagBCh->GetBinContent(ibin);
	light = btagLighth->GetBinContent(ibin);
    
	unc = sqrt( bc * bc + light * light);
	btagh->SetBinContent( ibin, unc);
	btagPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light +
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );       
	sysh->SetBinContent( ibin, unc);
	sysPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light + stat * stat +  
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );	
	unch->SetBinContent( ibin, unc);
	uncPercenth->SetBinContent( ibin, unc / sig * 100.);
      }
      outSRDir->cd();

      datah->Write();
      bkgh->Write();

      sig_toth->Write();
      sigh->Write();
      effh->Write();
      
      sigLh->Write();
      effLh->Write();

      sigRh->Write();
      effRh->Write();

      jesh->Write();
      btagBCh->Write(); 
      btagLighth->Write();
      btagh->Write();
      
      sysh->Write();
      unch->Write();

      jesPercenth->Write();
      btagBCPercenth->Write(); 
      btagLightPercenth->Write();
      btagPercenth->Write();
      
      sysPercenth->Write();
      uncPercenth->Write();
    }
  }

  delete systematics[0];
  delete systematics[1];
  delete systematics[2];

  outFile->Close();
  sigFile->Close();
  bkgFile->Close();

  return 0;
}
void cetaflatHEM3t(int nIterN=1, double Ethr1=4, double Ethr2=150) {

    gStyle->SetOptLogz(0);
    gStyle->SetMarkerSize(0.7);
    gStyle->SetMarkerStyle(20);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetTitleOffset(1.7,"Y");
    gStyle->SetTitleOffset(0.9,"X");
    //gStyle->SetPadRightMargin(0.12);
    gStyle->SetPadTopMargin(0.06);
    gStyle->SetPadRightMargin(0.03);
    gStyle->SetPadLeftMargin(0.2);
    //gStyle->SetNdivisions(516);
    gStyle->SetStatH(0.09);
    gStyle->SetStatW(0.3);
    gStyle->SetTitleW(0.4);
    gStyle->SetTitleX(0.3);
    gStyle->SetOptStat(0);
    //gStyle->SetOptStat(1111111);
    gROOT->ForceStyle();

    char ctit[145];

    static const double theHBHEEtaBounds[] = { 0.000, 0.087, 0.087*2, 0.087*3, 0.087*4,
                                               0.087*5, 0.087*6, 0.087*7, 0.087*8, 0.087*9,
                                               0.087*10, 0.087*11, 0.087*12, 0.087*13, 0.087*14,
                                               0.087*15, 0.087*16, 0.087*17, 0.087*18, 0.087*19,
                                               1.74, 1.83, 1.93, 2.043, 2.172,
                                               2.332, 2.5, 2.65, 2.868, 3.000
                                             };

    static const double theHFEtaBounds[] = { 2.853, 2.964, 3.139, 3.314, 3.489, 3.664, 3.839,
                                             4.013, 4.191, 4.363, 4.538, 4.716, 4.889, 5.191
                                           };

    // ---------------- Histos input --------------------------------------

    char ftit[145];
    //sprintf(ftit,"%s","phi43val2012A");
    //sprintf(ftit,"%s","phi2012A_May");
    //sprintf(ftit,"%s","phiSym524_2012AB");
    //sprintf(ftit,"%s","phiSym524newGain_2012AB");
    //sprintf(ftit,"%s","phiSym524newGain_2012ABC");
    sprintf(ftit,"%s","phiSym533Corr45Gain507_2012D");

    sprintf(ctit,"/home/vodib/beam12/intercal/%s.root",ftit);
    TFile *fila = new TFile (ctit);
    cout<<"File= "<<ctit<<endl;

    TH1F *hcounter =   new TH1F(*((TH1F*)fila->Get("phaseHF/hcounter")));
    cout<<"Stat= "<<hcounter->GetBinContent(2)<<endl;
    cout<<"E within: "<<Ethr1<<" - "<<Ethr2<<endl;

    TH2F* hmapP = new TH2F("hmapP","E  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    TH2F* hmapP0 = new TH2F("hmapP0","E0  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    TH2F* hmapPc = new TH2F("hmapPc","corr  HEM;i#eta;i#phi",14,-29.5,-15.5,72,0,72);
    hmapPc->Sumw2();
    TH1F *hcorr1D = new TH1F("hcorr1D","Corr",150,0.5,2);
    TH1F *ht = new TH1F("ht","ht",20000,0,5e7);
    TH1F *htx = new TH1F("htx","htx",20000,0,5e5);
    TH1F *htr = new TH1F("htr","htr",5000,0,3);

    /*  HE mapping:
    if (ieta==16 && depth<3) continue;
    if (ieta==17 && depth>1) continue;
    if (ieta>17 && ieta<27 && depth==3) continue;
    if (ieta==29 && depth==3) continue;
    if (ieta>20 && iphi%2==0) continue;  */


    TH1F *hdatP[14][72], *hdatPx[14][72];
    for (int ii=0; ii<14; ii++) for (int jj=0; jj<72; jj++) {
            sprintf(ctit,"h%d_%d",ii+16,jj+1);
            hdatP[ii][jj] = new TH1F(ctit,ctit,10000,0,250);
        }

    TCanvas *cx[400];
    TSpline5 *tt;

    Double_t x,y,rPL,rPS,mLE,mSE,ermean,rms;
    Double_t xx[4000],yy[4000];
    Int_t nELP, nESP, nIter=0;
    Double_t mcorrL,scorrL,mcorrS,scorrS,erLP,erSP,rLP,drLP,rSP,corrL,corrS,dcorrL,dcorrS;
    double mLEphi[14];

    TCanvas *ccxx = new TCanvas("ccxx","ccxx",0,400,800,400);
    ccxx->Divide(2,1);
    for (int ii=0; ii<14; ii++) {
        int ieta=-(ii+16);

        mLE=mSE=0;   // ------------------for initial condition
        int nmLE=0, nmSE=0;
        ht->Reset();
        htx->Reset();
        for (int ll=0; ll<72; ll++) {
            int iphi=ll+1;

            if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
            if (abs(ieta)>20 && iphi%2==0) continue;

            hmapPc->SetBinContent(14-ii,ll+1,1);
            hmapPc->SetBinError(14-ii,ll+1,1.e-6);
            sprintf(ctit,"phaseHF/eHEspec/E_-%d_%d_3",abs(ieta),iphi);
            hdatPx[ii][ll]  =   new TH1F(*((TH1F*)fila->Get(ctit)));
            hdatPx[ii][ll]->SetAxisRange(Ethr1,Ethr2);
            rLP = hdatPx[ii][ll]->Integral()*hdatPx[ii][ll]->GetMean();
            hmapP0->SetBinContent(14-ii,ll+1,rLP);
            if (skipHEChannel(iphi,ieta)) continue;
            if (rLP>0) {
                ht->Fill(rLP);
                htx->Fill(rLP);
                mLE += rLP;
                nmLE++;
                drLP=rLP*sqrt(pow(1./hdatPx[ii][ll]->Integral(),2)+
                              pow(hdatPx[ii][ll]->GetMeanError()/hdatPx[ii][ll]->GetMean(),2));
                hmapP0->SetBinError(14-ii,ll+1,drLP);
            }
            else hmapP0->SetBinError(14-ii,ll+1,0);
        }
        if (nmLE>0) mLE /= nmLE;
        else mLE=0;
        ccxx->cd(1);
        ht->Draw("hist");
        ccxx->cd(2);
        htx->Draw("hist");
        ccxx->Update();
        if (htx->GetBinContent(20001)>1) histspec(ht,mLE,ermean,rms,4,-5);
        else histspec(htx,mLE,ermean,rms,4,-5);
        //histspec(ht,mLE,ermean,rms);
        mLEphi[ii]=mLE;
        printf("ieta %2d :  <E>= %8.1f \n",ieta,mLE);
        if (ht->GetMean()>0) htr->Fill(ht->GetRMS()/ht->GetMean());

        for (int jj=0; jj<72; jj++) {
            int iphi=jj+1;

            if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
            if (abs(ieta)>20 && iphi%2==0) continue;
            if (skipHEChannel(iphi,ieta)) {
                hmapP->SetBinContent(14-ii,jj+1,hmapP0->GetBinContent(14-ii,jj+1,rLP));
                continue;
            }

            for (nIter=1; nIter<nIterN; nIter++) { //cout<<nIter<<" |  ";
                if (hmapP0->GetBinContent(14-ii,jj+1)<=0) continue;
                corrL=hmapPc->GetBinContent(14-ii,jj+1);
                hdatP[ii][jj]->Reset();

                for (int kk=1; kk<=hdatPx[ii][jj]->GetNbinsX(); kk++) {
                    xx[kk-1]=hdatPx[ii][jj]->GetBinCenter(kk);
                    yy[kk-1]=hdatPx[ii][jj]->GetBinContent(kk);
                }
                tt = new TSpline5("tt",xx,yy,1000,"",10,20);

                for (int kk=1; kk<=hdatP[ii][jj]->GetNbinsX(); kk++) {
                    x=hdatP[ii][jj]->GetBinCenter(kk);
                    y=hdatP[ii][jj]->GetBinContent(kk);
                    hdatP[ii][jj]->Fill(x*corrL,tt->Eval(x)/10.0);
                }
                tt->Delete();

                hdatP[ii][jj]->SetAxisRange(Ethr1,Ethr2);
                rLP = hdatP[ii][jj]->Integral()*hdatP[ii][jj]->GetMean();
                dcorrL=(rLP-mLE)/mLE;
                if (fabs(dcorrL)>0.5) dcorrL=0.5*dcorrL/fabs(dcorrL);
                if (rLP>0) drLP=
                        sqrt(pow(hdatP[ii][jj]->GetMeanError()/hdatP[ii][jj]->GetMean(),2)+
                             1.f/hdatP[ii][jj]->Integral()+
                             pow(dcorrL/(1.0+sqrt((float) nIter)),2));
                else drLP=1.e-6;
                if (fabs(dcorrL)>0.001) {
                    //corrL*=1-20*dcorrL/(40+nIter*nIter);
                    //corrL*=1-dcorrL/(2+nIter);
                    corrL*=1-dcorrL/(1.0+sqrt((float) nIter));
                    //printf("%2d : %2d / %2d / 1 %7.3f %7.3f\n",nIter,ieta,iphi,dcorrL,corrL);
                    hmapPc->SetBinContent(14-ii,jj+1,corrL);
                    hmapPc->SetBinError(14-ii,jj+1,corrL*drLP);
                    hmapP->SetBinContent(14-ii,jj+1,rLP);
                }
                else {
                    printf("%2d : %2d / %2d / 3 %7.3f %8.4f %8.4f\n",
                           nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
                    hmapP->SetBinContent(14-ii,jj+1,rLP);
                    hmapPc->SetBinError(14-ii,jj+1,corrL*drLP);
                    break;
                }
                if (nIter==nIterN-1)
                    printf("%2d : %2d / %2d / 3 %8.4f %8.4f %8.4f\n",nIter,ieta,iphi,dcorrL,corrL,corrL*drLP);
            }
        }
    }

    printf("\nieta      eta  width  dE/dPhidEta\n");
    double xeta[14], weta[14], yield[14];
    int ind=0;
    for (int i=0; i<14; i++) {
        int ieta=-(i+16);
        if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;
        xeta[ind]=-(theHBHEEtaBounds[i+15]+theHBHEEtaBounds[i+16])/2;
        weta[ind]=(theHBHEEtaBounds[i+16]-theHBHEEtaBounds[i+15]);
        yield[ind]=mLEphi[i];
        if (abs(ieta)<21) yield[ind]*=72/weta[ind];
        else yield[ind]*=36/weta[ind];
        printf("%3d   3 %7.3f%7.3f   %g\n",ieta,xeta[ind],weta[ind],yield[ind]);
        ind++;
    }
    TCanvas *cgL = new TCanvas("cgL","cgL",300,300,600,600);
    TGraphErrors *grL = new TGraphErrors(ind,xeta,yield,0,0);
    grL->SetTitle("HEM ;#eta;E / #Delta#eta ,  GeV");
    grL->Draw("1+PAl");
    cgL->Print("pictHEplot/phiProfHEM3.gif");
    //cgL->Print("HEmc/phiProfM3.gif");


    //TFile *histf = new TFile("HEM3mc.root","RECREATE");

    FILE *ft1;
    sprintf(ctit,"corrHEM3_%s_%d_%d.txt",ftit,((int) Ethr1),((int) Ethr2));
    //sprintf(ctit,"corrHEM3_MC_%d_%d.txt",((int) Ethr1),((int) Ethr2));
    if ((ft1 = fopen(ctit,"w"))==NULL) {              // Open new file
        printf("\nNo file %s open => EXIT\n\n",file);
        return;
    }
    printf("\n\n File '%s' open \n\n",ctit);

    TH1D *hprL[14],*hprL0[14],*hprcL[16];
    TCanvas *cpr[14],*ccc[16];
    TLine *lin1 = new TLine(0,1,71,1);
    lin1->SetLineWidth(1);

    int noff=0;
    for (int ii=0; ii<14; ii++) {

        int ieta=-(ii+16);
        if (abs(ieta)!=16 && abs(ieta)!=27 && abs(ieta)!=28) continue;

        sprintf(ctit,"HEMcorr_%d_3",ieta);  // draw corrections
        hprcL[ii] = hmapPc->ProjectionY(ctit,14-ii,14-ii);
        hprcL[ii]->SetTitle(ctit);
        ccc[ii] = new TCanvas(ctit,ctit,800,100,500,500);
        hprcL[ii]->SetMinimum(0.41);
        hprcL[ii]->SetMaximum(hprcL[ii]->GetMaximum()*1.1);
        hprcL[ii]->SetTitleOffset(0.9,"X");
        hprcL[ii]->Draw("e");
        lin1->Draw();
        sprintf(ctit,"pictHEplot/HEM3corr_%d.gif",ieta);
        //sprintf(ctit,"HEmc/HEM3c_4_100G_%d.gif",ieta);
        ccc[ii]->Print(ctit);
        //hprcL[ii]->Write();

        sprintf(ctit,"HEM_E_%d_3;i#phi;GeV",ieta);
        hprL0[ii] = hmapP0->ProjectionY(ctit,14-ii,14-ii);
        hprL0[ii]->SetTitle(ctit);
        sprintf(ctit,"HEM__%d",ieta);
        hprL[ii] = hmapP->ProjectionY(ctit,14-ii,14-ii);
        if (abs(ieta)>20) {
            hprL[ii]->Rebin();
            hprL0[ii]->Rebin();
        }
        cpr[ii] = new TCanvas(ctit,ctit,800,100,500,500);
        hprL0[ii]->SetFillColor(3);
        hprL0[ii]->SetLineColor(3);
        hprL0[ii]->SetLineWidth(1);
        hprL0[ii]->SetTitleOffset(0.9,"X");
        hprL0[ii]->SetMinimum(0);
        hprL0[ii]->Draw("hist");
        hprL[ii]->Draw("samehist");
        sprintf(ctit,"pictHEplot/HEM_E_%d_3.gif",ieta);
        //sprintf(ctit,"HEmc/HEM_E_%d_3.gif",ieta);
        cpr[ii]->Print(ctit);
        //hprL0[ii]->Write();

        for (int jj=0; jj<72; jj++) {
            int ieta=-(ii+16);
            int iphi=jj+1;

            if (abs(ieta)>20 && iphi%2==0) continue;

            corrL=hmapPc->GetBinContent(14-ii,jj+1);
            dcorrL=hmapPc->GetBinError(14-ii,jj+1);
            hcorr1D->Fill(corrL);
            noff++;
            //printf("%2d : %2d / %2d / 3 %8.4f %8.4f\n",noff,ieta,iphi,corrL,dcorrL);
            fprintf(ft1,"%2d   %2d   3 %8.4f %8.4f\n",ieta,iphi,corrL,dcorrL);
        }
    }
    fclose(ft1);

    TCanvas *c1corr =new TCanvas("c1corr","c1corr",30,30,600,600);
    hcorr1D->Draw("hist");
    histStat(hcorr1D,1);
    c1corr->Print("pictHEplot/corrHEM3.gif");
    //c1corr->Print("HEmc/corrHEM3.gif");

    TCanvas *ctr = new TCanvas("ctr","ctr",0,0,650,600);
    htr->Draw("hist");
    ctr->Update();

    TCanvas *chmapP = new TCanvas("chmapP","chmapP",0,0,650,600);
    chmapP->cd();
    chmapP->SetRightMargin(0.12);
    chmapP->SetLogz();
    hmapP->SetAxisRange(hmapP->GetBinContent(14,1)/2,-1111,"Z");
    hmapP->Draw("colz");
    chmapP->Print("pictHEplot/hmapHEM3.gif");
    chmapP->Update();

    TCanvas *chmapP0 = new TCanvas("chmapP0","chmapP0",0,0,650,600);
    chmapP0->cd();
    chmapP0->SetRightMargin(0.12);
    chmapP0->SetLogz();
    hmapP0->SetAxisRange(hmapP0->GetBinContent(14,1)/2,-1111,"Z");
    hmapP0->Draw("colz");
    chmapP0->Print("pictHEplot/hmap0HEM3.gif");
    chmapP0->Update();

    TCanvas *chmapPc = new TCanvas("chmapPc","chmapPc",0,0,650,600);
    chmapPc->cd();
    chmapPc->SetRightMargin(0.12);
    hmapPc->SetAxisRange(0.6,2,"Z");
    hmapPc->Draw("colz");
    chmapPc->Print("pictHEplot/hmapcHEM3.gif");
    chmapPc->Update();

    sprintf(ctit,"HEM3o_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
    TFile *histf = new TFile(ctit,"RECREATE");
    hmapP->Write();
    hmapP0->Write();
    hmapPc->Write();
    histf->Close();

}
Beispiel #10
0
void ana_Run11_eff()
{

  const int rebin = 1;

  TFile *f = TFile::Open("Rootfiles/Run11_eff.root","read");

  // Run with weigth
  TH2F *hMcPtVsEta = (TH2F*)f->Get("mcJpsiPtY");
  TH2F *hRcPtVsEta = (TH2F*)f->Get("hHt2JpsiPE");

  draw2D(hMcPtVsEta);
  draw2D(hRcPtVsEta);

  hMcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPt = (TH1F*)hMcPtVsEta->ProjectionY("hMcPt");
  hMcPt->Rebin(rebin);
  hMcPt->SetMarkerStyle(20);
  draw1D(hMcPt,"",kTRUE);

  hRcPtVsEta->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hRcPt = (TH1F*)hRcPtVsEta->ProjectionY("hRcPt");
  hRcPt->Rebin(rebin);
  hRcPt->SetMarkerStyle(21);
  hRcPt->SetMarkerColor(2);
  hRcPt->SetLineColor(2);
  hRcPt->Draw("sames P");

  TH1F *hRatio = (TH1F*)hRcPt->Clone("hRatio_fromRunning");
  hRatio->Rebin(100);
  hMcPt->Rebin(100);
  hRatio->Divide(hMcPt);
  cEff = draw1D(hRatio,"");

  // Run without weight
  TH2F *hMcPtVsEtaNoWeight = (TH2F*)f->Get("mcJpsiPtY_Or");
  draw2D(hMcPtVsEtaNoWeight);  

  TH2F *hMcPtVsRcNoWeight = (TH2F*)f->Get("hJpsiRcvsMC_Cut1");
  hMcPtVsRcNoWeight->RebinX(rebin);
  hMcPtVsRcNoWeight->RebinY(rebin);
  draw2D(hMcPtVsRcNoWeight);

  hMcPtVsEtaNoWeight->GetXaxis()->SetRangeUser(-1+1e-6,1-1e-6);
  TH1F *hMcPtNoWeight = (TH1F*)hMcPtVsEtaNoWeight->ProjectionY("hMcPtNoWeight");
  hMcPtNoWeight->Rebin(rebin);
  hMcPtNoWeight->SetMarkerStyle(20);
  hMcPtNoWeight->SetMinimum(1);
  draw1D(hMcPtNoWeight,"",kTRUE);

  TH1F *hRcPtNoWeight = (TH1F*)hMcPtVsRcNoWeight->ProjectionX("hRcPtNoWeight");
  hRcPtNoWeight->SetMarkerStyle(21);
  hRcPtNoWeight->SetMarkerColor(2);
  hRcPtNoWeight->SetLineColor(2);
  hRcPtNoWeight->Draw("sames P");

  TH1F *hRatioNoWeight = (TH1F*)hRcPtNoWeight->Clone("hRatioNoWeight");
  hRatioNoWeight->Divide(hMcPtNoWeight);
  cEff->cd();
  hRatioNoWeight->SetMarkerColor(4);
  hRatioNoWeight->Draw("samesP");

  // weight with input histogram
  TH1F *hMcPtWeight = (TH1F*)hMcPtNoWeight->Clone("hMcPtWeight");
  TH2F *hMcPtVsRcWeight = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcWeight");
  for(int ibin=1; ibin<=hMcPtVsRcNoWeight->GetNbinsX(); ibin++)
    {
      double scale = hMcPt->GetBinContent(ibin);
      hMcPtWeight->SetBinContent(ibin,hMcPtWeight->GetBinContent(ibin)*scale);
      hMcPtWeight->SetBinError(ibin,hMcPtWeight->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcWeight->SetBinContent(ibin,jbin,hMcPtVsRcWeight->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcWeight->SetBinError(ibin,jbin,hMcPtVsRcWeight->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtWeight = (TH1F*)hMcPtVsRcWeight->ProjectionY("hRcPtWeight");
  hRcPtWeight->SetMarkerStyle(21);
  hRcPtWeight->SetMarkerColor(2);
  hRcPtWeight->SetLineColor(2);

  draw2D(hMcPtVsRcWeight);
  draw1D(hMcPtWeight,"",kTRUE);
  hRcPtWeight->Draw("sames P");
  
  TH1F *hRatioWeight = (TH1F*)hRcPtWeight->Clone("hRatioWeight");
  hRatioWeight->Divide(hMcPtWeight);
  cEff->cd();
  hRatioWeight->SetMarkerColor(6);
  hRatioWeight->Draw("samesP");

  TH1F *hCheck = (TH1F*)hRatioWeight->Clone("check");
  hCheck->Divide(hRatio);
  draw1D(hCheck);

  // weight with fitted function
  TCanvas *c = new TCanvas("Fit","Fit",800,600);
  SetPadMargin(gPad,0.15,0.15);
  gPad->SetLogy();
  TH1F *h = new TH1F("histogram",";;;",7,0,30);
  h->GetYaxis()->SetRangeUser(1e-7,100);
  h->Draw();

  TFile *fdata = TFile::Open("Rootfiles/Spectrum_in_bin.root","read");
  TGraphErrors	*gr = (TGraphErrors*)fdata->Get("gall");
  gr->SetMarkerColor(1);
  gr->SetLineColor(1);
  gr->GetXaxis()->SetRangeUser(0,30);
  gr->Draw("sames PE");
  TF1 *func = new TF1("func",InvPt,0,30,4);
  func->SetParameters(0.4,-0.4796,4.229,-7.54);
  gr->Fit(func,"RL");

  TH1F *hMcPtFunc = (TH1F*)hMcPtNoWeight->Clone("hMcPtFunc");
  TH2F *hMcPtVsRcFunc = (TH2F*)hMcPtVsRcNoWeight->Clone("hMcPtVsRcFunc");
  for(int ibin=1; ibin<=hMcPtVsRcFunc->GetNbinsX(); ibin++)
    {
      double scale = func->Eval(hMcPtFunc->GetBinCenter(ibin));
      hMcPtFunc->SetBinContent(ibin,hMcPtFunc->GetBinContent(ibin)*scale);
      hMcPtFunc->SetBinError(ibin,hMcPtFunc->GetBinError(ibin)*scale);
      for(int jbin=1; jbin<=hMcPtVsRcNoWeight->GetNbinsY(); jbin++)
	{
	  hMcPtVsRcFunc->SetBinContent(ibin,jbin,hMcPtVsRcFunc->GetBinContent(ibin,jbin)*scale);
	  hMcPtVsRcFunc->SetBinError(ibin,jbin,hMcPtVsRcFunc->GetBinError(ibin,jbin)*scale);
	}
    }
  TH1F *hRcPtFunc = (TH1F*)hMcPtVsRcFunc->ProjectionY("hRcPtFunc");
  hRcPtFunc->SetMarkerStyle(21);
  hRcPtFunc->SetMarkerColor(2);
  hRcPtFunc->SetLineColor(2);
  hMcPtVsRcFunc->GetZaxis()->SetRangeUser(1e-4,1e2);
  draw2D(hMcPtVsRcFunc);
  hMcPtFunc->GetYaxis()->SetRangeUser(1e-4,5e4);
  draw1D(hMcPtFunc,"",kTRUE);
  hRcPtFunc->Draw("sames P");

  TH1F *hRatioFunc = (TH1F*)hRcPtFunc->Clone("hRatioFunc");
  hRatioFunc->Rebin(100);
  hMcPtFunc->Rebin(100);
  hRatioFunc->Divide(hMcPtFunc);
  cEff->cd();
  hRatioFunc->SetMarkerColor(5);
  hRatioFunc->Draw("samesP");
  
  TH1F *hCheck2 = (TH1F*)hRatioFunc->Clone("check2");
  hCheck2->Divide(hRatio);
  draw1D(hCheck2);

}
Beispiel #11
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;
}