Ejemplo n.º 1
0
///
/// Scale the error of a given observable.
/// Both stat and syst errors are being scaled by the same factor.
/// In order to become effective, the PDF needs to be rebuild by
/// calling buildCov() and buildPdf().
///
/// \param obsname	- observable name. It may or may not include a unique ID string, both works.
/// \param scale	- the scale factor the current error is being multiplied with
/// \return		- true if successful
///
bool PDF_Abs::ScaleError(TString obsname, float scale)
{
	// remove unique ID if necessary
	TString UID = "UID";
	if ( obsname.Contains(UID) ){
		obsname.Replace(obsname.Index(UID), obsname.Length(), ""); // delete the unique ID. That should leave just the observable name.
	}
	// find the index of the observable - if it exists at all!
	if ( !hasObservable(obsname) ){
		cout << "PDF_Abs::ScaleError() : ERROR : observable '" << obsname << "' not found." << endl;
		return false;
	}
	int index = -1;
	for ( int i=0; i<getNobs(); i++ ){
		if ( observables->at(i)->GetName()==obsname ){
			index = i;
			break;
		}
	}
	if ( index==-1 ){
		// this should never happen...
		cout << "PDF_Abs::ScaleError() : ERROR : internal self inconsistency discovered. Exit." << endl;
		assert(0);
	}
	// scale error
	StatErr[index] *= scale;
	SystErr[index] *= scale;
	// update error source string
	obsErrSource += " (PDF_Abs::ScaleError(): scaled error of " + obsname + ")";
	return true;
}
Ejemplo n.º 2
0
TString nPart(Int_t part,TString string)
{
    if (part <= 0) return "";
    for (int i = 1; i < part; i++)    //part-1 times
    {
        if (string.Index(";") < 0) return "";
        string.Replace(0,string.Index(";")+1,"",0);
    }
    if (string.Index(";") >= 0)
        string.Remove(string.Index(";"));
    return string;
}
///
/// Compute the file name of the parameter file defining the Asimov
/// point where the Asimov toy is generated at.
/// The combiner name will be followed by the Asimov addition (getAsimovCombinerNameAddition()),
/// but without the number denoting the Asimov point in the file, as the file contains all points.
/// Format of returned filename:
///
/// plots/par/basename_combinernameAsimov[_+N][_-N]_var1[_var2]_genpoints.dat
///
/// \param c - Combiner object
/// \return - filename
///
TString FileNameBuilder::getFileNameAsimovPar(const Combiner *c)
{
	TString name = "plots/par/";
	name += getFileBaseName(c);
	// remove any string after the "Asimov" token and the first "_" after that
	// e.g.: "combinerAsimov3_" -> "combinerAsimov_"
	int startOfToken = name.Index(m_asimov);
	int startOfFirstUnderscore = name.Index("_",startOfToken);
	int length = startOfFirstUnderscore-(startOfToken+m_asimov.Sizeof())+1;
	name.Replace(startOfToken+m_asimov.Sizeof()-1, length, "");
	name += "_genpoints.dat";
	return name;
}
TVirtualPad* ParameterEvolutionPlotter::selectNewPad()
{
	TCanvas* c1 = m_canvases[m_canvases.size()-1];
	if ( m_padId>=6 ){
		// Create a new canvas that has the old title "foo 3" but with
		// incremented number: "foo 4". Only one-digit numbers are supported.
		TString title = c1->GetTitle();
		int oldNumber = TString(title[title.Sizeof()-2]).Atoi(); // get last character and turn into integer
		title.Replace(title.Sizeof()-2,1,Form("%i",++oldNumber)); // replace last character with incremented integer
		c1 = selectNewCanvas(title);
	}
	m_padId+=1;
	return c1->cd(m_padId);
}
Ejemplo n.º 5
0
void writeFile(const char* inRootFile)
{
  TFile inRoot(inRootFile);
  if(!inRoot.IsOpen()){
    cout << "Cannot open " << inRootFile << endl;
    return;
  }
  TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator();
  TKey* key;

  TString outText = inRootFile;
  outText.Replace(0,outText.Last('/')+1,"");

  ofstream os(outText.Data());

  char buf[500];

  int count(0);
  while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){
    cout << key->GetName() << endl;
    TH1* h = (TH1*)inRoot.Get(key->GetName());
    if(h->GetDimension()!=1) continue;

    if(++count>1) break;

    int nBin = h->GetNbinsX();
    os << "name: " << h->GetName() << endl
       << "title: " << h->GetTitle() << endl
       << "bins: " << h->GetNbinsX() << endl
       << "min: " << h->GetXaxis()->GetBinLowEdge(1) 
       << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl;

    for(int i=1; i<=nBin; i++){
      os << "bin: " << i << " value: " << (float)h->GetBinContent(i)
	 << " error: " << (float)h->GetBinError(i) << endl;
    }
  }
   
}
Ejemplo n.º 6
0
void
RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
                                          int calculatorType,
                                          int testStatType, 
                                          bool useCLs,  
                                          int npoints,
                                          const char * fileNameBase ){

   // analyze result produced by the inverter, optionally save it in a file 
   
  
   double lowerLimit = 0;
   double llError = 0;
#if defined ROOT_SVN_VERSION &&  ROOT_SVN_VERSION >= 44126
   if (r->IsTwoSided()) {
      lowerLimit = r->LowerLimit();
      llError = r->LowerLimitEstimatedError();
   }
#else
   lowerLimit = r->LowerLimit();
   llError = r->LowerLimitEstimatedError();
#endif

   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();

   //std::cout << "DEBUG : [ " << lowerLimit << " , " << upperLimit << "  ] " << std::endl;
      
   if (lowerLimit < upperLimit*(1.- 1.E-4) && lowerLimit != 0) 
      std::cout << "The computed lower limit is: " << lowerLimit << " +/- " << llError << std::endl;
   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
  

   // compute expected limit
   std::cout << "Expected upper limits, using the B (alternate) model : " << std::endl;
   std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;
   std::cout << " expected limit (-2 sig) " << r->GetExpectedUpperLimit(-2) << std::endl;
   std::cout << " expected limit (+2 sig) " << r->GetExpectedUpperLimit(2) << std::endl;
  

   printf("\n\n  owen: (-2s,-1s,m,1s,2s)  %5.2f   %5.2f   %5.2f   %5.2f   %5.2f\n\n",
      r->GetExpectedUpperLimit(-2),
      r->GetExpectedUpperLimit(-1),
      r->GetExpectedUpperLimit(0),
      r->GetExpectedUpperLimit(1),
      r->GetExpectedUpperLimit(2) ) ;
  
   // write result in a file 
   if (r != NULL && mWriteResult) {
    
      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : (calculatorType == 1) ? "Hybr" : "Asym";
      const char *  limitType = (useCLs) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      if (mResultFileName.IsNull()) {
         mResultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
         //strip the / from the filename
         if (mMassValue.size()>0) {
            mResultFileName += mMassValue.c_str();
            mResultFileName += "_";
         }
    
         TString name = fileNameBase; 
         name.Replace(0, name.Last('/')+1, "");
         mResultFileName += name;
      }

      TFile * fileOut = new TFile(mResultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   
  
  
   // plot the result ( p values vs scan points) 
   std::string typeName = "";
   if (calculatorType == 0 )
      typeName = "Frequentist";
   if (calculatorType == 1 )
      typeName = "Hybrid";   
   else if (calculatorType == 2 || calculatorType == 3) { 
      typeName = "Asymptotic";
      mPlotHypoTestResult = false; 
   }
  
   const char * resultName = r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName.c_str(),resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);

   // plot in a new canvas with style
   TString c1Name = TString::Format("%s_Scan",typeName.c_str());
   TCanvas * c1 = new TCanvas(c1Name); 
   c1->SetLogy(false);

   plot->Draw("CLb 2CL");  // plot all and Clb

   // if (useCLs) 
   //    plot->Draw("CLb 2CL");  // plot all and Clb
   // else 
   //    plot->Draw("");  // plot all and Clb
  
   const int nEntries = r->ArraySize();
  
   // plot test statistics distributions for the two hypothesis 
   if (mPlotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      if (nEntries > 1) { 
         int ny = TMath::CeilNint(TMath::Sqrt(nEntries));
         int nx = TMath::CeilNint(double(nEntries)/ny);
         c2->Divide( nx,ny);
      }
      for (int i=0; i<nEntries; i++) {
         if (nEntries > 1) c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
   }
}
Ejemplo n.º 7
0
void minuitFit()
{

  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  cout << "Must Use Same Binning as previous Analysis!" << endl;

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  haveName = kFALSE;
  char fname[100];
  TFile* file;
  Bool_t makePDF = checkMakePDF();
  Bool_t makeROOT = checkMakeRoot();
  if(makeROOT){
    sprintf(fname,"/Users/zach/Research/pythia/200GeVTemplate/FFOutput/%s_FIT.root",FileNameR);
    file = new TFile(fname,"RECREATE");
    if (file->IsOpen()==kFALSE)
    {
      std::cout << "!!! Outfile Not Opened !!!" << std::endl;
      makeROOT = kFALSE;
    }
  }


  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/200GeVTemplate/currentTemplate.root");
  TFile *fT = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fT->IsOpen()==kFALSE || fD->IsOpen()==kFALSE)
  { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
    << "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
    exit(1); }

  // Set constants and projection bins (from header file anaConst, analysis constants)

  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;

  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  TCanvas* fitResultP = new TCanvas("fitResultP","RB Previous Analysis",150,0,1150,1000);
  TCanvas* scaleCheck = new TCanvas("scaleCheck","Check scale diff",150,0,1150,1000);
  TCanvas* prettyPlot = new TCanvas("prettyPlot","PrettyPlot",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);
  fitResultP->Divide(2,2);
  scaleCheck->Divide(1,2);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[4][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Double_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH2F*)fD->Get("histoNorms");
   // Get Previous Analysis
  TFile *file3 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_25_35.root");
  Hdphi[0]  = (TH1D*)file3->Get("fit_25_35");
  HpphiD[0] = (TH1D*)file3->Get("De_25_35");
  HpphiB[0] = (TH1D*)file3->Get("Be_25_35");
  TFile *file4 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_55_65.root");
  Hdphi[1]  = (TH1D*)file4->Get("fit_55_65");
  HpphiD[1] = (TH1D*)file4->Get("De_55_65");
  HpphiB[1] = (TH1D*)file4->Get("Be_55_65");

  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
  {
    bPtNorms[ptbin]   = (TH1F*)fT->Get(Form("beEventTally_%i",ptbin));
    cPtNorms[ptbin]   = (TH1F*)fT->Get(Form("ceEventTally_%i",ptbin));

    norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
    norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
    normB = bPtNorms[ptbin]->GetBinContent(1);
    normC = cPtNorms[ptbin]->GetBinContent(1);

    cout << ptbin << "; 0: " << norm0 << " 2: " << norm2 << endl;

    if( norm0 == 0)
    {
      cout << ptbin << " For this bin, some norm0 = 0" << endl;
      continue;
    }
    if( norm2 == 0 )
    {
      cout << ptbin << " For this bin, some norm2 = 0" << endl;
      continue;
    }
    if( normB == 0 )
    {
      cout << ptbin << " For this bin, some normB = 0" << endl;
      continue;
    }
    if( normC == 0)
    {
      cout << ptbin << " For this bin, some normC = 0" << endl;
      continue;
    }
    plotbin = ptbin;
    // Init necessary plotting tools
    lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
    sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
    lbl[ptbin]->AddText(textLabel);
    lbl[ptbin]->SetFillColor(kWhite);

    projB[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawbe_%i",ptbin));
    projC[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawce_%i",ptbin));
    projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
    projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
 
    pileupCorrect[ptbin][0] = (TH1D*)fD->Get(Form("pileupCorrection_%i_0",ptbin));
    pileupCorrect[ptbin][1] = (TH1D*)fD->Get(Form("pileupCorrection_%i_2",ptbin));
    pileupCorrect[ptbin][0]->Sumw2();
    pileupCorrect[ptbin][1]->Sumw2();

    // Do any rebinning
    Int_t RB = 1;
    projB[ptbin]->Rebin(RB);
    projC[ptbin]->Rebin(RB);
    projData0[ptbin]->Rebin(RB);
    projData2[ptbin]->Rebin(RB);

    // Clone to make plots without effecting fits
    plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
    plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
    plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

    // Set features that are the same in plots
    projData0[ptbin]->SetLineColor(kBlue);
    projData2[ptbin]->SetLineColor(kGreen+3);
    projB[ptbin]->SetLineColor(kRed);
    projC[ptbin]->SetLineColor(kBlack);
    projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
    plotD0[ptbin]->SetLineColor(kBlue);
    plotD2[ptbin]->SetLineColor(kGreen+3);
    plotD0[ptbin]->SetMarkerStyle(20);
    plotD0[ptbin]->SetMarkerColor(kBlue);
    plotD0[ptbin]->SetMarkerSize(0.4);
    plotB[ptbin]->SetLineColor(kRed);
    plotC[ptbin]->SetLineColor(kBlack);
    plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

    combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    combData[ptbin] -> Add(projData2[ptbin]);
    combData[ptbin]->SetLineColor(kBlue);
    combData[ptbin]->SetMarkerStyle(20);
    combData[ptbin]->SetMarkerColor(kBlue);
    combData[ptbin]->SetMarkerSize(0.4);
    combData[ptbin]->SetTitle("");

    // Normalize
    projB[ptbin]     -> Scale(1./normB);
    projC[ptbin]     -> Scale(1./normC);
    projData0[ptbin] -> Scale(1./norm0);
    projData2[ptbin] -> Scale(1./norm2);
    plotD0[ptbin]    -> Scale(1./norm0);
    plotD2[ptbin]    -> Scale(1./norm2);
    plotB[ptbin]     -> Scale(1./normB);
    plotC[ptbin]     -> Scale(1./normC);
    combData[ptbin]  -> Scale(1./(norm0+norm2));

    // Subtract Pileup correction (data only)
    projData0[ptbin]->Sumw2();projData2[ptbin]->Sumw2();
    //projData0[ptbin]->Add(pileupCorrect[ptbin][0],-1);
    //projData2[ptbin]->Add(pileupCorrect[ptbin][1],-1);

    // Draw Templates on own plots
    if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
    if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
    plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.8);
    plotC[ptbin]  -> Draw("hist");
    plotB[ptbin]  -> Draw("same hist");
    plotD0[ptbin] -> Draw("same");
    plotD2[ptbin] -> Draw("same");
    lbl[ptbin]    -> Draw("same");

    TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
    leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
    leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
    leg->AddEntry(projData0[ptbin],"HT0","lpe");
    leg->AddEntry(projData2[ptbin],"HT2","lpe");
    leg->Draw();

    deltaPhi->cd(1);
    Hdphi[0]->Draw("same");
    deltaPhi->cd(4);
    Hdphi[1]->Draw("same");

      if(ptbin == 1)
      {
        prettyPlot->cd();
        plotC[ptbin]->GetYaxis()->SetRangeUser(0,0.35);
        plotC[ptbin]->SetMarkerStyle(20);
        plotC[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerStyle(21);
        plotB[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerColor(kRed);
        plotD0[ptbin]->SetMarkerStyle(22);
        plotD0[ptbin]->SetMarkerSize(0.9);
        plotC[ptbin]->GetXaxis()->SetTitle("#Delta#phi_{NPE-h} (rad)");
        plotC[ptbin]->GetYaxis()->SetTitle("#frac{1}{N_{NPE}} #frac{dN}{d(#Delta#phi)}");
        plotC[ptbin]->DrawClone("P");
        plotB[ptbin]->DrawClone("same P");
        plotD0[ptbin]->DrawClone("same P");
        TLegend* legPret = new TLegend(0.65,0.6,0.85,0.85);
        legPret->AddEntry(plotB[ptbin],"B #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotC[ptbin],"D #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotD0[ptbin],"NPE-h 2012 STAR Data","LPE");
        lbl[ptbin]->Draw("same");
        legPret->Draw("same");
      }

    /*// Draw Scale Check
      scaleCheck->cd(1);
      TH1F* HT0 = (TH1F*) plotD0[0]->Clone();
      HT0->Divide(HT0,Hdphi[0],1,1);
      HT0->Draw();
      scaleCheck->cd(2);
      TH1F* HT2 = (TH1F*) plotD2[3]->Clone();
      HT2->Divide(HT2,Hdphi[1],1,1);
      HT0->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->Draw();
      lbl[ptbin]->Draw("same");
      TLegend* legSC = new TLegend(0.65,0.6,0.85,0.85);
      legSC->AddEntry(HT0,"HT0/prevdata","lpe");
      legSC->AddEntry(HT2,"HT2/prevdata","lpe");
      legSC->Draw();*/

    /////////////////////
    // Do the actual fits
    /////////////////////

    currentPtBin = ptbin;
    cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    TMinuit* gMinuit = new TMinuit(1);
    gMinuit->SetFCN(chi2_0);
    currentPtBin = ptbin;
    doFit(gMinuit,p01[ptbin],p00[ptbin],e01[ptbin],e00[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] < 6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      dx[plotCount0] = 0.;
      ptOFF1[plotCount0] = pT[ptbin];
      Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
      eb0[plotCount0] = e01[ptbin];
      plotCount0++;
    }

    // Plot results
    fitResult0->cd(ptbin+1);
    TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
    TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
    TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
    stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
    stat[0][ptbin]->InsertText(statLabel);
    stat[0][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[0][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");


    cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_2);
    doFit(gMinuit,p21[ptbin],p20[ptbin],e21[ptbin],e20[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] > 3.6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      ptOFF2[plotCount2] = pT[ptbin];
      Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
      eb2[plotCount2] = e21[ptbin];
      plotCount2++;
    }

    // Plot results
    fitResult2->cd(ptbin+1);
    dClone = (TH1D*) projData2[ptbin]->Clone();
    cClone = (TH1D*) projC[ptbin]->Clone();
    bClone = (TH1D*) projB[ptbin]->Clone();
    stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
    stat[2][ptbin]->InsertText(statLabel);
    stat[2][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[2][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");

    cout << "!!!!!!! HTC ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_C);
    doFit(gMinuit,pC1[ptbin],pC0[ptbin],eC1[ptbin],eC0[ptbin]);
    // assign to plotting variables
    pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
    RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
    ebC[plotCount] = eC1[ptbin];
    plotCount++;
  }

  cout << "!!!!!!! Previous Data: 0"<<" !!!!!!!"<< endl;

  //////////
  // 2.5-3.5 GeV Bin
  //////////

  gMinuit->SetFCN(chi2_P0);
  doFit(gMinuit,RbP[0],SF[0],EbP[0],eSF[0]);

  // assign plotting variables
  pTP[0] = 3.;

  // Plot results
  fitResultP->cd(1);
  /*TH1D* dClone = (TH1D*) Hdphi[0]->Clone();
    TH1D* cClone = (TH1D*) projC[0]->Clone();
    TH1D* bClone = (TH1D*) projB[0]->Clone();*/
  TH1D* dClone = (TH1D*) projData0[0]->Clone();
  TH1D* cClone = (TH1D*) HpphiD[0]->Clone();
  TH1D* bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][0] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][0]->InsertText(statLabel);
  stat[3][0]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[0])*SF[0]); bClone->Scale(RbP[0]*SF[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][0]->Draw("same");

  ////////
  // 5.5-6.5 GeV Bin
  ////////

  gMinuit->SetFCN(chi2_P1);
  doFit(gMinuit,RbP[1],SF[1],EbP[1],eSF[1]);

  // assign plotting variables
  pTP[1] = 6.;

  // Plot results
  fitResultP->cd(2);
  /*dClone = (TH1D*) Hdphi[1]->Clone();
    cClone = (TH1D*) projC[3]->Clone();
    bClone = (TH1D*) projB[3]->Clone();*/
  dClone = (TH1D*) projData2[3]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][1] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][1]->InsertText(statLabel);
  stat[3][1]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[1])*SF[1]); bClone->Scale(RbP[1]*SF[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][1]->Draw("same");

  ////////
  // Old Data, Old Template
  ///////
  gMinuit->SetFCN(chi2_PP);
  doFit(gMinuit,RbPP[0],SFPP[0],EbPP[0],eSFPP[0]);

  // assign plotting variables
  pTPP[0] = 3.;

  // Plot results
  fitResultP->cd(3);
  dClone = (TH1D*) Hdphi[0]->Clone();
  cClone = (TH1D*) HpphiD[0]->Clone();
  bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][2] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][2]->InsertText(statLabel);
  stat[3][2]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[0])*SFPP[0]); bClone->Scale(RbPP[0]*SFPP[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][2]->Draw("same");

  // Bin at 6 GeV
  gMinuit->SetFCN(chi2_PP1);
  doFit(gMinuit,RbPP[1],SFPP[1],EbPP[1],eSFPP[1]);

  // assign plotting variables
  pTPP[1] = 6.;

  // Plot results
  fitResultP->cd(4);
  dClone = (TH1D*) Hdphi[1]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][3] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][3]->InsertText(statLabel);
  stat[3][3]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[1])*SFPP[1]); bClone->Scale(RbPP[1]*SFPP[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][3]->Draw("same");


  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/200GeVTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/200GeVTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);
  TGraphErrors *grPr    = new TGraphErrors(2,pTP,RbP,0,EbP);
  TGraphErrors *grPPr   = new TGraphErrors(2,pTPP,RbPP,0,EbPP);


  c1->cd(1);

  grP->SetTitle("");
  grP->GetXaxis()->SetTitle("NPE p_{T} (GeV/c)");
  grP->GetYaxis()->SetTitle("r_{B}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  grP->GetXaxis()->SetLimits(0,10);
  grP->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  grPr->SetMarkerStyle(29);
  grPr->SetMarkerColor(9);
  grPr->SetLineColor(9);
  grPPr->SetMarkerStyle(29);
  grPPr->SetMarkerColor(49);
  grPPr->SetLineColor(49);


  grP->Draw("AP");
  //grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  gr0->Draw("same P");
 // grPr->Draw("same P");
  //grPPr->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.48,0.85);
  leg2->AddEntry(gr0,"STAR Run 12 - Low p_{T} Analysis","pe");
  leg2->AddEntry(gr2,"STAR Run 12 - High p_{T} Analysis","pe");
  //leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grP,"STAR Run 6 Analysis (Stat. Uncertainty)","pe");
//  leg2->AddEntry(grPr,"Run 12 Data, Run 5/6 Templates)","pe");
  //leg2->AddEntry(grPPr,"Run 5/6 Refit (prev Template)","pe");
  leg2->AddEntry(grF,"FONLL Calculation","l");
  leg2->Draw("same");

  // Write to Root File if open
  if(makeROOT){
    file3->Close();
    file4->Close();
    file->cd();
    grP->Write("PreviousData");
    //grC->Write("same P");
    gr2->Write("HT2");
    grF->Write("FONLL");
    grFmax->Write("FONLLmax");
    grFmin->Write("FONLLmin");
    gr0->Write("HT0");
    // grPr->Write("PrevTempMyData");
    //grPPr->Write("PrevTempPreData");
  }

  // Make PDF with output canvases
  if(makePDF)
  {
    //Set front page
    TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
    fp->cd();
    TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
    bLabel->SetFillColor(38);
    bLabel->Draw();
    TLatex tl;
    tl.SetNDC();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.033);
    char tlName[100];
    char tlName2[100];

    TString titlename = FileName;
    int found = titlename.Last('/');
    if(found >= 0){
      titlename.Replace(0, found+1, "");
    } 
    sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
    tl.SetTextSize(0.05);
    tl.SetTextColor(kWhite);
    tl.DrawLatex(0.05, 0.92,tlName);

    TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
    bFoot->SetFillColor(38);
    bFoot->Draw();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.05);
    tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
    tl.SetTextColor(kBlack);
    tl.SetTextSize(0.03);
    tl.DrawLatex(0.1, 0.14, titlename);
    sprintf(tlName,"TEST");
    tl.DrawLatex(0.1, 0.8,tlName);

    // Place canvases in order
    TCanvas* temp = new TCanvas();
    sprintf(name, "FFOutput/%s.pdf[", FileName);
    temp->Print(name);
    sprintf(name, "FFOutput/%s.pdf", FileName);

    temp = deltaPhi; 
    temp->Print(name);
    temp = fitResult0;
    temp->Print(name);
    temp = fitResult2;
    temp->Print(name);
    // temp = fitResultC;
    // temp->Print(name);
    temp = c1;
    temp->Print(name);

    sprintf(name, "FFOutput/%s.pdf]", FileName);
    temp->Print(name);
  }
  if(makeROOT)
  {
    file->Write();
    file->Close();
  }
}
Ejemplo n.º 8
0
//___________________________________________________________________
Int_t studyBinZero(TString pathData, TString fileNameData, TString listName = "",
                   Double_t etaLow = -0.9, Double_t etaUp = 0.9,
                   Double_t lowerCentrality = -2, Double_t upperCentrality = -2)
{
  PrintSettingsAxisRangeForMultiplicityAxisForMB();
  
  TString pathNameData = Form("%s/%s", pathData.Data(), fileNameData.Data());
  
  if (listName == "") {
    listName = pathNameData;
    listName.Replace(0, listName.Last('/') + 1, "");
    listName.ReplaceAll(".root", "");
  }
  
  TObjArray* histList = 0x0;
  
  TFile* f = TFile::Open(pathNameData.Data());
  if (!f)  {
    std::cout << std::endl;
    std::cout << "Failed to open file \"" << pathNameData.Data() << "\"!" << std::endl;
    return -1;
  }
  
  histList = (TObjArray*)(f->Get(listName.Data()));
  if (!histList) {
    std::cout << std::endl;
    std::cout << "Failed to load list \"" << listName.Data() << "\"!" << std::endl;
    return -1;
  }
  
  // Extract the data histograms
  TH1* hNumEventsTriggerSel = dynamic_cast<TH1*>(histList->FindObject("fhEventsTriggerSel"));
  TH1* hNumEventsTriggerSelVtxCut = dynamic_cast<TH1*>(histList->FindObject("fhEventsTriggerSelVtxCut"));
  TH1* hNumEventsTriggerSelVtxCutZ= dynamic_cast<TH1*>(histList->FindObject("fhEventsProcessedNoPileUpRejection"));
  TH1* hNumEventsTriggerSelVtxCutZPileUpRej= dynamic_cast<TH1*>(histList->FindObject("fhEventsProcessed"));
  
  THnSparse* hDataTriggerSel = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSel"));
  THnSparse* hDataTriggerSelVtxCut = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCut"));
  THnSparse* hDataTriggerSelVtxCutZ = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCutZ"));
  THnSparse* hDataTriggerSelVtxCutZPileUpRej = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCutZPileUpRej"));
  
  setSparseErrors(hDataTriggerSel);
  setSparseErrors(hDataTriggerSelVtxCut);
  setSparseErrors(hDataTriggerSelVtxCutZ);
  setSparseErrors(hDataTriggerSelVtxCutZPileUpRej);
  
  
  
  // Set multiplicity range, if desired. Note that mult and pT axes are the same for all histos
  Int_t lowerCentralityBinLimit = -1;
  Int_t upperCentralityBinLimit = -2;
  Bool_t restrictCentralityAxis = kFALSE;
  Double_t actualLowerCentrality = -1.;
  Double_t actualUpperCentrality = -1.;
  
  if (lowerCentrality >= -1 && upperCentrality >= -1) {
    // Add subtract a very small number to avoid problems with values right on the border between to bins
    lowerCentralityBinLimit = hNumEventsTriggerSel->GetXaxis()->FindFixBin(lowerCentrality + 0.001);
    upperCentralityBinLimit = hNumEventsTriggerSel->GetXaxis()->FindFixBin(upperCentrality - 0.001);
    
    // Check if the values look reasonable
    if (lowerCentralityBinLimit <= upperCentralityBinLimit && lowerCentralityBinLimit >= 1
        && upperCentralityBinLimit <= hNumEventsTriggerSel->GetXaxis()->GetNbins()) {
      actualLowerCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinLowEdge(lowerCentralityBinLimit);
      actualUpperCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinUpEdge(upperCentralityBinLimit);

      restrictCentralityAxis = kTRUE;
    }
    else {
      std::cout << std::endl;
      std::cout << "Requested centrality range out of limits or upper and lower limit are switched!" << std::endl;
      return -1;
    }
  }
  
  if (!restrictCentralityAxis)
    GetAxisRangeForMultiplicityAxisForMB(hNumEventsTriggerSel->GetXaxis(), lowerCentralityBinLimit, upperCentralityBinLimit);
  
  hNumEventsTriggerSel->GetXaxis()->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
  
  actualLowerCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinLowEdge(hNumEventsTriggerSel->GetXaxis()->GetFirst());
  actualUpperCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinUpEdge(hNumEventsTriggerSel->GetXaxis()->GetLast());
  
  std::cout << "centrality: ";
  if (restrictCentralityAxis) {
    std::cout << actualLowerCentrality << " - " << actualUpperCentrality << std::endl;
    std::cout << "WARNING: Does it really make sense to restrict the centrality? Usually, centrality estimators imply centrality >= 0!"
              << std::endl;
  }
  else
    std::cout << "MB (" << actualLowerCentrality << " - " << actualUpperCentrality << ")" << std::endl;
    
  if (restrictCentralityAxis) {
    hDataTriggerSel->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCut->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCutZ->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCutZPileUpRej->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
  }
  
  
  // Restrict eta range
  const Int_t lowerEtaBinLimit = hDataTriggerSel->GetAxis(iEta)->FindFixBin(etaLow + 0.0001);
  const Int_t upperEtaBinLimit = hDataTriggerSel->GetAxis(iEta)->FindFixBin(etaUp  - 0.0001);
  
  const Double_t actualLowerEta = hDataTriggerSel->GetAxis(iEta)->GetBinLowEdge(lowerEtaBinLimit);
  const Double_t actualUpperEta = hDataTriggerSel->GetAxis(iEta)->GetBinUpEdge(upperEtaBinLimit);
  
  std::cout << "Eta: ";
  std::cout << actualLowerEta << " - " << actualUpperEta << std::endl;
  
  
  
  Bool_t symmetricInEta = TMath::Abs(TMath::Abs(actualLowerEta) - TMath::Abs(actualUpperEta)) < 1e-6;
  TString etaRange = symmetricInEta ? Form("|#it{#eta}| < %.1f", TMath::Abs(actualLowerEta)) 
                                    : Form("%.1f < #it{#eta} < %.1f", actualLowerEta, actualUpperEta); 
  
  hDataTriggerSel->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCut->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCutZ->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCutZPileUpRej->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  
  // Obtain number of events for each class
  // Note: Under- and overflow automatically taken into account for unrestricted axis by using -1 and -2 for limits
  const Double_t numEvtsTriggerSel = hNumEventsTriggerSel->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCut = hNumEventsTriggerSelVtxCut->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCutZ = hNumEventsTriggerSelVtxCutZ->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCutZPileUpRej = hNumEventsTriggerSelVtxCutZPileUpRej->Integral(lowerCentralityBinLimit,
                                                                                                    upperCentralityBinLimit);
  
  // Project pT spectra
  TH1D* hSpectraTriggerSel = (TH1D*)hDataTriggerSel->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCut = (TH1D*)hDataTriggerSelVtxCut->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCutZ = (TH1D*)hDataTriggerSelVtxCutZ->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCutZPileUpRej = (TH1D*)hDataTriggerSelVtxCutZPileUpRej->Projection(iPt, "e");
  
  // Normalise histos to 1/Nevt dN/dPt
  normaliseHist(hSpectraTriggerSel, numEvtsTriggerSel);
  normaliseHist(hSpectraTriggerSelVtxCut, numEvtsTriggerSelVtxCut);
  normaliseHist(hSpectraTriggerSelVtxCutZ, numEvtsTriggerSelVtxCutZ);
  normaliseHist(hSpectraTriggerSelVtxCutZPileUpRej, numEvtsTriggerSelVtxCutZPileUpRej);
  
  setupHist(hSpectraTriggerSel, kBlack, "Trigger selection");
  setupHist(hSpectraTriggerSelVtxCut, kRed, "& vertex cut");
  setupHist(hSpectraTriggerSelVtxCutZ, kBlue, "& vertex #it{z} cut");
  setupHist(hSpectraTriggerSelVtxCutZPileUpRej, kGreen, "& pile-up rejection");
  
  TCanvas* canvSpectra = new TCanvas("canvSpectra", "Spectra", 760, 420);
  canvSpectra->SetLogx();
  canvSpectra->SetLogy();
  canvSpectra->SetGrid(0, 0);
  SetCanvasMargins(canvSpectra);
  
  TLegend* leg = new TLegend(0.14, 0.26, 0.62, 0.55);
  leg->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg->AddEntry(hSpectraTriggerSel, "", "l");
  leg->AddEntry(hSpectraTriggerSelVtxCut, "", "l");
  leg->AddEntry(hSpectraTriggerSelVtxCutZ, "", "l");
  if (drawPileUp)
    leg->AddEntry(hSpectraTriggerSelVtxCutZPileUpRej, "", "l");
  SetupLegend(leg);
  leg->SetMargin(0.15);
  
  hSpectraTriggerSel->Draw();
  hSpectraTriggerSelVtxCut->Draw("same");
  hSpectraTriggerSelVtxCutZ->Draw("same");
  if (drawPileUp)
    hSpectraTriggerSelVtxCutZPileUpRej->Draw("same");
  
  leg->Draw("same");
  
  // Ratios (take binomial errors, since real sub-samples)
  
  TH1D* hRatioVtxCut = new TH1D(*hSpectraTriggerSelVtxCut);
  hRatioVtxCut->SetName("hRatioVtxCut");
  setupHist(hRatioVtxCut, kBlack, "MB & vtx / MB");
  hRatioVtxCut->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioVtxCut->Divide(hRatioVtxCut, hSpectraTriggerSel, 1., 1., "B");
  hRatioVtxCut->GetYaxis()->SetRangeUser(1.08, 1.14);
  
  // Mean ratio of spectra and of Nevt
  TF1* funcRatioVtxCut = new TF1("funcRatioVtxCut", "pol0",
                                 0.15, hRatioVtxCut->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCut->FindLastBinAbove(0)));
  funcRatioVtxCut->SetLineWidth(2);
  funcRatioVtxCut->SetLineColor(kRed);
  hRatioVtxCut->Fit(funcRatioVtxCut, "N");
  const Double_t meanRatioVtxCut = funcRatioVtxCut->GetParameter(0);
  const Double_t ratioNevtVtxCut = numEvtsTriggerSelVtxCut > 0 ? numEvtsTriggerSel / numEvtsTriggerSelVtxCut : -1.;
  const Double_t doubleRatioMinusOne = meanRatioVtxCut > 0 ? (ratioNevtVtxCut / meanRatioVtxCut - 1.) : -999.;
  
  
  
  TH1D* hRatioVtxCutZ = new TH1D(*hSpectraTriggerSelVtxCutZ);
  hRatioVtxCutZ->SetName("hRatioVtxCutZ");
  setupHist(hRatioVtxCutZ, kBlack, "MB & vtx & #it{z} vtx / MB & vtx");
  hRatioVtxCutZ->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioVtxCutZ->Divide(hRatioVtxCutZ, hSpectraTriggerSelVtxCut, 1., 1., "B");
  hRatioVtxCutZ->GetYaxis()->SetRangeUser(0.95, 1.05);
  
  // Mean ratio of spectra and of Nevt
  TF1* funcRatioVtxCutZ = new TF1("funcRatioVtxCutZ", "pol0",
                                  0.15, hRatioVtxCutZ->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCutZ->FindLastBinAbove(0)));
  hRatioVtxCutZ->Fit(funcRatioVtxCutZ, "N");
  funcRatioVtxCutZ->SetLineWidth(2);
  funcRatioVtxCutZ->SetLineColor(kRed);
  const Double_t meanRatioVtxCutZ = funcRatioVtxCutZ->GetParameter(0);
  const Double_t ratioNevtVtxCutZ = numEvtsTriggerSelVtxCutZ > 0 ? numEvtsTriggerSelVtxCut / numEvtsTriggerSelVtxCutZ : -1.;
  
  TH1D* hRatioPileUp = new TH1D(*hSpectraTriggerSelVtxCutZPileUpRej);
  hRatioPileUp->SetName("hRatioPileUp");
  setupHist(hRatioPileUp, kBlack, "MB & vtx & #it{z} vtx & pile-up / MB & vtx & #it{z} vtx");
  hRatioPileUp->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioPileUp->Divide(hRatioPileUp, hSpectraTriggerSelVtxCutZ, 1., 1., "B");
  
  /*
  TF1* funcRatioPileUp = new TF1("funcRatioPileUp", "pol0",
                                 0.15, hRatioPileUp->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCutZPileUpRej->FindLastBinAbove(0)));
  hRatioPileUp->Fit(funcRatioPileUp, "N");*/
  
  ClearTitleFromHistoInCanvas(canvSpectra);
  
  TCanvas* canvRatioVtx = new TCanvas("canvRatioVtx", "Ratio vertex", 760, 420);
  canvRatioVtx->SetLogx();
  canvRatioVtx->SetGrid(0, 1);
  SetCanvasMargins(canvRatioVtx);
  
  hRatioVtxCut->Draw();
  funcRatioVtxCut->Draw("same");
  
  TLegend* leg2 = new TLegend(0.22, 0.7, drawPileUp ? 0.87 : 0.72, 0.9);
  leg2->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg2->AddEntry(hRatioVtxCut, "", "l");
  SetupLegend(leg2);
  leg2->SetMargin(0.1);
  
  leg2->Draw("same");
  
  ClearTitleFromHistoInCanvas(canvRatioVtx);
  
  TCanvas* canvRatioOther = new TCanvas("canvRatioOther", "Ratio others", 760, 420);
  canvRatioOther->SetLogx();
  canvRatioOther->SetGrid(0, 1);
  SetCanvasMargins(canvRatioOther);
  
  hRatioVtxCutZ->Draw();
  if (drawPileUp)
    hRatioPileUp->Draw("same");

  TLegend* leg3 = new TLegend(0.22, drawPileUp ? 0.63 : 0.7, drawPileUp ? 0.87 : 0.72, 0.9);
  leg3->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg3->AddEntry(hRatioVtxCutZ, "", "l");
  if (drawPileUp)
    leg3->AddEntry(hRatioPileUp, "", "l");
  SetupLegend(leg3);
  leg3->SetMargin(0.1);
  
  leg3->Draw("same");
  
  ClearTitleFromHistoInCanvas(canvRatioOther);

  
  printf("meanRatioVtxCut %f <-> ratioNevtVtxCut %f => meanRatioVtxCutZ/ratioNevtVtxCutZ - 1 = %f\nmeanRatioVtxCutZ %f <-> ratioNevtVtxCutZ %f\n",
         meanRatioVtxCut, ratioNevtVtxCut, doubleRatioMinusOne, meanRatioVtxCutZ, ratioNevtVtxCutZ);
  
  
  TNamed* settings = new TNamed(
      Form("Settings: Data file \"%s\", lowerEta %.2f, uppEta %.2f, lowerCentrality %.3f, upperCentrality %.3f, doubleRatioMinusOne %.4f\n",
           pathNameData.Data(), etaLow, etaUp, lowerCentrality, upperCentrality, doubleRatioMinusOne), "");
  
  // Save results to file
  TString saveFileName = pathNameData;
  saveFileName = Form("%s_binZeroStudy.root", saveFileName.ReplaceAll(".root", "").Data());
  TFile *saveFile = TFile::Open(saveFileName.Data(), "RECREATE");
  saveFile->cd();
  hSpectraTriggerSel->Write();
  hSpectraTriggerSelVtxCut->Write();
  hSpectraTriggerSelVtxCutZ->Write();
  hSpectraTriggerSelVtxCutZPileUpRej->Write();
  
  hRatioVtxCut->Write();
  hRatioVtxCutZ->Write();
  hRatioPileUp->Write();
  
  funcRatioVtxCut->Write();
  funcRatioVtxCutZ->Write();
  
  canvSpectra->Write();
  canvRatioVtx->Write();
  canvRatioOther->Write();
  
  settings->Write();
  
  saveFile->Close();
  
  TString temp = saveFileName;
  canvRatioVtx->SaveAs(Form("%s", temp.ReplaceAll(".root", "_ratioVtx.pdf").Data()));
  temp = saveFileName;
  canvRatioOther->SaveAs(Form("%s", temp.ReplaceAll(".root", "_ratioOther.pdf").Data()));
  
  PrintSettingsAxisRangeForMultiplicityAxisForMB();
  
  return 0;
}
Ejemplo n.º 9
0
void offline(const char* FileName="test")
{
    TH1F::SetDefaultSumw2();
    // Set Style parameters for this macro
    gStyle->SetOptTitle(1); // Show Title (off by default for cleanliness)
    gErrorIgnoreLevel = kError; // Set Verbosity Level (kPrint shows all)

    // Set Output options
    Int_t number;
    Bool_t fPaintAll = checkPaintAllTrigs();
    checkBatchMode();
    Bool_t makePDF = checkMakePDF();
    Bool_t makeROOT= checkMakeRoot();

    // Open ROOT File
    char name[1000];
    sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s.root",FileName);
    TFile *f = new TFile(name,"READ");
    if (f->IsOpen()==kFALSE)
    {   std::cout << "!!! File Not Found !!!" << std::endl;
        exit(1);
    }
    // f->ls(); // - DEBUG by printing all objects in ROOT file

    char fname[100];
    TFile* file;
    if(makeROOT) {
        sprintf(fname,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s_processed.root",FileName);
        file = new TFile(fname,"RECREATE");
        if (file->IsOpen()==kFALSE)
        {
            std::cout << "!!! Outfile Not Opened !!!" << std::endl;
            makeROOT = kFALSE;
        }
    }

    const Int_t numPtBins = anaConst::nPtBins;
    Float_t lowpt[numPtBins],highpt[numPtBins];
    for(Int_t c=0; c< numPtBins; c++) {
        lowpt[c] = anaConst::lpt[c];
        highpt[c] = anaConst::hpt[c];
    }
    Float_t hptCut=anaConst::hptCut;
    const Int_t numTrigs = 4;
    Double_t epsilon[numPtBins] = {0.593164, 0.626663, 0.655916, 0.674654, 0.685596, 0.700600, 0.716682, 0.724638, 0.713977, 0.730550, 0.735204, 0.744336, 0.761323, 0.758423};
    Float_t hptMax=25; // Set max above range to allow overflow
    Float_t lowPhi=anaConst::lowPhi, highPhi=anaConst::highPhi;
    Double_t pu[2][numPtBins][numTrigs]; // To store fit parameters for later use
    Double_t hhNorm, HHScale, hadPur;

    TH1D * LSIM[numPtBins][numTrigs];
    TH1D * USIM[numPtBins][numTrigs];
    TH1D * USIMNP[numPtBins][numTrigs];
    TH1D * LSIMNP[numPtBins][numTrigs];
    TH1D * INCLNP[numPtBins][numTrigs];
    TH1D * INCL[numPtBins][numTrigs];
    TH1D * LSIM2[numPtBins][numTrigs];
    TH1D * USIM2[numPtBins][numTrigs];
    TH1D * INCL2[numPtBins][numTrigs];
    TH1D * LSMM[numPtBins][numTrigs];
    TH1D * USMM[numPtBins][numTrigs];
    TH1D * HHDP[numPtBins][numTrigs];
    TH1D * NSPI[numPtBins][numTrigs];
    TH2F * MON[numTrigs];
    TH1F * AVGTRKS[numTrigs];
    TH2F * MON2[numTrigs];
    TH1F * AVGTRKS2[numTrigs];
    TH2F* mh2PhiQPt[numTrigs];
    TH2F* mh2nSigmaEPt[numTrigs];
    TH2F* mh2nSigmaEPt_eID[numTrigs];
    TH3F* mh3DelPhiIncl[numTrigs];
    TH3F* mh3DelPhiPhotLS[numTrigs];
    TH3F* mh3DelPhiPhotUS[numTrigs];
    TH3F* mh3DelPhiPhotUSNP[numTrigs];
    TH3F* mh3DelPhiPhotLSNP[numTrigs];
    TH3F* mh3DelPhiInclNP[numTrigs];
    TH3F* mh3DelPhiInclWt[numTrigs];
    TH3F* mh3DelPhiPhotLSWt[numTrigs];
    TH3F* mh3DelPhiPhotUSWt[numTrigs];
    TH2F* mh2InvMassPtLS[numTrigs];
    TH2F* mh2InvMassPtUS[numTrigs];
    TH2F* mh2PtEZdcx[numTrigs];
    TH2F* mh2PtEZdcxUS[numTrigs];
    TH2F* mh2PtEZdcxLS[numTrigs];
    TH2F* mh2PtEZdcxHad[numTrigs];
    TH3F* mh3nTracksZdcx[numTrigs];
    TH3F* mh3nTracksZdcxUS[numTrigs];
    TH3F* mh3nTracksZdcxLS[numTrigs];
    TH3F* mh3nTracksZdcxHad[numTrigs];
    TH3F* mh3MixedDelPhi;
    TH3F* mh3MixedDelEta;
    TH3F* mh3MixedEtaPhi;
    TH3F* mh3DelPhiHadHad[numTrigs];
    TH2F* mh2nSigmaPion[numTrigs];
    TH1F* mh1PtHadTracks[numTrigs];
    TH1F* mh1PtETracks[numTrigs];
    TH1D* projHPhi[numPtBins][numTrigs];
    TH1D* projnSigmaE[numPtBins][numTrigs];
    TH1D* projnSigmaE_eID[numPtBins][numTrigs];
    TH1D* projDelPhiIncl[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSNP[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSWt[numPtBins][numTrigs];
    TH1D* projDelPhiHadHad[numPtBins][numTrigs];
    TH1D* projInvMassLS[numPtBins][numTrigs];
    TH1D* projInvMassUS[numPtBins][numTrigs];
    TH1D* projnSigmaPion[numPtBins][numTrigs];
    TH1D* projEMixedEtaPhi;
    TH1D* projPMixedEtaPhi;
    TH2D* proj2DMixedEtaPhi;
    TH2D* proj2DMixedEvent[numPtBins];
    TH1D* projMixedDelPhi[numPtBins];
    TH1D* projMixedDelEta[numPtBins];
    TH2F* histoNorms;
    TH1D* projZDCxHad[numPtBins][numTrigs];
    TH1D* projZDCxTrig[numPtBins][numTrigs];
    TH1D* projZDCxHadUS[numPtBins][numTrigs];
    TH1D* projZDCxTrigUS[numPtBins][numTrigs];
    TH1D* projZDCxHadLS[numPtBins][numTrigs];
    TH1D* projZDCxTrigLS[numPtBins][numTrigs];
    TH1D* projZDCxHadHad[numPtBins][numTrigs];
    TH1D* projZDCxTrigHad[numPtBins][numTrigs];
    TProfile2D* profileZDCx[numTrigs];
    TCanvas * c[numTrigs];
    TCanvas * c2[numTrigs];
    TCanvas * IN[numTrigs];
    TCanvas * IN2[numTrigs];
    TCanvas * pile[numTrigs];
    TCanvas * pileHad[numTrigs];
    TCanvas * result[numTrigs];
    TCanvas * result2[numTrigs];
    TCanvas * inMass[numTrigs];
    TCanvas * USComp[numTrigs];
    TCanvas * LSComp[numTrigs];
    TCanvas * InclComp[numTrigs];
    TCanvas * cHH[numTrigs];
    TCanvas * nSigPi[numTrigs];
    TCanvas * allDist[numTrigs];
    TCanvas * mixedC;
    TCanvas * mixedCbinEta;
    TCanvas * mixedCbinPhi;
    TCanvas * mixedCbin;
    TCanvas * singlePlot;

    TPaveText* lbl[numPtBins];
    TPaveText* stat[numPtBins];
    char textLabel[100];
    singlePlot =  new TCanvas("singlePlot","Single Plot",150,0,1150,1000);

    // Trigger Independent Hists
    mixedC     = new TCanvas("mixedC","Mixed Events",150,0,1150,1000);
    mixedCbinEta = new TCanvas("mixedCbinEta","Mixed Events Eta",150,0,1150,1000);
    mixedCbinPhi = new TCanvas("mixedCbinPhi","Mixed Events Phi",150,0,1150,1000);
    mixedCbin = new TCanvas("mixedCbin","Mixed Events 2D",150,0,1150,1000);

    mixedC       -> Divide(2,2);
    mixedCbinEta -> Divide(4,3);
    mixedCbinPhi -> Divide(4,3);

    mh3MixedDelPhi = (TH3F*)f->Get("mh3MixedDelPhi");
    mh3MixedDelEta = (TH3F*)f->Get("mh3MixedDelEta");
    mh3MixedEtaPhi = (TH3F*)f->Get("mh3MixedEtaPhi");

    ///////////////////////////
    projPMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionX("projPMixedEtaPhi");
    projEMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionY("projEMixedEtaPhi");
    proj2DMixedEtaPhi = (TH2D*)mh3MixedEtaPhi -> Project3D("yx");
    Int_t RB2 = 2;
    projEMixedEtaPhi->Rebin(RB2);
    projPMixedEtaPhi->Rebin(RB2);

    mixedC->cd(1);
    mh3MixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    mh3MixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    mh3MixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    mh3MixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    mh3MixedEtaPhi->GetZaxis()->SetTitle("P_{t,e}");
    mh3MixedEtaPhi->Draw();
    mixedC->cd(2);
    projPMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    projPMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    projPMixedEtaPhi->GetYaxis()->SetRangeUser(0,20000);
    projPMixedEtaPhi->SetTitle("Mixed Event #Delta#phi");
    projPMixedEtaPhi->Draw();
    mixedC->cd(3);
    projEMixedEtaPhi->GetXaxis()->SetRangeUser(-2.5,2.5);
    projEMixedEtaPhi->GetXaxis()->SetTitle("#Delta#eta");
    projEMixedEtaPhi->SetTitle("Mixed Event #Delta#eta");
    projEMixedEtaPhi->Draw();
    mixedC->cd(4);
    mixedC->SetLogz(1);
    proj2DMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    proj2DMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    proj2DMixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    proj2DMixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    proj2DMixedEtaPhi->Draw("colz");

    TH3F* temp3D[numPtBins];
    // PtBins for Mixed Event
    for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

        // Init necessary plotting tools
        lbl[ptbin] = new TPaveText(.2,.8,.5,.85,Form("NB NDC%i",ptbin));
        sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
        lbl[ptbin]->AddText(textLabel);
        lbl[ptbin]->SetFillColor(kWhite);

        projMixedDelPhi[ptbin] = mh3MixedEtaPhi->ProjectionX(Form("projMixedDelPhi_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);
        projMixedDelEta[ptbin] = mh3MixedEtaPhi->ProjectionY(Form("projMixedDelEta_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);

        mixedCbinEta->cd(ptbin+1);
        projMixedDelEta[ptbin]->GetXaxis()->SetRangeUser(-2.5,2.5);
        projMixedDelEta[ptbin]->GetXaxis()->SetTitle("#Delta#eta");
        projMixedDelEta[ptbin]->Draw();

        mixedCbinPhi->cd(ptbin+1);
        projMixedDelPhi[ptbin]->GetXaxis()->SetRangeUser(lowPhi-.5,highPhi+.5);
        // projMixedDelPhi[ptbin]->GetYaxis()->SetRangeUser(0,2000);
        projMixedDelPhi[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        projMixedDelPhi[ptbin]->Draw();

        /*   temp3D[ptbin] = (TH3F*)mh3MixedEtaPhi->Clone(); // make a clone to set axis range on for 3D to 2D projection
        temp3D[ptbin]->GetZaxis()->SetRangeUser(lowpt[ptbin],highpt[ptbin]); // project3d only projects active range
        proj2DMixedEvent[ptbin] = (TH2D*)temp3D[ptbin] -> Project3D("yx");
        proj2DMixedEvent[ptbin]->SetName(Form("proj2DMixedEvent_%i",ptbin));

        mixedCbin->cd(ptbin+1);
        proj2DMixedEvent[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        proj2DMixedEvent[ptbin]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
        proj2DMixedEvent[ptbin]->GetYaxis()->SetTitle("#Delta#eta");
        proj2DMixedEvent[ptbin]->GetYaxis()->SetRangeUser(-1.5,1.5);
        proj2DMixedEvent[ptbin]->Draw("colz");*/

    }

    /// TRIGGER LOOP
    histoNorms = new TH2F("histoNorms","",4,0,12,20,0,20); // Fill normalization in a single histogram for accessing later

    for(Int_t trig = 0; trig < numTrigs; trig++) {

        if(!fPaintAll && (trig == 1 || trig == 3)) continue;
        // Create and Segment Canvas
        c[trig]        = new TCanvas(Form("c%i",trig),"Photonic Hists",150,0,1150,1000);
        IN[trig]       = new TCanvas(Form("IN%i",trig),"Inclusive Hists",150,0,1150,1000);
        pile[trig]     = new TCanvas(Form("pile%i",trig),"Pileup Monitor",150,0,1150,1000);
        pileHad[trig]  = new TCanvas(Form("pileHad%i",trig),"Pileup Monitor",150,0,1150,1000);
        //  pileTrig[trig] = new TCanvas(Form("pileTrig%i",trig),"Pileup Monitor",150,0,1150,1000);
        inMass[trig]   = new TCanvas(Form("inMass%i",trig),"Invariant Mass",150,0,1150,1000);
        result[trig]   = new TCanvas(Form("result%i",trig),"Inclusive - Photonic",150,0,1150,1000);
        USComp[trig]   = new TCanvas(Form("USComp%i",trig),"Unlike Sign Distributions",150,0,1150,1000);
        LSComp[trig]   = new TCanvas(Form("LSComp%i",trig),"Like Sign Distributions",150,0,1150,1000);
        InclComp[trig] = new TCanvas(Form("InclComp%i",trig),"Inclusive Distributions",150,0,1150,1000);
        cHH[trig]      = new TCanvas(Form("cHH%i",trig),"Hadron-Hadron Distributions",150,0,1150,1000);
        nSigPi[trig]   = new TCanvas(Form("nSigPi_%i",trig),"n#sigma#pi QA",150,0,1150,1000);
        allDist[trig]  = new TCanvas(Form("allDist_%i",trig),"Distribution Comparison",150,0,1150,1000);
        c[trig]        -> Divide(4,3);
        inMass[trig]   -> Divide(4,3);
        IN[trig]       -> Divide(4,3);
        pile[trig]     -> Divide(4,3);
        result[trig]   -> Divide(4,3);
        USComp[trig]   -> Divide(4,3);
        LSComp[trig]   -> Divide(4,3);
        InclComp[trig] -> Divide(4,3);
        cHH[trig]      -> Divide(4,3);
        nSigPi[trig]   -> Divide(4,3);
        allDist[trig]  -> Divide(4,3);

        // Make Projections (first get 2d/3d hists, then project)
        mh2PhiQPt[trig]         = (TH2F*)f->Get(Form("mh2PhiQPt_%i",trig));
        mh2nSigmaEPt[trig]      = (TH2F*)f->Get(Form("mh2nSigmaEPt_%i",trig));
        mh2nSigmaEPt_eID[trig]  = (TH2F*)f->Get(Form("mh2nSigmaEPt_eID_%i",trig));
        mh3DelPhiIncl[trig]     = (TH3F*)f->Get(Form("mh3DelPhiIncl_%i",trig));
        mh3DelPhiPhotLS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotLS_%i",trig));
        mh3DelPhiPhotUS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotUS_%i",trig));
        mh3DelPhiPhotUSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSNP_%i",trig));
        mh3DelPhiPhotLSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSNP_%i",trig));
        mh3DelPhiInclNP[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotInclNP_%i",trig));
        mh3DelPhiInclWt[trig]   = (TH3F*)f->Get(Form("mh3DelPhiInclWt_%i",trig));
        mh3DelPhiPhotLSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSWt_%i",trig));
        mh3DelPhiPhotUSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSWt_%i",trig));
        mh2InvMassPtLS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtLS_%i",trig));
        mh2InvMassPtUS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtUS_%i",trig));
        mh3DelPhiHadHad[trig]   = (TH3F*)f->Get(Form("mh3DelPhiHadHad_%i",trig));
        mh1PtHadTracks[trig]    = (TH1F*)f->Get(Form("mh1PtHadTracks_%i",trig));
        mh1PtETracks[trig]      = (TH1F*)f->Get(Form("mh1PtETracks_%i",trig));
        mh2nSigmaPion[trig]     = (TH2F*)f->Get(Form("mh2nSigmaPionPt_%i",trig));

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
        {
            // - Make projections into electron ptbins
            projHPhi[ptbin][trig] = mh2PhiQPt[trig]->ProjectionX(Form("projHPhi_%i_%i",ptbin,trig),mh2PhiQPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2PhiQPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE[ptbin][trig] = mh2nSigmaEPt[trig]->ProjectionX(Form("projnSigmaE_%i_%i",ptbin,trig),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE_eID[ptbin][trig] = mh2nSigmaEPt_eID[trig]->ProjectionX(Form("projnSigmaE_eID_%i_%i",ptbin,trig),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiIncl[ptbin][trig] = mh3DelPhiIncl[trig]->ProjectionX(Form("projDelPhiIncl_%i_%i",ptbin,trig),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUS[ptbin][trig] = mh3DelPhiPhotUS[trig]->ProjectionX(Form("projDelPhiPhotUS_%i_%i",ptbin,trig),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSNP[ptbin][trig] = mh3DelPhiPhotUSNP[trig]->ProjectionX(Form("projDelPhiPhotUSNP_%i_%i",ptbin,trig),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSNP[ptbin][trig] = mh3DelPhiPhotLSNP[trig]->ProjectionX(Form("projDelPhiPhotLSNP_%i_%i",ptbin,trig),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclNP[ptbin][trig] = mh3DelPhiInclNP[trig]->ProjectionX(Form("projDelPhiInclNP_%i_%i",ptbin,trig),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclWt[ptbin][trig] = mh3DelPhiInclWt[trig]->ProjectionX(Form("projDelPhiInclWt_%i_%i",ptbin,trig),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSWt[ptbin][trig] = mh3DelPhiPhotUSWt[trig]->ProjectionX(Form("projDelPhiPhotUSWt_%i_%i",ptbin,trig),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSWt[ptbin][trig] = mh3DelPhiPhotLSWt[trig]->ProjectionX(Form("projDelPhiPhotLSWt_%i_%i",ptbin,trig),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projInvMassUS[ptbin][trig] = mh2InvMassPtUS[trig]->ProjectionX(Form("projInvMassUS_%i_%i",ptbin,trig),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projInvMassLS[ptbin][trig] = mh2InvMassPtLS[trig]->ProjectionX(Form("projInvMassLS_%i_%i",ptbin,trig),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiHadHad[ptbin][trig] = mh3DelPhiHadHad[trig]->ProjectionX(Form("projDelPhiHadHad_%i_%i",ptbin,trig),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiHadHad[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projnSigmaPion[ptbin][trig] = mh2nSigmaPion[trig]->ProjectionX(Form("projnSigmaPion_%i_%i",ptbin,trig),mh2nSigmaPion[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaPion[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);
        }

        for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

            // Init necessary plotting tools
            lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
            sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
            lbl[ptbin]->AddText(textLabel);
            lbl[ptbin]->SetFillColor(kWhite);

            // Calculate electron purity from pol3 fit of xiaozhi data
            Float_t ptAv = (lowpt[ptbin]+highpt[ptbin])/2.;
            Float_t p[3] = {0.9743, 0.02128, -0.00438};
            Float_t purity = p[0] + (p[1]*ptAv)+(p[2]*ptAv*ptAv);
            hadPur = 1-purity;

            // Calculate PHe Reconstruction Eff from Xiaozhi embedding (fit)
            Float_t par[5] = {.26214, 4.75137, .526075, .0276979, .00054599};
            Float_t x = ptAv;
            Float_t eps = par[0]*TMath::Log(par[1]*x - par[2]*x*x + par[3]*x*x*x - par[4]*x*x*x*x);
            epsilon[ptbin] = eps;

            // Make stats label with purity and effeciency
            char statLabel[100];
            stat[ptbin] = new TPaveText(.4,.3,.85,.35,Form("NB NDC%i",ptbin));
            sprintf(statLabel,"Eff: %.2f; ePure:%.2f",epsilon[ptbin],purity);
            stat[ptbin]->InsertText(statLabel);
            stat[ptbin]->SetFillColor(kWhite);

            // Calculate Normalization for NPE delPhi
            Int_t inclNorm = mh1PtETracks[trig]->Integral(mh1PtETracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtETracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            Int_t LSNorm   = projInvMassLS[ptbin][trig]->Integral();
            Int_t USNorm   = projInvMassUS[ptbin][trig]->Integral();
            hhNorm   = mh1PtHadTracks[trig]->Integral(mh1PtHadTracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtHadTracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            HHScale = (Float_t)inclNorm/(Float_t)hhNorm; // so the purity comparison is 1:1
            Float_t Norm = (Float_t)inclNorm - (1/epsilon[ptbin] - 1.)*(Float_t)USNorm + (1/epsilon[ptbin])*(Float_t)LSNorm - HHScale*hadPur*hhNorm; // Use the number of "signal" counts
            histoNorms->SetBinContent(histoNorms->GetBin(trig+1,ptbin+1), Norm); // Find the bin and fill with the Normalization
            //cout << trig << "; " << ptbin << ": " << Norm << endl;

            Int_t counter = numPtBins*trig+ptbin;
            // DEBUG cout << counter << endl;
            c[trig]->cd(ptbin+1);
            // Assign to a single, simpler name for manip
            LSIM[ptbin][trig]  = projDelPhiPhotLS[ptbin][trig];
            USIM[ptbin][trig]  = projDelPhiPhotUS[ptbin][trig];
            USIMNP[ptbin][trig]= projDelPhiPhotUSNP[ptbin][trig];
            LSIMNP[ptbin][trig]= projDelPhiPhotLSNP[ptbin][trig];
            INCLNP[ptbin][trig]= projDelPhiInclNP[ptbin][trig];
            INCL[ptbin][trig]  = projDelPhiIncl[ptbin][trig];
            INCL2[ptbin][trig] = projDelPhiInclWt[ptbin][trig];
            LSIM2[ptbin][trig] = projDelPhiPhotLSWt[ptbin][trig];
            USIM2[ptbin][trig] = projDelPhiPhotUSWt[ptbin][trig];
            LSMM[ptbin][trig]  = projInvMassLS[ptbin][trig];
            USMM[ptbin][trig]  = projInvMassUS[ptbin][trig];
            HHDP[ptbin][trig]  = projDelPhiHadHad[ptbin][trig];
            NSPI[ptbin][trig]  = projnSigmaPion[ptbin][trig];
            // Rebin all as necessary
            Int_t RB = 1;
            LSIM[ptbin][trig]  -> Rebin(RB);
            USIM[ptbin][trig]  -> Rebin(RB);
            USIMNP[ptbin][trig]-> Rebin(RB);
            LSIMNP[ptbin][trig]-> Rebin(RB);
            INCLNP[ptbin][trig]-> Rebin(RB);
            INCL[ptbin][trig]  -> Rebin(RB);
            INCL2[ptbin][trig] -> Rebin(RB);
            LSIM2[ptbin][trig] -> Rebin(RB);
            USIM2[ptbin][trig] -> Rebin(RB);
            HHDP[ptbin][trig]  -> Rebin(RB);
            NSPI[ptbin][trig]  -> Rebin(10);

            // Actually manipulate histos and plot (photnic del Phi)

            USIMNP[ptbin][trig]->SetLineColor(kRed);
            USIMNP[ptbin][trig]->SetLineWidth(1);
            USIMNP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USIMNP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USIMNP[ptbin][trig]->SetTitle("Photonic Electron Reconstruction (No Partner Track)");
            else if (ptbin == 1 && trig !=3)
                USIMNP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USIMNP[ptbin][trig]->SetTitle("MB");
            else
                USIMNP[ptbin][trig]->SetTitle("");
            USIMNP[ptbin][trig]->Draw("");

            LSIMNP[ptbin][trig]->SetLineColor(kBlack);
            LSIMNP[ptbin][trig]->SetLineWidth(1);
            LSIMNP[ptbin][trig]->Draw(" same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (USNP-LS)
            TH1F *SUB = (TH1F*)USIMNP[ptbin][trig]->Clone(); //
            SUB->SetName("Subtraction");      // Create SUB as a clone of USIMNP
            SUB->Add(LSIMNP[ptbin][trig],-1);
            SUB->SetLineColor(kBlue);
            SUB->SetLineWidth(1);
            SUB->SetFillStyle(3001);
            SUB->SetFillColor(kBlue);
            SUB->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* leg = new TLegend(0.2,0.73,0.55,0.85);
            leg->AddEntry(USIMNP[ptbin][trig],"Unlike Sign","lpe");
            leg->AddEntry(LSIM[ptbin][trig],"Like Sign", "lpe");
            leg->AddEntry(SUB,"Unlike - Like", "lpe");
            leg->Draw();

            // Plot different US (w/wo partner)
            USComp[trig]->cd(ptbin+1);
            TH1F *USwP = (TH1F*)USIM[ptbin][trig]->Clone();
            USwP->SetLineColor(kRed); //with partner tracks
            USwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USwP->SetTitle("Photonic Unlike Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                USwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USwP->SetTitle("MB");
            else
                USwP->SetTitle("");
            USwP->Draw("");
            TH1F *USnP = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USnP->SetLineColor(kBlack);
            USnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legUS = new TLegend(0.35,0.8,0.77,0.87);
            legUS->AddEntry(USwP,"With Partner Track","lpe");
            legUS->AddEntry(USnP,"Partner Track Removed", "lpe");
            legUS->Draw();

            // Plot different LS (w/wo partner)
            LSComp[trig]->cd(ptbin+1);
            TH1F *LSwP = (TH1F*)LSIM[ptbin][trig]->Clone();
            LSwP->SetLineColor(kRed); //with partner tracks
            LSwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            LSwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                LSwP->SetTitle("Photonic Like Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                LSwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                LSwP->SetTitle("MB");
            else
                LSwP->SetTitle("");
            LSwP->Draw("");
            TH1F *LSnP = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            LSnP->SetLineColor(kBlack);
            LSnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legLS = new TLegend(0.35,0.8,0.77,0.87);
            legLS->AddEntry(LSwP,"With Partner Track","lpe");
            legLS->AddEntry(LSnP,"Partner Track Removed", "lpe");
            legLS->Draw();

            // Plot different Incl (w/wo partner)
            InclComp[trig]->cd(ptbin+1);
            TH1F *InclwP = (TH1F*)INCL[ptbin][trig]->Clone();
            InclwP->SetLineColor(kRed); //with partner tracks
            InclwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            InclwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                InclwP->SetTitle("Inclusive Distributions");
            else if (ptbin == 1 && trig !=3)
                InclwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                InclwP->SetTitle("MB");
            else
                InclwP->SetTitle("");
            InclwP->Draw("");
            TH1F *InclnP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            InclnP->SetLineColor(kBlack);
            InclnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legIncl = new TLegend(0.35,0.8,0.77,0.87);
            legIncl->AddEntry(InclwP,"Inclusive","lpe");
            legIncl->AddEntry(InclnP,"Semi-Inclusive", "lpe");
            legIncl->Draw();

            // Actually manipulate histos and plot (photonic InvMass)
            inMass[trig]->cd(ptbin+1);
            USMM[ptbin][trig]->SetLineColor(kRed);
            USMM[ptbin][trig]->SetLineWidth(1);
            USMM[ptbin][trig]->GetXaxis()->SetTitle("InvMass (GeV/c^{2})");
            USMM[ptbin][trig]->GetXaxis()->SetRangeUser(0,0.4);
            if(ptbin == 0)
                USMM[ptbin][trig]->SetTitle("Photonic Electron Reconstruction");
            else if (ptbin == 1 && trig !=3)
                USMM[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USMM[ptbin][trig]->SetTitle("MB");
            else
                USMM[ptbin][trig]->SetTitle("");
            USMM[ptbin][trig]->Draw("");

            LSMM[ptbin][trig]->SetLineColor(kBlack);
            LSMM[ptbin][trig]->SetLineWidth(1);
            LSMM[ptbin][trig]->Draw("same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (US-LS)
            TH1F *SUB4 = (TH1F*)USMM[ptbin][trig]->Clone(); //
            SUB4->SetName("Subtraction");      // Create SUB as a clone of USIM
            SUB4->Add(LSMM[ptbin][trig],-1);
            SUB4->SetLineColor(kBlue);
            SUB4->SetLineWidth(1);
            SUB4->SetFillStyle(3001);
            SUB4->SetFillColor(kBlue);
            SUB4->Draw("same");
            TLegend* leg2 = new TLegend(0.45,0.6,0.85,0.75);
            leg2->AddEntry(USMM[ptbin][trig],"Unlike Sign","lpe");
            leg2->AddEntry(LSMM[ptbin][trig],"Like Sign", "lpe");
            leg2->AddEntry(SUB4,"Unlike - Like", "lpe");
            leg2->Draw();

            // Handle Inclusive Hists
            IN[trig]->cd(ptbin+1);
            INCL[ptbin][trig]->SetLineColor(kBlue);
            INCL[ptbin][trig]->SetLineWidth(1);
            INCL[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCL[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                INCL[ptbin][trig]->SetTitle("Inclusive Electrons");
            else if (ptbin == 1 && trig !=3)
                INCL[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCL[ptbin][trig]->SetTitle("MB");
            else
                INCL[ptbin][trig]->SetTitle("");
            INCL[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            IN[trig]->Update();

            // Plot Had-Had correlations
            cHH[trig]->cd(ptbin+1);
            HHDP[ptbin][trig]->SetLineColor(kGreen+3);
            HHDP[ptbin][trig]->SetLineWidth(1);
            HHDP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            HHDP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                HHDP[ptbin][trig]->SetTitle("Hadron-Hadron Correlations");
            else if (ptbin == 1 && trig !=3)
                HHDP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                HHDP[ptbin][trig]->SetTitle("MB");
            else
                HHDP[ptbin][trig]->SetTitle("");
            HHDP[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");


            // Subtraction of Inclusive - (1/e - 1)US + (1/e)LS - (1-purity)HadHad
            result[trig]->cd(ptbin+1);
            TH1F *INCDP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *ULDP  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LSDP  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADDP = (TH1F*)HHDP[ptbin][trig]->Clone();
            INCDP->SetName(Form("scaleNPEhDelPhi_%i_%i",trig,ptbin));
            ULDP->Scale(1./epsilon[ptbin] - 1.); // Scale each distribution by associated factors
            LSDP->Scale(1./epsilon[ptbin]);
            HADDP->Scale(HHScale*hadPur);
            INCDP->Add(ULDP,-1);
            INCDP->Add(LSDP,1);
            INCDP->Add(HADDP,-1);
            TH1F *unscaleINCDP = (TH1F*)INCDP->Clone();   //
            unscaleINCDP->SetName(Form("NPEhDelPhi_%i_%i",trig,ptbin)); // Make a clone before normalization, to pass to fit program
            INCDP->Scale(1./((Double_t)Norm));//*INCDP->GetBinWidth(1)));
            INCDP->SetLineColor(kBlack);
            INCDP->SetLineWidth(1);
            INCDP->SetFillStyle(3001);
            INCDP->SetFillColor(kYellow);
            INCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            INCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                INCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                INCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCDP->SetTitle("MB");
            else
                INCDP->SetTitle("");
            INCDP->Draw("");
            lbl[ptbin]->Draw("same");

            // Setup unscaled for fractionFit (don't normalize here!)
            unscaleINCDP->SetLineColor(kBlack);
            unscaleINCDP->SetLineWidth(1);
            unscaleINCDP->SetFillStyle(3001);
            unscaleINCDP->SetFillColor(kYellow);
            unscaleINCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            unscaleINCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            unscaleINCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            unscaleINCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                unscaleINCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                unscaleINCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                unscaleINCDP->SetTitle("MB");
            else
                unscaleINCDP->SetTitle("");

            // nSigmaPion QA
            nSigPi[trig]->cd(ptbin+1);
            NSPI[ptbin][trig]->SetLineColor(kGreen+3);
            NSPI[ptbin][trig]->SetLineWidth(1);
            NSPI[ptbin][trig]->GetXaxis()->SetTitle("n#sigma_{#pi}");
            NSPI[ptbin][trig]->GetXaxis()->SetRangeUser(-2.,2.);
            if(ptbin == 0)
                NSPI[ptbin][trig]->SetTitle("n Sigma Pion (n#sigma_{#pi})");
            else if (ptbin == 1 && trig !=3)
                NSPI[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                NSPI[ptbin][trig]->SetTitle("MB");
            else
                NSPI[ptbin][trig]->SetTitle("");
            NSPI[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            // All Distributions
            allDist[trig]->cd(ptbin+1);
            TH1F *INCLUSIVE = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *UNLIKE  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LIKE  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADRON = (TH1F*)HHDP[ptbin][trig]->Clone();
            TH1F *USmLS  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USmLS->Add(LIKE,-1);
            USmLS->Scale(1./(USNorm-LSNorm));
            INCLUSIVE->Scale(1./inclNorm);
            UNLIKE->Scale(1./USNorm);
            LIKE->Scale(1./LSNorm);
            HADRON->Scale(1./hhNorm);
            INCLUSIVE->SetLineColor(7);
            LIKE->SetLineColor(kBlue);
            INCLUSIVE->GetYaxis()->SetRangeUser(0.01,2);
            gPad->SetLogy(1);
            INCLUSIVE->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCLUSIVE->SetMarkerStyle(20);
            UNLIKE->SetMarkerStyle(21);
            LIKE->SetMarkerStyle(22);
            HADRON->SetMarkerStyle(23);
            USmLS->SetMarkerStyle(34);
            INCLUSIVE->SetMarkerColor(7);
            INCLUSIVE->SetMarkerSize(0.3);
            UNLIKE->SetMarkerSize(0.3);
            LIKE->SetMarkerSize(0.3);
            HADRON->SetMarkerSize(0.3);
            USmLS->SetMarkerSize(0.3);
            INCLUSIVE->SetMarkerColor(7);
            UNLIKE->SetMarkerColor(kRed);
            LIKE->SetMarkerColor(kBlue);
            HADRON->SetMarkerColor(kGreen+3);
            INCLUSIVE->Draw("");
            UNLIKE->Draw("same");
            LIKE->Draw("same");
            HADRON->Draw("same");
            USmLS->Draw("same");
            INCDP->Draw("same");
            lbl[ptbin]->Draw("same");
            stat[ptbin]->Draw("same");
            TLegend* legAll = new TLegend(0.45,0.11,0.85,0.3);
            legAll->AddEntry(INCLUSIVE,"Inclusive","lpe");
            legAll->AddEntry(UNLIKE,"Unlike Sign","lpe");
            legAll->AddEntry(LIKE,"Like Sign", "lpe");
            legAll->AddEntry(HADRON,"Hadron-Hadron", "lpe");
            legAll->AddEntry(USmLS,"Unlike-Like","lpe");
            legAll->AddEntry(INCDP,"NPE-h","lpe");
            legAll->Draw("same");

        }

        // Pileup Calculation (using just the hPtCut in the anaConst.h)
        /* mh3nTracksZdcx[trig]    = (TH3F*)f->Get(Form("mh3nTracksZdcx_%i_%i",trig,0));   // originally filled for various hpT cuts, use 0 which starts at hpt > 0.3
        mh3nTracksZdcxUS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxUS_%i_%i",trig,0)); // These histos are (epT,hpT,ZDCx), get nHadrons vs ZDCx
        mh3nTracksZdcxLS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxLS_%i_%i",trig,0));
        mh3nTracksZdcxHad[trig] = (TH3F*)f->Get(Form("mh3nTracksZdcxHad_%i_%i",trig,0));
        mh3nTracksZdcx[trig]->Sumw2(); mh3nTracksZdcxUS[trig]->Sumw2(); mh3nTracksZdcxLS[trig]->Sumw2();  mh3nTracksZdcxHad[trig]->Sumw2();

        mh2PtEZdcx[trig]       = (TH2F*)f->Get(Form("mh2PtEZdcx_%i",trig));            // Filled (epT,ZDCx). Get nTrigs vs ZDCx
        mh2PtEZdcxUS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxUS_%i",trig));
        mh2PtEZdcxLS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxLS_%i",trig));
        mh2PtEZdcxHad[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxHad_%i",trig));
        mh2PtEZdcx[trig]->Sumw2(); mh2PtEZdcxUS[trig]->Sumw2(); mh2PtEZdcxLS[trig]->Sumw2(); mh2PtEZdcxHad[trig]->Sumw2();

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)// cut in to trigger pt slices
          {
        projZDCxHad[ptbin][trig] = mh3nTracksZdcx[trig]->ProjectionZ(Form("projZDCxHad_%i_%i",ptbin,trig),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadUS[ptbin][trig] = mh3nTracksZdcxUS[trig]->ProjectionZ(Form("projZDCxHadUS_%i_%i",ptbin,trig),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadLS[ptbin][trig] = mh3nTracksZdcxLS[trig]->ProjectionZ(Form("projZDCxHadLS_%i_%i",ptbin,trig),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadHad[ptbin][trig] = mh3nTracksZdcxHad[trig]->ProjectionZ(Form("projZDCxHadHad_%i_%i",ptbin,trig),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptMax));

        projZDCxTrig[ptbin][trig] = mh2PtEZdcx[trig]->ProjectionY(Form("projZDCxTrig_%i_%i",ptbin,trig),mh2PtEZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigUS[ptbin][trig] = mh2PtEZdcxUS[trig]->ProjectionY(Form("projZDCxTrigUS_%i_%i",ptbin,trig),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigLS[ptbin][trig] = mh2PtEZdcxLS[trig]->ProjectionY(Form("projZDCxTrigLS_%i_%i",ptbin,trig),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigHad[ptbin][trig] = mh2PtEZdcxHad[trig]->ProjectionY(Form("projZDCxTrigHad_%i_%i",ptbin,trig),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);

        // Get Total number of hadrons in pileup (first scale each distribution by efficiency, just like data)
        projZDCxHadUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxHadLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxHadHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadUS[ptbin][trig], -1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadLS[ptbin][trig], 1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadHad[ptbin][trig], -1.);

        // Get Total number of trigs in pileup (first scale each distribution by efficiency, just like data)
        projZDCxTrigUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxTrigLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxTrigHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigUS[ptbin][trig], -1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigLS[ptbin][trig], 1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigHad[ptbin][trig], -1.);

        // Actually do the division of total hadrons/total trigs
        projZDCxHad[ptbin][trig]->Divide(projZDCxTrig[ptbin][trig]);

        // plot projections
        pile[trig]->cd(ptbin+1);
        projZDCxHad[ptbin][trig]->SetLineColor(kBlack);
        projZDCxHad[ptbin][trig]->GetXaxis()->SetTitle("ZDCx");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetTitle("<nHadrons>/<nTracks>");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetRangeUser(0,20);
        //
        gStyle->SetOptFit(1111);
        projZDCxHad[ptbin][trig]->Fit("pol1");
        projZDCxHad[ptbin][trig]->GetFunction("pol1")->SetLineColor(kRed);
        TPaveStats *st = ((TPaveStats*)(projZDCxHad[ptbin][trig]->GetListOfFunctions()->FindObject("stats")));
        if (st) {
          st->SetTextColor(projZDCxHad[ptbin][trig]->GetFunction("pol1")->GetLineColor());
          st->SetX1NDC(0.64); st->SetX2NDC(0.99);
          st->SetY1NDC(0.4); st->SetY2NDC(0.6);
        }
        pile[trig]->Modified();pile[trig]->Update();
        projZDCxHad[ptbin][trig]->Draw("");

        // Get Fit information and store to use in corrections
        TF1 *fitResult = projZDCxHad[ptbin][trig]->GetFunction("pol1");
        pu[0][ptbin][trig] = fitResult->GetParameter(0);
        pu[1][ptbin][trig] = fitResult->GetParameter(1);
           	cout << trig << " " << ptbin << ": " << pu[0][ptbin][trig] << " " << pu[1][ptbin][trig] << endl;
        }*/
    }

    // Draw on "SinglePlot" canvas for saving single plots from grid
    TPad* pNew = (TPad*)result[2]->GetPad(4)->Clone();
    singlePlot->cd();
    pNew->ResizePad();
    pNew->Draw();

    // Make PDF with output canvases
    if(makePDF)
    {
        //Set front page
        TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
        fp->cd();
        TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
        bLabel->SetFillColor(38);
        bLabel->Draw();
        TLatex tl;
        tl.SetNDC();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.033);
        char tlName[100];
        char tlName2[100];

        TString titlename = FileName;
        int found = titlename.Last('/');
        if(found >= 0) {
            titlename.Replace(0, found+1, "");
        }
        sprintf(tlName, "RUN 12 pp 200 GeV NPE-h    #Delta#phi Analysis");
        tl.SetTextSize(0.05);
        tl.SetTextColor(kWhite);
        tl.DrawLatex(0.05, 0.92,tlName);

        TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
        bFoot->SetFillColor(38);
        bFoot->Draw();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.05);
        tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
        tl.SetTextColor(kBlack);
        tl.SetTextSize(0.03);
        tl.DrawLatex(0.1, 0.14, titlename);
        sprintf(tlName,"eID: -1 < n  #sigma_{e TPC} < 3;  #left|gDCA #right| < 1 cm; 0.3 < p/E < 1.5;");
        tl.DrawLatex(0.1, 0.8,tlName);
        sprintf(tlName,"       nHitsFit > 20; nHits   #frac{dE}{dx} > 15; nHitFit/Max > 0.52;    #left|#eta#right| < 0.7;");
        tl.DrawLatex(0.1, 0.75,tlName);
        sprintf(tlName,"       n #phi > 1; n #eta > 1;  #left|dZ#right| < 3 cm;  #left|d#phi#right| < 0.015;");
        tl.DrawLatex(0.1, 0.7,tlName);
        sprintf(tlName,"hID: p_{T} > 0.5;  #left|#eta#right| < 1; nHitsFit > 15; nHits   #frac{dE}{dx} > 10; DCA < 1 cm;");
        tl.DrawLatex(0.1, 0.6,tlName);
        sprintf(tlName,"Event:  #left|V_{z}#right| < 35 cm;");
        tl.DrawLatex(0.1, 0.5,tlName);
        sprintf(tlName,"Triggers:  BHT0; BHT2;");
        tl.DrawLatex(0.1, 0.4,tlName);


        // Place canvases in order
        TCanvas* temp = new TCanvas();
        sprintf(name, "%s.pdf[", FileName);
        temp->Print(name);
        sprintf(name, "%s.pdf", FileName);
        temp = fp; // print front page
        temp->Print(name);
        temp = mixedC;
        temp->Print(name);
        temp = mixedCbinEta;
        temp->Print(name);
        temp = mixedCbinPhi;
        temp->Print(name);
        temp = mixedCbin;
        temp->Print(name);
        for(Int_t ii=0; ii<numTrigs; ii++)
        {
            if(!fPaintAll && (ii==1 || ii==3))
                continue;
            temp = IN[ii];
            temp->Print(name);
            temp = c[ii];
            temp->Print(name);
            temp = cHH[ii];
            temp->Print(name);
            temp = result[ii];
            temp->Print(name);
            temp = pile[ii];
            temp->Print(name);
            /*temp = inMass[ii];
            temp->Print(name);
            temp = USComp[ii];
            temp->Print(name);
            temp = LSComp[ii];
            temp->Print(name);
            temp = InclComp[ii];
            temp->Print(name);*/
            temp = nSigPi[ii];
            temp->Print(name);
            temp = allDist[ii];
            temp->Print(name);

        }
        sprintf(name, "%s.pdf]", FileName);
        temp->Print(name);
    }

    if(makeROOT)
    {
        file->Write();
        file->Close();
    }
}
Ejemplo n.º 10
0
//___________________________________________________________________
Int_t extractPtResolution(TString pathNameData, TString listName,
                          Int_t chargeMode /*kNegCharge = -1, kAllCharged = 0, kPosCharge = 1*/,
                          Double_t lowerCentrality /*= -2*/, Double_t upperCentrality /*= -2*/,
                          Double_t lowerJetPt /*= -1*/ , Double_t upperJetPt/* = -1*/)
{
  if (listName == "") {
    listName = pathNameData;
    listName.Replace(0, listName.Last('/') + 1, "");
    listName.ReplaceAll(".root", "");
  }
  
  TString pathData = pathNameData;
  pathData.Replace(pathData.Last('/'), pathData.Length(), "");
  
  TH1D* hPtResolutionFit[AliPID::kSPECIES] = {0x0, };
  TH2D* hPtResolution[AliPID::kSPECIES] = {0x0, };
  THnSparse* hPtResolutionRaw[AliPID::kSPECIES] = {0x0, };

  TFile* fileData = TFile::Open(pathNameData.Data());
  if (!fileData) {
    printf("Failed to open data file \"%s\"\n", pathNameData.Data());
    return -1;
  }
  
  TObjArray* histList = (TObjArray*)(fileData->Get(listName.Data()));
  
  if (!histList) {
    printf("Failed to load list!\n");
    return -1;
  }
  
  Double_t actualLowerCentrality = -2;
  Double_t actualUpperCentrality = -2;
  
  Double_t actualLowerJetPt = -1.;
  Double_t actualUpperJetPt = -1.;
  
  Bool_t restrictJetPtAxis = (lowerJetPt >= 0 && upperJetPt >= 0);
  const Bool_t restrictCentrality = ((lowerCentrality >= -1) && (upperCentrality >= -1));
  
  for (Int_t species = 0; species < AliPID::kSPECIES; species++) {
    const TString sparseName = Form("fPtResolution_%s", AliPID::ParticleShortName(species));
    hPtResolutionRaw[species] = (THnSparse*)histList->FindObject(sparseName.Data());
    
    if (!hPtResolutionRaw[species]) {
      printf("Failed to load THnSparse for %s: %s!\n", AliPID::ParticleShortName(species), sparseName.Data());
      return -1;
    }
    
    // Set proper errors, if not yet calculated
    if (!hPtResolutionRaw[species]->GetCalculateErrors()) {
      std::cout << "Re-calculating errors of " << hPtResolutionRaw[species]->GetName() << "..." << std::endl;
      
      hPtResolutionRaw[species]->Sumw2();
      
      Long64_t nBinsPtResolutionRaw = hPtResolutionRaw[species]->GetNbins();
      Double_t binContent = 0;
      for (Long64_t bin = 0; bin < nBinsPtResolutionRaw; bin++) {
        binContent = hPtResolutionRaw[species]->GetBinContent(bin);
        hPtResolutionRaw[species]->SetBinError(bin, TMath::Sqrt(binContent));
      }
    }
    
    // Integral(lowerCentBinLimit, uppCentBinLimit) will not be restricted if these values are kept
    const Int_t lowerCentralityBinLimit = restrictCentrality ? hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->FindBin(lowerCentrality + 0.001) 
                                                                    : -1;
    const Int_t upperCentralityBinLimit = restrictCentrality ? hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->FindBin(upperCentrality - 0.001) 
                                                                    : -2;
    
    
    if (restrictCentrality) {
      actualLowerCentrality = hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->GetBinLowEdge(lowerCentralityBinLimit);
      actualUpperCentrality = hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->GetBinLowEdge(upperCentralityBinLimit);
      
      hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    }
    
    const Bool_t restrictCharge = (chargeMode != kAllCharged);
    
    Int_t lowerChargeBinLimit = -1;
    Int_t upperChargeBinLimit = -2;
      
    if (restrictCharge) {
      // Add subtract a very small number to avoid problems with values right on the border between to bins
      if (chargeMode == kNegCharge) {
        lowerChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(-1. + 0.001);
        upperChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(0. - 0.001);
      }
      else if (chargeMode == kPosCharge) {
        lowerChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(0. + 0.001);
        upperChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(1. - 0.001);
      }
      
      // Check if the values look reasonable
      if (lowerChargeBinLimit <= upperChargeBinLimit && lowerChargeBinLimit >= 1
          && upperChargeBinLimit <= hPtResolutionRaw[species]->GetAxis(kPtResCharge)->GetNbins()) {
        // OK
      }
      else {
        std::cout << std::endl;
        std::cout << "Requested charge range out of limits or upper and lower limit are switched!" << std::endl;
        return -1;
      }
      
      hPtResolutionRaw[species]->GetAxis(kPtResCharge)->SetRange(lowerChargeBinLimit, upperChargeBinLimit);
    }
    
    // If desired, restrict jetPt axis
    Int_t lowerJetPtBinLimit = -1;
    Int_t upperJetPtBinLimit = -1;
    
    if (restrictJetPtAxis) {
      // Add subtract a very small number to avoid problems with values right on the border between to bins
      lowerJetPtBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->FindBin(lowerJetPt + 0.001);
      upperJetPtBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->FindBin(upperJetPt - 0.001);
      
      // Check if the values look reasonable
      if (lowerJetPtBinLimit <= upperJetPtBinLimit && lowerJetPtBinLimit >= 1 &&
          upperJetPtBinLimit <= hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetNbins()) {
        actualLowerJetPt = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetBinLowEdge(lowerJetPtBinLimit);
        actualUpperJetPt = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetBinUpEdge(upperJetPtBinLimit);

        restrictJetPtAxis = kTRUE;
      }
      else {
        std::cout << std::endl;
        std::cout << "Requested jet pT range out of limits or upper and lower limit are switched!" << std::endl;
        return -1;
      }
    }
    
    std::cout << "jet pT: ";
    if (restrictJetPtAxis) {
      std::cout << actualLowerJetPt << " - " << actualUpperJetPt << std::endl;
      hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->SetRange(lowerJetPtBinLimit, upperJetPtBinLimit);
    }
    else {
      std::cout << "All" << std::endl;
    }
    
    hPtResolution[species] = hPtResolutionRaw[species]->Projection(kPtResGenPt, kPtResRecPt, "e");
    hPtResolution[species]->SetName(Form("hPtResolution_%s", AliPID::ParticleShortName(species)));
    hPtResolution[species]->SetTitle(Form("%s", AliPID::ParticleLatexName(species)));
    hPtResolution[species]->SetStats(kFALSE);
    hPtResolution[species]->SetLineColor(getLineColorAliPID(species));
    hPtResolution[species]->SetMarkerColor(getLineColorAliPID(species));
    
    normaliseHist(hPtResolution[species]);
    
    TObjArray aSlices;
    hPtResolution[species]->FitSlicesY(0, 0, -1, 0, "QNR", &aSlices);
    TH1D* hMean = (TH1D*)(aSlices.At(1));
    TH1D* hSigma = (TH1D*)(aSlices.At(2));
    
    hPtResolutionFit[species] = new TH1D(*hSigma);
    hPtResolutionFit[species]->SetName(Form("hPtResolutionFit_%s", AliPID::ParticleShortName(species)));
    hPtResolutionFit[species]->SetTitle(Form("%s", AliPID::ParticleLatexName(species)));
    hPtResolutionFit[species]->SetLineColor(getLineColorAliPID(species));
    hPtResolutionFit[species]->SetMarkerColor(getLineColorAliPID(species));
    
    hPtResolutionFit[species]->Divide(hSigma, hMean);
  }
  
  
  
  // Save results to file
  TString chargeString = "";
  if (chargeMode == kPosCharge)
    chargeString = "_posCharge";
  else if (chargeMode == kNegCharge)
    chargeString = "_negCharge";
  
  TString saveFileName = pathNameData;
  saveFileName.Replace(0, pathNameData.Last('/') + 1, "");
  
  TString savePath = pathNameData;
  savePath.ReplaceAll(Form("/%s", saveFileName.Data()), "");
  
  saveFileName.Prepend("output_extractedPTResolution_");
  TString centralityString = restrictCentrality ? Form("_centrality_%.0f_%.0f.root", actualLowerCentrality,
                                                       actualUpperCentrality)
                                                    : "_centrality_all";
  TString jetPtString = restrictJetPtAxis ? Form("_jetPt_%.0f_%.0f.root", actualLowerJetPt, actualUpperJetPt)
                                          : "";  
  saveFileName.ReplaceAll(".root", Form("%s%s%s.root", centralityString.Data(), jetPtString.Data(), chargeString.Data()));
  
  TString saveFilePathName = Form("%s/%s", savePath.Data(), saveFileName.Data());
  TFile* saveFile = TFile::Open(saveFilePathName.Data(), "RECREATE");
  
  if (!saveFile) {
    printf("Failed to save results to file \"%s\"!\n", saveFilePathName.Data());
    return -1;
  }
  
  saveFile->cd();
  
  for (Int_t species = 0; species < AliPID::kSPECIES; species++) {
    if (hPtResolution[species])
      hPtResolution[species]->Write();
    
    if (hPtResolutionFit[species])
      hPtResolutionFit[species]->Write();
  }
  
  TNamed* settings = new TNamed(
      Form("Settings: Data file \"%s\", lowerCentrality %.3f, upperCentrality %.3f, lowerJetPt %.1f, upperJetPt %.1f\n",
           pathNameData.Data(), lowerCentrality, upperCentrality, lowerJetPt, upperJetPt), "");
  settings->Write();
  
  saveFile->Close();
  
  
  return 0;
}
Ejemplo n.º 11
0
void minuitFit()
{
  
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);

  Bool_t makePDF = checkMakePDF();
  
  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentB.root");
  TFile *fB = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentC.root");
  TFile *fC = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fB->IsOpen()==kFALSE || fC->IsOpen()==kFALSE)
    { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
		<< "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
      exit(1); }
  
  // Set constants and projection bins (from header file anaConst, analysis constants)
  
  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;
  Double_t p00[numPtBins],p01[numPtBins],p20[numPtBins],p21[numPtBins];
  Double_t e00[numPtBins],e01[numPtBins],e20[numPtBins],e21[numPtBins];
  Double_t pC0[numPtBins],pC1[numPtBins],eC0[numPtBins],eC1[numPtBins];
  Double_t Rb0[numPtBins],Rb2[numPtBins],RbC[numPtBins],pT[numPtBins];
  Double_t eb0[numPtBins],eb2[numPtBins],ebC[numPtBins],dx[numPtBins];
  Double_t ptOFF1[numPtBins],ptOFF2[numPtBins];
  Int_t plotCount0 = 0, plotCount2 = 0, plotCount = 0;
  
  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[3][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Float_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH1F*)fD->Get("histoNorms");
  bPtNorms   = (TH1F*)fB->Get("ptNorm");
  cPtNorms   = (TH1F*)fC->Get("ptNorm");
  
  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
    {
      norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
      norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
      normB = bPtNorms->GetBinContent(bPtNorms->GetBin(ptbin+1));
      normC = cPtNorms->GetBinContent(cPtNorms->GetBin(ptbin+1));

      if(norm0 == 0)
	{
	  cout << ptbin << " For this bin, some norm0 = 0" << endl;
	  continue;
	}
      if( norm2 == 0 )
	{
	  cout << ptbin << " For this bin, some norm2 = 0" << endl;
	  continue;
	}
      if( normB == 0 )
	{
	  cout << ptbin << " For this bin, some normB = 0" << endl;
	  continue;
	}
      if(normC == 0)
	{
	  cout << ptbin << " For this bin, some normC = 0" << endl;
	  continue;
	}
      plotbin = ptbin;
      // Init necessary plotting tools
      lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
      sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
      lbl[ptbin]->AddText(textLabel);
      lbl[ptbin]->SetFillColor(kWhite);

      projB[ptbin] = (TH1D*)fB->Get(Form("delPhi_%i",ptbin));
      projC[ptbin] = (TH1D*)fC->Get(Form("delPhi_%i",ptbin));
      projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
      projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
      // Do any rebinning
      Int_t RB = 1;
      projB[ptbin]->Rebin(RB);
      projC[ptbin]->Rebin(RB);
      projData0[ptbin]->Rebin(RB);
      projData2[ptbin]->Rebin(RB);

      // Clone to make plots without effecting fits
      plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
      plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
      plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

      // Set features that are the same in plots
      projData0[ptbin]->SetLineColor(kBlue);
      projData2[ptbin]->SetLineColor(kGreen+3);
      projB[ptbin]->SetLineColor(kRed);
      projC[ptbin]->SetLineColor(kBlack);
      projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
      plotD0[ptbin]->SetLineColor(kBlue);
      plotD2[ptbin]->SetLineColor(kGreen+3);
      plotD0[ptbin]->SetMarkerStyle(20);
      plotD0[ptbin]->SetMarkerColor(kBlue);
      plotD0[ptbin]->SetMarkerSize(0.4);
      plotB[ptbin]->SetLineColor(kRed);
      plotC[ptbin]->SetLineColor(kBlack);
      plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

      combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      combData[ptbin] -> Add(projData2[ptbin]);
      combData[ptbin]->SetLineColor(kBlue);
      combData[ptbin]->SetMarkerStyle(20);
      combData[ptbin]->SetMarkerColor(kBlue);
      combData[ptbin]->SetMarkerSize(0.4);
      combData[ptbin]->SetTitle("");
      
      // Normalize
      projB[ptbin]     -> Scale(1/normB);
      projC[ptbin]     -> Scale(1/normC);
      projData0[ptbin] -> Scale(1/norm0);
      projData2[ptbin] -> Scale(1/norm2);
      plotD0[ptbin]    -> Scale(1/norm0);
      plotD2[ptbin]    -> Scale(1/norm2);
      plotB[ptbin]     -> Scale(1/(normB));
      plotC[ptbin]     -> Scale(1/(normC));
      combData[ptbin]  -> Scale(1/(norm0+norm2));
    /*projB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projB[ptbin]->GetBinContent(70));
      projC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projC[ptbin]->GetBinContent(70));
      plotB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotB[ptbin]->GetBinContent(70));
      plotC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotC[ptbin]->GetBinContent(70));
      */
      
      // Draw Templates on own plots
      if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
      if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
      plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.5);
      plotC[ptbin]  -> Draw("hist");
      plotB[ptbin]  -> Draw("same hist");
      plotD0[ptbin] -> Draw("same");
      plotD2[ptbin] -> Draw("same");
      lbl[ptbin]    -> Draw("same");

      TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
      leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
      leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
      leg->AddEntry(projData0[ptbin],"HT0","lpe");
      leg->AddEntry(projData2[ptbin],"HT2","lpe");
      leg->Draw();

      /////////////////////
      // Do the actual fits
      /////////////////////

      cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      currentPtBin = ptbin;
      double arglist[10];int ierflg=0;
      TMinuit *gMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gMinuit->SetMaxIterations(50000);
      gMinuit->SetFCN(chi2_0);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart[2]={0.3,1}; //frac
      double step[2]={0.01,0.01}; //starting step
      gMinuit->mnparm(0,"BtoNPE frac",vstart[0],step[0],0.000,2,ierflg);
      gMinuit->mnparm(1,"Scale Factor",vstart[1],step[1],0.000,2,ierflg);
      //simple scan to get better start values
      gMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      double dum1,dum2;
      TString *str0 = new TString("BtoNPE frac");
      TString *str1 = new TString("Scale Factor");
      gMinuit->mnpout(0,*str0,p01[ptbin],e01[ptbin],dum1,dum2,ierflg);
      gMinuit->mnpout(1,*str1,p00[ptbin],e00[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT0 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p01[ptbin] << " rC: " << p00[ptbin] << endl
	   << "erB: " << e01[ptbin] << " erC: " << e00[ptbin] << endl << endl;
      
      //Print results
      double amin,edm,errdef;
      int nvpar,nparx,icstat;
      gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] < 6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  dx[plotCount0] = 0.;
	  ptOFF1[plotCount0] = pT[ptbin];
	  Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
	  eb0[plotCount0] = e01[ptbin];
	  plotCount0++;
	}
    
      // Plot results
      fitResult0->cd(ptbin+1);
      TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
      TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
      TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
      stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
      stat[0][ptbin]->InsertText(statLabel);
      stat[0][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[0][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");
            

      cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResult2->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *g2Minuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      g2Minuit->SetMaxIterations(50000);
      g2Minuit->SetFCN(chi2_2);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      g2Minuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart2[2]={0.3,1}; //frac
      double step2[2]={0.01,0.01}; //starting step
      g2Minuit->mnparm(0,"BtoNPE frac",vstart2[0],step2[0],0.000,2,ierflg);
      g2Minuit->mnparm(1,"Scale Factor",vstart2[1],step2[1],0.000,2,ierflg);
      //simple scan to get better start values
      g2Minuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      g2Minuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str2 = new TString("BtoNPE frac");
      TString *str3 = new TString("Scale Factor");
      g2Minuit->mnpout(0,*str2,p21[ptbin],e21[ptbin],dum1,dum2,ierflg);
      g2Minuit->mnpout(1,*str3,p20[ptbin],e20[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT2 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p21[ptbin] << " rC: " << p20[ptbin] << endl
	   << "erB: " << e21[ptbin] << " erC: " << e20[ptbin] << endl << endl;
      
      //Print results
      g2Minuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      g2Minuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] > 3.6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  ptOFF2[plotCount2] = pT[ptbin];
	  Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
	  eb2[plotCount2] = e21[ptbin];
	  plotCount2++;
	}

      // Plot results
      fitResult2->cd(ptbin+1);
      dClone = (TH1D*) projData2[ptbin]->Clone();
      cClone = (TH1D*) projC[ptbin]->Clone();
      bClone = (TH1D*) projB[ptbin]->Clone();
      stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
      stat[2][ptbin]->InsertText(statLabel);
      stat[2][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[2][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");

      cout << "!!!!!!! HT0&2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResultC->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *gCMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gCMinuit->SetMaxIterations(50000);
      gCMinuit->SetFCN(chi2_C);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gCMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstartC[2]={0.3,1}; //frac
      double stepC[2]={0.01,0.01}; //starting step
      gCMinuit->mnparm(0,"BtoNPE frac",vstartC[0],stepC[0],0.000,2,ierflg);
      gCMinuit->mnparm(1,"Scale Factor",vstartC[1],stepC[1],0.000,2,ierflg);
      //simple scan to get better start values
      gCMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gCMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str4 = new TString("BtoNPE frac");
      TString *str5 = new TString("Scale Factor");
      gCMinuit->mnpout(0,*str4,pC1[ptbin],eC1[ptbin],dum1,dum2,ierflg);
      gCMinuit->mnpout(1,*str5,pC0[ptbin],eC0[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HTC PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << pC1[ptbin] << " rC: " << pC0[ptbin] << endl
	   << "erB: " << eC1[ptbin] << " erC: " << eC0[ptbin] << endl << endl;

      //Print results
      gCMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gCMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
      ebC[plotCount] = eC1[ptbin];
      plotCount++;
    }

  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/ptHatTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/ptHatTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);

  c1->cd(1);

  gr0->SetTitle("Bottom Contribution");
  gr0->GetXaxis()->SetTitle("p_{T,e}");
  gr0->GetYaxis()->SetTitle("#frac{r_{B}}{(r_{B}+r_{C})}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  gr0->GetXaxis()->SetLimits(1,14);
  gr0->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  
  
  gr0->Draw("AP");
  // grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  grP->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.4,0.85);
  leg2->AddEntry(gr0,"High Tower 0 Trigs","pe");
  leg2->AddEntry(gr2,"High Tower 2 Trigs","pe");
  // leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grF,"FONLL (Uncertainty: Scale Only)","l");
  leg2->AddEntry(grP,"Run 5/6 Analysis (Stat Uncertainty)","pe");
  leg2->Draw("same");
  
   // Make PDF with output canvases
  if(makePDF)
    {
      //Set front page
      TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
      fp->cd();
      TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
      bLabel->SetFillColor(38);
      bLabel->Draw();
      TLatex tl;
      tl.SetNDC();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.033);
      char tlName[100];
      char tlName2[100];
      
      TString titlename = FileName;
      int found = titlename.Last('/');
      if(found >= 0){
	titlename.Replace(0, found+1, "");
      } 
      sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
      tl.SetTextSize(0.05);
      tl.SetTextColor(kWhite);
      tl.DrawLatex(0.05, 0.92,tlName);
      
      TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
      bFoot->SetFillColor(38);
      bFoot->Draw();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.05);
      tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
      tl.SetTextColor(kBlack);
      tl.SetTextSize(0.03);
      tl.DrawLatex(0.1, 0.14, titlename);
      sprintf(tlName,"TEST");
      tl.DrawLatex(0.1, 0.8,tlName);
      
      // Place canvases in order
      TCanvas* temp = new TCanvas();
      sprintf(name, "FFOutput/%s.pdf[", FileName);
      temp->Print(name);
      sprintf(name, "FFOutput/%s.pdf", FileName);

      temp = deltaPhi; 
      temp->Print(name);
      temp = fitResult0;
      temp->Print(name);
      temp = fitResult2;
      temp->Print(name);
      temp = fitResultC;
      temp->Print(name);
      temp = c1;
      temp->Print(name);
      
      sprintf(name, "FFOutput/%s.pdf]", FileName);
      temp->Print(name);
    }
}
Ejemplo n.º 12
0
void
RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
                                          int calculatorType,
                                          int testStatType, 
                                          bool useCLs,  
                                          int npoints,
                                          const char * fileNameBase ){

   // analyize result produced by the inverter, optionally save it in a file 
   
   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();
  
   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
  
   // compute expected limit
   std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;
   std::cout << " expected limit (-2 sig) " << r->GetExpectedUpperLimit(-2) << std::endl;
   std::cout << " expected limit (+2 sig) " << r->GetExpectedUpperLimit(2) << std::endl;
  
  
   // write result in a file 
   if (r != NULL && mWriteResult) {
    
      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : (calculatorType == 1) ? "Hybr" : "Asym";
      const char *  limitType = (useCLs) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      TString resultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
      //strip the / from the filename
      if (mMassValue.size()>0) {
         resultFileName += mMassValue.c_str();
         resultFileName += "_";
      }
    
      TString name = fileNameBase; 
      name.Replace(0, name.Last('/')+1, "");
      resultFileName += name;
    
      TFile * fileOut = new TFile(resultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   
  
  
   // plot the result ( p values vs scan points) 
   std::string typeName = "";
   if (calculatorType == 0 )
      typeName = "Frequentist";
   if (calculatorType == 1 )
      typeName = "Hybrid";   
   else if (calculatorType == 2 ) { 
      typeName = "Asymptotic";
      mPlotHypoTestResult = false; 
   }
  
   const char * resultName = r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName.c_str(),resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);
   plot->Draw("CLb 2CL");  // plot all and Clb
  
   const int nEntries = r->ArraySize();
  
   // plot test statistics distributions for the two hypothesis 
   if (mPlotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      if (nEntries > 1) { 
         int ny = TMath::CeilNint( sqrt(nEntries) );
         int nx = TMath::CeilNint(double(nEntries)/ny);
         c2->Divide( nx,ny);
      }
      for (int i=0; i<nEntries; i++) {
         if (nEntries > 1) c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
   }
}
Ejemplo n.º 13
0
void write_ist_pednoise() {
	gSystem->Setenv("DB_ACCESS_MODE", "write");
  	gROOT->Macro("LoadLogger.C");
  	gSystem->Load("St_base.so");
  	gSystem->Load("libStDb_Tables.so");
  	gSystem->Load("StDbLib.so");

	std::ifstream fPDlist("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/pedNoiseFiles_Corr/pedRunList_Corr.txt");
        if(!fPDlist.is_open())
        {
                std::cout << " There is no corrected pedRunList file! " << endl;
                exit(0);
        }

        while(!fPDlist.eof()) {
                TString  sPDfile;
                fPDlist >> sPDfile;

                int found = sPDfile.Last('_');
                if(found >= 0)
                        sPDfile.Replace(0, found + 1, "");

                found = sPDfile.Last('.');
                if(found >= 0)
                        sPDfile.Replace(found, sPDfile.Length(), "");

                int runnumb = sPDfile.Atoi();
                if(runnumb)
                        pedRunNumVec.push_back(runnumb);
        }
        fPDlist.close();
	const int nPedRuns = pedRunNumVec.size();
	cout << nPedRuns << " good pedestal runs recorded! " << endl;
        if(debug) {
                for(int i=0; i<nPedRuns; i++)
                        cout << i << "th pedestal run: " << pedRunNumVec[i] << endl;
        }


  	std::ifstream fCosmicRunList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/cmNoise_cosmic/cosmicRunlist.txt");
        if(!fCosmicRunList.is_open())
        {
                std::cout << " There is no cosmicRunList file! " << endl;
                exit(0);
        }

        while(!fCosmicRunList.eof()) {
                TString  sCMNfile;
                fCosmicRunList >> sCMNfile;

                int found = sCMNfile.First('.');
                if(found >= 0)
                        sCMNfile.Replace(found, sCMNfile.Length(), "");

                int runnumb = sCMNfile.Atoi();
                if(runnumb)
                        cosmicRunNumVec.push_back(runnumb);
        }
        fCosmicRunList.close();
	const int nCosmicRuns = cosmicRunNumVec.size();
	cout << nCosmicRuns << " good cosmic runs recorded! " << endl;
        if(debug) {
                for(int i=0; i<nCosmicRuns; i++)
                        cout << i << "th cosmic run: " << cosmicRunNumVec[i] << endl;
        }

	Int_t   isBadChannel[110592];
        Int_t   isBadChip[864];
	//loop pedestal runs
	for(int iRun=0; iRun<nPedRuns; iRun++)
        {
                int runNumber = pedRunNumVec[iRun];
		//below only for testing
		//if(runNumber<15065020) continue;

                int TbinPD = PDTBin(runNumber);
		cout << "Reading pedestal run " << runNumber << " with " << TbinPD << " time bins! " << endl;
		
		//retrieve time stamp information
		char cmd[256];
            	sprintf(cmd, "/usr/bin/mysql -h dbbak.starp.bnl.gov --port=3413 -e \"SELECT FROM_UNIXTIME(startRunTime) as beginTime_human FROM RunLog.runDescriptor WHERE runNumber = %d\" >timeStamp_tmp", runNumber);
            	system(cmd);

            	TString mTimeStamp;
            	FILE *inR = fopen("timeStamp_tmp","r");
            	while(!feof(inR)) {
                	char buff[64];
                	if(fgets(buff,sizeof(buff),inR) == 0) continue ;
                	switch(buff[0]) {
                    		case 'b' : //beginTime_human
                        		continue ;
                	}
                	mTimeStamp = Form(buff);
            	}
            	fclose(inR);

            	sprintf(cmd, "/bin/rm timeStamp_tmp");
            	system(cmd);

		int found = 19;
            	mTimeStamp.Replace(found, mTimeStamp.Length(), "");
            	cout << iRun << ": \t" << runNumber << "\t" << mTimeStamp << endl;
	
		//find the closest cosmic run to match, and using its common-mode noise
		int diffRun = 15000000, miniDiffRun = 15000000;
		int matchedCosmicRunNumber = 15032029;
		for(int iCosmic=0; iCosmic<nCosmicRuns; iCosmic++) {
			diffRun = cosmicRunNumVec[iCosmic] - runNumber;
			if(diffRun < miniDiffRun && diffRun > 0) { //corresponding cosmic run should come after the pedestal run
				miniDiffRun = diffRun;
				matchedCosmicRunNumber = cosmicRunNumVec[iCosmic];
			}
		}
		if(runNumber>=15158006) matchedCosmicRunNumber = 15157002; //if no later cosmic runs found, then use the last one
		int TbinCMN = CMTBin(matchedCosmicRunNumber);
		cout << "Matched cosmic run " << matchedCosmicRunNumber << " with " << TbinCMN << " time bins! " << endl;
		
		StDbManager* mgr = StDbManager::Instance();
  		StDbConfigNode* node = mgr->initConfig("Calibrations_ist");
  		StDbTable* dbtable = node->addDbTable("istPedNoise");
  		mgr->setStoreTime(mTimeStamp.Data());
		
		//open matched CMN DB file
		std::ifstream inCMN(Form("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/cmNoise_cosmic/%d.istCmNoise.dat", matchedCosmicRunNumber));
    		if (!inCMN.is_open()) {
    			std::cout << " There is no CMN DB file  " << end ;
    			exit(0);
    		}

		//open corrected pedestal/RMS DB file
		std::ifstream inPD(Form("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/pedNoiseFiles_Corr/IST_pedestals_%d.txt", runNumber));
    		if (!inPD.is_open()) {
    			std::cout << " There is no PED/RMS DB file  " << end ;
    			exit(0);
    		}
	
		//retreive online masking chip/channel and offline channel masking
		for(int i=0; i<110592; i++) {
                    isBadChannel[i] = 0;
                }

		for(int i=0; i<864; i++) {
                    isBadChip[i] = 0;
                }
		
		//online masking-out chips
		int tem_Run, tem_Rdo, tem_Arm, tem_Group, tem_Apv, tem_Status, ChipEID;
		int deadChipsInRun14 = 31, deadChipCounter=0;
                if(runNumber<15181030) {
                    std::ifstream deadChipList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_dead.txt");
                }
                else {
                    std::ifstream deadChipList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_dead_AuHe3.txt");
                    deadChipsInRun14 = 29; //since run 15174075 (June 23, 2014), two chips (566/567) were taken out of online mask-out chip list
                }
		if(!deadChipList.is_open()) 
		{
                        cout << "ist_apv_dead file was NOT found " << endl;
                        exit(0);
                }

		int deadChipId = -1;
                while(!deadChipList.eof() && deadChipCounter<deadChipsInRun14) {
                    deadChipList >> tem_Rdo >> tem_Arm >> tem_Apv;
                    deadChipId = (tem_Rdo-1)*6*24 + tem_Arm*24 + tem_Apv; //electronics ID
                    if(deadChipId<0 || deadChipId>=864) continue;

		    int deadChipGeomIdx = elecIdToGeomId(deadChipId);
                    isBadChip[deadChipGeomIdx-1] = 1; //dead chip
                    deadChipCounter++;
                }
                deadChipList.close();
		cout << "Number of online masking-out chips: " << deadChipCounter << endl;

		//mis-configured chips
                std::ifstream misConfigChiplist("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_bad.txt");
                if(!misConfigChiplist.is_open())
                {
                        cout << "ist_apv_bad file was NOT found " << endl;
                        exit(0);
                }
		
		int badChipCounter = 0;
		while(!misConfigChiplist.eof()) //mis-configured chips recorded since 15065020
                {
                        misConfigChiplist >> tem_Run >> tem_Rdo >> tem_Arm >> tem_Group >> tem_Apv >> tem_Status;
                        if(tem_Run == matchedCosmicRunNumber)
                        {
                                ChipEID = (tem_Rdo - 1) * 6 * 24 + tem_Arm * 24 + tem_Group * 12 + tem_Apv;
                                if(ChipEID<0 || ChipEID>=864) continue;

				int badChipGeomIdx = elecIdToGeomId(ChipEID);
                                isBadChip[badChipGeomIdx-1] = 2; //mis-configured chip
                                badChipCounter++;
                        }
                }
                misConfigChiplist.close();
		cout << "Number of offine masking-out chips: " << badChipCounter << endl;

		//online masking-out channel list
		Int_t   rdoIndex = -1, armIndex = -1, apvIndex = -1, chanIndex = -1;
                Int_t   channelId = -1;

		std::ifstream badChannelListOnline("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/channelMaskingList_ist_online.txt"); //179 bad channels masked out online
		if(!badChannelListOnline.is_open()) 
		{
                        cout << "channelMaskingList_ist_online file was NOT found " << endl;
                        exit(0);
                }

		int deadChannelCounter = 0;
                while(!badChannelListOnline.eof()) {
                        badChannelListOnline >> rdoIndex >> armIndex >> apvIndex >> chanIndex;
                        channelId = (rdoIndex-1)*6*24 + armIndex*24 + apvIndex*128 + chanIndex;
                        isBadChannel[channelId] = 1;
			deadChannelCounter++;
                }
                badChannelListOnline.close();
		cout << "Number of online masking-out channels: " << deadChannelCounter << endl;

		//offline masking-out channel list
                std::ifstream badChannelListOfflineB("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ChannelMaskList.20140601.txt"); //336 bad channels masked out offline
		if(!badChannelListOfflineB.is_open())
		{
			cout << "ChannelMaskList.20140601 file was NOT found " << endl;
                        exit(0);
		}

		int badChannelCounter = 0;
                while(!badChannelListOfflineB.eof()) {
                        badChannelListOfflineB >> channelId;
                        isBadChannel[channelId] = 2;
			badChannelCounter++;
                }
                badChannelListOfflineB.close();
		cout << "Number of offline masking-out channels: " << badChannelCounter << endl;

		istPedNoise_st table;
		for (int i = 0; i < 110592; i++) {
    			table.pedestal[i] = 0;
    			table.rmsNoise[i] = 0;
  		}

  		for (int i = 0; i < 864; i++) {
    			table.cmNoise[i] = 0;
  		}

		//Pedestal and RMS Noise
		Float_t pedestalT, rmsT;
		Float_t averagePed = 0., averageRms = 0.;
		Int_t timebin = -1;
		channelId = -1;
		for (int counter=0; counter<110592*TbinPD; counter++){
			inPD >> rdoIndex >> armIndex >> apvIndex >> chanIndex >> timebin >> pedestalT >> rmsT;
			channelId = (rdoIndex - 1) * 6 * 24 * 128 + armIndex * 24 * 128 + apvIndex * 128 + chanIndex;
			if(channelId<0 || channelId>=110592) continue;
    			averagePed += pedestalT/TbinPD;
    			averageRms += rmsT/TbinPD;

    			if(((timebin+1)/TbinPD) && ((counter+1)/TbinPD)) {
        			//cout << counter/TbinPD << ": channelId = " << channelId<<"\t pedestal = "<<averagePed<<"\t rms = "<<averageRms<<endl;

        			table.pedestal[channelId] = (int)averagePed;
        			table.rmsNoise[channelId] = (int)(averageRms*100);
				//masking-out online/offline bad channels
				if(isBadChannel[channelId]) 
					table.rmsNoise[channelId] = 10000;
				if(debug)
					cout << counter/TbinPD << ": channelId = " << channelId << "\t pedestal = " << table.pedestal[channelId] << "\t rms = " << table.rmsNoise[channelId] <<endl;
        			averagePed = 0.;
        			averageRms = 0.;
    			}
  		}
  		inPD.close();

		//Common Mode Noise
		Float_t cmNoiseT;
		Float_t averageCmNoise = 0.;
		Int_t chipId;
		Int_t numTimeBins = 9; //IST CMN DB files output 9 time bins format in default
		for(int counter=0; counter<864*numTimeBins; counter++){
    			inCMN >> chipId >> timebin >> cmNoiseT;
    			averageCmNoise += cmNoiseT/TbinCMN;

    			if(((timebin+1)/numTimeBins) && ((counter+1)/numTimeBins)) {
        			//cout << counter/numTimeBins << ": chipId = " << chipId << " cmNoiseT = " << averageCmNoise << endl;
        			table.cmNoise[chipId] = (int)(averageCmNoise*100);
				//masking-out online/offline bad chips
				if(isBadChip[chipId])
					table.cmNoise[chipId] = 10000;
				if(debug)
					cout << counter/numTimeBins << ": chipId = " << chipId << " cmNoiseT = " << table.cmNoise[chipId] << endl;
        			averageCmNoise = 0.;
    			}
  		}
  		inCMN.close();

		// Please comment out below lines if you do testing, or it will write the DB!!!!
		// Store data to the StDbTable
		dbtable->SetTable((char*)&table, 1);

		// Store table to database
		mgr->storeDbTable(dbtable);

		//exit(0); //only for testing
	}
};
Ejemplo n.º 14
0
void offline(const char* FileName="test", Int_t mode = 0)
{
  if (strcmp(FileName, "") == 0 || mode == 0 || mode > 2)
    {
      cout << "Error in input of offline('fileName',mode):" << endl
	   << "mode 1: c/cbar; mode 2: b/bbar." << endl
	   << "Need File Name: ''pythia_tree_Aug##_#''" << endl;
      abort();
    }
  
  // Set Style parameters for this macro
  //gStyle->SetOptTitle(1); // Show Title (off by default for cleanliness)
  gErrorIgnoreLevel = kError; // Set Verbosity Level (kPrint shows all)

   // Set Output options
  Int_t number;
  checkBatchMode();
  Bool_t makePDF = checkMakePDF();
  Bool_t makeROOT= checkMakeRoot();

  // Use mode input to decide whether C or B templates to work on
  char type[10] = "X";
  if(mode == 1)
    sprintf(type, "C");
  if(mode == 2)
    sprintf(type, "B");

  // Open output file
  char fname[100];
  TFile* file;
  if(makeROOT){
    sprintf(fname,"/Users/zach/Research/pythia/ptHatTemplate/%s_%s_processed.root",FileName,type);
    file = new TFile(fname,"RECREATE");
    if (file->IsOpen()==kFALSE)
      {
	std::cout << "!!! Outfile Not Opened !!!" << std::endl;
	makeROOT = kFALSE;
      }
  }

  // Initialize Histos for Summing and other global vars
  const Int_t numPtHatBins = 8;
  const Int_t numPtBins = anaConst::nPtBins;
  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;
  Float_t hptMax=25; // Set max above range to allow overflow

  TH1F* ptHat     = new TH1F("pThat", "" ,1500, 0, 150);
  TH1F* ptHatCorr = new TH1F("pThatCorrected", "" ,1500, 0, 150);
  TH3F* mh3delPhi;
  TH2F* mh2npePt;
  TH1F* hStats;
  TH2F* mh2ptHatPt;
  TH1D* projpthatall;
  char hist[100];
  TH1F* delPhi[numPtBins];
  TH1F* NpeY[numPtBins];
  TH1F* ptNorm;
  TH1D* projDelPhi[numPtBins];
  TH1D* projNpeY[numPtBins];
  TH1D* projptHat[numPtBins];
  TH1F* temp;
  TH1F* delPhi2535 = new TH1F("delPhi2535","",200,-10,10);
  TH1F* trigCount = new TH1F("trigCount","",10,0,10);
  Float_t norm2535;
  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++) // initialize all before the actual sorting
    { delPhi[ptbin]= new TH1F(Form("delPhi_%i",ptbin), "Delta Phi" ,200, -10, 10);
      delPhi[ptbin]->Sumw2();
      NpeY[ptbin] = new TH1F(Form("NpeY_%i",ptbin),"NpeY",60,-3,3);
    }
  ptNorm = new TH1F("ptNorm", "pT Norm" ,200, 0, 20);
  ptNorm ->Sumw2();
      
  Float_t totalNorm[numPtBins]={0.};
  Double_t wt=0.;
   
  Int_t pthatlow[numPtHatBins] = {0,1,2,4,8,16,32,64};
  Int_t pthathigh[numPtHatBins]= {1,2,4,8,16,32,64,128};

  // Make Canvases
  TCanvas* deltaPhi = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  deltaPhi -> Divide(4,3);
  TCanvas* ptHatC = new TCanvas("ptHatC","ptHat Stitching Comparison",150,0,1150,1000);
  ptHatC   -> Divide(1,2);

  TPaveText* lbl[numPtBins];
  char textLabel[100];
  char name[1000];
 
  // Loop over all ptHat bins
  for(Int_t pthBin=0; pthBin < numPtHatBins; pthBin++)
    {
      
      // Open ROOT File (example: output/pythia_tree_Aug31_1_C2_4.root)
      sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/%s_%s%i_%i.root",FileName,type,pthatlow[pthBin],pthathigh[pthBin]); 
      TFile *f = new TFile(name,"READ");
      if (f->IsOpen()==kFALSE)
	{ std::cout << "!!! File Not Found !!!" << std::endl;
	  exit(1); }
      else
	{ cout << name << " is open!" << endl;}
            
      char histName[100];
      // Get Histos from run output
     
      sprintf(hist, "histo3D%s0", type);
      mh3delPhi    = (TH3F*)f->Get(hist);
      sprintf(hist, "histos2D%s1", type);
      mh2npePt     = (TH2F*)f->Get(hist);
      sprintf(hist, "histos2D%s10", type);
      mh2ptHatPt   = (TH2F*)f->Get(hist);
      sprintf(hist, "hStatistics");
      hStats       = (TH1F*)f->Get(hist);
      sprintf(hist, "delPhi");
      temp         = (TH1F*)f->Get(hist);
      sprintf(hist, "trigCount");
      trigCount    = (TH1F*)f->Get(hist);
          
      // Calculate Weight factors
      wt = 1e9*1e-3*(hStats->GetBinContent(1)/hStats->GetBinContent(2)); // Taken from Zhenyu's method. The 1e# factors are luminosity(?) corrections?
      projpthatall = mh2ptHatPt->ProjectionY("test",0,-1);
      ptHat -> Add(projpthatall);
      ptHatCorr -> Add(projpthatall,wt);

      // pt bin independent
      delPhi2535 -> Add(temp,wt); // still need weight from pthat
      //trigCount -> Scale(wt);     // "      "    "     "     "
      norm2535 += trigCount->GetBinContent(1);
      //delPhi2535 -> Scale(1./norm2535);
   
      // Analyze each ptH bin individually, adding to the overall hists
      for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
	{
	  // DEBUGcout << "pthbin: " << pthBin << " ptbin: " << ptbin << endl;
	  projDelPhi[ptbin] = mh3delPhi->ProjectionZ(Form("projDelPhi_%i",ptbin),mh3delPhi->GetXaxis()->FindBin(lowpt[ptbin]),mh3delPhi->GetXaxis()->FindBin(highpt[ptbin])-1,mh3delPhi->GetYaxis()->FindBin(hptCut),mh3delPhi->GetYaxis()->FindBin(hptMax));
	  projNpeY[ptbin]   = mh2npePt->ProjectionY(Form("projNpeY_%i",ptbin),mh2npePt->GetXaxis()->FindBin(lowpt[ptbin]),mh2npePt->GetXaxis()->FindBin(highpt[ptbin])-1);
	  projptHat[ptbin]  = mh2ptHatPt->ProjectionY(Form("projPtHat_%i",ptbin),mh2ptHatPt->GetXaxis()->FindBin(lowpt[ptbin]),mh2ptHatPt->GetXaxis()->FindBin(highpt[ptbin])-1);
	
	  delPhi[ptbin] -> Add(projDelPhi[ptbin],wt);
	  NpeY[ptbin] -> Add(projNpeY[ptbin],wt);
	  
	  // Calculate scaling Factor
	  Double_t Norm = NpeY[ptbin]->Integral();
	  ptNorm->SetBinContent(ptNorm->GetBin(ptbin+1),Norm);
	  totalNorm[ptbin] += Norm;
	 
	}
    }

  // For making plots

  ptHatC->cd(1);
  gPad-> SetLogy();
  ptHat->GetXaxis()->SetTitle("pT-Hat (GeV/c)");
  ptHat->SetTitle("Raw pT Hat");
  ptHat->Draw();
  ptHatC->cd(2);
  gPad-> SetLogy();
  ptHatCorr->GetXaxis()->SetTitle("pT-Hat (GeV/c)");
  ptHatCorr->SetTitle("Weighted pT Hat");
  ptHatCorr->Draw();
  
  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
    {
      // Init necessary plotting tools
      lbl[ptbin] = new TPaveText(.2,.8,.5,.85,Form("NB NDC%i",ptbin));
      sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
      lbl[ptbin]->AddText(textLabel);
      lbl[ptbin]->SetFillColor(kWhite);

      deltaPhi->cd(ptbin+1);
      delPhi[ptbin]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
      // delPhi[ptbin]->Sumw2();
      //cout << totalNorm[ptbin] << endl;
      //delPhi[ptbin]->Scale(wt);
      delPhi[ptbin]->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
      delPhi[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
      if(ptbin == 0)
	{
	  if(mode == 1)
	    delPhi[ptbin]->SetTitle("Pythia NPE-had #Delta#phi - c/#bar{c}");
	  if(mode == 2)
	    delPhi[ptbin]->SetTitle("Pythia NPE-had #Delta#phi - b/#bar{b}");
	}
      else
	delPhi[ptbin]->SetTitle("");
      if(ptbin < 13){
	delPhi[ptbin]->Draw("E");
	lbl[ptbin]->Draw("same");
      }
    }
  
      
  // Make PDF with output canvases
  if(makePDF)
    {
      //Set front page
      TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
      fp->cd();
      TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
      bLabel->SetFillColor(38);
      bLabel->Draw();
      TLatex tl;
      tl.SetNDC();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.033);
      char tlName[100];
      char tlName2[100];
      
      TString titlename = FileName;
      int found = titlename.Last('/');
      if(found >= 0){
	titlename.Replace(0, found+1, "");
      } 
      sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Pythia Templates");
      tl.SetTextSize(0.05);
      tl.SetTextColor(kWhite);
      tl.DrawLatex(0.05, 0.92,tlName);
      
      TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
      bFoot->SetFillColor(38);
      bFoot->Draw();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.05);
      tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
      tl.SetTextColor(kBlack);
      tl.SetTextSize(0.03);
      tl.DrawLatex(0.1, 0.14, titlename);
      sprintf(tlName,"TEST");
      tl.DrawLatex(0.1, 0.8,tlName);
      
      // Place canvases in order
      TCanvas* temp = new TCanvas();
      sprintf(name, "%s.pdf[", FileName);
      temp->Print(name);
      sprintf(name, "%s.pdf", FileName);
      temp = fp; // print front page
      temp->Print(name);
      temp = ptHatC;
      temp->Print(name);
      temp = deltaPhi;
      temp->Print(name);
      sprintf(name, "%s.pdf]", FileName);
      temp->Print(name);
    }

  if(makeROOT)
    {
      file->Write();
      file->Close();
    }
}
void TSelectionClass::saveHistos()
{
	cout<<"save Histo: "<<hFiducialCutSilicon->GetTitle()<<endl;
	TString name = hFiducialCutSilicon->GetName();
	name.Insert(0,"c");
	TCanvas *c1= fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSilicon);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
	delete c1;
	c1 = 0;
    delete hFiducialCutSilicon;

	name = hFiducialCutSiliconDiamondHit->GetName();
	name.Insert(0,"c");
	c1 = fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSiliconDiamondHit,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
	delete c1;
	c1=0;
    delete hFiducialCutSiliconDiamondHit;

	name = "c";
	name.Append(hFiducialCutSiliconOneAndOnlyOneDiamondHit->GetName());
	c1= fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSiliconOneAndOnlyOneDiamondHit,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
    delete c1;
    c1=0;
    delete hFiducialCutSiliconOneAndOnlyOneDiamondHit;

	name = "c";
	name.Append(hSelectedEvents->GetName());
	c1 = fiducialCuts->getAllFiducialCutsCanvas(hSelectedEvents,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
    delete c1;
    c1=0;
    delete hSelectedEvents;

    map<Int_t,TH2F*>::iterator it;
    for (it = mapFiducialCutSiliconDiamondHitSamePattern.begin(); it!=mapFiducialCutSiliconDiamondHitSamePattern.end(); it++){
        TH2F* histo = (*it).second;
        name = histo->GetName();
        name.Replace(0,1,"c");
        c1 = fiducialCuts->getAllFiducialCutsCanvas(histo,true);
        c1->SetName(name);
        histSaver->SaveCanvas(c1);
        delete c1;
        c1=0;
        delete histo;
    }
	hAnalysisFraction->Scale(.1);
	hAnalysisFraction->SetStats(false);
	//	hAnalysisFraction->GetYaxis()->SetRangeUser(0,100);
	histSaver->SaveHistogram(hAnalysisFraction);
	delete hAnalysisFraction;


    histSaver->SaveHistogram(hDiamondPatternFiducialPattern);

    histSaver->SaveHistogram(hDiamondPatternFiducialPatternNoMapping);
    name = "stackPatternMapping";
    hDiamondPatternFiducialPattern->SetLineColor(kGreen);
    hDiamondPatternFiducialPatternNoMapping->SetLineColor(kRed);
    THStack *stack = new THStack(name,name);
    stack->Add(hDiamondPatternFiducialPattern);
    stack->Add(hDiamondPatternFiducialPatternNoMapping);
    stack->Draw();
    if(stack->GetXaxis()) stack->GetXaxis()->SetTitle("pattern no.");
    if(stack->GetYaxis()) stack->GetYaxis()->SetTitle("number of entries #");
    histSaver->SaveStack(stack,"hist",true);
    if(stack) delete stack;
    histSaver->SaveHistogram(pDiamondPatternFiducialPatternProfile);
    if(hDiamondPatternFiducialPatternNoMapping) delete hDiamondPatternFiducialPatternNoMapping;
    if(hDiamondPatternFiducialPattern) delete hDiamondPatternFiducialPattern;
    if (pDiamondPatternFiducialPatternProfile) delete pDiamondPatternFiducialPatternProfile;
}