Example #1
0
void mytestreweight(){


  TFile*finput=new TFile("fworking.root");
  TH1D*hBPtFONLL=(TH1D*)finput->Get("hBPt");
  TH1D*hDPtFONLL=(TH1D*)finput->Get("hDPt");
  TH2D*hD=(TH2D*)finput->Get("hD");
  
   hD->SetXTitle("B p_{T} (GeV/c)");
   hD->SetYTitle("D^{0} p_{T} (GeV/c)");
   hBPtFONLL->SetXTitle("B p_{T} (GeV/c)");
   hDPtFONLL->SetXTitle("D p_{T} (GeV/c)");
  
  TH2D *hDreweight = (TH2D*)hD->Clone("hDreweight");
  TH1D *hBPtPythia = hD->ProjectionX("hBPtPythia");
  TH1D *hDPtPythia = hD->ProjectionY("hDPtPythia");

   for (int x=1;x<=hDreweight->GetNbinsX()+1;x++){  //loop over the B pt bins
      if (hBPtPythia->GetBinContent(x)==0) continue;
      double ratio = hBPtFONLL->GetBinContent(x)/hBPtPythia->GetBinContent(x);  // in each pt bin we calculate the ratio of pythiaB/FONLLB 
       
      for (int y=1;y<=hDreweight->GetNbinsY()+1;y++){   //loop over the D pt bins
         double ratio2 = ratio;                                              //copy the ratio for each B bin
         double val = hDreweight->GetBinContent(x,y)*ratio2;
         double valError = hDreweight->GetBinError(x,y)*ratio2;
	 hDreweight->SetBinContent(x,y,val);
	 hDreweight->SetBinError(x,y,valError);
      }   
   }

  TH1D *hBPtPythiaReweight = hDreweight->ProjectionX("hBPtPythiaReweight");
  TH1D *hDPtPythiaReweight = hDreweight->ProjectionY("hDPtPythiaReweight");
  
  hBPtPythiaReweight->Divide(hBPtFONLL);
   
  TCanvas*canvas=new TCanvas("canvas","canvas",1000,500);  
  canvas->SetLogy();
  canvas->Divide(3,1);
  canvas->cd(1);
  hBPtFONLL->Draw();
  canvas->cd(2);
  hBPtPythia->Draw();
  canvas->cd(3);
  hBPtPythiaReweight->Draw();

}
Example #2
0
void DrawTH2DZ(TFile* File, char* Histos_Name, char* legend, char* Title, char* Xlegend, char* Ylegend, double xmin, double xmax, double ymin, double ymax,  bool save, char* save_path, bool Normalization)
{
   TH2D* Histos = File->Get(Histos_Name);
   Histos->SetTitle();
   Histos->SetStats(kFALSE);
   Histos->GetXaxis()->SetTitle(Xlegend);
   Histos->GetYaxis()->SetTitle(Ylegend);
   Histos->GetYaxis()->SetTitleOffset(1.20);
//   Histos->GetYaxis()->SetTitleOffset(1.0);
   if(xmin!=xmax)Histos->SetAxisRange(xmin,xmax,"X");
   if(ymin!=ymax)Histos->SetAxisRange(ymin,ymax,"Y");

   if(Normalization){
      for(int x=0;x<Histos->GetXaxis()->GetNbins();x++){     
         TH1D* tmp = Histos->ProjectionY("",x,x);
	 double Integral = tmp->Integral();
         if(Integral==0)continue;
         double Factor = 1/Integral;
         for(int y=0;y<Histos->GetYaxis()->GetNbins();y++){
            Histos->SetBinContent(x,y, Histos->GetBinContent(x,y)*Factor );
            Histos->SetBinError  (x,y, Histos->GetBinError  (x,y)*Factor );
         }
      }
   }




   Histos->Draw("COLZ");
   gPad->SetLogz(1);
/*   c1->Update();
   TPaletteAxis* palette = (TPaletteAxis*)Histos->GetListOfFunctions()->FindObject("palette");
   palette->SetLabelOffset(0.1);
   palette->SetTitleOffset(0.1);
   c1->Modified();
*/

  
   if(save==1){
//        char path[255]; sprintf(path,"Pictures/PNG/%s.png",save_path);  c1->SaveAs(path);
//        char path[255]; sprintf(path,"Pictures/EPS/%s.eps",save_path);  c1->SaveAs(path);
//        char path[255]; sprintf(path,"Pictures/C/%s.C"  ,save_path);  c1->SaveAs(path);
           c1->SaveAs(save_path);

   }
}
Example #3
0
std::pair<Matrix, Matrix> roothist_to_matrix(const TH2D & hist, bool transpose){
    int ngen = hist.GetNbinsY();
    int nreco = hist.GetNbinsX();
    if(transpose){
        swap(ngen, nreco);
    }
    
    Matrix m = Matrix(nreco, ngen);
    Matrix m_e = Matrix(nreco, ngen);
    
    for(int i=0; i<nreco; ++i){
        for(int j=0; j<ngen; ++j){
            int nx = i+1;
            int ny = j+1;
            if(transpose) swap(nx, ny);
            m(i,j) = hist.GetBinContent(nx, ny);
            m_e(i,j) = hist.GetBinError(nx, ny);
        }
    }
    return pair<Matrix, Matrix>(move(m), move(m_e));
}
Example #4
0
void ExtractOutputHistos(Bool_t onlyPrims=0,Bool_t onlyPion=0,Int_t plotFlag=0) {

  //  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);

  const Int_t nbins=20;
  Double_t ptmin=0.06;//04;
  Double_t ptmax=2.0;//GeV
  Double_t logxmin = TMath::Log10(ptmin);
  Double_t logxmax = TMath::Log10(ptmax);
  Double_t binwidth = (logxmax-logxmin)/(nbins+1);
  enum {nb=nbins+1};
  Double_t xbins[nb];
  xbins[0] = ptmin;
  for (Int_t i=1;i<=nbins;i++) {
    xbins[i] = ptmin + TMath::Power(10,logxmin+(i)*binwidth);
    //    cout<<xbins[i]<<endl;
  }
  //  TH1F *h = new TH1F("h","hist with log x axis",nbins,xbins);

  TH1F *hMultCount = new TH1F("mult","averaged multiplicity (charg. prim)",80,-4.,4.);
  hMultCount->GetXaxis()->SetTitle("eta");
  hMultCount->GetYaxis()->SetTitle("N/d#eta");

  TH1F *hAllMC = new TH1F("allMC","All Tracks MC primaries",nbins,xbins);
  TH1F *hAllFound = new TH1F("allFound","All Tracks found",nbins,xbins);
  TH1F *hImperfect = new TH1F("imperfect","Imperfect tracks",nbins,xbins);
  TH1F *hPerfect = new TH1F("perfect","Perfect tracks",nbins,xbins);
  TH1F *hEff = new TH1F("efficiency","Efficiency (Perfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hFake = new TH1F("fake","Fake tracks (Inperfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hPurity = new TH1F("purity","Purity (Perfect tracks in \"All Found\")",nbins,xbins);
  TH1F *hAnna = new TH1F("annaEff","AnnalisaEff ",nbins,xbins);
  TH1F *hNoMCTrack = new TH1F("noMCtrack","noMCtrack ",nbins,xbins);

  TH1F *hEta = new TH1F("","",50,-2,2);
  //  TH1F *hEtaMC = new TH1F("","",50,-2,2);

  TH2D *h2Ddca = new TH2D("dca2D","DCAvsPt2D",nbins,xbins,50,-0.05,0.05);
  TH2D *h2Dpt = new TH2D("dPt2D","dPtdvsPt2D",nbins,xbins,50,-25,25);

  // open run loader and load gAlice, kinematics and header
  AliRunLoader* runLoader = AliRunLoader::Open("galice.root");
  if (!runLoader) {
    Error("Check kine", "getting run loader from file %s failed",
          "galice.root");
    return;
  }
  runLoader->LoadgAlice();
  gAlice = runLoader->GetAliRun();
  if (!gAlice) {
    Error("Check kine", "no galice object found");
    return;
  }
  runLoader->LoadHeader();
  runLoader->LoadKinematics();

  TFile* esdFile = TFile::Open("AliESDs.root");
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", "AliESDs.root");
    return;
  }
  AliESDEvent *esd = new AliESDEvent();
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return;
  }
  esd->ReadFromTree(tree);
  
  Int_t nTrackTotalMC = 0;
  Int_t nTrackFound = 0;
  Int_t nTrackImperfect = 0;
  Int_t nTrackPerfect = 0;
  Int_t nNoMCTrack = 0;

  
  for(Int_t iEv =0; iEv<tree->GetEntries(); iEv++){
    tree->GetEvent(iEv);
    runLoader->GetEvent(iEv);
    
    printf("+++ event %i (of %lld) +++++++++++++++++++++++  # ESDtracks: %d \n",iEv,tree->GetEntries()-1,esd->GetNumberOfTracks());
    Int_t nESDtracks = esd->GetNumberOfTracks();
    for (Int_t iTrack = 0; iTrack < nESDtracks; iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);
      if (!(iTrack%1000)) printf("event %i: ESD track count %d (of %d)\n",iEv,iTrack,nESDtracks);

      Int_t label = track->GetLabel();
  
      Int_t idx[12];
      //      Int_t ncl = track->GetITSclusters(idx);
   
      if(label<0) {
	//	cout<< " ESD track label " << label;
	//	cout<<"  ---> imperfect track (label "<<label<<"<0) !! -> track Pt: "<< track->Pt() << endl;
      }

      AliStack* stack = runLoader->Stack();
      //     nTrackTotalMC += stack->GetNprimary();
    

      TParticle* particle = stack->Particle(TMath::Abs(label)); 
      Double_t pt = track->Pt();
      
      if(particle) {

	if (TMath::Abs(particle->Eta())>etaCut) continue;

	Double_t ptMC = particle->Pt();

	// Efficiencies
	if (onlyPion && TMath::Abs(particle->GetPdgCode())!=211) continue;

	if ( (!onlyPrims) || stack->IsPhysicalPrimary(TMath::Abs(label))) {
	  //  cout<<" # clusters "<<ncl<<endl;

	  nTrackFound++;
	  hAllFound->Fill(ptMC);
	  hEta->Fill(track->Eta());
	  
	  if (label<0) {
	    nTrackImperfect++;
	    hImperfect->Fill(ptMC);
	  } else {
	    nTrackPerfect++;
	    hPerfect->Fill(ptMC);
	  }

	}


	// following only for "true tracks, pions

	if(particle->Pt() < 0.001)continue;
	if (TMath::Abs(particle->GetPdgCode())!=211) continue;
	if (label>0) {
	  
	  // Impact parameters for Pions only
	  Double_t dca = track->GetD(0,0,0.5);
	  h2Ddca->Fill(ptMC,dca);
	  
	  // Pt resolution for Pions only
	  Double_t dPt = (pt-ptMC)/ptMC*100;
	  h2Dpt->Fill(ptMC,dPt);
	}

      } else {
	nNoMCTrackFound++;
	hNoMCTrack->Fill(pt);
	cout<<" according MC particle not found"<<endl;
      }
      
    } //entries track esd
  

  }//entries tree
  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

 
  // Count trackable MC tracks
  CountTrackableMCs(hAllMC, onlyPrims, onlyPion);


  // Count trackable MC tracks
  CountPrimaries(hMultCount);

 


  // Get Errors right
  hMultCount->Sumw2();
  hAllMC->Sumw2();   
  hAllFound->Sumw2();
  hPerfect->Sumw2(); 
  hImperfect->Sumw2(); 
  h2Dpt->Sumw2();
  h2Ddca->Sumw2();

  // -- Global efficienies

  nTrackTotalMC = hAllMC->GetEntries();
  Double_t eff = ((Double_t)nTrackPerfect)/nTrackTotalMC;
  printf("-> Total number of events: %lld -> MCtracks %d -> nPerfect %d  -> Eff: %3.2lf \n",
	 tree->GetEntries(),nTrackTotalMC,nTrackPerfect,eff);

  Double_t purity = ((Double_t)nTrackPerfect)/nTrackFound;
  printf("-> Total number of events: %lld -> FoundTracks %d -> nPerfect %d  -> Purity: %3.2lf \n",
	 tree->GetEntries(),nTrackFound,nTrackPerfect,purity);

  // Efficiencies - and normalize to 100%

  TF1 f1("f1","100+x*0",0.,1.e3);

  hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
  hPurity->Multiply(&f1);
  hPurity->SetMarkerColor(kGreen);
  hPurity->SetMarkerStyle(21);
  hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hPurity->SetStats(0);

  hPurity->GetYaxis()->SetRangeUser(0,100);
  hPurity->SetTitle("Efficiency & Purity");

  hEff->Divide(hPerfect,hAllMC,1,1,"b");
  hEff->Multiply(&f1);
  hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hEff->SetMarkerColor(kBlue);
  hEff->SetMarkerStyle(21);
  hEff->SetStats(0);

  hFake->Divide(hImperfect,hAllMC,1,1,"b");
  hFake->Multiply(&f1);
  hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hFake->SetMarkerColor(kRed);
  hFake->SetMarkerStyle(21);
  hFake->SetStats(0);


  hAnna->Divide(hAllFound,hAllMC,1,1,"b");
  hAnna->Multiply(&f1);
  hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hAnna->SetMarkerColor(kBlack);
  hAnna->SetMarkerStyle(21);
  hAnna->SetStats(0);

  TCanvas *c1 = new TCanvas("c1","NoMCTrackFound");//,200,10,900,900);
  TVirtualPad *pad =   c1->cd();
  pad->SetGridx();   pad->SetGridy();
  hNoMCTrack->Draw();

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  hPurity->Draw("E");
  hEff->Draw("Same E");
  hFake->Draw("Same E");
  hAnna->Draw("Same E");

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
  leg->Draw();


  if (plotFlag==1){
    hAllMC->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAllMC->Draw();  // MC pt distribution
    hAllFound->SetLineColor(2);
    hAllFound->Draw("same");  // MC pt distribution
  }
 
 
  /*

  .L ~/ITSupgrade/BuildDetector/DetectorK.cxx+
  
  // All NEW
  DetectorK its("ALICE","ITS");
  its.MakeAliceAllNew(0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,3,2);
  c->Draw("C");


  // Current
  DetectorK its("ALICE","ITS");
  its.MakeAliceCurrent(0,0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,4,2);
  c->Draw("C");

  */

  TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
  c3->Divide(2,1); c3->cd(1);
  // Impact parameter

  // Impact parameter resolution ---------------
  h2Ddca->Draw("colz");
  h2Ddca->FitSlicesY() ;
  TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
  TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
  TGraphErrors *d0 = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
    d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
    d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
  }
  d0->SetMarkerStyle(21);
  d0->SetMaximum(200);  d0->SetMinimum(0);
  d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
  d0->SetName("dca");  d0->SetTitle("DCAvsPt");

  c3->cd(1);  h2Ddca->Draw("surf2");
  c3->cd(2);  d0->Draw("APE");

  // PT RESOLUTION ------------
  TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);
  c4->Divide(2,1); c4->cd(1);
  // Impact parameter
  h2Dpt->Draw("colz");
  h2Dpt->FitSlicesY() ;
  TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
  TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
  TGraphErrors *gPt = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
    gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
    gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
  }
  gPt->SetMarkerStyle(21);
  gPt->SetMaximum(20);  gPt->SetMinimum(0);
  gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
  gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");

  c4->cd(1);  h2Dpt->Draw("surf2");
  c4->cd(2);  gPt->Draw("APE");


  // EXPORT --------

  TFile f("histos.root","RECREATE");

  hMultCount->Write();
  hAllMC->Write();
  hAllFound->Write();
  hImperfect->Write();
  hPerfect->Write();
  hNoMCTrack->Write();

  hPurity->Write();
  hEff->Write();
  hFake->Write();
  hAnna->Write();

  h2Ddca->Write();
  d0->Write();

  h2Dpt->Write();
  gPt->Write();

  f.Close();

  return;

}
Example #5
0
void plotMerged(Bool_t onlyPlot=0) {

  gStyle->SetPalette(1);
 
  TFile f("histoSum.root","UPDATE");

  TH1F* hAllMC = f.Get("allMC");
  TH1F* hAllFound= f.Get("allFound");
  TH1F* hImperfect= f.Get("imperfect");
  TH1F* hPerfect= f.Get("perfect");
  TH1F* hNoMCTrack= f.Get("noMCtrack");
  
  
  // have to be recalculated
  TH1F* hPurity = f.Get("purity");
  TH1F* hEff= f.Get("efficiency");
  TH1F* hFake= f.Get("fake");
  TH1F* hAnna= f.Get("annaEff");

  TH2D* h2Ddca= f.Get("dca2D");
  TGraphErrors *d0= f.Get("dca");

  TH2D* h2Dpt= f.Get("dPt2D");
  TGraphErrors *gPt= f.Get("dPt");


  if (!onlyPlot) {
    /*    // Get Errors right
    hAllMC->Sumw2();   
    hAllFound->Sumw2();
    hPerfect->Sumw2(); 
    hImperfect->Sumw2(); 
    h2Dpt->Sumw2();
    h2Ddca->Sumw2();
    */

    // Efficiencies - and normalize to 100%
    
    TF1 f1("f1","100+x*0",0.,1.e3);
    
    hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
    hPurity->Multiply(&f1);
    hPurity->SetMarkerColor(kGreen);
    hPurity->SetMarkerStyle(21);
    hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hPurity->SetStats(0);
    
    hPurity->GetYaxis()->SetRangeUser(0,100);
    hPurity->SetTitle("Efficiency & Purity");
    
    hEff->Divide(hPerfect,hAllMC,1,1,"b");
    hEff->Multiply(&f1);
    hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hEff->SetMarkerColor(kBlue);
    hEff->SetMarkerStyle(21);
    hEff->SetStats(0);
    
    hFake->Divide(hImperfect,hAllMC,1,1,"b");
    hFake->Multiply(&f1);
    hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hFake->SetMarkerColor(kRed);
    hFake->SetMarkerStyle(21);
    hFake->SetStats(0);
    
    hAnna->Divide(hAllFound,hAllMC,1,1,"b");
    hAnna->Multiply(&f1);
    hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAnna->SetMarkerColor(kBlack);
    hAnna->SetMarkerStyle(21);
    hAnna->SetStats(0);
    
    
    // Impact parameter resolution ---------------
    TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
    c3->Divide(2,1); c3->cd(1);
    h2Ddca->DrawCopy("colz");
    h2Ddca->FitSlicesY() ;
    TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
    TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
    TGraphErrors *d0 = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
      d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
      d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
    }
    d0->SetMarkerStyle(21);
    d0->SetMaximum(200);  d0->SetMinimum(0);
    d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
    d0->SetName("dca");  d0->SetTitle("DCAvsPt");
    //  c3->cd(1);  h2Ddca->Draw("surf2");
    c3->cd(2);  d0->Draw("APE");
    
    // PT RESOLUTION ------------
    TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);  
    c4->Divide(2,1); c4->cd(1);
    h2Dpt->DrawCopy("colz");
    h2Dpt->FitSlicesY() ;
    TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
    TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
    TGraphErrors *gPt = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
      gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
      gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
    }
    gPt->SetMarkerStyle(21);
    gPt->SetMaximum(20);  gPt->SetMinimum(0);
    gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
    gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");
    //  c4->cd(1);  h2Dpt->Draw("surf2");
    c4->cd(2);  gPt->Draw("APE");


    // overwrite with normalized graphs
    hPurity->Write();
    hEff->Write();
    hFake->Write();
    hAnna->Write();
    h2Ddca->Write();
    d0->Write();
    h2Dpt->Write();
    gPt->Write();
   
  }
  
  // Plots

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
 

  hPurity->DrawCopy("E");
  hEff->DrawCopy("Same E");
  hFake->DrawCopy("Same E");
  hAnna->DrawCopy("Same E");
  leg->Draw();

  c2->SaveAs("EffPlot.png");

  f.Close();



}
int main(int argc, char *argv[])
{
  ApplyLHCbStyle();
  double maxrate;
  switch(argc)
  {
    case 2:
      maxrate=-1;
      break;
    case 3:
      if(atoi(argv[2]))
        maxrate=atoi(argv[2]);
      else
      {
        cout << "Argument not a number" << endl;
        return 1;
      }
      break;
    default:
      cout << "Usage: " << argv[0] << " <Filename> [<Max rate>]" << endl;
      return 1;
  }
  if(system("[ -a figs ]") != 0)
  {
    cout << "Directory ./figs/ does not exist" << endl;
    const int mkdirerr = system("mkdir figs");
    if(mkdirerr != 0)
    {
      cout << "Error code " << mkdirerr << " while creating ./figs/" << endl;
    }
    else
    {
      cout << "Directory ./figs/ created" << endl;
    }
  }
  TFile* file = new TFile(argv[1]);
  if(!file->IsOpen())
  {
    cout << "Exiting" << endl;
    return 1;
  }
  TTree* tree = (TTree*)file->Get("metatree");
  int iHV; tree->SetBranchAddress("HV", &iHV);
  vector<int> HVs;
  string HV;
  int n = tree->GetEntries();
  TCanvas* mapscan, * histcan, * graphcan, * indivgraphcan[4];
  TPad* mapspad[4], * histpad[4];
  TH1D* hist;
  TH2D* map;
  string title[4] = {"JB", "JT", "ST", "SB"};
//  string title[4] = {"FA0026", "DA0024", "FA0019", "FA0006"};
  TGraphErrors* graph[4];
  TMultiGraph* mg;
  TLegend* lg;
  float xlo, xhi, ylo, yhi;
//  rainbowgradient();
  heatmapgradient();
//  DarkBodyRadiator();
//  DarkBodyRadiator2();
//  redbluegradient();
//  heatmapRB();
  string plotname;
  stringstream plotnamestream;
  double* x[4], * y[4], * xe[4], * ye[4];
  for(int j = 0; j < 4; j++)
  {
    x[j]  = new double[n];
    y[j]  = new double[n];
    xe[j] = new double[n];
    ye[j] = new double[n];
  }

  Double_t maxima[4];
  cout << "Entering loop of " << n << " events." << endl;
  for(int i = 0; i < n; i++)
  {
    tree->GetEntry(i);
    HVs.push_back(iHV);
    HV = itoa(iHV);
    for(int j = 0; j < 4; j++)
    {
      map = (TH2D*)file->Get(("DarkMap"+HV+"V"+itoa(j)).c_str());
      maxima[j] = map->GetMaximum();
    }
  }
  sort(HVs.begin(), HVs.end());
  if(maxrate==-1)
  {
    for(int i = 1; i < 4; i++)
    {
      maxrate = TMath::Max(maxima[i-1], maxima[i]);
      maxima[i]=maxrate;
    }
  }
//  cout << "Plotting with a maximum rate of " << maxrate << endl;
  for(int i = 0; i < n; i++)
  {
    HV = itoa(HVs[i]);
    plotnamestream << "DarkRate" << setfill('0') << setw(4) << HVs[i];
    plotnamestream >> plotname;
    histcan = new TCanvas(plotname.c_str(), "", 800, 800);
    plotnamestream.clear();
    histcan->Draw();
    plotnamestream << "DarkMap" << setfill('0') << setw(4) << HVs[i];
    plotnamestream >> plotname;
    mapscan = new TCanvas(plotname.c_str(), "", 800, 800);
    plotnamestream.clear();
    mapscan->Draw();
    for(int j = 0; j < 4; j++)
    {
      // Set limits
      xlo = 0.5*((j/2)%2);
      xhi = xlo+0.5;
      ylo = 0.5*((j+((j/2)%2))%2);
      yhi = ylo+0.5;
      // 2D maps
      mapscan->cd();
      mapspad[j] = new TPad("", "", xlo, ylo, xhi, yhi);
      mapspad[j]->SetLeftMargin(  0.05);
      mapspad[j]->SetRightMargin( 0.15);
      mapspad[j]->SetTopMargin(   0.05);
      mapspad[j]->SetBottomMargin(0.05);
      mapspad[j]->Draw();
      mapspad[j]->cd();
      map = (TH2D*)file->Get(("DarkMap"+HV+"V"+itoa(j)).c_str());
      map->SetTitle("");
      map->SetMaximum(maxrate);
      map->SetMinimum(0);
      map->Draw("COLZ");
      // 1D histogram
      histcan->cd();
      histpad[j] = new TPad("", "", xlo, ylo, xhi, yhi);
      histpad[j]->SetLeftMargin(  0.05);
      histpad[j]->SetRightMargin( 0.15);
      histpad[j]->SetTopMargin(   0.05);
      histpad[j]->SetBottomMargin(0.05);
      histpad[j]->Draw();
      histpad[j]->SetLogy();
      histpad[j]->cd();
      hist = new TH1D(("hist"+itoa(i)+itoa(j)).c_str(), title[j].c_str(), 100, 0, maxrate);
      tree->Draw(("rate"+itoa(j)+">>"+hist->GetName()).c_str(), "", "", 1, i);
      // Graph
      x[j][i]  = HVs[i];
      xe[j][i] = 0;
      y[j][i]  = 0;
      ye[j][i] = 0;
      double yval = 0, yerr = 0;
      double npix = 0;
      for(int k = 0; k < 64; k++)
      {
        yval = map->GetBinContent((k/8)+1, (k%8)+1);
        yerr = map->GetBinError((k/8)+1, (k%8)+1);
        if(yval<0) continue;
        y[j][i]  += yval;
        ye[j][i] += yerr*yerr;
        npix++;
      }
      y[j][i]  /= npix;
      ye[j][i] = sqrt(ye[j][i])/npix;
      cout << npix << "\t" <<  y[j][i] << "±" << ye[j][i] << endl;
    }
    gStyle->SetOptStat("m");
    histcan->SaveAs(("./figs/"+(string)histcan->GetName()+".pdf").c_str());
    histcan->SaveAs(("./figs/"+(string)histcan->GetName()+".png").c_str());
    mapscan->SaveAs(("./figs/"+(string)mapscan->GetName()+".pdf").c_str());
    mapscan->SaveAs(("./figs/"+(string)mapscan->GetName()+".png").c_str());
  }
  mg = new TMultiGraph();
  lg = new TLegend(0.17,0.6,0.45,0.82);
  lg->SetFillStyle(0);
  lg->SetLineWidth(0);
  int linecolour[4] = {kBlue,kRed+1,kGreen+1,kViolet};
  int linestyle[4]  = {2,9,3,5};
  int index[4] = {1, 0, 2, 3}; // More sensible order
  for(int k = 0; k < 4; k++)
  {
    int j = index[k];
    graph[j] = new TGraphErrors(n, x[j], y[j], xe[j], ye[j]);
    graph[j]->SetTitle(title[j].c_str());
    graph[j]->SetLineWidth(2);
    indivgraphcan[j] = new TCanvas((title[j]+"graph").c_str(),"",1000,900);
    indivgraphcan[j]->Draw();
    graph[j]->GetXaxis()->SetTitle("High Voltage [V]");
    graph[j]->GetYaxis()->SetTitle("Dark count rate [Hz]");
    graph[j]->GetYaxis()->SetTitleOffset(1.25);
    graph[j]->SetMinimum(0);
    graph[j]->Draw("APL");
    indivgraphcan[j]->SaveAs(("./figs/graph"+title[j]+".pdf").c_str());
    graph[j]->SetLineColor(linecolour[j]);
    graph[j]->Fit("pol1");
    graph[j]->GetFunction("pol1")->SetLineColor(graph[j]->GetLineColor());
    graph[j]->GetFunction("pol1")->SetLineStyle(linestyle[j]);
    lg->AddEntry(graph[j]->GetFunction("pol1"),title[j].c_str(),"L");
    mg->Add(graph[j], "P");
  }
  graphcan = new TCanvas("graph", "", 900, 900);
  graphcan->cd();
  graphcan->Draw();
  mg->SetMinimum(0);
  mg->Draw("APL");
  mg->GetXaxis()->SetTitle("High Voltage [V]");
  mg->GetYaxis()->SetTitle("Dark count rate [Hz]");
  mg->GetXaxis()->SetTitleOffset(1.2);
  mg->GetYaxis()->SetTitleOffset(1.2);
  GetLHCbName()->Draw();
  lg->Draw();
  graphcan->SaveAs("figs/graph.pdf");

  cout << "\\hline" << endl << "Voltage";
  for(int j = 0; j < 4; j++)
  {
    cout << " & " << title[j];
  }
  cout << "\\\\\\hline" << endl;
  for(int i = 0; i < n; i++)
  {
    cout << HVs[i];
    for(int j = 0; j < 4; j++)
    {
      cout << setprecision(3) << " & " << y[j][i];
    }
    cout << "\\\\\\hline" << endl;
  }
  return 0;
}