Exemplo n.º 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;
	};
Exemplo n.º 2
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();
    }
// }}}
};
Exemplo n.º 3
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;
  
}
Exemplo n.º 4
0
TH2F* mergeBackground(TFile* fa,const char* pattern,const char * theSbtag,const char* newname,const string scenario) {
  std::cout << "mergeBackground: newname = " << newname << std::endl;
  const int nTrig=4;
  const int nfc=3;
  const int ncateg=3;
  string sfc[nfc] = { "q", "c", "b" };
  TH2F* theData[nTrig][nfc][ncateg];
  if (fa == NULL) {
    std::cout << "mergeBackground: no hfile opened" << std::endl;
    return NULL;
  }

  int nTrigUse = 4;
  if (scenario == "LowMass2011") {
    nTrigUse = 3;
  }
  std::cout << " mergeBackground:  nTrigUse=" << nTrigUse << std::endl;

  // no weights
  for (int iTrig=0; iTrig<nTrigUse; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	//string sname( Form(Form("%sTrig%d",pattern,iTrig),sfc[ifc].c_str(),theSbtag,icateg,icateg) );
	string sname( Form("bgPredict/MassBTagPred_%s_%s_Cat%dTpat%dTrig%d",
			   sfc[ifc].c_str(),theSbtag,icateg,icateg,iTrig) );
	theData[iTrig][ifc][icateg] = (TH2F*) fa->Get( sname.c_str());
	if (theData[iTrig][ifc][icateg] == NULL) {
	  std::cout << "mergeBackground: histogram " << sname << " not found" << std::endl;
	  return 0;
	}
    //theData[ii]->Draw();
      }
    }
  }

  TH2F* mergedData = new TH2F( *theData[0][0][0] );
  mergedData->SetName( newname );
  mergedData->SetTitle( newname );
  for (int iTrig=0; iTrig<nTrigUse; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	if (! ((iTrig == 0) && (ifc == 0) && (icateg == 0) )) {
	  mergedData->Add( theData[iTrig][ifc][icateg] );
	  std::cout << "mergeBackground: adding " << theData[iTrig][ifc][icateg]->GetName() << std::endl;
	}
      }
    }
  }  
  std::cout << "mergeBackground: newname(4) = " << newname << std::endl;

  // cross check total weight
  double tw = 0;
  for (int iTrig=0; iTrig<nTrigUse; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	tw += theData[iTrig][ifc][icateg]->GetSum();
      }
    }
  }
  std::cout << newname << " Sum = " << tw << "  mergedData = " << mergedData->GetSum() << std::endl;
  std::cout << mergedData->GetName() << std::endl;
  
  // final normalization (from control region)
  double wScale = 1;
  string sb( theSbtag );
  if (scenario == "LowMass2011") {
    {
      if ( sb == "CSVT" ) {
	wScale = 1.07817;
      } else if ( sb == "TCHPT" ) {
	wScale = 0.970401;
      }
    }
  } else if (scenario == "MediumMass2011") {
    {
      if ( sb == "CSVT" ) {
	wScale = 0.9505;
      } else if ( sb == "TCHPT" ) {
	wScale = 0.874897;
      }
    }
  } else {
    std::cout << "merge background: bad scenario " << scenario << std::endl;
    return 0;
  }
  std::cout << "Use expected background scale factor of " << wScale << " for " << theSbtag 
	    << " scenario " << scenario << std::endl;
  mergedData->Scale( wScale );
  std::cout << newname << " After final normalization: " << mergedData->GetSum() << std::endl;

  return mergedData;
}
Exemplo n.º 5
0
int main(int argc, char **argv) {

  // This allows you to view ROOT-based graphics in your C++ program
  // If you don't want view graphics (eg just read/process/write data files), 
  // this can be ignored
  TApplication theApp("App", &argc, argv);

  TCanvas* canvas = new TCanvas();
  // ***************************************
  // not important for this exmple
  // Set a bunch of parameters to make the plot look nice
  canvas->SetFillColor(0);
  canvas->UseCurrentStyle();
  canvas->SetBorderMode(0);        // still leaves red frame bottom and right
  canvas->SetFrameBorderMode(0);   // need this to turn off red hist frame!
  gROOT->SetStyle("Plain");
  canvas->UseCurrentStyle();
  gROOT->ForceStyle();
  canvas->Divide(2, 1);

  gStyle->SetOptStat(0);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetTitleSize(0.04);
  gStyle->SetTitleFont(42, "hxy");      // for histogram and axis titles
  gStyle->SetLabelFont(42, "xyz");      // for axis labels (values)
  gROOT->ForceStyle();
  // ***************************************

  TFile *f=new TFile("fitInputs.root");
  TH2F *hist1 = (TH2F*)f->Get("hdata");
  TH2F *hback = (TH2F*)f->Get("hbkg"); 
 
  double xmin = 0.0;
  double xmax = 6.0;
  double ymin = 0.0;
  double ymax=6.0;  
  // Initialize minuit, set initial values etc. of parameters.
  const int npar = 6;              // the number of parameters
 
  TMinuit minuit(npar);
  minuit.SetFCN(fcn);              // the fcn to be minized 
  // (eg calculates chi^2 or NLL, not the
  // parameterization of the data!


  TF2* myfunc = new TF2("myfunc", gausPdf, xmin, xmax, ymin, ymax, npar);  
  // use this to fit the data and get results
  double par[npar];               // the start values
  double stepSize[npar];          // step sizes 
  double minVal[npar];            // minimum bound on parameter 
  double maxVal[npar];            // maximum bound on parameter
  TString parName[npar];

  par[0] = hback->GetMaximum();       // guesses for starting the fit
  par[1] = hist1->GetMaximum();                     
  par[2] = 3.555;                     //use mean and rms values from histogram
  par[3] = 1.17;                      //as initial guesses for parameters 
  par[4] = 1.879;
  par[5] = 1.229;
  stepSize[0] = TMath::Abs(par[0]*0.1);   
  stepSize[1] = TMath::Abs(par[1]*0.1);   // step size MUST be positive!
  stepSize[2] = TMath::Abs(par[2]*0.1);
  stepSize[3] = TMath::Abs(par[3]*0.1);
  stepSize[4] = TMath::Abs(par[4]*0.1);
  stepSize[5] = TMath::Abs(par[5]*0.1);
  minVal[0] = 0;      // if min and max values = 0, parameter is unbounded.
  maxVal[0] = 0;
  minVal[1] = 0; 
  maxVal[1] = 0;
  minVal[2] = 0;
  maxVal[2] = 6;
  minVal[3] = 0;
  maxVal[3] = 6;
  minVal[4] = 0;
  maxVal[4] = 6;
  minVal[5] = 0;
  maxVal[5] = 6;

  parName[0] = "Bkg";
  parName[1] = "A";
  parName[2] = "x0";
  parName[3] = "sigma_x";
  parName[4] = "y0";
  parName[5] = "sigma_y";

  for (int i=0; i<npar; i++){
    minuit.DefineParameter(i, parName[i].Data(), 
			   par[i], stepSize[i], minVal[i], maxVal[i]);
  }


  // here we define the pointers to pass information to Minuit's fcn
  // not pretty, but works well
  hdata=hist1;
  hback->Scale(1.0/3600.0); //scale over total number of entries first
  hb=hback;
  fparam=myfunc;

  // Do the minimization!
  minuit.Migrad();       // Minuit's best minimization algorithm
  double outpar[npar], err[npar];
  for (int i=0; i<npar; i++){
    minuit.GetParameter(i,outpar[i],err[i]);
  }
  TH2F *residual = new TH2F("residual", "Residuals Plot: data-fit", 
			    50, 0, 6, 50, 0, 6);
  myfunc->SetParameters(outpar);
  for (int i=1; i<=hist1->GetNbinsX(); i++){
    for(int j=1; j<=hist1->GetNbinsY(); j++){
      double x = hist1->GetBinCenter(i);
      double y = hist1->GetBinCenter(j);
      double f= myfunc->Eval(x, y);
      double r = hist1->GetBinContent(i, j) -f;
      residual->Fill(x, y, r);
    }
  }


  canvas->cd(1);
  residual->GetXaxis()->SetTitle("x");
  residual->GetYaxis()->SetTitle("y");
  residual->GetXaxis()->CenterTitle();
  residual->GetYaxis()->CenterTitle();
  residual->GetXaxis()->SetTitleOffset(1.25);
  residual->GetYaxis()->SetTitleOffset(1.25);
  residual->Draw("colz");
  canvas->cd(2);
  hist1->Add(hback, -outpar[0]);
  hist1->SetTitle("Data Signal with Fitted Background Subtracted");
  hist1->GetXaxis()->SetTitle("x");
  hist1->GetYaxis()->SetTitle("y");
  hist1->GetZaxis()->SetTitle("signal value");
  hist1->GetXaxis()->CenterTitle();
  hist1->GetYaxis()->CenterTitle();
  hist1->GetXaxis()->SetTitleOffset(1.25);
  hist1->GetYaxis()->SetTitleOffset(1.25);
  hist1->Draw("lego");

 
  cout << "To exit, quit ROOT from the File menu of the plot (or use control-C)" << endl;
  theApp.Run(true);
  canvas->Close();

  return 0;

}
Exemplo n.º 6
0
void PlotV2ForJetAndTrack(){


  /* Variable */
  double ETMIN = 15;
  
  /* File Loading */
  TFile *f1 = new TFile("../root_files/ANA_spectAnaGEN_March26_PtAll_Ntot400K_proq20_FullExt_Large_VariedN.root");

  TFile *f2=0, *f3=0, *f4=0;
  f2 = new TFile("../root_files/ANA_spectAnaGEN_March26_PtAll_Ntot400K_proq20_FullExt_Large_VariedN_jetQ_fractLog2.00_phidep_a7.00_b10.00.root");

  /* Histogram Loading */
  TH1F *hdnevtminpthat = (TH1F*) f1->Get("dNevtMinPtHat");

  TH1F *hjetspecv0 = (TH1F*) f1->Get("dNJetdEt");

  TH2F *hjetspecdphiv0 = (TH2F*) f1->Get("dNJetdEtdPhi");
  TH2F *hjetspecdphiv0_q1 = (TH2F*) f2->Get("dNJetdEtdPhi");
  TH2F *hjetspecdcos2phiv0_q1 = (TH2F*) f2->Get("dNJetdEtdCos2Phi");

  TH2F *hdntrkdptdpthat = (TH2F*) f1->Get("dNTrkdPtdPtHat");

  TH3F *hdntrkdptdjetetdphi = (TH3F*) f1->Get("dNTrkdPtdJetEtdPhi");
  TH3F *hdntrkdptdpthatdjetet = (TH3F*) f1->Get("dNTrkdPtdPtHatdJetEt");
  

  double small = 1e-3;
  double tot_evt_minpthat = hdnevtminpthat->GetEntries();

  cout<<"Number of min_pt_hat event sample = "<<tot_evt_minpthat<<endl;

  if(tot_evt_minpthat<1E-22){
    cout<<"This sample doesn't include the minimum pt hat bin sample!"<<endl;
    return;
  }

  /* Overall Normalization */
  hjetspecv0->Scale(1./tot_evt_minpthat);
  hjetspecdphiv0->Scale(1./tot_evt_minpthat);
  hjetspecdphiv0_q1->Scale(1./tot_evt_minpthat);
  hdntrkdptdpthat->Scale(1./tot_evt_minpthat);
  hdntrkdptdjetetdphi->Scale(1./tot_evt_minpthat);
  hdntrkdptdpthatdjetet->Scale(1./tot_evt_minpthat);

  /* Dividing By Bin Width */
  divideByWidth(hjetspecv0);


  /* Duplications of Some Histograms */
  TH2F *hjetspecdphiv0_cln = (TH2F*) hjetspecdphiv0->Clone("hjetspecdphiv0_cln");
  TH2F *hjetspecdphiv0_q1_cln = (TH2F*) hjetspecdphiv0_q1->Clone("hjetspecdphiv0_q1_cln");
  TH3F *hdntrkdptdjetetdphi_cln = (TH3F*) hdntrkdptdjetetdphi->Clone("hdntrkdptdjetetdphi_cln");


  /* Dum Histograms */
  TH1D *hdum = new TH1D("hdum","",200,-3.2,3.2);
  hdum->SetStats(0);
  hdum->SetAxisRange(-0.001,0.1,"Y");
  hdum->GetXaxis()->SetTitle("#phi - #psi (rad)");
  hdum->GetXaxis()->CenterTitle();
  hdum->GetYaxis()->SetTitle("A.U");
  hdum->GetYaxis()->CenterTitle();
  hdum->GetXaxis()->SetMoreLogLabels();
  setHist(hdum);

  TH1D *hdum_1 = (TH1D*) hdum->Clone("hdum_1");
  hdum_1->SetAxisRange(0.0,2.0,"X");
  hdum_1->SetAxisRange(-0.001,0.2,"Y");
  hdum_1->GetXaxis()->SetTitle("2cos(#phi - #psi (rad))");
  

  /* ------------ Jet V2 --------------- */

  cout<<"Number of ET bins = "<<hjetspecdphiv0_q1->GetNbinsX()<<endl;

  TCanvas *c0 = new TCanvas("c0","",1250,930);
  makeMultiPanelCanvas(c0,5,4,0.0,0.0,0.2,0.2,0.02);

  TCanvas *c0_1 = new TCanvas("c0_1","",1250,930);
  makeMultiPanelCanvas(c0_1,5,4,0.0,0.0,0.2,0.2,0.02);


  int index = 0;
  hjetspecdphiv0_q1->RebinX(10);  // as original bin is too fine
  hjetspecdcos2phiv0_q1->RebinX(10);

  TH1D *hjetspecdphiv0_q1_projx= (TH1D*) hjetspecdphiv0_q1->ProjectionX("hjetspecdphiv0_q1_projx",0,-1,"e");
  TH1D *hjetspecdcos2phiv0_q1_projx= (TH1D*) hjetspecdcos2phiv0_q1->ProjectionX("hjetspecdcos2phiv0_q1_projx",0,-1,"e");

  for(int i=0;i<hjetspecdphiv0_q1->GetNbinsX();i++){
    
    double etmin = hjetspecdphiv0_q1->GetXaxis()->GetBinLowEdge(i+1);
    double etmax = hjetspecdphiv0_q1->GetXaxis()->GetBinUpEdge(i+1);

    // dPhi distribution of Jet
    TH1D *hjetspec_dphi = (TH1D*) hjetspecdphiv0_q1->ProjectionY("",i+1,i+1,"e");
    hjetspec_dphi->SetName(Form("hjetspec_dphi_et%1.0fto%1.0f",etmin,etmax));     

    // cos(dPhi) distribution of Jet
    TH1D *hjetspec_dcosphi = (TH1D*) hjetspecdcos2phiv0_q1->ProjectionY("",i+1,i+1,"e");
    hjetspec_dcosphi->SetName(Form("hjetspec_dcosphi_et%1.0fto%1.0f",etmin,etmax));

    // --> rebinning
    hjetspec_dphi->Rebin(4);
    hjetspec_dphi->Scale(1./4.);
    
    hjetspec_dcosphi->Rebin(4);
    hjetspec_dcosphi->Scale(1./4.);

    // --> dN/dphi (not necessary, though)
    //divideByWidth(hjetspec_dphi);

    // --> Normalization 
    hjetspec_dphi->Scale(1./hjetspec_dphi->Integral());
    hjetspec_dcosphi->Scale(1./hjetspec_dcosphi->Integral());


    // Draw
    if(etmin<ETMIN) continue;
    if(i%2+1) index++;
    if(index<20) {

      // Fitting methods
      c0->cd(index);
      hdum->Draw("");
      hjetspec_dphi->SetMarkerStyle(20);
      hjetspec_dphi->SetMarkerSize(1.0);
      hjetspec_dphi->Draw("pzsame");

      TLatex *tl_jet = new TLatex(0.5,0.8,Form("%1.1f<E_{T}<%1.1f",etmin,etmax));
      tl_jet->SetTextFont(63);
      tl_jet->SetTextSize(16);
      tl_jet->SetTextColor(kBlack);
      tl_jet->SetLineWidth(1);
      tl_jet->SetNDC();
      tl_jet->Draw("");

      // Fitting
      TF1 *fit1 = new TF1("fit1",FourierDecomp,-3.2,3.2,7);
      //for(int k=0;k<7;k++) fit1->SetParLimits(k,0,10);
      hjetspec_dphi->Fit(fit1,"RNQ");
      
      fit1->SetLineColor(kRed);
      fit1->SetLineWidth(2);
      fit1->Draw("same");

      double par1[7];
      const int binn = sizeof(par1)/sizeof(double) - 1;
      for(int j=0;j<binn;j++) par1[j] = 0.0;
      par1[0] = fit1->GetParameter(0);
      par1[2] = fit1->GetParameter(2);
      //cout<<"par1[2] = "<<par1[2]<<endl;

      TF1 *fit1_v2 = new TF1("fit1_v2",FourierDecomp,-3.2,3.2,7);
      fit1_v2->SetParameters(par1);
      fit1_v2->SetLineColor(kBlue);
      fit1_v2->SetLineWidth(2);
      fit1_v2->Draw("same");
      
      // Extracting methods
      c0_1->cd(index);
      hdum_1->Draw("");
      hjetspec_dcosphi->SetMarkerStyle(20);
      hjetspec_dcosphi->SetMarkerSize(1.0);
      hjetspec_dcosphi->Draw("pzsame");

      cout<<"PAR0 = "<<fit1->GetParameter(0)<<" PAR1 = "<<fit1->GetParameter(1)
	  <<" PAR2 = "<<fit1->GetParameter(2)<<" PAR3 = "<<fit1->GetParameter(3)<<endl;
      //cout<<"fit1->GetParameter(2) = "<<fit1->GetParameter(2)<<endl;
      //cout<<" hjetspec_dcosphi = "<<hjetspec_dcosphi->GetMean()<<endl;
      
      // v2 vs pT
      hjetspecdphiv0_q1_projx->SetBinContent(i+1,fit1->GetParameter(2));
      hjetspecdcos2phiv0_q1_projx->SetBinContent(i+1,GetMeanV2(hjetspec_dcosphi));
      //hjetspecdcos2phiv0_q1_projx->SetBinContent(i+1,hjetspec_dcosphi->Integral()/hjetspec_dcosphi->GetEntries());
      //hjetspecdcos2phiv0_q1_projx->SetBinContent(i+1,hjetspec_dcosphi->GetMean());
    }

    
  }

  // Drawing V2 (pT)
  TCanvas *c1 =new TCanvas("c1","v_{2} as a function of p_{T}",500,500);
  hjetspecdphiv0_q1_projx->SetStats(0);
  //hjetspecdphiv0_q1_projx->SetAxisRange(-0.0001,0.001,"Y");
  hjetspecdphiv0_q1_projx->SetAxisRange(-0.0001,2.0,"Y");    
  hjetspecdphiv0_q1_projx->SetAxisRange(ETMIN,300,"X");
  hjetspecdphiv0_q1_projx->GetYaxis()->SetTitle("Jet v_{2}");
  hjetspecdphiv0_q1_projx->GetXaxis()->SetTitle("Jet E_{T}");
  hjetspecdphiv0_q1_projx->GetXaxis()->CenterTitle();
  hjetspecdphiv0_q1_projx->GetYaxis()->CenterTitle();
  hjetspecdphiv0_q1_projx->GetXaxis()->SetMoreLogLabels();
  hjetspecdphiv0_q1_projx->SetMarkerSize(1.2);
  hjetspecdphiv0_q1_projx->Draw("");
  
  hjetspecdcos2phiv0_q1_projx->SetMarkerColor(kRed);
  hjetspecdcos2phiv0_q1_projx->SetMarkerSize(1.2);
  hjetspecdcos2phiv0_q1_projx->Draw("pzsame");



  /* ---------------- Convoluting Jet Spectra with FF ---------------- */

  // Obtain FF 
  // - 3D of (track pt, pthat, jet et) 
  // - 1D of dN/dET 

  //ObtainFF(hdntrkdptdpthatdjetet, hjetspecv0);
  Obtain2DFF(hdntrkdptdjetetdphi, hjetspecv0);
  
  TH2D *hdntrkdptdphi_cln = (TH2D*) hdntrkdptdjetetdphi_cln->Project3D("zxe");
  hdntrkdptdphi_cln->Reset();

  for(int ij=0;ij<hjetspecdphiv0_cln->GetNbinsX();ij++){

    double etmin = hjetspecdphiv0_cln->GetXaxis()->GetBinLowEdge(ij+1);
    double etmax = hjetspecdphiv0_cln->GetXaxis()->GetBinUpEdge(ij+1);

    // dPhi distribution of Jet
    TH1D *hjetspec_dphi_cln = (TH1D*) hjetspecdphiv0_q1_cln->ProjectionY("",ij+1,ij+1,"e");
    hjetspec_dphi_cln->SetName(Form("hjetspec_dphi_cln_et%1.0fto%1.0f",etmin,etmax));

    // FF (pt,phi) 
    TH2D *hdntrkdpt_2dff_cln2 = (TH2D*) gDirectory->Get(Form("hdntrkdpt_2dff_et%1.0fto%1.0f",etmin,etmax));
    if(hdntrkdpt_2dff_cln2==0) continue;  // don't use empty histograms  

    // Loop over phi in each jet ET bin 
    for(int ijk=0;ijk<hjetspec_dphi_cln->GetNbinsX();ijk++){ 
      
      double phimin = hjetspec_dphi_cln->GetXaxis()->GetBinLowEdge(ijk+1);
      double phimax = hjetspec_dphi_cln->GetXaxis()->GetBinUpEdge(ijk+1);

      //cout<<"phi: "<<phimin<<" to "<<phimax<<endl;

      //TH1D *hdntrkdpt_1dff_cln2 = (TH1D*) hdntrkdpt_2dff_cln2->ProjectionY("",ijk,ijk,"e");
      //hdntrkdpt_1dff_cln2->SetName(Form("hdntrkdpt_1dff_cln2_phi%1.0fto%1.0f",phimin,phimax));

      double dsigma_v0 = hjetspec_dphi_cln->GetBinContent(ijk+1);
      //hdntrkdpt_1dff_cln2->Scale(dsigma_v0);

      // Scale each (pt,phi) 
      for(int m=0;m<hdntrkdpt_2dff_cln2->GetNbinsX();m++){

	double ffval = hdntrkdpt_2dff_cln2->GetBinContent(m,ijk);
	double ffvalerr = hdntrkdpt_2dff_cln2->GetBinError(m,ijk);

	hdntrkdpt_2dff_cln2->SetBinContent(m,ijk,ffval*dsigma_v0);
	hdntrkdpt_2dff_cln2->SetBinError(m,ijk,ffvalerr*dsigma_v0);
      } // end of m

    }// end of ijk

    hdntrkdptdphi_cln->Add(hdntrkdpt_2dff_cln2);

  }// end of convolution

  /* ----------------------- Charged Particle V2 ----------------- */
  TCanvas *c2 =new TCanvas("c2","Track p_{T} vs #phi",500,500);
  hdntrkdptdphi_cln->Draw("COLZ");
  //hdntrkdptdphi_cln->ProjectionX()->Draw("");
  //hdntrkdptdphi_cln->ProjectionY()->Draw("");   
  

  TCanvas *c0_2 = new TCanvas("c0_2","",1250,930);
  makeMultiPanelCanvas(c0_2,5,4,0.0,0.0,0.2,0.2,0.02);


  for(int n=0;n<hdntrkdptdphi_cln->GetNbinsX();n++){
    
    
  }
  



}
Exemplo n.º 7
0
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}
Exemplo n.º 8
0
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;
}
Exemplo n.º 9
0
// This ROOT macro plots the stopping depth of the muons in local coordinates
void StoppingDepth(std::string filename) {

  TCanvas* c1 = new TCanvas("c1", "c1");
  c1->SetRightMargin(0.15);
  int n_entries = 100000;

  TFile* file = new TFile(filename.c_str(), "READ");
  TTree* tree = (TTree*) file->Get("tree");
  double n_input_muons = tree->GetEntries();

  size_t secondslash = filename.rfind("/")+1; // don't want to include the slash
  size_t firstdot = filename.rfind(".");
  size_t n_chars = firstdot - secondslash;
  std::string base_filename = filename.substr(secondslash, n_chars);
  std::string histtitle = "Plot of the Stopping Depth of Muons in " + base_filename;
  TH2F* hStopDepth = new TH2F("hStopDepth", histtitle.c_str(), 120,-6,6, 120,-5,55);
  hStopDepth->GetYaxis()->SetTitle("Local Z [#mum]");
  hStopDepth->GetXaxis()->SetTitle("Local X [cm]");
  hStopDepth->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}");
  hStopDepth->Scale(1.0 / n_input_muons);
  hStopDepth->SetStats(false);

  tree->Draw("-1*((M_local_Oz*10000)-25):M_local_Ox>>hStopDepth", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries);
  
  c1->Update();
  std::string canvasname = "hStopDepth_" + base_filename + ".png";
  //  c1->Print(canvasname.c_str());

  TH1D* hStopZDepth = hStopDepth->ProjectionY();
  hStopZDepth->Draw();
  hStopZDepth->SetStats(false);
  hStopZDepth->GetYaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}");
  //  hStopZDepth->Scale(1.0 / n_input_muons);
  c1->Update();
  canvasname = "hStopZDepth_" + base_filename + ".png";
  //  c1->Print(canvasname.c_str());

  TH2F* hStopDepthVsTime = new TH2F("hStopDepthVsTime", histtitle.c_str(), 120,-30,30, 120,0,12);
  hStopDepthVsTime->GetXaxis()->SetTitle("Local Z [#mum]");
  hStopDepthVsTime->GetYaxis()->SetTitle("Time [ns]");
  hStopDepthVsTime->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}");
  hStopDepthVsTime->Scale(1.0 / n_input_muons);
  hStopDepthVsTime->SetStats(false);

  //  tree->Draw("M_Ot:M_local_Oz*10000>>hStopDepthVsTime", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries);
  
  c1->Update();
  canvasname = "hStopDepthVsTime_" + base_filename + ".png";
  //  c1->Print(canvasname.c_str());

  TH2F* hStopDepthVsMomentum = new TH2F("hStopDepthVsMomentum", histtitle.c_str(), 120,-30,30, 120,0,30);
  hStopDepthVsMomentum->GetXaxis()->SetTitle("Local Z [#mum]");
  hStopDepthVsMomentum->GetYaxis()->SetTitle("Momentum [MeV]");
  hStopDepthVsMomentum->GetZaxis()->SetTitle("N_{stop-#mu} / N_{input-#mu}");
  hStopDepthVsMomentum->Scale(1.0 / n_input_muons);
  hStopDepthVsMomentum->SetStats(false);

  //  tree->Draw("sqrt(M_px*M_px + M_py*M_py+ M_pz*M_pz)*1000:M_local_Oz*10000>>hStopDepthVsMomentum", "M_particleName==\"mu-\" && M_volName==\"Target\" && M_stopped == 1", "COLZ", n_entries);
  
  c1->Update();
  canvasname = "hStopDepthVsMomentum_" + base_filename + ".png";
  //  c1->Print(canvasname.c_str());
  //  file->Close();

  std::string outfilename = "plot_" + base_filename + ".root";
  TFile* output = new TFile(outfilename.c_str(), "RECREATE");
  hStopDepth->Write();
  hStopZDepth->Write();
  hStopDepthVsTime->Write();
  hStopDepthVsMomentum->Write();
  output->Close();
}
Exemplo n.º 10
0
void makeSMSCards(){

  //---------------------------------------
  // load TChain
  //---------------------------------------
  
  TChain *ch = new TChain("T1");
  ch->Add("output/V00-02-13/wzsms_baby_oldIso.root");
  char* version = (char*) "V00-00-14";

  //---------------------------------------
  // load denominator histogram
  //---------------------------------------

  TFile* fdenom = TFile::Open("output/V00-02-13/wzsms_ngen.root");
  TH2F*  hdenom = (TH2F*) fdenom->Get("hmass");
  hdenom->Scale(10.0);

  //---------------------------------------
  // selection
  //---------------------------------------

  TCut weight   ("19500.0 * trgeff * vtxweight");
  //TCut weight   ("19500.0 * trgeff * vtxweight * (1./100000.)");
  //TCut weight   ("9.2 * trgeff * vtxweight * weight");

  // MEDIUM WP
  TCut presel   ("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvm==0 && mjj>70   && mjj<110   && nlep==2 && njets>=2     && leptype<2");
  TCut preseljup("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvm==0 && mjjup>70 && mjjup<110 && nlep==2 && njetsup>=2   && leptype<2");
  TCut preseljdn("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvm==0 && mjjdn>70 && mjjdn<110 && nlep==2 && njetsdn>=2   && leptype<2");

  /*
  // LOOSE WP
  TCut presel   ("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvl==0 && mjj>70   && mjj<110   && nlep==2 && njets>=2     && leptype<2");
  TCut preseljup("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvl==0 && mjjup>70 && mjjup<110 && nlep==2 && njetsup>=2   && leptype<2");
  TCut preseljdn("lep2.pt()>20.0 && dilmass>81 && dilmass<101 && nbcsvl==0 && mjjdn>70 && mjjdn<110 && nlep==2 && njetsdn>=2   && leptype<2");
  */

  const unsigned int nbins = 5;
  float metcuts[nbins+1] = {80,100,120,150,200,9999999};

  TCut sigall(Form("pfmet>%.0f"  ,metcuts[0]));
  TCut sigalldn(Form("pfmetdn>%.0f",metcuts[0]));

  cout << "Full signal region            " << sigall.GetTitle()   << endl;
  cout << "Full signal region (JES down) " << sigalldn.GetTitle() << endl;

  TCut sigcut[nbins];
  TCut sigcutup[nbins];
  TCut sigcutdn[nbins];

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    sigcut[i]   = TCut(Form("pfmet  >%.0f && pfmet<%.0f"   , metcuts[i] , metcuts[i+1]));
    sigcutup[i] = TCut(Form("pfmetup>%.0f && pfmetup<%.0f" , metcuts[i] , metcuts[i+1]));
    sigcutdn[i] = TCut(Form("pfmetdn>%.0f && pfmetdn<%.0f" , metcuts[i] , metcuts[i+1]));

    cout << "Region  : " << i << endl;
    cout << "Nominal : " << sigcut[i].GetTitle()   << endl;
    cout << "JES up  : " << sigcutup[i].GetTitle() << endl;
    cout << "JES dn  : " << sigcutdn[i].GetTitle() << endl << endl;
  }
  
  //---------------------------------------
  // preselection and signal region yields
  //---------------------------------------

  TH2F* h[nbins];
  TH2F* hjup[nbins];
  TH2F* hjdn[nbins];

  int   nx   =    41;
  float xmin =  -5.0;
  float xmax = 405.0;

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        = new TH2F( Form("h_%i",i)        , Form("h_%i",i)           , nx,xmin,xmax,nx,xmin,xmax);
    hjup[i]     = new TH2F( Form("hjup_%i",i)     , Form("hjup_%i",i)        , nx,xmin,xmax,nx,xmin,xmax);
    hjdn[i]     = new TH2F( Form("hjdn_%i",i)     , Form("hjdn_%i",i)        , nx,xmin,xmax,nx,xmin,xmax);
    
    h[i]    ->Sumw2();
    hjup[i] ->Sumw2();
    hjdn[i] ->Sumw2();
  }
  
  TH2F* hall    = new TH2F( "hall"    , "hall"    , nx,xmin,xmax,nx,xmin,xmax);
  TH2F* hjdnall = new TH2F( "hjdnall" , "hjdnall" , nx,xmin,xmax,nx,xmin,xmax);
  
  hall->Sumw2();
  
  TCanvas *ctemp = new TCanvas();
  ctemp->cd();

  cout << "Filling histos..." << endl;
  for( unsigned int ibin = 0 ; ibin < nbins ; ibin++ ){
    ch->Draw(Form("ml:mg>>h_%i"    , ibin) , (presel    + sigcut[ibin]   ) * weight);
    ch->Draw(Form("ml:mg>>hjup_%i" , ibin) , (preseljup + sigcutup[ibin] ) * weight);
    ch->Draw(Form("ml:mg>>hjdn_%i" , ibin) , (preseljdn + sigcutdn[ibin] ) * weight);

    h[ibin]->Divide(hdenom);
    hjup[ibin]->Divide(hdenom);
    hjdn[ibin]->Divide(hdenom);
  }

  ch->Draw("ml:mg>>hall"        , (presel    + sigall     ) * weight);
  ch->Draw("ml:mg>>hjdnall"     , (preseljdn + sigalldn   ) * weight);

  hall->Divide(hdenom);
  hjdnall->Divide(hdenom);

  delete ctemp;

  ofstream* doScript = new ofstream();
  doScript->open(Form("cards/%s/doLimits.sh",version));

  ofstream* doScript_CLs = new ofstream();
  doScript_CLs->open(Form("cards/%s/doLimits_CLs.sh",version));

  ofstream* doScript_CLs1 = new ofstream();
  doScript_CLs1->open(Form("cards/%s/doLimits_CLs1.sh",version));

  ofstream* doScript_CLs2 = new ofstream();
  doScript_CLs2->open(Form("cards/%s/doLimits_CLs2.sh",version));

  ofstream* doScript_CLs3 = new ofstream();
  doScript_CLs3->open(Form("cards/%s/doLimits_CLs3.sh",version));

  ofstream* doScript_CLs4 = new ofstream();
  doScript_CLs4->open(Form("cards/%s/doLimits_CLs4.sh",version));

  ofstream* doScript_CLs_mL0 = new ofstream();
  doScript_CLs_mL0->open(Form("cards/%s/doLimits_mL0.sh",version));

  ofstream* doScript_CLs_mL50 = new ofstream();
  doScript_CLs_mL50->open(Form("cards/%s/doLimits_mL50.sh",version));

  ofstream* doScript_CLs_mL100 = new ofstream();
  doScript_CLs_mL100->open(Form("cards/%s/doLimits_mL100.sh",version));

  ofstream* filelist = new ofstream();
  filelist->open(Form("cards/%s/file_list.txt",version));

  ofstream* filelist_CLs = new ofstream();
  filelist_CLs->open(Form("cards/%s/file_list_CLs.txt",version));


  //---------------------------------------
  // make and fill data and bkg histos
  //---------------------------------------

  /*
  // MEDIUM WP
  //signal regions             80-100 100-120 120-150 150-200    >200
  float Zbkg_yield[nbins]    = { 40.9 ,  7.0 ,  3.1 ,  1.6 ,     0.8  };
  float Zbkg_err[nbins]      = { 12.4 ,  2.2 ,  0.9 ,  0.5 ,     0.3  };
  float OFbkg_yield[nbins]   = { 17.9 , 11.3 ,  6.9 ,  2.4 ,     0.4  };
  float OFbkg_err[nbins]     = {  3.3 ,  2.2 ,  1.5 ,  1.1 ,     0.3  };
  float WZbkg_yield[nbins]   = {  3.9 ,  2.1 ,  1.6 ,  1.0 ,     0.5  };
  float WZbkg_err[nbins]     = {  2.7 ,  1.5 ,  1.1 ,  0.7 ,     0.5  };
  float ZZbkg_yield[nbins]   = {  1.8 ,  1.0 ,  1.1 ,  0.8 ,     0.7  };
  float ZZbkg_err[nbins]     = {  0.9 ,  0.5 ,  0.6 ,  0.4 ,     0.7  };
  float rarebkg_yield[nbins] = {  0.3 ,  0.2 ,  0.3 ,  0.2 ,     0.2  };
  float rarebkg_err[nbins]   = {  0.2 ,  0.1 ,  0.1 ,  0.1 ,     0.2  };
  int   data_yield[nbins]    = {   56 ,   24 ,   16 ,    3 ,       1  };
  */

  /*
  // LOOSE WP
  //signal regions             80-100 100-120 120-150 150-200    >200
  float Zbkg_yield[nbins]    = { 29.7 ,  3.8 ,  2.2 ,  1.4 ,     0.5  };
  float Zbkg_err[nbins]      = {  9.1 ,  1.2 ,  0.7 ,  0.4 ,     0.2  };
  float OFbkg_yield[nbins]   = {  6.3 ,  5.0 ,  2.7 ,  1.4 ,     0.1  };
  float OFbkg_err[nbins]     = {  1.4 ,  1.2 ,  0.7 ,  0.7 ,     0.1  };
  float WZbkg_yield[nbins]   = {  2.6 ,  1.5 ,  1.0 ,  0.7 ,     0.3  };
  float WZbkg_err[nbins]     = {  1.8 ,  1.0 ,  0.7 ,  0.5 ,     0.3  };
  float ZZbkg_yield[nbins]   = {  1.4 ,  0.8 ,  0.8 ,  0.6 ,     0.5  };
  float ZZbkg_err[nbins]     = {  0.7 ,  0.4 ,  0.4 ,  0.3 ,     0.5  };
  float rarebkg_yield[nbins] = {  0.2 ,  0.1 ,  0.2 ,  0.2 ,     0.1  };
  float rarebkg_err[nbins]   = {  0.1 ,  0.1 ,  0.1 ,  0.1 ,     0.1  };
  int   data_yield[nbins]    = {   40 ,   10 ,   10 ,    2 ,       1  };
  */

  /*
  // MEDIUM WP, 19.3/fb RESULTS
  float Zbkg_yield[nbins]    = { 68.9 ,  7.8 ,  4.8 ,  2.1 ,     0.5  };
  float Zbkg_err[nbins]      = { 21.2 ,  2.5 ,  1.5 ,  0.7 ,     0.1  };
  float OFbkg_yield[nbins]   = { 35.2 , 21.9 , 13.2 ,  5.7 ,     0.8  };
  float OFbkg_err[nbins]     = {  6.2 ,  4.0 ,  2.5 ,  1.6 ,     0.4  };
  float WZbkg_yield[nbins]   = {  7.4 ,  4.0 ,  3.3 ,  2.0 ,     0.9  };
  float WZbkg_err[nbins]     = {  3.7 ,  2.0 ,  1.6 ,  1.0 ,     0.9  };
  float ZZbkg_yield[nbins]   = {  3.2 ,  1.9 ,  2.1 ,  1.5 ,     1.4  };
  float ZZbkg_err[nbins]     = {  1.6 ,  1.0 ,  1.1 ,  0.8 ,     1.4  };
  float rarebkg_yield[nbins] = {  0.9 ,  0.4 ,  0.9 ,  0.6 ,     0.4  };
  float rarebkg_err[nbins]   = {  0.5 ,  0.2 ,  0.5 ,  0.3 ,     0.4  };
  int   data_yield[nbins]    = {  115 ,   36 ,   25 ,   13 ,       4  };
  */

  // MEDIUM WP, 19.5/fb RESULTS
  // float Zbkg_yield[nbins]    = { 64.5 ,  7.8 ,  3.7 ,  2.0 ,     0.4  };
  // float Zbkg_err[nbins]      = { 22.2 ,  3.1 ,  1.6 ,  1.0 ,     0.3  };
  // float OFbkg_yield[nbins]   = { 35.2 , 21.9 , 13.2 ,  5.7 ,     0.8  };
  // float OFbkg_err[nbins]     = {  6.2 ,  4.0 ,  2.5 ,  1.6 ,     0.4  };
  // float WZbkg_yield[nbins]   = {  7.4 ,  4.0 ,  3.3 ,  2.0 ,     0.9  };
  // float WZbkg_err[nbins]     = {  3.7 ,  2.0 ,  1.6 ,  1.0 ,     0.9  };
  // float ZZbkg_yield[nbins]   = {  3.2 ,  1.9 ,  2.1 ,  1.5 ,     1.4  };
  // float ZZbkg_err[nbins]     = {  1.6 ,  1.0 ,  1.1 ,  0.8 ,     1.4  };
  // float rarebkg_yield[nbins] = {  0.9 ,  0.4 ,  0.9 ,  0.6 ,     0.4  };
  // float rarebkg_err[nbins]   = {  0.5 ,  0.2 ,  0.5 ,  0.3 ,     0.4  };
  // int   data_yield[nbins]    = {  115 ,   36 ,   25 ,   13 ,       4  };

  // MEDIUM WP, 19.5/fb RESULTS (fix b-veto)
  float Zbkg_yield[nbins]    = { 64.5 ,  7.8 ,  3.7 ,  2.0 ,     0.4  };
  float Zbkg_err[nbins]      = { 22.2 ,  3.1 ,  1.6 ,  1.0 ,     0.3  };
  float OFbkg_yield[nbins]   = { 35.2 , 21.9 , 13.2 ,  5.7 ,     0.8  };
  float OFbkg_err[nbins]     = {  6.2 ,  4.0 ,  2.5 ,  1.6 ,     0.4  };
  float WZbkg_yield[nbins]   = {  6.8 ,  3.7 ,  2.9 ,  1.9 ,     0.9  };
  float WZbkg_err[nbins]     = {  3.4 ,  1.9 ,  1.5 ,  0.9 ,     0.4  };
  float ZZbkg_yield[nbins]   = {  2.8 ,  1.8 ,  1.9 ,  1.4 ,     1.3  };
  float ZZbkg_err[nbins]     = {  1.4 ,  0.9 ,  0.9 ,  0.7 ,     0.7  };
  float rarebkg_yield[nbins] = {  0.5 ,  0.2 ,  0.4 ,  0.4 ,     0.3  };
  float rarebkg_err[nbins]   = {  0.2 ,  0.1 ,  0.2 ,  0.2 ,     0.1  };
  int   data_yield[nbins]    = {  115 ,   36 ,   25 ,   13 ,       4  };

  int   data_tot  = 0;
  float Zbkg_tot  = 0;
  float OFbkg_tot = 0;
  float WZbkg_tot = 0;
  float ZZbkg_tot = 0;
  float rarebkg_tot = 0;

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    cout << "Bin      " << i << endl;
    cout << "Data     " << data_yield[i] << endl;
    cout << "Z  bkg   " << Form("%.1f +/- %.1f" ,Zbkg_yield[i]    , Zbkg_err[i])    << endl;
    cout << "OF bkg   " << Form("%.1f +/- %.1f" ,OFbkg_yield[i]   , OFbkg_err[i])   << endl;
    cout << "WZ bkg   " << Form("%.1f +/- %.1f" ,WZbkg_yield[i]   , WZbkg_err[i])   << endl;
    cout << "ZZ bkg   " << Form("%.1f +/- %.1f" ,ZZbkg_yield[i]   , ZZbkg_err[i])   << endl;
    cout << "rare bkg " << Form("%.1f +/- %.1f" ,rarebkg_yield[i] , rarebkg_err[i]) << endl;

    data_tot     += data_yield[i];
    Zbkg_tot     += Zbkg_yield[i];
    OFbkg_tot    += OFbkg_yield[i];
    WZbkg_tot    += WZbkg_yield[i];
    ZZbkg_tot    += ZZbkg_yield[i];
    rarebkg_tot  += rarebkg_yield[i];
  }

  cout << "Total data     " << data_tot    << endl;
  cout << "Total Z  bkg   " << Zbkg_tot    << endl;
  cout << "Total OF bkg   " << OFbkg_tot   << endl;
  cout << "Total WZ bkg   " << WZbkg_tot   << endl;
  cout << "Total ZZ bkg   " << ZZbkg_tot   << endl;
  cout << "Total rare bkg " << rarebkg_tot << endl;

  TH1F* histo_Data = new TH1F("histo_Data","histo_Data",nbins,0,nbins);

  TH1F* histo_Zbkg               = new TH1F("histo_Zbkg"                ,"histo_Zbkg"           ,nbins,0,nbins);
  TH1F* histo_Zbkg_errUp         = new TH1F("histo_Zbkg_errZUp"         ,"histo_Zbkg_errZUp"    ,nbins,0,nbins);
  TH1F* histo_Zbkg_errDown       = new TH1F("histo_Zbkg_errZDown"       ,"histo_Zbkg_errZDown"  ,nbins,0,nbins);

  TH1F* histo_OFbkg              = new TH1F("histo_OFbkg"               ,"histo_OFbkg"          ,nbins,0,nbins);
  TH1F* histo_OFbkg_errUp        = new TH1F("histo_OFbkg_errOFUp"       ,"histo_OFbkg_errOFUp"  ,nbins,0,nbins);
  TH1F* histo_OFbkg_errDown      = new TH1F("histo_OFbkg_errOFDown"     ,"histo_OFbkg_errOFDown",nbins,0,nbins);

  TH1F* histo_WZbkg              = new TH1F("histo_WZbkg"               ,"histo_WZbkg"          ,nbins,0,nbins);
  TH1F* histo_WZbkg_errUp        = new TH1F("histo_WZbkg_errWZUp"       ,"histo_WZbkg_errWZUp"  ,nbins,0,nbins);
  TH1F* histo_WZbkg_errDown      = new TH1F("histo_WZbkg_errWZDown"     ,"histo_WZbkg_errWZDown",nbins,0,nbins);

  TH1F* histo_ZZbkg              = new TH1F("histo_ZZbkg"               ,"histo_ZZbkg"          ,nbins,0,nbins);
  TH1F* histo_ZZbkg_errUp        = new TH1F("histo_ZZbkg_errZZUp"       ,"histo_ZZbkg_errZZUp"  ,nbins,0,nbins);
  TH1F* histo_ZZbkg_errDown      = new TH1F("histo_ZZbkg_errZZDown"     ,"histo_ZZbkg_errZZDown",nbins,0,nbins);
            
  TH1F* histo_rarebkg            = new TH1F("histo_rarebkg"             ,"histo_rarebkg"             ,nbins,0,nbins);
  TH1F* histo_rarebkg_errUp      = new TH1F("histo_rarebkg_errRAREUp"   ,"histo_rarebkg_errRAREUp"   ,nbins,0,nbins);
  TH1F* histo_rarebkg_errDown    = new TH1F("histo_rarebkg_errRAREDown" ,"histo_rarebkg_errRAREDown" ,nbins,0,nbins);
      
  for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){

    histo_Data                -> SetBinContent(ibin+1, data_yield[ibin] );

    histo_Zbkg                -> SetBinContent(ibin+1, Zbkg_yield[ibin]);
    histo_Zbkg_errUp          -> SetBinContent(ibin+1, Zbkg_yield[ibin] + Zbkg_err[ibin] );
    histo_Zbkg_errDown        -> SetBinContent(ibin+1, TMath::Max(Zbkg_yield[ibin] - Zbkg_err[ibin],(float)0.0) );

    histo_OFbkg               -> SetBinContent(ibin+1, OFbkg_yield[ibin]);
    histo_OFbkg_errUp         -> SetBinContent(ibin+1, OFbkg_yield[ibin] + OFbkg_err[ibin] );
    histo_OFbkg_errDown       -> SetBinContent(ibin+1, TMath::Max(OFbkg_yield[ibin] - OFbkg_err[ibin],(float)0.0) );

    histo_WZbkg               -> SetBinContent(ibin+1, WZbkg_yield[ibin]);
    histo_WZbkg_errUp         -> SetBinContent(ibin+1, WZbkg_yield[ibin] + WZbkg_err[ibin] );
    histo_WZbkg_errDown       -> SetBinContent(ibin+1, TMath::Max(WZbkg_yield[ibin] - WZbkg_err[ibin],(float)0.0) );

    histo_ZZbkg               -> SetBinContent(ibin+1, ZZbkg_yield[ibin]);
    histo_ZZbkg_errUp         -> SetBinContent(ibin+1, ZZbkg_yield[ibin] + ZZbkg_err[ibin] );
    histo_ZZbkg_errDown       -> SetBinContent(ibin+1, TMath::Max(ZZbkg_yield[ibin] - ZZbkg_err[ibin],(float)0.0) );

    histo_rarebkg             -> SetBinContent(ibin+1, rarebkg_yield[ibin]);
    histo_rarebkg_errUp       -> SetBinContent(ibin+1, rarebkg_yield[ibin] + rarebkg_err[ibin] );
    histo_rarebkg_errDown     -> SetBinContent(ibin+1, TMath::Max(rarebkg_yield[ibin] - rarebkg_err[ibin],(float)0.0) );
  }


  //------------------------------------------
  // loop over SMS points
  //------------------------------------------

  int counter = 0;

  for( int mgbin = 1 ; mgbin <= hall->GetXaxis()->GetNbins() ; mgbin++ ){
    for( int mlbin = 1 ; mlbin <= hall->GetYaxis()->GetNbins() ; mlbin++ ){

      //if( !( mgbin == 17 && mlbin == 5 ) ) continue;

      int mg  = hall->GetXaxis()->GetBinCenter(mgbin);
      int ml  = hall->GetXaxis()->GetBinCenter(mlbin);

      // bool pass = false;

      // if( mg==150 && ml==0  ) pass = true;
      // if( mg==200 && ml==0  ) pass = true;
      // if( mg==250 && ml==0  ) pass = true;
      // if( mg==150 && ml==25 ) pass = true;
      // if( mg==200 && ml==50 ) pass = true;
      // if( mg==250 && ml==50 ) pass = true;
      // if( mg==200 && ml==80 ) pass = true;
      // if( mg==250 && ml==80 ) pass = true;
      
      // if( !pass ) continue;

      cout << endl;
      cout << "----------------------------------" << endl;
      cout << "mg    " << mg    << " ml    " << ml    << endl;
      cout << "mgbin " << mgbin << " mlbin " << mlbin << endl;
      cout << "----------------------------------" << endl;

      if( hjdnall->GetBinContent(mgbin,mlbin) < 1e-10 ) continue;

      float nom = hall->GetBinContent(mgbin,mlbin);

      //---------------------------------------
      // make signal histos
      //---------------------------------------

      TH1F* histo_SMS               = new TH1F( Form("histo_SMS_%i_%i"              ,mgbin,mlbin) , Form("histo_SMS_%i_%i"              ,mgbin,mlbin) , nbins,0,nbins);
      TH1F* histo_SMS_JES_shapeUp   = new TH1F( Form("histo_SMS_%i_%i_JES_shapeUp"  ,mgbin,mlbin) , Form("histo_SMS_%i_%i_JES_shapeUp"  ,mgbin,mlbin) , nbins,0,nbins);
      TH1F* histo_SMS_JES_shapeDown = new TH1F( Form("histo_SMS_%i_%i_JES_shapeDown",mgbin,mlbin) , Form("histo_SMS_%i_%i_JES_shapeDown",mgbin,mlbin) , nbins,0,nbins);

      float sigtot    = 0;
      float sigtotjdn = 0;

      cout << "Signal yield" << endl;
      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++ ){
	float yieldnom = h[ibin]->GetBinContent(mgbin,mlbin);
	float yieldjup = hjup[ibin]->GetBinContent(mgbin,mlbin);
	float yieldjdn = hjdn[ibin]->GetBinContent(mgbin,mlbin);

	sigtot    += yieldnom;
	sigtotjdn += yieldjdn;

	histo_SMS->SetBinContent              ( ibin + 1 , yieldnom );
	histo_SMS_JES_shapeUp->SetBinContent  ( ibin + 1 , yieldjup );
	histo_SMS_JES_shapeDown->SetBinContent( ibin + 1 , yieldjdn );
      
	cout << "Bin " << ibin << " " << yieldnom << endl;
      }

      cout << "Total signal yield " << sigtot << endl;

      if( sigtotjdn < 1e-10 ) continue;
      //if( sigtot    < 2     ) continue;

      counter++;

      *doScript << Form("../../../../test/lands.exe -M Bayesian -d SMS_%i_%i.txt",mgbin,mlbin)         << endl;

      *doScript_CLs << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      *filelist << Form("cards/%s/SMS_%i_%i.txt_Bayesian_bysObsLimit.root",version,mgbin,mlbin)        << endl;

      *filelist_CLs << Form("cards/%s/SMS_%i_%i_m2lnQ.root",version,mgbin,mlbin)        << endl;

      if( counter%4 == 0 ) *doScript_CLs1 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( counter%4 == 1 ) *doScript_CLs2 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( counter%4 == 2 ) *doScript_CLs3 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( counter%4 == 3 ) *doScript_CLs4 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( mlbin==1 ) *doScript_CLs_mL0 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( mlbin==3 ) *doScript_CLs_mL50 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      if( mlbin==5 ) *doScript_CLs_mL100 << Form("../../../../test/lands.exe -d SMS_%i_%i.txt  -M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -n SMS_%i_%i -rMin 0 -rMax 100",mgbin,mlbin,mgbin,mlbin) << endl;

      printCard( Form("SMS_%i_%i",mgbin,mlbin) , sigtot , Zbkg_tot , OFbkg_tot , WZbkg_tot , ZZbkg_tot , rarebkg_tot , data_tot , version );


      TFile *f = TFile::Open( Form("rootfiles/%s/SMS_%i_%i.root",version,mgbin,mlbin) , "RECREATE");
      f->cd();
      histo_Data->Write();
      histo_Zbkg->Write();
      histo_Zbkg_errUp->Write();
      histo_Zbkg_errDown->Write();
      histo_OFbkg->Write();
      histo_OFbkg_errUp->Write();
      histo_OFbkg_errDown->Write();
      histo_WZbkg->Write();
      histo_WZbkg_errUp->Write();
      histo_WZbkg_errDown->Write();
      histo_ZZbkg->Write();
      histo_ZZbkg_errUp->Write();
      histo_ZZbkg_errDown->Write();
      histo_rarebkg->Write();
      histo_rarebkg_errUp->Write();
      histo_rarebkg_errDown->Write();
      histo_SMS->Write();
      histo_SMS_JES_shapeUp->Write();
      histo_SMS_JES_shapeDown->Write();
      f->Close();

      delete histo_SMS;
      delete histo_SMS_JES_shapeUp;
      delete histo_SMS_JES_shapeDown;
    }
  }

  doScript->close();
  doScript_CLs->close();
  doScript_CLs1->close();
  doScript_CLs2->close();
  doScript_CLs3->close();
  doScript_CLs4->close();
  doScript_CLs_mL0->close();
  doScript_CLs_mL50->close();
  filelist->close();
  filelist_CLs->close();

}
Exemplo n.º 11
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;
}
Exemplo n.º 12
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
void twoDlinearcombination(TH2F* first, int firsttype, TH2F* second, int secondtype, TH2F* input, int inputtype, TH2F* finaloutput, int outputtype, TH2F* finaloutput2, int output2type){
	TH2F* output = (TH2F*) input->Clone();
	TH2F* output2 = (TH2F*) output->Clone();
	if(outputtype==kIntHist || outputtype==kSigHist){
		if(inputtype==kBSI25Hist && firsttype==kSigHist && secondtype==kBkgHist){
			output->Add(first, -25.0);
			output->Add(second, -1.0);
			output->Scale(0.2);
			if (outputtype == kSigHist){ delete output; output = (TH2F*) first->Clone(); }

			output2->Add(first, -25.0);
			output2->Add(second, -1.0);
			output2->Scale(0.2);
			if (output2type == kSigHist){ delete output2; output2 = (TH2F*) first->Clone(); }
		}
		if(inputtype==kBSI25Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}		
		if(inputtype==kBSI25Hist && firsttype==kBSI10Hist && secondtype==kBkgHist){
			//double scaleval = 1./(-50. + 25.*sqrt(10.));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi10 = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi25 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi25,25,bsi10,10,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi25, 25, bsi10, 10, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		if(inputtype==kBSI10Hist && firsttype==kBSIHist && secondtype==kBkgHist){
			//double scaleval = 1./(10 - sqrt(10));
			for (int binx = 1; binx <= output->GetNbinsX(); binx++){
				for (int biny = 1; biny <= output->GetNbinsY(); biny++){
					double bsi = first->GetBinContent(binx,biny);
					double bkg = second->GetBinContent(binx,biny);
					double bsi10 = output->GetBinContent(binx,biny);

					double weight=doLinearCombination(bsi10,10,bsi,1,bkg,outputtype);
					output->SetBinContent(binx,biny,weight);
					if (finaloutput2 != 0){
						double weight2 = doLinearCombination(bsi10, 10, bsi, 1, bkg, output2type);
						output2->SetBinContent(binx, biny, weight2);
					}
				}
			}
		}
		for (int binx = 1; binx <= output->GetNbinsX(); binx++){
			for (int biny = 1; biny <= output->GetNbinsY(); biny++){
				finaloutput->SetBinContent(binx, biny, output->GetBinContent(binx, biny));
				if (finaloutput2 != 0) finaloutput2->SetBinContent(binx,biny,output2->GetBinContent(binx,biny));
			}
		}
	}
	else{cout<<"Option not yet supported. Exiting..."<<endl; assert(0);};
	delete output;
	delete output2;
}
Exemplo n.º 14
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;
}