Example #1
0
//------------------------------------------------------------------------
void DrawQTC()
{
  
  TCanvas *c1 = new TCanvas("c1", "QTC C side",0,48,1280,951);
   c1->Divide(4,3);
   // c1->Divide(2,3);
  
  Char_t buf1[10];
  for (Int_t i=0; i<12; i++)
    {
      c1->cd(i+1);
      sprintf(buf1,"QTC%i",i+1);
      
      TH1F *qtc = (TH1F*) gFile->Get(buf1);
      
      Float_t mean = qtc->GetMean();
      Float_t rms = qtc->GetRMS();
      Float_t hminR=mean - 0.1*mean;
      Float_t hmaxR =mean + 0.1*mean;
      qtc->GetXaxis()->SetRange(hminR,hmaxR);
      Float_t hmin=mean - 3*rms;
      Float_t hmax =mean + 3*rms;
      qtc->GetXaxis()->SetRange(hmin,hmax);

     // TF1 *g2 = new TF1("g2", "gaus", hmin, hmax);
       //             qtc->Fit("g2","RQ");
	qtc->GetXaxis()->SetLabelSize(0.03);
       
       qtc->Draw();
    }
  
  TCanvas *c2 = new TCanvas("c2", "QTC A side",0,48,1280,951);
   c2->Divide(4,3);
   // c1->Divide(2,3);
  
  Char_t buf1[10];
  for (Int_t i=12; i<24; i++)
    {
      c2->cd(i+1-12);
      sprintf(buf1,"QTC%i",i+1);
      
      TH1F *qtc = (TH1F*) gFile->Get(buf1);
      
      Float_t mean = qtc->GetMean();
      Float_t rms = qtc->GetRMS();
      Float_t hminR=mean - 0.1*mean;
      Float_t hmaxR =mean + 0.1*mean;
      qtc->GetXaxis()->SetRange(hminR,hmaxR);
      Float_t hmin=mean - 3*rms;
      Float_t hmax =mean + 3*rms;
      qtc->GetXaxis()->SetRange(hmin,hmax);
      // TF1 *g2 = new TF1("g2", "gaus", hmin, hmax);
       //             qtc->Fit("g2","RQ");
 	qtc->GetXaxis()->SetLabelSize(0.03);
      
       qtc->Draw();
    }
  
  
}
Example #2
0
vector<double> one_fit(bool do_fit)
{
    TH1F* h = new TH1F("h","h", 20, -10, 10);
    h->FillRandom("gaus");
    vector<double> ret;
    if (do_fit) {
        h->Fit("gaus","");
        TF1* g = h->GetFunction("gaus");
        h->Draw();
        canvas->Modified();
        canvas->Update();
        for (int ind=0; ind < 3; ++ind) {
            ret.push_back(g->GetParameter(ind));
        }
    }
    else {
        for (int ind=0; ind < 3; ++ind) {
            ret.push_back(0.0);
        }
    }
    
    ret.push_back(h->GetMean());
    ret.push_back(h->GetRMS());
    delete h;
    return ret;
}
Example #3
0
double Chip::getMeanValueOfStrips(){
  double value=0;
  double maxValue=0;
  //TH1F * Histo = new TH1F("name","title",1000,0,);
  
  for(int i = 1 ; i <= 8 ; i++){
    if(this->getChipStrip(i)->getRate() > maxValue){
      maxValue = this->getChipStrip(i)->getRate();
    }
  }
  
  TH1F * Histo = new TH1F("name","title",1000,0,maxValue);
  for(int i = 1 ; i <= 8;i++){
    if( ! this->getChipStrip(i)->getIsDisconnected()){
      Histo->Fill(this->getChipStrip(i)->getRate());
    }
  }
  
  value = Histo->GetMean();
  delete Histo;
  if (maxValue == 0){
    cout << "maxValue is zero ! " << endl;
    value = maxValue;
  }
  
  return value;
}
void KVElasticCountRates::PrintResults(Double_t beam_intensity)
{
   // Print mean energy deposit & counting rate for given beam intensity in particles per second

   TIter it(&fHistos);
   TH1F* h;
   fRates.clear();

   std::vector<count_rate> count_rates;

   while ((h = (TH1F*)it())) {
      TString name = h->GetName();
      if (!name.EndsWith("_dW") && !name.EndsWith("_map")) {
         TH2F* map = (TH2F*)fHistos.FindObject(name + "_map");
         double rate = h->Integral() * fAtomicDensity * beam_intensity * fVolume / fNtirages;
         double emean = h->GetMean();
         KVDetector* det = gMultiDetArray->GetDetector(name);
         double fluence = rate / det->GetEntranceWindowSurfaceArea();
         double dissipation = emean * rate / det->GetEntranceWindowSurfaceArea();
         count_rates.push_back(
            count_rate(name, rate, emean, map->GetMean(), map->GetMean(2), fluence, dissipation)
         );
         fRates[name.Data()] = KVElasticCountRate(rate, emean, fluence, dissipation);
      }
   }
   std::sort(count_rates.begin(), count_rates.end(), compare_count_rates);

   for (std::vector<count_rate>::iterator it = count_rates.begin(); it != count_rates.end(); ++it) {
      it->print();
   }
}
void explore_zmass_boost()
{
  // Tell root not to draw everything to the screen.
  gROOT->SetBatch();

  //    TString dyfilename         = TString("/home/acarnes/h2mumu/samples/stage1/monte_carlo/bg/stage_1_dy_jetsToLL_asympt50_ALL.root");
  TString dyfilename         = TString("/home/acarnes/h2mumu/samples/stage1/monte_carlo/bg/stage_1_dy_ZToMuMu_asympt50_ALL.root");
  TString datafilename         = TString("/home/acarnes/h2mumu/samples/stage1/data_from_json/Cert_246908-251883_13TeV_PromptReco_Collisions15_JSON_v2/stage_1_doubleMuon_RunBPrompt_MINIAOD.root");

  TString savedir = TString("../png/dy_vs_data/run1cuts_v2_golden_json/dyzmumu/");

  // Initialize the DiMuPlottingSystems for MC and data
  DiMuPlottingSystem* dpsdata = new DiMuPlottingSystem(datafilename);
  DiMuPlottingSystem* dpsdy = new DiMuPlottingSystem(dyfilename);
  addDiMuMassPrimeBranch(dpsdata);
  dpsdata->applyRun1Cuts();
  dpsdy->applyRun1Cuts();

  // Get the 2D histos
  TH2F* hdataZPt = ZMassVsZPtHist2D("data_zpt", "recoCandMassPrime", "(14,0,60,30,87,95)", dpsdata);
  TH2F* hdyZPt = ZMassVsZPtHist2D("dy_zpt", "recoCandMass", "(14,0,60,30,87,95)", dpsdy);

  //overlayTProfiles(TH2F* hdata, TH2F* hdy, TString bininfo, TString savename)
  TProfile* p = overlayTProfiles(hdataZPt, hdyZPt, 90, 92, savedir+"z_mass_vs_z_pt.png");
  gStyle->SetOptFit(0011);
  fitTProfileCustom(p);
  TCanvas* c = new TCanvas();
  c->cd();
  p->Draw("hist c");
  p->Draw("E0 X0 same");
  dpsdata->arrangeStatBox(c);
  c->Draw();
  c->Print("blah2.png");

  // Look at RMS
  c->Clear();
  c->cd();
  c->SetGridx(kTRUE);
  c->SetGridy(kTRUE);
  c->cd();
  TH1F* h = dpsdata->hist1D("recoCandMass", "(100,87,95)", "");
  TH1F* h2 = dpsdata->hist1D("recoCandMassPrime", "(100,87,95)", "");
  h2->SetLineColor(2);
  h->Draw("");
  h2->Draw("same");

  std::cout << "mass  rms: " << h->GetRMS() << std::endl;
  std::cout << "mass' rms: " << h2->GetRMS() << std::endl;
  std::cout << "mass  mean: " << h->GetMean() << std::endl;
  std::cout << "mass' mean: " << h2->GetMean() << std::endl;
  std::cout << "mass  num: " << h->Integral() << std::endl;
  std::cout << "mass' num: " << h2->Integral() << std::endl;

  DiMuPlottingSystem* dps = new DiMuPlottingSystem();
  dps->arrangeStatBox(c);
  c->Draw();
  c->Print("newfit.png");
}
Example #6
0
void PlotHistsNhitsPerModule(TFile* f, TTree* tr, TString strMillepedeRes, TString strOutdir)
{
  TString canvName="c_";
  canvName+=strMillepedeRes;
  canvName+="_";
  canvName+=StrPlotType(NHITS);
  canvName.ReplaceAll(".res","");


  //enum {PXB,PXF,TIB,TID,TOB,TEC};
  int colors[6]={1,2,3,4,6,7};
//  TString labels[6]={"PXB","PXF","TIB","TID","TOB","TEC"};

  f->cd();
  TCanvas* canv = new TCanvas(canvName,canvName,600,600);
  canv->SetLogx();
  canv->SetLogy();

  for (int ind=1; ind<=1; ind++){
    TString strHist = "hNhits_";
    strHist+=StrPar(ind);
    TString strCut="label<700000 && ((label%20-1)%9+1)==";
    strCut+=ind;
    TStyle style; 
    style.SetTitleFontSize(0.2);
    THStack *hSt = new THStack("hNhits","# of derivatives (~tracks or hits) per module");
    TLegend *leg = new TLegend(0.75,0.65,0.95,0.95);
    for (int inv=0; inv<6; inv++){
      std::cout<<"- - - - - -"<<std::endl;
      std::cout<<subdLabels[inv]<<":"<<std::endl;
      std::cout<<StrCutSubd(inv)<<": "<<tr->GetEntries(StrCutSubd(inv))<<" parameters"<<std::endl;
      TString strHist1=strHist;
      strHist1+=ind;
      strHist1+=inv;
      TH1F* hValInt = new TH1F(strHist1,strHist1,300,10,15000);  
      TString strCut1 = strCut+TString(" && ")+StrCutSubd(inv);
      tr->Draw(TString("Nhits>>")+strHist1,strCut1,"goff");
      std::cout<<"# hits = "<<(int)hValInt->GetMean()<<"+-"<<(int)hValInt->GetRMS()<<std::endl;
      hValInt->SetLineColor(1);
      hValInt->SetFillColor(colors[inv]);
      hValInt->SetLineWidth(2);
      hSt->Add(hValInt);
      leg->AddEntry(hValInt,subdLabels[inv],"f");
      leg->SetFillColor(0);
    }
    hSt->Draw();
    leg->Draw("same");
    
  }//end of loop over ind

  canvName+=".png";
  TString saveName=strOutdir+canvName;
  canv->SaveAs(saveName);
  saveName.ReplaceAll(".png",".pdf");
  canv->SaveAs(saveName);
}//end of PlotHistsNhitsPerModule
Example #7
0
double GetVariable(const char *var,TCut cut)
{
  TTree *t=(TTree*) gROOT->FindObject("t");

  TH1F *htemp = (TH1F*) gROOT->FindObject("htemp");
  if(htemp) delete htemp;
  t->Draw(Form("%s>>htemp",var),cut);
  htemp = (TH1F*) gROOT->FindObject("htemp");
  return double(htemp->GetMean());
}
Example #8
0
void GetChamberIDs(int IDArray[9]){
TCanvas *IDcanv = new TCanvas ("idGraph", "idGraph");
IDcanv->cd();
TH1F *idDummy = new TH1F("idDummy", "idDummy", 10, 220000000, 221000000);
idDummy->Draw();
for (int chamber=0; chamber<9; ++chamber){
  TString idCut = Form ("cham==%d", chamber);
  Calibration->Project("idDummy", "id", idCut);
  Int_t idNum = idDummy->GetMean();
  IDArray[chamber]=idNum;
}
}
void billtr(Int_t compress) {
   //read N histograms from a tree
   timer.Start();
   TFile f("billt.root");
   TH1F *h = 0;
   TTree *T = (TTree*)f.Get("T");
   T->SetBranchAddress("event",&h);
   TH1F *hmeant = new TH1F("hmeant","hist mean from tree",100,0,1);
   Long64_t nentries = T->GetEntries();
   for (Long64_t i=0;i<nentries;i++) {
      T->GetEntry(i);
      hmeant->Fill(h->GetMean());
   }
   timer.Stop();
   printf("billtr%d : RT=%7.3f s, Cpu=%7.3f s\n",compress,timer.RealTime(),timer.CpuTime());
}
Example #10
0
File: langaus.C Project: Y--/root
void langaus() {
   // Fill Histogram
   Int_t data[100] = {0,0,0,0,0,0,2,6,11,18,18,55,90,141,255,323,454,563,681,
                    737,821,796,832,720,637,558,519,460,357,291,279,241,212,
                    153,164,139,106,95,91,76,80,80,59,58,51,30,49,23,35,28,23,
                    22,27,27,24,20,16,17,14,20,12,12,13,10,17,7,6,12,6,12,4,
                    9,9,10,3,4,5,2,4,1,5,5,1,7,1,6,3,3,3,4,5,4,4,2,2,7,2,4};
   TH1F *hSNR = new TH1F("snr","Signal-to-noise",400,0,400);

   for (Int_t i=0; i<100; i++) hSNR->Fill(i,data[i]);

   // Fitting SNR histo
   printf("Fitting...\n");

   // Setting fit range and start values
   Double_t fr[2];
   Double_t sv[4], pllo[4], plhi[4], fp[4], fpe[4];
   fr[0]=0.3*hSNR->GetMean();
   fr[1]=3.0*hSNR->GetMean();

   pllo[0]=0.5; pllo[1]=5.0; pllo[2]=1.0; pllo[3]=0.4;
   plhi[0]=5.0; plhi[1]=50.0; plhi[2]=1000000.0; plhi[3]=5.0;
   sv[0]=1.8; sv[1]=20.0; sv[2]=50000.0; sv[3]=3.0;

   Double_t chisqr;
   Int_t    ndf;
   TF1 *fitsnr = langaufit(hSNR,fr,sv,pllo,plhi,fp,fpe,&chisqr,&ndf);

   Double_t SNRPeak, SNRFWHM;
   langaupro(fp,SNRPeak,SNRFWHM);

   printf("Fitting done\nPlotting results...\n");

   // Global style settings
   gStyle->SetOptStat(1111);
   gStyle->SetOptFit(111);
   gStyle->SetLabelSize(0.03,"x");
   gStyle->SetLabelSize(0.03,"y");

   hSNR->GetXaxis()->SetRange(0,70);
   hSNR->Draw();
   fitsnr->Draw("lsame");
}
void billr(Int_t compress) {
   //read N histograms from keys
   timer.Start();
   TFile f("bill.root");
   TIter next(f.GetListOfKeys());
   TH1F *h;
   TH1::AddDirectory(kFALSE);
   TKey *key;
   Int_t i=0;
   TH1F *hmean = new TH1F("hmean","hist mean from keys",100,0,1);
   
   while ((key=(TKey*)next())) {
      h = (TH1F*)key->ReadObj();
      hmean->Fill(h->GetMean());
      delete h;
      i++;
   }
   timer.Stop();
   printf("billr%d  : RT=%7.3f s, Cpu=%7.3f s\n",compress,timer.RealTime(),timer.CpuTime());
}
Example #12
0
void makePlot(vector<TTree*> sigTree,vector<double> sigWeight,
	      vector<int> ptHatLo, vector<int> ptHatHi,
              std::string var,TCut cut,TH1F* h,bool norm)
{
   TH1F *hRes = (TH1F*)h->Clone();
   hRes->SetName("hRes");
   hRes->Sumw2();
  
   char tmp[300];
   for (unsigned int i=0; i<sigTree.size(); i++)
     {
       // first determine the pthat cut
       
       sprintf(tmp, "ptHat >= %d && ptHat <= %d",ptHatLo[i], ptHatHi[i]);
       TCut ptHatCut = tmp;
       TCut allCut = cut + ptHatCut;
       cout << "Current cut = " << allCut.GetTitle() << endl;
       TH1F *htmp = (TH1F*)h->Clone();
       htmp->SetName("htmp");
       sigTree[i]->Draw(Form("%s>>htmp",var.data()),allCut);
       htmp->Sumw2();
       htmp->Scale(sigWeight[i]);
       cout << "scale = " << sigWeight[i] << endl;
       cout << "After scaling htmp -> entries() " << htmp->GetEntries() << endl;
       cout << "After scaling htmp -> Integral() " << htmp->Integral() << endl;
       cout << "After scaling htmp -> GetMean()  " << htmp->GetMean() << endl;
       cout << "After scaling htmp -> GetRMS()  " << htmp->GetRMS() << endl;
       hRes->Add(htmp);
       delete htmp;
   }
   h->Sumw2();
   h->Add(hRes);
   if(norm)h->Scale(1.0/(double)h->Integral(0,1000));
   cout << "After scaling h-> entries() " << h->GetEntries() << endl;
   cout << "After scaling h-> Integral() " << h->Integral() << endl;
   cout << "After scaling h -> GetMean()  " << h->GetMean() << endl;
   cout << "After scaling h -> GetRMS()  " << h->GetRMS() << endl;
   
   delete hRes;
}
Example #13
0
void langaus() {
  // Fill Histogram
  
  TFile *f=new TFile("fitInputs.root");
  TH1F *hSNR = (TH1F*)f->Get("hxsobs");

  // Fitting SNR histo
  printf("Fitting...\n");

  // Setting fit range and start values
  Double_t fr[2];
  Double_t sv[4], pllo[4], plhi[4], fp[4], fpe[4];
  fr[0]=0.3*hSNR->GetMean();
  fr[1]=3.0*hSNR->GetMean();

  pllo[0]=0.5; pllo[1]=5.0; pllo[2]=1.0; pllo[3]=0.4;
  plhi[0]=5.0; plhi[1]=50.0; plhi[2]=1000000.0; plhi[3]=5.0;
  sv[0]=1.8; sv[1]=20.0; sv[2]=50000.0; sv[3]=3.0;

  Double_t chisqr;
  Int_t    ndf;
  TF1 *fitsnr = langaufit(hSNR,fr,sv,pllo,plhi,fp,fpe,&chisqr,&ndf);
   
  Double_t SNRPeak, SNRFWHM;
  langaupro(fp,SNRPeak,SNRFWHM);

  printf("Fitting done\nPlotting results...\n");

  // Global style settings
  gStyle->SetOptStat(1111);
  gStyle->SetOptFit(111);
  gStyle->SetLabelSize(0.03,"x");
  gStyle->SetLabelSize(0.03,"y");

  hSNR->GetXaxis()->SetRange(0,70);
  hSNR->Draw();
  fitsnr->Draw("lsame");
}
Example #14
0
void DumpRecenterParv2(){
    TString pro = "Pro104";
    int taxi = 8583;
    TFile *fin;
    int nrun = GetTotalRun();
    if(nrun<0) exit("Empty run list file!");

    TFile *fout = new TFile(Form("Recentering.root"),"Recreate");
    TVectorD vecmean;
    TVectorD vecrms;
    vecmean.ResizeTo(ncent*nbbcz*nhar*nsub*nxy);
    vecrms.ResizeTo(ncent*nbbcz*nhar*nsub*nxy);
    for(int irun=0;irun<nrun;irun++){
     cout<<irun<<" of total "<<nrun<<" runs"<<endl;
     int RunNumber=GetRun(irun);
     fin = TFile::Open(Form("Run15pAu200MinBias/output_fvtxwithcntrecenter_%d.root",RunNumber));
     //ofstream fout(Form("Calibration/%s/Recentering_%d.dat",dataset.Data(),GetRun(irun)));
     for(int icent=0;icent<ncent;icent++){
      for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
       for(int ihar=0;ihar<nhar;ihar++){
        for(int isub=0;isub<nsub;isub++){
         for(int ixy=0;ixy<nxy;ixy++){
             TH1F* q = (TH1F*)fin->Get(Form("q_%d_%d_%d_%d_%d",icent,ibbcz,ihar,isub,ixy));
             float mean = q->GetMean();
             float rms = q->GetRMS();
             vecmean[icent*nbbcz*nhar*nsub*nxy+ibbcz*nhar*nsub*nxy+ihar*nsub*nxy+isub*nxy+ixy] = mean;
             vecrms[icent*nbbcz*nhar*nsub*nxy+ibbcz*nhar*nsub*nxy+ihar*nsub*nxy+isub*nxy+ixy] = rms;
         }
        }
       }
      }
     }
    fout->cd();
    vecmean.Write(Form("mean_%d",RunNumber));
    vecrms.Write(Form("rms_%d",RunNumber));
    fin->Close();
    }
}
Example #15
0
void mkChanCorrPlots( void )
{
    Float_t meancopo[kNfls];
    Float_t meancrspo[kNfls];
    Float_t rmscopo[kNfls];
    Float_t rmscrspo[kNfls];

    TFile* fout = TFile::Open( outfn, "recreate" );

    TGraphErrors* gCopo02 = new TGraphErrors;
    TGraphErrors* gCopo13 = new TGraphErrors;
    
    TGraphErrors* gCrspo02 = new TGraphErrors;
    TGraphErrors* gCrspo13 = new TGraphErrors;

    for( UChar_t f = 0; f < kNfls; f++ )
    {
        Float_t mean[kNChCmb];
        Float_t rms[kNChCmb];

        TFile* ifl = TFile::Open( infn[f] );
 
        for( UChar_t c = 0; c < NSnConstants::kNchans; c++ )
        {
            for( UChar_t c2 = c + 1; c2 < NSnConstants::kNchans; c2++ )
            {
                TH1F* h = dynamic_cast<TH1F*>(ifl->Get(Form("hCC%d%d", c, c2)));

                UInt_t idx  = TSnRecoChanOffsets::IndexFor(c2, c);
                mean[idx]   = h->GetMean( );
                rms[idx]    = h->GetRMS( );
            }
        }

        meancopo[f]     = mean[TSnRecoChanOffsets::IndexFor(copoC[f] + 2, 
                                                                   copoC[f])];
        meancrspo[f]    = mean[TSnRecoChanOffsets::IndexFor(crspoC[f] + 2, 
                                                                   crspoC[f])];

        rmscopo[f]      = rms[TSnRecoChanOffsets::IndexFor(copoC[f] + 2, 
                                                                   copoC[f])];
        rmscrspo[f]     = rms[TSnRecoChanOffsets::IndexFor(crspoC[f] + 2, 
                                                                   crspoC[f])];

        Printf( "co po mean: %f rms: %f run: %u", meancopo[f], rmscopo[f], 
                                                                    y[f] );
        Printf( "cross po mean: %f rms: %f run: %u\n", meancrspo[f], 
                                                        rmscrspo[f], y[f] );

        ifl->Close( );
    }

//    Float_t y[kNfls]    = { 1., 1., 1., 1., 1., 1., 1., 1. };
    Float_t ye[kNfls]   = { 0., 0., 0., 0., 0., 0., 0., 0. }; 

    fout->cd( );

    UInt_t nc0 = 0;
    UInt_t nc1 = 0;

    for( UChar_t f = 0; f < kNfls; f++ )
    {
        if( copoC[f] == 0 && crspoC[f] == 1 )
        {
            gCopo02->SetPoint( nc0, meancopo[f], 0. );
            gCrspo13->SetPoint( nc0, meancrspo[f], 0. );

            gCrspo13->SetPointError( nc0, rmscrspo[f], ye[f] );
            gCopo02->SetPointError( nc0++, rmscopo[f], ye[f] );

            gCopo02->SetMarkerColor( kRed );
            gCopo02->SetLineColor( kRed );
            gCopo02->GetHistogram()->SetMinimum( -0.5 );
            gCopo02->GetHistogram()->SetMaximum( 1.5 );

            gCrspo13->SetMarkerColor( kRed );
            gCrspo13->SetLineColor( kRed );
            gCrspo13->GetHistogram()->SetMinimum( -0.5 );
            gCrspo13->GetHistogram()->SetMaximum( 1.5 );
        }            
        if( copoC[f] == 1 && crspoC[f] == 0 )
        {
            gCopo13->SetPoint( nc1, meancopo[f], 1. );
            gCrspo02->SetPoint( nc1, meancrspo[f], 1. );

            gCrspo02->SetPointError( nc1, rmscrspo[f], ye[f] );
            gCopo13->SetPointError( nc1++, rmscopo[f], ye[f] );

            gCopo13->SetMarkerColor( kBlack );
            gCopo13->SetLineColor( kBlack );
            gCopo13->GetHistogram()->SetMinimum( -0.5 );
            gCopo13->GetHistogram()->SetMaximum( 1.5 );

            gCrspo02->SetMarkerColor( kBlack );
            gCrspo02->SetLineColor( kBlack );
            gCrspo02->GetHistogram()->SetMinimum( -0.5 );
            gCrspo02->GetHistogram()->SetMaximum( 1.5 );
        }
    }

    TLegend* leg = new TLegend( 0.258, 0.742, 0.410, 0.993 );
    leg->SetBorderSize( 0 );
    leg->SetFillColor( 0 );

    TLegend* legcr = new TLegend( 0.258, 0.742, 0.410, 0.993 );
    legcr->SetBorderSize( 0 );
    legcr->SetFillColor( 0 );
    legcr->SetFillStyle( 0 );
    legcr->SetEntrySeparation( 0.01 );
    legcr->SetTextSize( 0.04 );
//    gCopo = new TGraphErrors( kNfls, meancopo, y, rmscopo, ye );
    TCanvas* c = new TCanvas( "c", "", 800, 400 );
    c->Divide( 2, 1 );

    c->cd( 1 );
    gCopo02->SetName( "gcopoCC02" );
    gCopo02->Draw( "AP*" );
    gCopo13->Draw( "P*" );

    leg->AddEntry( gCopo02, "Ch 0 & Ch 2 Co. Po.", "lp" );
    leg->AddEntry( gCopo13, "Ch 1 & Ch 3 Co. Po.", "lp" );
    leg->Draw( );

    gCopo02->Write( ); 

    c->cd( 2 );
    gCrspo13->SetName( "gcrspoCC13" );
    gCrspo13->Draw( "AP*" );
    gCrspo13->GetXaxis()->SetLimits( 0.45, 0.85 );

    gCrspo02->SetName( "gcrspoCC02" );
    gCrspo02->Draw( "P*" );

    legcr->AddEntry( gCrspo13, "Ch 1 & Ch 3 Cross Po.", "lp" );
    legcr->AddEntry( gCrspo02, "Ch 0 & Ch 2 Cross Po.", "lp" );
    legcr->Draw( );

    gCrspo13->Write( ); 


    TCanvas* c2 = new TCanvas( "c2", "", 800, 800 );
    c2->cd( 1 );
    gCopo13->SetName( "gcopoCC13" );
    gCopo13->Draw( "AP*" );
    gCopo13->Write( );

//    fout->Write( );
    fout->Close( );
} 
Example #16
0
void Getvn(){
    TString str;
    TFile *fin;
    int nrun = GetTotalRun();
    if(nrun<0) exit("Empty run list file!");

     ofstream fout, fout1, fout2;
     int iharE=0;
     if(nhar==1) iharE=1;
     for(int icent=0;icent<ncent;icent++){
      for(int ihar=0;ihar<nhar;ihar++){
       for(int isub=0;isub<nsub;isub++){
        int n = ihar+1.0+iharE;
        if(isub==1)
         str = "FVTX1S";
        else if(isub==2)
         str = "FVTX2S";
        else continue;
         fout1.open(Form("Run15pAu200MinBias/res%d_%d_%s.dat",n,icent,str.Data())); //using str as event plane detector
         fout2.open(Form("Run15pAu200MinBias/psi%d_%d_%s.dat",n,icent,str.Data())); //using str as event plane detector
         float reso = 1.;//GetReso(icent,ihar,isub);
         fout1<<reso<<endl;
         TH2F* hvobs = new TH2F(Form("hvobs_%d_%d_%d",icent,ihar,isub),Form("hvobs_%d_%d_%d",icent,ihar,isub),60,0,6,220,-1.1,1.1);
         TH2F* hvobssq = new TH2F(Form("hvobssq_%d_%d_%d",icent,ihar,isub),Form("hvobssq_%d_%d_%d",icent,ihar,isub),60,0,6,220,-1.1,1.1);
        for(int irun=0;irun<nrun;irun++){
         fout2<<GetRun(irun)<<" "<<GoodRun(icent,ihar,isub,irun)<<endl;
        }
        for(int iphi=0;iphi<nphi;iphi++){
         string phistr = (iphi==0)?"east":"west";
         fout.open(Form("Run15pAu200MinBias/v%d_%d_%s_%s.dat",n,icent,phistr.c_str(),str.Data())); //using str as event plane detector
        for(int irun=0;irun<nrun;irun++){
        // cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<irun<<endl;
         fin = TFile::Open(Form("Run15pAu200MinBias/output_fvtxwithcntEP_%d.root",GetRun(irun)));
         if(!(GoodRun(icent,ihar,isub,irun)>0.2 && GoodRun(icent,ihar,isub,irun)<3.0)){
         cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<GetRun(irun)<<" is bad run!"<<endl;
        continue;
         }
         TH2F* hvobstemp = (TH2F*)fin->Get(Form("vobs%s_%d_%d_%d",str.Data(),icent,ihar,iphi));
         TH2F* hvobssqtemp = (TH2F*)fin->Get(Form("vobs%ssq_%d_%d_%d",str.Data(),icent,ihar,iphi));
         hvobs->Add(hvobstemp);
         hvobssq->Add(hvobssqtemp);
         fin->Close();
        }
            TH1F* ptProj = (TH1F*)hvobs->ProjectionX(Form("hptProj"),0,-1);
         for(int ipt=0;ipt<npt-1;ipt++){
            TH1F* hvobsProj = (TH1F*)hvobs->ProjectionY(Form("hvobsProj_%d",ipt),hvobs->GetXaxis()->FindBin(ptbin[ipt]),hvobs->GetXaxis()->FindBin(ptbin[ipt+1]));
            TH1F* hvobssqProj = (TH1F*)hvobssq->ProjectionY(Form("hvobssqProj_%d",ipt),hvobs->GetXaxis()->FindBin(ptbin[ipt]),hvobs->GetXaxis()->FindBin(ptbin[ipt+1]));
            float vobs = hvobsProj->GetMean();
            float Ntracks = hvobsProj->GetEntries();
            float vobssq = hvobsProj->GetMean();
            float v = vobs/reso;
            float verr = sqrt(vobssq/reso/reso-(v*v))/sqrt(Ntracks);
            ptProj->GetXaxis()->SetRangeUser(ptbin[ipt],ptbin[ipt+1]);
            float pt = ptProj->GetMean();
            fout<<pt<<" "<<v<<" "<<" "<<verr<<endl;
         }
        fout.close();
         }
        fout1.close();
        fout2.close();
        }
        }
     }
}
Example #17
0
void plot_ZJetBalance(int JetAlgo) {

  Float_t pt[NGenPtBins];
  TString ptBin[NGenPtBins];

  
  for(int i=0; i<NGenPtBins; i++) {
    pt[i] = 0.5*( GenPt[i] + GenPt[i+1] );
    ptBin[i] = Form("%d_%d", (int) GenPt[i], (int) GenPt[i+1] );
  }


  Float_t errpt[NGenPtBins];
  Float_t genMean[NGenPtBins];
  Float_t genSigma[NGenPtBins]; 
  Float_t recoMean[NGenPtBins]; 
  Float_t recoSigma[NGenPtBins];
 

  TString algoSt;
  if(JetAlgo==0) algoSt = "_ic5";
  if(JetAlgo==1) algoSt = "_ic7";
  if(JetAlgo==2) algoSt = "_mp5";
  if(JetAlgo==3) algoSt = "_mp7";
  if(JetAlgo==4) algoSt = "_kt6";

  TString textFilename = "ZjetPtBalance" + algoSt + TString(".txt");
  TString JetResponseFilename 
    = "Histograms_ZjetResponse" + algoSt + TString(".root");

  FILE *file = fopen(textFilename,"w+");
  fprintf( file ,"%s    %s   %s   %s   %s \n", "pT bin", 
	   "genMean", "genSigma", "recoMean", "recoSigma");

  TH1F* responseHistGen;
  TH1F* responseHistReco;
  TH1F* genJetpt;
  TH1F* caloJetpt;
  TH1F* Zpt;

  if(storeResponsHistogramsInRootFile == true) {
    TFile respHistFile(JetResponseFilename,"RECREATE");
  }


  for(int i=0; i<NGenPtBins; i++) {

    responseHistGen = new TH1F("responseHistGen_"+ptBin[i],"", 40, 0.0, 2.0);
    responseHistGen->Sumw2();
    TAxis* responseHistGenx = responseHistGen->GetXaxis();
    TAxis* responseHistGeny = responseHistGen->GetYaxis();
    responseHistGenx->SetTitle("p_{T,Jet} / p_{T,Z}   ");
    responseHistGeny->SetTitle("Events / 0.05         ");
    responseHistGeny->SetTitleOffset(1.2);
    
    responseHistReco = new TH1F("responseHistReco_"+ptBin[i],"", 40, 0.0, 2.0);
    responseHistReco->Sumw2();
    responseHistReco->SetLineColor(2);
    responseHistReco->SetMarkerColor(2);
    

    genJetpt = new TH1F("genJetpt_"+ptBin[i],"", NGenPtBins-1, GenPt);
    genJetpt->Sumw2();

    caloJetpt = new TH1F("caloJetpt_"+ptBin[i],"", NGenPtBins-1, GenPt);
    caloJetpt->Sumw2();

    recoZpt = new TH1F("recoZpt_"+ptBin[i],"", NGenPtBins-1, GenPt);
    recoZpt->Sumw2();

    errpt[i]     = 0.0;
    genMean[i]   = 0.0;
    genSigma[i]  = 0.0; 
    recoMean[i]  = 0.0; 
    recoSigma[i] = 0.0;


    plot_ZJetBalance(  JetAlgo, i, *responseHistGen, *responseHistReco, 
		      *genJetpt, *caloJetpt, *recoZpt);

    genMean[i]   = (Float_t) responseHistGen->GetMean(1);
    genSigma[i]  = (Float_t) responseHistGen->GetMean(11);
    recoMean[i]  = (Float_t) responseHistReco->GetMean(1); 
    recoSigma[i] = (Float_t) responseHistReco->GetMean(11);


    if(storeResponseInTextFile == true) {
      fprintf( file ,"%5.1f   %5.4f   %5.4f   %5.4f   %5.4f \n", pt[i],
	       genMean[i], genSigma[i], recoMean[i], recoSigma[i] );
    }

    if(storeResponsHistogramsInRootFile == true) {
      respHistFile.cd();
      responseHistGen->Write();
      responseHistReco->Write();
      genJetpt->Write();
      caloJetpt->Write();
      recoZpt->Write();
    }
    
    delete responseHistGen;
    delete responseHistReco;
    delete genJetpt;
    delete caloJetpt;
    delete recoZpt;
  }

  fclose(file);
  respHistFile.Close();





  if(makeplot_Response == true) {
    // plot full spectrum
    TGraphErrors *ptbalanceGen  = new TGraphErrors(NGenPtBins, pt, genMean, 
						   errpt, genSigma);
    TGraphErrors *ptbalanceReco = new TGraphErrors(NGenPtBins, pt, recoMean, 
						   errpt, recoSigma);
    // plot Zmumu values
    Float_t ptmm[9] = { 40.0, 60.0, 100.0, 140.0, 200.0, 250.0, 
			330.0, 400.0, 520.0 };
    Float_t balancemm[9] = { 0.496, 0.568, 0.66, 0.71, 0.75, 0.765, 
			     0.775, 0.79, 0.81 }; 
    TGraph *ptbalancemm = new TGraph( 9, ptmm, balancemm);


    ptbalanceGen->GetXaxis()->SetTitle("p_{T}^{Z} [GeV/c]     ");
    ptbalanceGen->GetYaxis()->SetTitle("p_{T}^{Jet} / p_{T}^{Z}   ");
    ptbalanceGen->SetMarkerStyle(22);
    ptbalanceGen->SetMarkerSize(1.2);
    ptbalanceGen->SetTitle("");
    ptbalanceGen->SetMinimum(0.2);
    ptbalanceReco->SetMarkerColor(2);
    ptbalanceReco->SetLineColor(2);
    ptbalanceReco->SetMarkerStyle(22);
    ptbalanceReco->SetMarkerSize(1.2);
    ptbalanceReco->SetMinimum(0.2);
    ptbalancemm->SetMarkerStyle(24);
    ptbalancemm->SetMarkerSize(1.2);
    ptbalancemm->SetMinimum(0.2);
    ptbalancemm->SetMarkerColor(4);
    ptbalancemm->SetLineColor(4);

    TCanvas c1("c1","",800,600);
    c1.SetGrid();
    ptbalanceGen->Draw("APL");
    ptbalanceReco->Draw("PL");
    ptbalancemm->Draw("PL");
    leg_hist = new TLegend(0.6,0.35,0.85,0.55);
    leg_hist->AddEntry( ptbalanceGen, "Generator level", "l");
    leg_hist->AddEntry( ptbalanceReco,"Calorimeter level","l");
    leg_hist->AddEntry( ptbalancemm,"Z#rightarrow#mu#mu","l");
    leg_hist->SetFillColor(0);
    leg_hist->Draw();
    c1.SaveAs("PtBalanceVsPt.eps");
    c1.SaveAs("PtBalanceVsPt.gif");
    c1.SaveAs("PtBalanceVsPt.root");
    c1.Close();
    delete leg_hist;
    delete ptbalanceGen;
    delete ptbalanceReco;
    delete ptbalancemm;
  }

}
int evaluate( std::string filelist, std::string outfile )
{
  gStyle->SetOptStat(0);

  TCanvas *ctemp = new TCanvas();

  TCanvas *cres = new TCanvas("TimeDependence");
  TH1F* hres = new TH1F("hres","",100,0,650);
  hres->GetYaxis()->SetRangeUser(0,50);
  hres->SetTitle("");
  hres->GetXaxis()->SetTitle("time (s)");
  hres->GetYaxis()->SetTitle("B_{int} (mT)");
  hres->Draw();
  leg = new TLegend(0.2,0.6,0.9,0.9);
//  leg->SetHeader("The Legend Title"); // option "C" allows to center the header
  leg->SetNColumns(5);

  vector< double > v_Bint;
  vector< double > v_BintErr;
  vector< double > v_Bext;
  vector< double > v_BextErr;

  /* Loop over all lines in input file */
  std::ifstream infilelist(filelist);
  std::string line;

  unsigned colorcounter=38;

  while (std::getline(infilelist, line))
  {
    // skip lines with '#' and empty lines
    if ( line.find("#") != string::npos )
      {
        cout << "Skip line " << line << endl;
        continue;
      }

    if ( line == "" )
      continue;

    //cout << "Processing file " << line << endl;


    TString infilename("data_calib/");
    infilename.Append(line);

    TFile *fin = new TFile( infilename );
    TTree *tin = (TTree*)fin->Get("t");

    ctemp->cd();
    tin->Draw("Bi:time");
    TGraph *gtime = new TGraph(tin->GetEntries(), &(tin->GetV2()[0]), &(tin->GetV1()[0]));
    gtime->SetLineColor(colorcounter);
    colorcounter++;

    TH1F* hBext = new TH1F("hBext","",100,0,1000);
    tin->Draw("Bo >> hBext");

    cres->cd();
    gtime->Draw("lsame");

    double Bext_i = hBext->GetMean();
    double BextErr_i = hBext->GetRMS();

    double Bint_i = gtime->Eval(590);
    double BintErr_i = 0;

    /* add legend entry */
    TString legname("B_ext ~ ");
    legname += (int)Bext_i;
    leg->AddEntry(gtime,legname,"l");

    cout << "B_ext: " << Bext_i << " \t B_int: " << Bint_i << endl;

    v_Bint.push_back(Bint_i);
    v_BintErr.push_back(BintErr_i);
    v_Bext.push_back(Bext_i);
    v_BextErr.push_back(BextErr_i);

  }

  cres->cd();
  leg->Draw();

  TGraphErrors *gfinal = new TGraphErrors(v_Bext.size(), &(v_Bext[0]), &(v_Bint[0]), &(v_BextErr[0]), &(v_BintErr[0]));
  gfinal->Sort();
  gfinal->SetName("Bint_Vs_Bext");
  gfinal->SetTitle("");
  gfinal->GetXaxis()->SetTitle("B_{ext} (mT)");
  gfinal->GetYaxis()->SetTitle("B_{int} (mT)");

  TCanvas *cfinal = new TCanvas();
  gfinal->Draw("APL");

  /* Save output graph */
  TString outfilename("output/");
  outfilename.Append(outfile);
  TFile *fout = new TFile(outfilename,"RECREATE");

  cres->Write();
  gfinal->Write();

  fout->Close();

  /* Write result to txt output file */
  TString outfilenametxt = outfilename;
  outfilenametxt.ReplaceAll(".root",".txt");

  ofstream foutxt;
  foutxt.open( outfilenametxt );
  foutxt <<  "# Bo sig_Bo Bi sig_Bi shield sig_shield sf sig_sf time_dependent" << endl;

  for ( int i = 0; i < gfinal->GetN(); i++ )
  {
    double Bo = gfinal->GetX()[i];
    double sig_Bo = gfinal->GetEX()[i];
    double Bi = gfinal->GetY()[i];
    double sig_Bi = gfinal->GetEY()[i];
    double shield = 0;
    double sig_shield = 0;
    double sf = 0;
    double sig_sf = 0;
    double time_dependent = 0;

    foutxt <<  Bo << " " << sig_Bo << " " << Bi << " " << sig_Bi << " "
         << shield << " " << sig_shield << " " << sf << " " << sig_sf
         << " " << time_dependent << endl;
  }

  return 0;
}
Example #19
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);

  TH1F* hA_l = new TH1F("hA_l",title, nbins, low, high);
  TH1F* hB_l = new TH1F("hB_l",title, nbins, low, high);
  TH1F* hC_l = new TH1F("hC_l",title, nbins, low, high);
  TH1F* hD_l = new TH1F("hD_l",title, nbins, low, high);
  hA->SetStats(0);
  hA->GetYaxis()->SetLabelSize(0.04);
  //hA->GetYaxis()->SetTitleOffset(1.3);
  hA->GetXaxis()->SetTitleOffset(1.1);
  hA->GetXaxis()->SetTitleFont(132);
  hA->GetXaxis()->SetTitleSize(0.042);
  hA->GetXaxis()->SetLabelSize(0.04);
  hA->SetLineWidth(2);

  //  hA->StatOverflows(true);
  //  hB->StatOverflows(true);
  //  hC->StatOverflows(true);
  //  hD->StatOverflows(true);

  int n1(0), n2(0), n3(0), n4(0), n5(0);
  if (files.Contains("20bx25")) {
    n1=5;
    n2=17;
    n3=21;
    n4=25;
    n5=40;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=25;
    n3=40;
    n4=55;
    n5=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=15;
    n3=22;
    n4=32;
    n5=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  //if (files.Contains("PU_S10")) {
  TString cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n1,n2);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hA", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n1,n2);
  chain->Project("hA_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n2,n3);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hB", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n2,n3);
  chain->Project("hB_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n3,n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hC", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n3,n4);
  chain->Project("hC_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d)",mu.Data(),n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hD", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d)",mu.Data(),n4);
  chain->Project("hD_l", var, cuts);
  // }
  // else {
  //  }
  
  float avg1(hA->GetMean());
  float avg2(hB->GetMean());
  float avg3(hC->GetMean());
  float avg4(hD->GetMean());

  hA->Scale(1/hA->Integral());
  hB->Scale(1/hB->Integral());
  hC->Scale(1/hC->Integral());
  hD->Scale(1/hD->Integral());

  hA->SetLineColor(1);
  hB->SetLineColor(2);
  hC->SetLineColor(3);
  hD->SetLineColor(4);

  hA->SetLineWidth(2);
  hB->SetLineWidth(2);
  hC->SetLineWidth(2);
  hD->SetLineWidth(2);

  float avg1_l(hA_l->GetMean());
  float avg2_l(hB_l->GetMean());
  float avg3_l(hC_l->GetMean());
  float avg4_l(hD_l->GetMean());

  hA_l->Scale(1/hA_l->Integral());
  hB_l->Scale(1/hB_l->Integral());
  hC_l->Scale(1/hC_l->Integral());
  hD_l->Scale(1/hD_l->Integral());

  hA_l->SetLineColor(12);
  hB_l->SetLineColor(46);
  hC_l->SetLineColor(8);
  hD_l->SetLineColor(7);

  hA_l->SetLineWidth(2);
  hB_l->SetLineWidth(2);
  hC_l->SetLineWidth(2);
  hD_l->SetLineWidth(2);

  TCanvas* c1 = new TCanvas();
  float max = TMath::Max(hA->GetMaximum(), hB->GetMaximum());
  if (hC->GetMaximum()>max) max = hC->GetMaximum();
  if (hD->GetMaximum()>max) max = hD->GetMaximum();

  hA->SetMaximum(max*1.1);
  hA->Draw("hist");
  hB->Draw("hist,same");
  hC->Draw("hist,same");
  hD->Draw("hist,same");
  hA_l->Draw("hist,same");
  hB_l->Draw("hist,same");
  hC_l->Draw("hist,same");
  hD_l->Draw("hist,same");

  TLegend* leg = new TLegend(0.42,0.6,0.9,0.9);
  leg->SetFillStyle(0);
  char label[1000];
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n1,n2,avg1);
  leg->AddEntry(hA,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n2,n3,avg2);
  leg->AddEntry(hB,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n3,n4,avg3);
  leg->AddEntry(hC,label,"lp");
  sprintf(label,"Early Ints.>%d (#mu=%3.3f)",n4,avg4);
  leg->AddEntry(hD,label,"lp");
  // leg->Draw();

  TString plotTitle ="relIso_vs_early_and_late_OOTPU_"+var+comments+".pdf";
  c1->Print(plotTitle);

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
void plot_uparaCorr_V_lumi_upara() {
  TFile *f = new TFile("data_wen_cell_noWPtCut_newDataSet.root");
  gDirectory->cd("UE_Hist");

  char name[50];
  const Int_t n_Lumi_Bins = 10;
  double Lumi_Average[n_Lumi_Bins], Lumi_Average_Err[n_Lumi_Bins];
  double UParaCorr_Lumi[n_Lumi_Bins], UParaCorr_Lumi_Err[n_Lumi_Bins];

  const Int_t n_UPara_Bins = 13;
  double UPara_Average[n_UPara_Bins], UPara_Average_Err[n_UPara_Bins];
  double UParaCorr_UPara[n_UPara_Bins], UParaCorr_UPara_Err[n_UPara_Bins];

  for(int i=0; i<n_Lumi_Bins; i++) {
    sprintf(name, "%s%d", "InstLumi_", i);
    TH1F *hLumi = gROOT->FindObject(name);
    Lumi_Average[i] = hLumi->GetMean();
    Lumi_Average_Err[i] = 0.;
    delete hLumi;

    // sum5towEt vs deltaPhi
    sprintf(name, "%s%d", "sum5towEt_Lumi_", i);
    TH1F *hLumi_Upara = gROOT->FindObject(name);
    TF1 *fitfunc = new TF1("fitf", fitf, 0.2, 0.4, 1);
    hLumi_Upara->Fit("fitf", "r");

    double param, param_err;
    fitfunc->GetParameters(&param);
    param_err = fitfunc->GetParError(0);
    
    UParaCorr_Lumi[i] = param;
    UParaCorr_Lumi_Err[i] = param_err;

    delete fitfunc;
    delete hLumi_Upara;
  }

 for(int i=0; i<n_UPara_Bins; i++) {
    sprintf(name, "%s%d", "UPara_", i);
    TH1F *hUPara = gROOT->FindObject(name);
    UPara_Average[i] = hUPara->GetMean();
    UPara_Average_Err[i] = 0.;
    delete hUPara;

    // sum5towEt vs deltaPhi
    sprintf(name, "%s%d", "sum5towEt_UPara_", i);
    TH1F *hUPara_Upara = gROOT->FindObject(name);
    TF1 *fitfunc = new TF1("fitf", fitf, 0.2, 0.4, 1);
    hUPara_Upara->Fit("fitf", "r");

    double param, param_err;
    fitfunc->GetParameters(&param);
    param_err = fitfunc->GetParError(0);
    
    UParaCorr_UPara[i] = param;
    UParaCorr_UPara_Err[i] = param_err;

    delete fitfunc;
    delete hUPara_Upara;
  }

  // uparallel vs luminosity
  TCanvas *c1 = new TCanvas("c1", "canvas");
  TGraphErrors *ge = new TGraphErrors(n_Lumi_Bins, Lumi_Average, UParaCorr_Lumi, Lumi_Average_Err, UParaCorr_Lumi_Err);  
  c1->SetGridx();
  c1->SetGridy();
  ge->Draw("AP");
  c1->Update();
  
  // uparallel vs uparallel
  TCanvas *c2 = new TCanvas("c2", "canvas");
  TGraphErrors *ge2 = new TGraphErrors(n_UPara_Bins, UPara_Average, UParaCorr_UPara, UPara_Average_Err, UParaCorr_UPara_Err);  
  c2->SetGridx();
  c2->SetGridy();
  ge2->Draw("AP");
  c2->Update();
}
Example #21
0
int main(int argc, char** argv){

 ///==================================================
 ///==== Draw Distribution with and without scale ====
 ///==================================================

 ///===============================================================================
 gROOT->Reset();
 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat(0);
 gStyle->SetOptFit(0);

 const Int_t __NRGBs = 5;
 const Int_t __NCont = 76;
 Double_t __stops[__NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
 Double_t __red[__NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
 Double_t __green[__NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
 Double_t __blue[__NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };

 TColor::CreateGradientColorTable(__NRGBs, __stops, __red, __green, __blue, __NCont);
 gStyle->SetNumberContours(__NCont);
 ///===============================================================================
 

 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }

 // Parse the config file
 parseConfigFile (argv[1]) ;

 std::string treeNameDATA  = gConfigParser -> readStringOption("InputDATA::treeName");
 std::string inputFileDATA = gConfigParser -> readStringOption("InputDATA::inputFile");
 double luminosity = gConfigParser -> readDoubleOption("InputDATA::luminosity");
 std::cout << ">>>>> InputDATA::treeName   " << treeNameDATA  << std::endl;
 std::cout << ">>>>> InputDATA::inputFile  " << inputFileDATA  << std::endl;
 std::cout << ">>>>> InputDATA::luminosity " << luminosity  << std::endl;

 std::string treeNameMC  = gConfigParser -> readStringOption("InputMC::treeName");
 std::vector< std::string > inputFileMC = gConfigParser -> readStringListOption("InputMC::inputFile");
 std::vector< std::string > inputSampleMC = gConfigParser -> readStringListOption("InputMC::nameSample");
 std::vector< double > xSecAndEfficiency = gConfigParser -> readDoubleListOption("InputMC::xsecEff");

 std::cout << ">>>>> InputMC::treeName  " << treeNameMC  << std::endl;
 std::cout << ">>>>> InputMC::inputFile size " << inputFileMC.size()  << std::endl;
 if (inputFileMC.size() != xSecAndEfficiency.size() || inputFileMC.size() != inputSampleMC.size()) {
     std::cerr << " >>>> Error: different number of samples and cross sections" << std::endl;
     return 0;
    }
 int nMC = inputFileMC.size();
 for (int iMC = 0; iMC < nMC; iMC++) {
    std::cout << ">>>>> InputMC::inputFile[" << iMC << "] = " << inputSampleMC.at(iMC) << " => " << inputFileMC.at(iMC)  << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity * xSecAndEfficiency.at(iMC) << std::endl;
 }


 int binX = gConfigParser -> readIntOption("Options::binX");
 double minX = gConfigParser -> readDoubleOption("Options::minX");
 double maxX = gConfigParser -> readDoubleOption("Options::maxX");
 std::string variableX = gConfigParser -> readStringOption("Options::variableX");
 std::cout << ">>>>> Options::binX      " << binX  << std::endl;
 std::cout << ">>>>> Options::minX      " << minX  << std::endl;
 std::cout << ">>>>> Options::maxX      " << maxX  << std::endl;
 std::cout << ">>>>> Options::variableX " << variableX.c_str() << std::endl;

 int binY = gConfigParser -> readIntOption("Options::binY");
 double minY = gConfigParser -> readDoubleOption("Options::minY");
 double maxY = gConfigParser -> readDoubleOption("Options::maxY");
 std::string variableY = gConfigParser -> readStringOption("Options::variableY");
 std::cout << ">>>>> Options::binY      " << binY  << std::endl;
 std::cout << ">>>>> Options::minY      " << minY  << std::endl;
 std::cout << ">>>>> Options::maxY      " << maxY  << std::endl;
 std::cout << ">>>>> Options::variableY " << variableY.c_str() << std::endl;
 
 int binRatio = gConfigParser -> readIntOption("Options::binRatio");
 double minRatio = gConfigParser -> readDoubleOption("Options::minRatio");
 double maxRatio = gConfigParser -> readDoubleOption("Options::maxRatio");
 std::cout << ">>>>> Options::minRatio      " << minRatio  << std::endl;
 std::cout << ">>>>> Options::maxRatio      " << maxRatio  << std::endl;
 
 
 std::string outputFile = gConfigParser -> readStringOption("Output::outputFile");
 std::cout << ">>>>> Output::outputFile  " << outputFile  << std::endl;


//  TString AdditionalCut = Form("eta > 1.5");// || eta < -1.5)");// && eleFBrem<0.5");
 TString AdditionalCut = Form("eta < -1.5");// || eta < -1.5)");// && eleFBrem<0.5");
//  TString AdditionalCut = Form("(eta > 1.5 || eta < -1.5)");// && abs(eleFBrem)<1");
 
 
 
 EColor vColor[100] = {
  kBlue,(EColor)(kBlue+1),(EColor) (kBlue+2),
  kRed,(EColor) (kRed+1),(EColor) (kRed+2),
  kGreen,(EColor) (kGreen+1),(EColor) (kGreen+2),
  kTeal,(EColor) (kTeal+1),
  kOrange,(EColor) (kOrange+1),
  kMagenta,(EColor) (kMagenta+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)};
 
 ///==== DATA ====
 TFile* fileInDATA = new TFile(inputFileDATA.c_str(),"READ");

 ///==== W ====
 TFile* fileInMC[nMC];
 for (int iMC = 0; iMC < nMC; iMC++) {
    fileInMC[iMC] = new TFile(inputFileMC.at(iMC).c_str(),"READ");
 }

 ///==== output ====
 TFile* outFile = new TFile(outputFile.c_str(),"RECREATE");
 outFile->cd();


 ///==== Prepare input trees ====
 TLegend* leg = new TLegend(0.55,0.7,0.95,0.95);
 leg->SetFillColor(0);

 TLegend* legDown = new TLegend(0.55,0.1,0.95,0.35);
 legDown->SetFillColor(0);

 TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str());
 int initialNumber;
 TH2F* HistoDATA = new TH2F("DATA","DATA",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioDATA = new TH1F("RatioDATA","RatioDATA",binRatio,minRatio,maxRatio);
 TString DrawDATA = Form("%s:%s >> DATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoDATA->SetMarkerSize(1);
 HistoDATA->SetMarkerStyle(20); 
 HistoDATA->GetXaxis()->SetTitle(variableX.c_str());
 HistoDATA->GetYaxis()->SetTitle(variableY.c_str());
 leg->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");
 legDown->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");

 DrawDATA = Form("(%s) / (%s) >> RatioDATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoRatioDATA->SetMarkerSize(1);
 HistoRatioDATA->SetMarkerStyle(20); 
 HistoRatioDATA->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
 
 TH2F* HistoMC[nMC];
 TH1F* HistoRatioMC[nMC];

 TH2F* HistoMC_SUM = new TH2F("HistoMC_SUM","HistoMC_SUM",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioMC_SUM = new TH1F("HistoRatioMC_SUM","HistoRatioMC_SUM",binRatio,minRatio,maxRatio);
 
 SetColorAndStyleHisto(*(HistoRatioMC_SUM),kBlue); 
 
 TTree* MyTreeMC[nMC];
 THStack* hsMC = new THStack("hsMC","hsMC");
 
 double MC_Expected = 0;
 
 for (int iMC = 0; iMC < nMC; iMC++) {
// for (int iMC = nMC-1; iMC >= 0; iMC--) {
  MyTreeMC[iMC] = (TTree*) fileInMC[iMC]->Get(treeNameMC.c_str());
  MyTreeMC[iMC]->SetBranchAddress("initialNumber",&initialNumber);
  MyTreeMC[iMC]->GetEntry(0);
  xSecAndEfficiency.at(iMC) = xSecAndEfficiency.at(iMC) / initialNumber; ///==== normalize to initial number of events
  HistoMC[iMC] = new TH2F(inputSampleMC.at(iMC).c_str(),inputSampleMC.at(iMC).c_str(),binX,minX,maxX,binY,minY,maxY);
  HistoRatioMC[iMC] = new TH1F(Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),binRatio,minRatio,maxRatio);
  
  TString Draw = Form("%s:%s >> %s",variableY.c_str(),variableX.c_str(),inputSampleMC.at(iMC).c_str());
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());

  Draw = Form("(%s) / (%s) >> %s",variableY.c_str(),variableX.c_str(),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()));
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());  
  HistoRatioMC[iMC]->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  std::cout << ">>>>>> " << inputSampleMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity << " : " << HistoMC[iMC]->GetEntries() << " = " << luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries() << std::endl;
  std::cout << "    >> " << Draw.Data() << std::endl;
  std::cout << "    >> " << HistoMC[iMC]->GetEntries() << " Entries" << std::endl;
 
  MC_Expected += luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries();
  
  HistoMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  HistoRatioMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  
  SetColorAndStyleHisto(*(HistoMC[iMC]),vColor[iMC]);
  SetColorAndStyleHisto(*(HistoRatioMC[iMC]),vColor[iMC]);
  
  HistoMC[iMC]->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC[iMC]->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoMC_SUM->Add(HistoMC[iMC]);
  HistoMC_SUM->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC_SUM->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoRatioMC_SUM->Add(HistoRatioMC[iMC]);
  HistoRatioMC_SUM->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  hsMC->Add(HistoMC[iMC]);
  if (iMC == 0) hsMC->Add(HistoMC[iMC]);
  leg->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
  legDown->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
 }
  
  
 ///==== make fit ====
 
 TH1D* htemp_prof = smartGausProfileXSQRTN(HistoDATA,2);  
 TGraphErrors grH = buildGEfromH_Personalized(*htemp_prof);
 grH.SetMarkerStyle(22);
 grH.SetMarkerSize(0.7);
 grH.SetMarkerColor(kBlue);
 grH.SetFillColor(kBlue);
 grH.SetFillStyle(3335);
 grH.SetLineWidth(1);
 grH.SetLineColor(kBlue);
 grH.GetXaxis()->SetTitle(variableX.c_str());
 grH.GetYaxis()->SetTitle(variableY.c_str());
 

 ///----------------------
 ///---- Plot results ----
 ///----------------------
 std::cerr << " MC expected : DATA = " << MC_Expected << " : " << HistoDATA->GetEntries() << std::endl;
 
 std::cerr << " HistoDATA->GetMaximum() = " << HistoDATA->GetMaximum() << std::endl;
 std::cerr << " HistoDATA->GetEntries() = " << HistoDATA->GetEntries() << std::endl;
 outFile->cd();
 
 TCanvas cResultDistro("cResultDistro","cResultDistro",900,900);
 cResultDistro.Divide(2,2);
 cResultDistro.cd(1);
 HistoDATA->DrawClone("colz");
 gPad->SetGrid();
 TString tLumiName = Form("#int L = %.4f pb^{-1}",luminosity);
 TLatex tLumi(1.5 * HistoDATA->GetMean(1),0.2 * HistoDATA->GetMaximum(),tLumiName.Data());
 tLumi.DrawClone();
 
 
 cResultDistro.cd(2);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 TString tEleName = Form("%d electrons",(int) HistoDATA->GetEntries());
 TLatex tEle(2.0 * HistoRatioDATA->GetMean(1),0.3 * HistoRatioDATA->GetMaximum(),tEleName.Data());
 tEle.DrawClone();
 gPad->SetGrid();

 
 cResultDistro.cd(3);
 grH.Draw("APL");
 double minFit = gConfigParser -> readDoubleOption("Options::minFit");
 double maxFit = gConfigParser -> readDoubleOption("Options::maxFit");
 std::cout << ">>>>> Options::minFit      " << minFit  << std::endl;
 std::cout << ">>>>> Options::maxFit      " << maxFit  << std::endl;
 
 TF1* funz = new TF1 ("funz","pol1",minFit,maxFit);
//  funz->FixParameter(0,0);
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 grH.Fit("funz","RMQ");
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffDATA = funz->GetParameter(1);
 double errCoeffDATA = funz->GetParError(1);
 
 gPad->SetGrid();
 
 
 cResultDistro.cd(4);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 tEle.DrawClone();
 gPad->SetGrid();
 gPad->SetLogy();
 
 
 TString nameImage = Form("%s_%s_%d.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImage.Data());
 TString nameImageRoot = Form("%s_%s_%d.root",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImageRoot.Data());

 
 
 TCanvas cResultDistroMC("cResultDistroMC","cResultDistroMC",800,800);
 cResultDistroMC.Divide(2,2);
 
 //  cResultDistroMC.Divide(2,nMC);
//  for (int iMC = 0; iMC < nMC; iMC++) {
//   cResultDistroMC.cd(2*iMC+1);
//   HistoMC[iMC]->DrawClone("colz");
//   HistoDATA->DrawClone("BOXsame");
//   cResultDistroMC.cd(2*iMC+2);
//   HistoRatioMC[iMC]->DrawNormalized("");
//   HistoRatioDATA->DrawNormalized("E1same");  
//  }

 cResultDistroMC.cd(1);
 HistoMC_SUM->DrawClone("colz");
 HistoDATA->DrawClone("BOXsame");
 gPad->SetGrid();
 
 ///==== make fit ====
 
 cResultDistroMC.cd(3);
 
 TH1D* MChtemp_prof = smartGausProfileXSQRTN(HistoMC_SUM,2);  
 TGraphErrors MCgrH = buildGEfromH_Personalized(*MChtemp_prof);
 MCgrH.SetMarkerStyle(22);
 MCgrH.SetMarkerSize(0.7);
 MCgrH.SetMarkerColor(kRed);
 MCgrH.SetFillColor(kRed);
 MCgrH.SetFillStyle(3335);
 MCgrH.SetLineWidth(1);
 MCgrH.SetLineColor(kRed);
 MCgrH.GetXaxis()->SetTitle(variableX.c_str());
 MCgrH.GetYaxis()->SetTitle(variableY.c_str());
 
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 MCgrH.Fit("funz","RMQ");
 
 std::cerr << " ================= " << std::endl;
 std::cerr << " ======= MC ====== " << std::endl;
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffMC = funz->GetParameter(1);
 double errCoeffMC = funz->GetParError(1);
 
 MCgrH.Draw("APL");
 gPad->SetGrid();
 
 
 cResultDistroMC.cd(4);
 MCgrH.Draw("APL");
 grH.Draw("PLSAME");
 gPad->SetGrid();
 
 
 TString nameImageLog = Form("%s_%s_%d_MC.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistroMC.SaveAs(nameImageLog.Data());
  
 
 std::cerr << " 1 - alpha = " << coeffDATA / coeffMC 
           << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
           << std::endl;


 std::cerr << " alpha = " << 1-coeffDATA / coeffMC 
	   << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
	   << std::endl;
   
   

//  TCanvas cResultDistro_1("cResultDistro_1","cResultDistro_1",800,800);
//  HistoRatioMC_SUM->Draw();
//  HistoRatioDATA->Draw("E1same");
//  tEle.DrawClone();
//  gPad->SetGrid();
//  gPad->SetLogy();
   
}
Example #22
0
void AnalyzeData(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt,
		Int_t startEv = 1, char *PedFile, Int_t DrawExtraGraphs = 0) {


	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// open file

	FILE *fdata = OpenDataFile(DataFile);
	struct channel_struct *p;
	struct channel_struct *dep;

	// create histograms
	// create list of histograms for channels and distribution

	TList *DistChList = new TList();
	TH1F *distch; // histo with distribution of cell-charge, for each channel

	TList *DistChSubList = new TList();
	TH1F *distchsub; // histo with distribution of cell-charge, pedestals subtracted, for each channel

	TList *DistCh0SubList = new TList();
	TH1F *distch0sub; // histo with distribution of cell-charge, pedestals subtracted,
	// channel 0 subtracted for each channel

	TList *grPedList = new TList();
	TGraphErrors *grPed; // for each channel, pedestal value and RMS for each cell is plotted

	TList *hCellList = new TList();
	TH1F *hCell; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos)
	TList *hCellSubList = new TList();
	TH1F *hCellSub; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos), pedestal subtracted

	TList *hRMSList = new TList();
	TH1F *hRMSdist; // histo with RMS distribution (statistical RMS of distribution)
	TList *hRMSFitList = new TList();
	TH1F *hRMSFitdist; // histo with RMS distribution (RMS of Gaussian fit)

	TList *grDataList = new TList();
	TGraphErrors *grData; // charge-cell and RMS for each cell is plotted

	TList *grDataSubList = new TList();
	TGraphErrors *grDataSub; // pedestal subtracted charge-cell and RMS for each cell is plotted


	for (int h = 0; h < DOMINO_NCH; h++) {
		//
		TString title = "Data Dist channel";
		title += h;
		distch = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
		DistChList->Add(distch);
		//
		TString title = "Data Dist Ped Sub channel";
		title += h;
		distchsub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistChSubList->Add(distchsub);
		//
		TString title = "Data Dist Ped Ch0 Sub channel";
		title += h;
		distch0sub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistCh0SubList->Add(distch0sub);
		//
		TString title = "Pedestal ch";
		title += h;
		grPed = new TGraphErrors(DOMINO_NCELL);
		grPed->SetTitle(title);
		grPedList->Add(grPed);
		//
		TString title = "Data ch";
		title += h;
		grData = new TGraphErrors(DOMINO_NCELL);
		grData->SetTitle(title);
		grDataList->Add(grData);
		//
		// Mean data and RMS for each channel and cell
		TString title = "Data PedSubtracted ch";
		title += h;
		grDataSub = new TGraphErrors(DOMINO_NCELL);
		grDataSub->SetTitle(title);
		grDataSubList->Add(grDataSub);
		//
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			TString title = "Data ch";
			title += h;
			title += " cell";
			title += ch;
			hCell = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
			hCellList->Add(hCell);
			// data (ped subtracted) distribution histos
			TString title = "Data PedSub ch";
			title += h;
			title += " cell ";
			title += ch;
			hCellSub = new TH1F(title, title, 2 * DominoDepthADC, -1
					* DominoDepthADC, DominoDepthADC);
			hCellSubList->Add(hCellSub);
		}
		// Data-RMS distribution histos
		TString title = "RMSDist channel";
		title += h;
		hRMSdist = new TH1F(title, title, 100, 0, 20.);
		hRMSList->Add(hRMSdist);
		// Data-RMS (calculated through a fit) distribution histos
		TString title = "RMSFitDist channel";
		title += h;
		hRMSFitdist = new TH1F(title, title, 100, 0, 20.);
		hRMSFitList->Add(hRMSFitdist);
	}
	//--------------
	//
	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);

	//    return;
	//
	// ====== Read data file and subtract the pedestals
	//
	// Count number of events in data file
	int nevtDataMax = 0;
	while (!feof(fdata)) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		nevtDataMax++;
	}
	printf("nevtDataMax: %d\n", nevtDataMax);

	if (nevt > (nevtDataMax - startEv) || nevt == 0)
		nevt = nevtDataMax - startEv;
	cout << endl << "==>> Processing " << nevt << " events from file "
			<< DataFile << endl;

	rewind(fdata);

	Int_t ievt = 1;
	// go to first event (startEv)
	while (ievt < startEv) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			break;
		ievt++;
	}
	// filling
	ievt = 1;
	Int_t flagEnd = 0;
	Double_t chtmp;
	Double_t PedVal, itmp, Ch0Val;
	// loop on events
	cout << endl << " --- read DATA file:" << fdata << endl;
	while (ievt <= nevt && !flagEnd) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			flagEnd = 1;
		if (ievt % (nevt / 10 + 1) == 0)
			cout << "*" << endl;
		p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
		dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

		TGraphErrors *grCh0 = new TGraphErrors(DOMINO_NCELL);

		// loop on channels
		for (int h = 0; h < DOMINO_NCH; h++) {
			// loop on cells
			distch = (TH1F *) DistChList->At(h);
			distchsub = (TH1F *) DistChSubList->At(h);
			grPed = (TGraphErrors *) grPedList->At(h);
			distch0sub = (TH1F *) DistCh0SubList->At(h);
			if(h==0) {
				for(i = 0; i < DOMINO_NCELL;i++) {
					grPed->GetPoint(i, itmp, PedVal);
					chtmp = (Double_t)(p->data[i]);
					chtmp = chtmp - PedVal;
					grCh0->SetPoint(i,itmp, chtmp);
				}
			}
			for (int i = 0; i < DOMINO_NCELL; i++) {
				// Read pedestal value for this cell
				grPed->GetPoint(i, itmp, PedVal);
				grCh0->GetPoint(i, itmp, Ch0Val);
				//                cout << itmp << ", " << PedVal << endl;
				// Read calibration correction for this cell
				//                CalFact =

				//charge distribution for each cell, pedestal subtracted
				chtmp = (Double_t)(p->data[i]); // data value
				//                cout  << "tcell, tcell, depth: " << chtmp << ","  << p->data[i] << "," << deptmp << endl;
				distch->Fill(chtmp);
				// Check data value: must be within DOMINO Depth
				//                if(chtmp > DominoDepthADC)
				//                    cout << " === WARNING!!! Channel " << h << " Cell " << i << " has value " << chtmp << endl;
				//                cout << "Charge: " << p->data[i] << endl;
				((TH1 *) hCellList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				// Now the pedestal is subtracted
				chtmp = chtmp - PedVal;
				distchsub->Fill(chtmp);
				((TH1 *) hCellSubList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				chtmp = chtmp - Ch0Val;
				distch0sub->Fill(chtmp);
			}
			p++; // next channel
		}
		ievt++; // next event
	}
	cout << endl;

	// now mean and RMS for each cell are computed and save in histos and graphs
	cout << " --- filling data histos and grphs " << endl;
	TF1 *fgauss = new TF1("fgauss", Gauss, -10., 10., 3);
	fgauss->SetParLimits(0, 0.1, 10000.);
	fgauss->SetParLimits(1, 0., 4096.);
	fgauss->SetParLimits(2, 0.1, 20.);
	Float_t mean, rms, meansub, rmssub;
	for (int h = 0; h < DOMINO_NCH; h++) {
		//        for (int h=5; h<6; h++){
		cout << " Channel:" << h << endl;
		hRMSdist = (TH1F *) hRMSList->At(h);
		hRMSFitdist = (TH1F *) hRMSFitList->At(h);
		grData = (TGraphErrors *) grDataList->At(h);
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			//            cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<<hCell->GetMean()<< "," << hCell->GetRMS()<<endl;
			hCell = (TH1F *) hCellList->At(h * DOMINO_NCELL + ch);
			mean = hCell->GetMean();
			rms = hCell->GetRMS();
			hCellSub = (TH1F *) hCellSubList->At(h * DOMINO_NCELL + ch);
			meansub = hCellSub->GetMean();
			rmssub = hCellSub->GetRMS();
			fgauss->SetParameter(0, (Double_t) nevt / 4.);
			fgauss->SetParameter(1, mean);
			fgauss->SetParameter(2, rms);
			//            hCell->Fit("fgauss","QN0");
			grData->SetPoint(ch, ch, mean);
			grData->SetPointError(ch, 0, rms);
			grDataSub->SetPoint(ch, ch, meansub);
			//            grDataSub->SetPointError(ch,0.5,rmssub);
			grDataSub->SetPointError(ch, 0.5, 2.1);
			hRMSdist->Fill(rms);
			hRMSFitdist->Fill(fgauss->GetParameter(2));
			//           cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<< mean << "," << rms<<endl;
		}
	}

	Double_t x, y, chtmp, x1, x2, y1, y2;

	/*TList *grCellCalibList = OpenCalibFile("CalibrationData1000events.root");

	TGraphErrors *grCellCalib;
	TGraphErrors *grDataSubCalib = new TGraphErrors(DOMINO_NCELL);
	grDataSubCalib->SetTitle("Data after calibration correction");
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);


	for(ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = ((TGraphErrors *) grCellCalibList->At(ch));
		grCellCalib->Fit("pol3", "Q");
		TF1 *pol3fit = ((TF1 *) grCellCalib->GetFunction("pol3"));
		grDataSub->GetPoint(ch, x, y);
		chtmp = y - (Double_t)(pol3fit->Eval(y/3.25));
		grDataSubCalib->SetPoint(ch, x, chtmp);
	}

	TCanvas *cGrTest = new TCanvas("grTest", "test per vedere i dati", 1000,1000);

	grDataSubCalib->Draw("APEL");*/


	TString Title = "Charge Distribution per channel";
	gStyle->SetOptFit(111);
	TCanvas *cdistch = new TCanvas("cdistch", Title, 1000, 1000);
	cdistch->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch->cd(i + 1);
		TH1 *dhist = (TH1 *) DistChList->At(i);
		dhist->DrawCopy();
		dhist->SetLineWidth(1);
		dhist->Fit("gaus", "Q");
		dhist->GetFunction("gaus")->SetLineColor(4);
		dhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals Subtracted per channel";
	TCanvas *cdistchsub = new TCanvas("cdistchsub", Title, 1000, 1000);
	cdistchsub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistchsub->cd(i + 1);
		TH1 *dsubhist = (TH1 *) DistChSubList->At(i);
		dsubhist->DrawCopy();
		dsubhist->SetLineWidth(1);
		dsubhist->Fit("gaus", "Q");
		dsubhist->GetFunction("gaus")->SetLineColor(4);
		dsubhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals and Ch0 Subtracted per channel";
	TCanvas *cdistch0sub = new TCanvas("cdistch0sub", Title, 1000, 1000);
	cdistch0sub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch0sub->cd(i + 1);
		TH1 *dch0subhist = (TH1 *) DistCh0SubList->At(i);
		dch0subhist->DrawCopy();
		dch0subhist->SetLineWidth(1);
		dch0subhist->Fit("gaus", "Q");
		dch0subhist->GetFunction("gaus")->SetLineColor(4);
		dch0subhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TCanvas *cDataSubTest = new TCanvas("cDataSubTest", "Data after pedestal subtraction", 1000, 1000);
	cDataSubTest->Divide(1,8);
	for (h = 0; h< DOMINO_NCH; h++) {
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		cDataSubTest->cd(h+1);
		grDataSub->GetYaxis()->SetLabelSize(0.06);
		grDataSub->GetXaxis()->SetLabelSize(0.06);
		grDataSub->Draw("APE");
	}

	TCanvas *cDataSubTestCh5 = new TCanvas("cDataSubTestCh5", "Data after pedestal subtraction Ch5", 1200, 800);
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);
	grDataSub->GetYaxis()->SetLabelSize(0.06);
	grDataSub->GetYaxis()->SetTitle("ADC Counts");
	grDataSub->GetXaxis()->SetTitle("Cell");
	grDataSub->GetXaxis()->SetLabelSize(0.06);
	TLine *refval = new TLine(0,350,1024,350);
	refval->SetLineWidth(3);
	refval->SetLineStyle(2);
	refval->SetLineColor(2);
	TLine *i1 = new TLine(121,-50,121,800);
	i1->SetLineStyle(2);
	TLine *i2 = new TLine(291,-50,291,800);
	i2->SetLineStyle(2);
	TLine *i3 = new TLine(461,-50,461,800);
	i3->SetLineStyle(2);
	TLine *i4 = new TLine(632,-50,632,800);
	i4->SetLineStyle(2);
	TLine *i5 = new TLine(803,-50,803,800);
	i5->SetLineStyle(2);
	TLine *i6 = new TLine(975,-50,975,800);
	i6->SetLineStyle(2);
	TLine *ireal1 = new TLine(121+20,600,121+20,800);
	ireal1->SetLineWidth(3);
	ireal1->SetLineColor(4);
	TLine *ireal2 = new TLine(291-20,600,291-20,800);
	ireal2->SetLineWidth(3);
	ireal2->SetLineColor(4);
	TLine *ireal3 = new TLine(461+20,600,461+20,800);
	ireal3->SetLineWidth(3);
	ireal3->SetLineColor(4);
	TLine *ireal4 = new TLine(632-20,600,632-20,800);
	ireal4->SetLineWidth(3);
	ireal4->SetLineColor(4);
	TLine *ireal5 = new TLine(803+20,600,803+20,800);
	ireal5->SetLineWidth(3);
	ireal5->SetLineColor(4);
	TLine *ireal6 = new TLine(975-20,600,975-20,800);
	ireal6->SetLineWidth(3);
	ireal6->SetLineColor(4);
	grDataSub->Draw("APE");
	refval->Draw("SAME");
	i1->Draw("SAME");
	i2->Draw("SAME");
	i3->Draw("SAME");
	i4->Draw("SAME");
	i5->Draw("SAME");
	i6->Draw("SAME");
	ireal1->Draw("SAME");
	ireal2->Draw("SAME");
	ireal3->Draw("SAME");
	ireal4->Draw("SAME");
	ireal5->Draw("SAME");
	ireal6->Draw("SAME");


	TCanvas *cDataTest = new TCanvas("cDataTest", "Raw Data", 1000,1000);
	cDataTest->Divide(1,8);
	for(h = 0; h < DOMINO_NCH; h++) {
		cDataTest->cd(h+1);
		grData = (TGraphErrors *) grDataList->At(h);
		grData->SetMarkerStyle(20);
		grData->SetMarkerSize(0.5);
		grData->Draw("APE");

	}

	// save root file with graph containing channel 5 data after pedestals subtraction.
	/*
	cout << "test" << endl;

	TString OutFile = DataSubFile;
	TFile *f = new TFile(OutFile,"RECREATE");
	int h = anaChannel;
	TString key="DataSubGraph";
	key += h;
	((TGraphErrors*)grDataSubList->At(h))->Write(key);
	f->Close();
	cout << " ---- Write data on file " << endl;
	 */

	// =======================================================//
	// =====================Matteo's Code=====================//
	// =======================================================//
	/*
	Int_t cht, incCht, decCht, xflag, nPeriods, iMax, iMin;
	Double_t xdiff, incDiff, decDiff, incDiffTemp, decDiffTemp, incXDiff, decXDiff;
	Double_t fitMax, fitMin, fitPeriod, chisquare;
	Double_t DominoXval[DOMINO_NCELL];
	Double_t DominoYval[DOMINO_NCELL];
	Double_t FitXval[DOMINO_NCELL];
	Double_t FitYval[DOMINO_NCELL];


        // opens grDataSub.root

        TString FileName = DataSubFile;
        TGraphErrors *grDataSub;
        int h = anaChannel;
        TFile *f = new TFile(FileName);
        TString key = "DataSubGraph";
        key += h;
        grDataSub = (TGraphErrors *) f->Get(key);
        f->Close();


	// Create a new graph with channel 5 data
	TGraphErrors *grDataSubAnaCh;
	int h = anaChannel;
	grDataSubAnaCh = (TGraphErrors *) grDataSubList->At(h);

	TGraphErrors *grDataSubFix = grDataSubAnaCh->Clone();
	TGraphErrors *grRes = new TGraphErrors(DOMINO_NCELL);
	TList *grResPeriodList = new TList();



	Double_t xtemp, ytemp, DominoMax, DominoMin;

	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		// get domino-output point and save in array
		grDataSubAnaCh->GetPoint(ch, DominoXval[ch], DominoYval[ch]);
	}

	// find the domino point with max y-value
	iMax = 0;
	for(int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] > DominoYval[iMax]) {
			DominoMax = DominoYval[ch];
			iMax = ch;
		}
	}

	cout << "DominoMax e': " << DominoMax << endl;

	// find the domino point with min y-value
	iMin = 0;
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] < DominoYval[iMin]) {
			DominoMin = DominoYval[ch];
			iMin = ch;
		}
	}

	cout << "DominoMin e': " << DominoMin << endl;

	// remove points from the graph that will be used for fit
	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		grDataSubFix->GetPoint(ch, xtemp, ytemp);
		if(ytemp > 0.8*DominoMax || ytemp < 0.2*DominoMin)
			grDataSubFix->RemovePoint(ch);
	}


	TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
	fsin->SetParameters(600., DOMINO_NCELL / 4., 150., 150.);
	fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	grDataSubFix->Fit("fsin");
	TF1 *fsinFit = grDataSubFix->GetFunction("fsin");
	fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	chisquare = grDataSub->Chisquare(fsinFit);
	cout << "il chi quadro della funzione di fit e' : " << chisquare << endl;

	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		// get Fit-value and save in array
		FitXval[ch] = DominoXval[ch];
		FitYval[ch] = fsinFit->Eval(FitXval[ch]);
	}

	fitPeriod = fsinFit->GetParameter("Period");
	cout << "il periodo della funzione e': " << fitPeriod << endl;

	nPeriods = (Int_t) (DOMINO_NCELL/fitPeriod);
	cout << "il numero di periodi della funzione e': " << nPeriods << endl;

	fitMax = fsinFit->GetMaximum();
	cout << "il massimo della funzione e': " << fitMax << endl;

	fitMin = fsinFit->GetMinimum();
	cout << "il minimo della funzione e': " << fitMin << endl;




	// computes the y difference between the ch-domino point and the i-fit point
	// and stops when the difference changes sign
	//
	// first and last points are not included in the cicle
	//
	// if the fit point y-value is bigger or smaller than the fit function max*0.8 or min*0.2
	// the point is removed

	for (int ch = 1; ch < DOMINO_NCELL - 1; ch++) {

		if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
			grRes->RemovePoint(ch);
			continue;
		}

		incDiff = DominoYval[ch] - FitYval[ch];
		incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

		decDiff = DominoYval[ch] - FitYval[ch];
		decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

		if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
			for (int i = ch; i < DOMINO_NCELL; i++, incDiff = incDiffTemp) {
				incDiffTemp = DominoYval[ch] - FitYval[i];

				if (sign(incDiff) != sign(incDiffTemp)) {
					if(abs(incDiffTemp) < abs(incDiff))
						incCht = i;
					else
						incCht = i - 1;
					break;
				}
			}
			xflag = 1;
		}
		else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
			for (int j = ch; j >= 0 ; j--, decDiff = decDiffTemp) {
				decDiffTemp = DominoYval[ch] - FitYval[j];

				if (sign(decDiff) != sign(decDiffTemp)) {
					if(abs(decDiffTemp) < abs(decDiff))
						decCht = j;
					else
						decCht = j + 1;
					break;
				}
			}
			xflag = -1;
		}

		if(xflag == 1)
			xdiff = FitXval[incCht] - DominoXval[ch];
		else
			xdiff = FitXval[decCht] - DominoXval[ch];

		grRes->SetPoint(ch, (Double_t) ch, xdiff);
	}

	cout << "Draw Time Residuals" << endl;
	TString Title = "Time Residuals";
	TCanvas *timeres = new TCanvas("timeres", Title, 1200, 780);
	grRes->SetMarkerStyle(20);
	grRes->SetMarkerSize(0.3);
	grRes->GetYaxis()->SetLabelSize(0.12);
	grRes->GetXaxis()->SetLabelSize(0.12);
	grRes->Draw("APE");


	// The previous graph is now split in N graphs, where N is the number of fit periods

	// this will be needed to set the function phase
	//
    //    iMax = 0;
	//
    //    for(ch = 0; ch < fitPeriod - 1; ch++) {
    //            if(FitYval[ch] > FitYval[iMax]) iMax = ch;
    //    }

	cout << "il primo massimo ha l'indice : " << iMax << endl;

	for (i = 0; i < nPeriods; i++) {
		TGraphErrors *grResPeriod = new TGraphErrors((Int_t) fitPeriod);
		grResPeriodList->Add(grResPeriod);

		for(ch = i*fitPeriod + 1; ch < fitPeriod + (i*fitPeriod); ch++) {

			if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
				grResPeriod->RemovePoint(ch);
				continue;
			}

			incDiff = DominoYval[ch] - FitYval[ch];
			incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

			decDiff = DominoYval[ch] - FitYval[ch];
			decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

			if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
				for (int k = ch; k < k*fitPeriod + fitPeriod; k++, incDiff = incDiffTemp) {
					incDiffTemp = DominoYval[ch] - FitYval[k];

					if (sign(incDiff) != sign(incDiffTemp)) {
						if(abs(incDiffTemp) < abs(incDiff))
							incCht = k;
						else
							incCht = k - 1;
						break;
					}
				}
				xflag = 1;
			}
			else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
				for (int j = ch; j > i*fitPeriod; j--, decDiff = decDiffTemp) {
					decDiffTemp = DominoYval[ch] - FitYval[j];

					if (sign(decDiff) != sign(decDiffTemp)) {
						if(abs(decDiffTemp) < abs(decDiff))
							decCht = j;
						else
							decCht = j + 1;
						break;
					}
				}
				xflag = -1;
			}

			if(xflag == 1)
				xdiff = FitXval[incCht] - DominoXval[ch];
			else
				xdiff = FitXval[decCht] - DominoXval[ch];

			grResPeriod->SetPoint(ch - i*fitPeriod, (Double_t) (ch - i*fitPeriod), xdiff);
		}
	}

	TCanvas *timeresperiod = new TCanvas("timeresperiod", "Time Residuals Period", 1200, 780);
	for(i = 0; i < nPeriods; i++) {
		grResPeriod = ((TGraphErrors *) grResPeriodList->At(i));
		grResPeriod->SetMarkerStyle(20);
		grResPeriod->SetMarkerSize(0.3);
		grResPeriod->GetYaxis()->SetLabelSize(0.12);
		grResPeriod->GetXaxis()->SetLabelSize(0.12);
		grResPeriod->Draw("APEsame");
	}

	cout << "Draw Data - Pedestals Subtracted" << endl;
	TString Title = "Average Charge - Pedestal subtracted";
	TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
	grDataSubAnaCh->SetMarkerStyle(20);
	grDataSubAnaCh->SetMarkerSize(0.3);
	grDataSubAnaCh->GetYaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->GetXaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->Draw("APE");
	fsinFit->Draw("same");
	 */
	// draw extra graphs
	if (DrawExtraGraphs == 1) {
		cout << " ----- DRAW Results ------" << endl;
		//================ DRAW Results ==================

		TCanvas *c = new TCanvas("ctmp", "test", 800, 800);
		c->Divide(3, 3);
		for (int pad = 1; pad < 10; pad++) {
			c->cd(pad);
			((TH1 *) hCellList->At(pad * 512 + 219))->DrawCopy();
			hCellSub = (TH1F *) hCellSubList->At(pad * 512 + 219);
			hCellSub->SetLineColor(2);
			hCellSub->DrawCopy("same");
		}

		cout << "Draw RMS distributions" << endl;
		TString Title = "RMS distributions per channel";
		TCanvas *c4 = new TCanvas("c4", Title, 700, 700);
		c4->Divide(3, 3);
		for (int i = 0; i < DOMINO_NCH; i++) {
			c4->cd(i + 2);
			hRMSdist = (TH1F *) hRMSList->At(i);
			hRMSFitdist = (TH1F *) hRMSFitList->At(i);
			hRMSFitdist->SetLineColor(2);
			hRMSFitdist->DrawCopy();
			hRMSdist->DrawCopy("same");
		}


		TList *grDataCh0SubList = new TList();
		TGraphErrors *grDataCh0Sub;
		for(h = 0; h< DOMINO_NCELL; h++) {
			grDataCh0Sub = new TGraphErrors(DOMINO_NCELL);
			grDataCh0SubList->Add(grDataCh0Sub);
		}

		TGraphErrors *grDataSubCh0 = (TGraphErrors *) grDataSubList->At(6);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSubCh0->GetPoint(ch, x1, y1);
				grDataSub->GetPoint(ch, x2, y2);
				grDataCh0Sub->SetPoint(ch, x1 , y2 - y1);
			}
		}

		TCanvas *cDataCH0Sub = new TCanvas("cDataCH0Sub","cDataCH0Sub", 1000,1000);
		cDataCH0Sub->Divide(1,8);
		for(h = 0; h < DOMINO_NCH; h++) {
			cDataCH0Sub->cd(h+1);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			grDataCh0Sub->GetYaxis()->SetLabelSize(0.12);
			grDataCh0Sub->GetXaxis()->SetLabelSize(0.12);
			grDataCh0Sub->Draw("APEL");
		}



		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1000, 1000);
		csubdata->Divide(3,3);

		for(h = 0; h < DOMINO_NCH; h++) {
			csubdata->cd(h+1);
			TString title = "DataSub channel ";
			title += h;
			TH1F *hCellDataSub = new TH1F(title, title, 100, -20, 20);
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellDataSub->Fill(y);
			}
			hCellDataSub->Fit("gaus", "Q");
			hCellDataSub->GetXaxis()->SetTitle("ADC Counts");
			hCellDataSub->GetFunction("gaus")->SetLineColor(4);
			hCellDataSub->DrawCopy();
		}

		cout << "breakpoint" << endl;
		TCanvas *csubdata2 = new TCanvas("csubdata2", "DataSub for every channel", 1000, 1000);
		TString title = "DataSub every channel ";
		TH1F *hCellChDataSubTot = new TH1F(title, title, 100, -20, 20);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellChDataSubTot->Fill(y);
			}
			hCellChDataSubTot->Fit("gaus", "Q");
			hCellChDataSubTot->GetXaxis()->SetTitle("ADC Counts");
			hCellChDataSubTot->GetFunction("gaus")->SetLineColor(4);
			hCellChDataSubTot->Draw();
		}

		cout << "Draw Pedestals" << endl;
		TString Title = "Pedestals";
		TCanvas *c2 = new TCanvas("c2", Title, 1050, 780);
		c2->SetBorderMode(0);
		c2->SetBorderSize(0.);
		c2->Divide(1, 8);
		//    gStyle->SetCanvasBorderMode(0.);
		//    gStyle->SetCanvasBorderSize(0.);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			c2->cd(h + 1);
			grPed = ((TGraphErrors *) grPedList->At(h));
			grPed->SetMarkerStyle(20);
			grPed->SetMarkerSize(0.5);
			grPed->GetYaxis()->SetLabelSize(0.12);
			grPed->GetXaxis()->SetLabelSize(0.12);
			//        cout <<  " err:" << grPed->GetErrorY(102) << " " ;
			//        cout << x << "--" << y << endl;
			grPed->Draw("APE");
		}

		cout << "Draw Data - Average charge" << endl;
		TString Title = "Average_Charge";
		TCanvas *cdata = new TCanvas("cdata", Title, 1050, 780);
		cdata->Divide(1, 8);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			cdata->cd(h + 1);
			grData = ((TGraphErrors *) grDataList->At(h));
			grData->SetMarkerStyle(20);
			grData->SetMarkerSize(0.3);
			grData->GetYaxis()->SetLabelSize(0.12);
			grData->GetXaxis()->SetLabelSize(0.12);
			grData->GetPoint(10, x, y);
			//        cout << x << "-" << y << endl;
			grData->Draw("APE");
		}

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
		csubdata->Divide(1, 8);
		TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
		TH1D *resDist = new TH1D("resDist", "Residuals Signal", 100, -100., 100.);

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Residuals";
		TCanvas *residuals = new TCanvas("residuals", Title, 1200, 780);
		resDist->DrawCopy();

	}

	fclose(fdata);

	hCellList->Delete();
	hCellSubList->Delete();
	hRMSList->Delete();
	hRMSFitList->Delete();
}
Example #23
0
void rateStudy() {
  const int NRUNS = 25;
  const int NCH = 32;
  const int NBINS = 32;

  TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);

  TMultiGraph *mg = new TMultiGraph();

  TLegend *legend=new TLegend(0.65,0.15,0.88,0.55);
  legend->SetNColumns(4);
  legend->SetFillColor(0);

  TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0);

  //Color buffer
  const int NCOLORS = 32;
  int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34,
                        28, 50, 51, 56, 58, 88, 99, 1, 208, 209,
                        218, 212, 210, 221, 224, 225, 226, 227, 228 };

  ifstream fin;
  //fin.open("runlist.txt");
  fin.open("filter_runlist.txt");

  string line = "";

  TFile* out = new TFile("outtemp.root", "REACREATE");
  TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS);
  TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50);
  TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0);


  for (int ch = 0; ch < NCH; ++ch) {

    //if ( ch==26 || ch==27 )
    //continue;

    //Graph points and errors
    Double_t x[NRUNS];
    Double_t y[NRUNS];
    Double_t errX[NRUNS] = {0};
    Double_t errY[NRUNS] = {0};

    int fileCounter = 0;
    while(getline(fin, line)) {
      vector<double> data = parse(line);
      stringstream filePath;
      filePath << "pmtratestudy/run" << data[0] << "*.root";
      cout << "opening file at " << filePath.str() << endl;
      cout << "file counter: " << fileCounter << " channel=" << ch << endl;
      //TFile* f = new TFile(filePath.str().c_str());
      //TTree* t = (TTree *)f->Get("eventtree");
      TChain* t = new TChain("eventtree");
      t->Add( filePath.str().c_str() );
      out->cd();

      x[fileCounter] = data[1];

      int nfires[NCH] = {0};
      int samples = 0;
      float chmax = 0.0;
      t->SetBranchAddress("nfires", &nfires);
      t->SetBranchAddress("samples", &samples);
      t->SetBranchAddress("chmax", &chmax);
      
      h->Reset();
      
      int nentries = t->GetEntries();
      for (int entry = 0; entry < nentries; ++entry) {
        t->GetEntry(entry);
        if (chmax < 100.0) {
          h->Fill(nfires[ch]);
        }
      }


      
      pois->SetParameter(0,1);
      pois->SetParameter(1, h->GetMean());

      h->Fit(pois,"RQ","",0,50);
      //TF1 *myfit = (TF1 *)h->GetFunction("pois");
      TF1 *myfit = (TF1 *)pois;
      Double_t lambda = myfit->GetParameter(1);  
      h->Draw();
      stringstream histFileName;
      histFileName << "hist/h" << data[0] << "_ch" << ch << ".png";
      c1->SaveAs(histFileName.str().c_str());
      //Graph with poisson method
#if 1
      y[fileCounter] = lambda / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6);
#endif
      //Graph with mean method
#if 0
      y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6);
#endif
      cout << x[fileCounter] << ", " << y[fileCounter] 
           << " | " << (samples - 1) << endl;
      delete t;
      //f->Close();
      fileCounter++;
    } 

    ppp->SetParameter(0,1);
    ppp->SetParameter(1,0.4);
     
    TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY);
    gr->SetLineColor(color[ch % NCOLORS]);
    cout << "color: " << color[ch % NCOLORS] << endl;
    gr->SetLineWidth(2);
    gr->SetMarkerStyle(7);
    gr->Fit("ppp","R0","Q0",0.045,2.0);
    TF1 *afit = (TF1 *)gr->GetFunction("ppp");
    Double_t aRate = 1/afit->GetParameter(1);  
    if (aRate > 0) {
      hRate->Fill(aRate);
    }
    gr->GetXaxis()->SetTitle("Run Date");
    gr->GetYaxis()->SetTitle("Rate [kHz]");

    stringstream entryName, fileName;
    entryName << "Channel" << ch;
    gr->SetTitle(entryName.str().c_str());
    fileName << "plots/" << ch << ".png";
    legend->AddEntry(gr, entryName.str().c_str());
    gr->Draw("alp");
    c1->SaveAs(fileName.str().c_str());
    mg->Add(gr);
    cout << "added plot to mg\n";
    fin.clear();
    fin.seekg(0, ios::beg);
  } // loop over channel
  hRate->Draw();
  hRate->Fit("gaus");
  c1->SaveAs("hrate.pdf");
  mg->Draw("alp");
  mg->GetXaxis()->SetTitle("Days since first run");
  mg->GetYaxis()->SetTitle("Rate [kHz]");
  mg->SetTitle("All channels: Rate vs. Days since first Run");

  legend->Draw();
  c1->SaveAs("mg.pdf");
  
}
Example #24
0
void acc_media(){

	TRandom3 rndgen;

  //efficienze
  //  float eps1 [3][3] = {{0.612,0.662,0.762},{0.425,0.470,0.612},{0.574,0.618,0.722}};
	double  rxmax, rymax, rD12, rD23, reps1, reps2, reps3; 
  float eps1 = 0.745;
  float s_eps1 = 0.003;
  float eps2 = 0.5658;
  float s_eps2 = 0.003;
  float eps3 = 0.6066;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_media.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      reps1 = rndgen.Gaus(eps1,s_eps1); //inserire distribuzione corretta
      reps2 = rndgen.Gaus(eps2,s_eps2);
      reps3 = rndgen.Gaus(eps3,s_eps3);
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);
      
	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1 && W2 < reps2 && W3 < reps3){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
Example #25
0
void EventFlow( TString Sig_name = "ALL", TString Bac_name = "/fdata/hepx/store/user/lpernie/Hhh/delphes_tt_4M_PU40_WtobtaumuALL_13May.root", TString Out="plots" ){

  TCanvas* myc1 = new TCanvas("myc1", "CMS", 600, 600);
  gStyle->SetOptStat(0);
  if(false){
  //Opening Inputs
  cout<<"Hello, I'm creating computing the EventFlow."<<endl;
  std::vector<TString> samples; samples.clear();
  if(Sig_name=="ALL"){
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B1_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B2_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B3_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B4_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B5_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B6_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B7_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B8_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B9_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B10_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B11_1M_PU40ALL_13May.root");
    samples.push_back("/fdata/hepx/store/user/lpernie/Hhh/delphes_B12_1M_PU40ALL_13May.root");
  }
  else samples.push_back(Sig_name);

  //Loop on the samples
  vector<float> AbsEff_s, N_s;
  AbsEff_s.clear(); N_s.clear();
  for(unsigned int j=0; j<samples.size(); j++ ){
    TString Comm = "mkdir -p " + Out;
    system( Comm.Data() );
    //Opening files
    cout<<"------------------- OPENING "<<samples[j]<<"-------------------------"<<endl;
    TFile* f_Sig = TFile::Open(samples[j].Data());
    if( !f_Sig ) cout<<"Waring! File: "<<samples[j]<<" not present!"<<endl;
    TFile* f_Bac = TFile::Open(Bac_name.Data());
    if( !f_Bac ) cout<<"Waring! File: "<<Bac_name<<" not present!"<<endl;
    TTree *T_Sig = (TTree*) f_Sig->Get("evtree");
    if( !T_Sig ) cout<<"Waring! TTree evtree in "<<samples[j]<<" not present!"<<endl;
    TTree *T_Bac = (TTree*) f_Bac->Get("evtree");
    if( !T_Bac ) cout<<"Waring! TTree evtree in "<<Bac_name<<" not present!"<<endl;
    //Get Weight
    TH1F *hW = new TH1F("hW","", 1000, 0., 50.);
    float NEntries_S = T_Sig->Draw("weight>>hW","weight>0","goff");
    float weight_S = hW->GetMean();
    float NEntries_B = T_Bac->Draw("weight>>hW","weight>0","goff");
    float weight_B = 3.40301;//hW->GetMean();
    cout<<"Signal: "<<samples[j]<<" has: "<<NEntries_S<<" * "<<weight_S<<" events = "<<NEntries_S*weight_S<<endl;
    cout<<"Background: "<<Bac_name<<" has: "<<NEntries_B<<" * "<<weight_B<<" events = "<<NEntries_B*weight_B<<endl;
    //Event Flow. (preselections = "hasRECOjet1 && hasRECOjet1 && hasMET && hastwomuons && hasdRljet)
    TString selection = "";
    int nCuts = 6;
    //TString B_tag = "(hasb1jet || hasb2jet)";
    TString B_tag = "(((b1jet_btag&2)>0 && (b2jet_btag&3)>0) || ((b1jet_btag&3)>0 && (b 2jet_btag&2)>0))";
    TString Cuts[]={"hasRECOjet1 && hasRECOjet2 && hasMET && hastwomuons",B_tag,"dR_l1l2<3.3 && dR_l1l2>0.07","dR_b1b2<5.","mass_l1l2<100 && mass_l1l2>5.","mass_b1b2>22"};
    TString Cuts_S[]={"Preselection","B-tag","$\\Delta$R(l1l2)","$\\Delta$R(b1b2)","m(l1l2)","m(b1b2)"};
    float nEv_S[nCuts], nEv_B[nCuts];
    for( int i=0; i<nCuts; i++){
	if( i==0 ){
	  selection = Cuts[i];
	  cout<<"\\begin{table}[h]"<<endl;
	  cout<<"\\centering"<<endl;
	  cout<<" \\begin{tabular}{c|c|c|c|c|c|c}"<<endl;
	  cout<<"   \\hline"<<endl;
	  cout<<"   Cut & N$_S$ & Abs$_{Eff}$ & Rel$_{Eff}$ & N$_B$ & Abs$_{Eff}$ & Rel$_{Eff}$\\\\"<<endl;
	  cout<<"   \\hline"<<endl;
	}
	else selection += ( " && " + Cuts[i]);
	TH1F *hs = new TH1F("hs","",100,0.,100);
	TH1F *hb = new TH1F("hb","",100,0.,100);
	T_Sig->Draw( "weight>>hs", "reweighting * (" + selection + ")", "goff" );
	T_Bac->Draw( "weight>>hb", "reweighting * (" + selection + ")", "goff" );
	nEv_S[i] = hs->Integral();
	nEv_B[i] = hb->Integral();
	delete hs;
	delete hb;
	if(i==1) cout<<Cuts_S[i]<<" & "<<nEv_S[i]*weight_S<<" & "<<"1"<<" & "<<"1"<<" & "<<nEv_B[i]*weight_B<<" & "<<"1"<<" & "<<"1"<<"\\\\"<<endl;
	if(i>1)  cout<<Cuts_S[i]<<" & "<<nEv_S[i]*weight_S<<" & "<<nEv_S[i]/nEv_S[1]<<" & "<<nEv_S[i]/nEv_S[i-1]<<" & "<<nEv_B[i]*weight_B<<" & "<<nEv_B[i]/nEv_B[1]<<" & "<<nEv_B[i]/nEv_B[i-1]<<"\\\\"<<endl;
	if(i==nCuts-1){
	  cout<<"   \\hline"<<endl;
	  cout<<" \\end{tabular}"<<endl;
	  cout<<"\\end{table}"<<endl;
	  AbsEff_s.push_back(nEv_S[i]/nEv_S[1]);
	  N_s.push_back(nEv_S[i]*weight_S);
	}
    }
  }// for samples

  TH1F *h_eff_abs = new TH1F( "h_eff_abs", "", int(samples.size()), 0, int(samples.size()) );
  TH1F *h_n_s = new TH1F( "h_n_s", "", int(samples.size()), 0, int(samples.size()) );
  for(unsigned int i=0; i<samples.size(); i++){
    h_eff_abs->SetBinContent( i+1, AbsEff_s[i] );
    h_n_s->SetBinContent( i+1, N_s[i] );
  }
  h_eff_abs->SetMinimum(0.9); h_eff_abs->GetXaxis()->SetTitle("Signal Sample"); h_eff_abs->GetYaxis()->SetTitle("Efficiency");
  h_eff_abs->Draw();
  myc1->SaveAs( Out + "/eff.pdf" );
  h_n_s->GetXaxis()->SetTitle("Signal Sample"); h_n_s->GetYaxis()->SetTitle("Events expected in 300 fb-1");
  h_n_s->Draw();
  myc1->SaveAs( Out + "/Nsig.pdf" );
  }
  //Sensitivity
  float Masses[26] = {250, 257,259, 340,342, 351,353, 414,416, 454,456, 510,512, 562,564, 603,604, 660,662, 713,715, 766,778, 839,841, 900};
  Int_t   Binnum = sizeof(Masses)/sizeof(Float_t) - 1;
  TH1F *h_sens = new TH1F( "h_sens", "", Binnum, Masses );
  h_sens->SetMarkerStyle(34);
  h_sens->SetMarkerColor(kBlue);
  h_sens->SetBinContent( 2, 2.31635);
  h_sens->SetBinContent( 4, 1.10901);
  h_sens->SetBinContent( 6, 0.934016);
  h_sens->SetBinContent( 8, 0.839262);
  h_sens->SetBinContent( 10, 1.17605);
  h_sens->SetBinContent( 12, 0.961658);
  h_sens->SetBinContent( 14, 0.733404);
  h_sens->SetBinContent( 16, 0.782335);
  h_sens->SetBinContent( 18, 0.918227);
  h_sens->SetBinContent( 20, 0.315506);
  h_sens->SetBinContent( 22, 0.0711883);
  h_sens->SetBinContent( 24, 0.018855);
  h_sens->SetMinimum(0.); h_sens->GetXaxis()->SetTitle("Signal Mass [GeV]"); h_sens->GetYaxis()->SetTitle("Sensitivity");
  h_sens->Draw("P");
  TH1F *h_sensCut = new TH1F( "h_sensCut", "", Binnum, Masses );
  h_sensCut->SetMarkerStyle(34);
  h_sensCut->SetMarkerColor(kRed);
  h_sensCut->SetBinContent( 2, 4.42847);
  h_sensCut->SetBinContent( 4, 2.16941);
  h_sensCut->SetBinContent( 6, 1.86745);
  h_sensCut->SetBinContent( 8, 1.80996);
  h_sensCut->SetBinContent( 10, 2.57802);
  h_sensCut->SetBinContent( 12, 2.47399);
  h_sensCut->SetBinContent( 14, 1.04581);
  h_sensCut->SetBinContent( 16, 1.55697);
  h_sensCut->SetBinContent( 18, 2.21026);
  h_sensCut->SetBinContent( 20, 0.225977);
  h_sensCut->SetBinContent( 22, 0.258508);
  h_sensCut->SetBinContent( 24, 0.0567165);
  h_sensCut->SetMinimum(0.); h_sensCut->GetXaxis()->SetTitle("Signal Mass [GeV]"); h_sensCut->GetYaxis()->SetTitle("Sensitivity");
  //h_sensCut->Draw("sameP");

  myc1->SaveAs( Out + "/Sens.pdf" );
}
Example #26
0
void plot1d(int hid) {
  gStyle->SetOptStat(0);
  char c[50];
  c1->Clear();  
  if(m1dHist[hid]==0){ 
    c1->Divide(2,2); 
    for(int quad=0; quad<kFgtNumQuads; quad++){
      TVirtualPad* pad1 = c1->cd(quad+1); 
      pad1->SetLogy(l1dHist[hid]);
      double xmin, xmax, ymin=0.0, ymax=0.0;
      if(l1dHist[hid]==1) ymin=0.1;
      for(int disc=0; disc<kFgtNumDiscs; disc++){
	sprintf(c,"%1d%1s-%s",disc+1,cquad[quad],c1dHist[hid]);
	//printf("Getting %s\n",c);
	TH1F *h = hist1[disc][quad][hid] = (TH1F*)file->Get(c);
	xmin=h->GetXaxis()->GetXmin();
	xmax=h->GetXaxis()->GetXmax();
	double m=h->GetMaximum();
	if(ymax<m) ymax=m;
	printf("disc=%d max=%6.1f ymax=%6.1f xmin=%6.1f xmax=%6.1f\n",disc+1,m,ymax,xmin,xmax);
      }
      sprintf(c,"Quad%1s-%s",cquad[quad],c1dHist[hid]);
      TH2F *frame = new TH2F(c,c,1,xmin,xmax,1,ymin,ymax*1.2); frame->SetStats(0); frame->Draw();
      for(int disc=0; disc<kFgtNumDiscs; disc++){
	TH1F *h=hist1[disc][quad][hid];
	h->SetLineColor(color[disc]); h->SetLineWidth(3); h->Draw("SAME");  
	if(f1dHist[hid]==0){
	  float mean=h->GetMean();
	  sprintf(c,"%1d%s mean=%6.2f",disc+1,cquad[quad],mean);
	}else if(f1dHist[hid]==1){	  
	  int res = h->Fit("gaus","0Q");
	  TF1 *f = h->GetFunction("gaus");
	  float sig = f->GetParameter(2);	
	  if(res==0 && sig>0.0001 && h->GetEntries()>5){
	    f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME");
	    sprintf(c,"%1d%s sig=%6.3f",disc+1,cquad[quad],sig);
	  }else{
	    sprintf(c,"%1d%s",disc+1,cquad[quad]);
	  }
	}else if(f1dHist[hid]==2){	  
	  int res = h->Fit("landau","0Q");
	  TF1 *f = h->GetFunction("landau");
	  float peak = f->GetParameter(1);	
	  if(res==0 && peak>0 && h->GetEntries()>5){
	    f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME");
	    sprintf(c,"%1d%s mpv=%6.0f",disc+1,cquad[quad],peak);
	  }else{
	    sprintf(c,"%1d%s",disc+1,cquad[quad]);
	  }
	}
	TText *t1;
	float x1= 0.2, x2= 0.55;
	float y1=0.8 - 0.07*disc;
	float y2=0.8 - 0.07*(disc-3);
        if(disc<3) { t1 = new TText(x1,y1,c); }
        else       { t1 = new TText(x2,y2,c); }
	t1->SetNDC();
	t1->SetTextSize(0.04); 
	t1->SetTextColor(color[disc]); 
	t1->Draw();
      }
    }
  }else{
    c1->Divide(4,6);
    gStyle->SetOptStat(0);
    gStyle->SetOptTitle(0);
    gStyle->SetOptFit(0);
    for(int disc=0; disc<kFgtNumDiscs; disc++){
      for(int quad=0; quad<kFgtNumQuads; quad++){
	TPad* pad = c1->cd(disc*4+quad+1);
	pad->SetRightMargin(0.01); pad->SetLeftMargin(0.1);
	pad->SetTopMargin(0.01);   pad->SetBottomMargin(0.1);
	pad->SetLogy(l1dHist[hid]);
	sprintf(c,"%1d%1s-%s",disc+1,cquad[quad],c1dHist[hid]);
	TH1F *h = hist1[disc][quad][hid] = (TH1F*)file->Get(c);
	h->SetFillColor(color[disc]);
	h->GetXaxis()->SetLabelSize(0.1);
	h->GetYaxis()->SetLabelSize(0.1);
	h->GetXaxis()->SetNdivisions(205);
	h->Draw();

	if(f1dHist[hid]==0){
	  float mean=h->GetMean();
	  sprintf(c,"%1d%s mean=%6.2f",disc+1,cquad[quad],mean);
	}else if(f1dHist[hid]==1){	  
	  int res = h->Fit("gaus","0Q");
	  TF1 *f = h->GetFunction("gaus");
	  float sig = f->GetParameter(2);	
	  if(res==0 && sig>0.0001 && h->GetEntries()>5){
	    f->SetLineColor(color[disc]); f->SetLineWidth(2); f->Draw("SAME");
	    sprintf(c,"%1d%s sig=%6.3f",disc+1,cquad[quad],sig);
	  }else{
	    sprintf(c,"%1d%s",disc+1,cquad[quad]);
	  }
	}else if(f1dHist[hid]==2){	  
	  int res = h->Fit("landau","0Q");
	  TF1 *f = h->GetFunction("landau");
	  float peak = f->GetParameter(1);	
	  if(res==0 && peak>0 && h->GetEntries()>5){
	    f->SetLineColor(1); f->SetLineWidth(2); f->Draw("SAME");
	    sprintf(c,"%1d%s mpv=%6.0f",disc+1,cquad[quad],peak);
	  }else{
	    sprintf(c,"%1d%s",disc+1,cquad[quad]);
	  }
	  if(hid==8) {mPeakC[disc][quad]=peak;}
	  if(hid==9) {
	    mPeakA[disc][quad]=peak;	    
	    int n=h->GetEntries();
	    if(n>0){
	      float cut=2800;
	      int bin=h->FindBin(cut);
	      int nbin=h->GetNbinsX();
	      float sat=h->Integral(bin,nbin+1);
	      //printf("bin=%d nbin=%d sat=%f\n",bin,nbin,sat);
	      mFracA[disc][quad]=sat/float(n);
	    }
	  }
	  if(hid==11) {mPeakL[disc][quad]=peak;} // printf("LandauPeak=%f\n",peak);}
	}
	TText *t1 = new TText(0.3,0.85,c);
	t1->SetNDC();
	t1->SetTextSize(0.15); 
	t1->SetTextColor(color[disc]); 
	t1->Draw();
      }
    }
  }
  c1->Update();
  save(c1dHist[hid]);
}
Example #27
0
void acc_zone(){

	TRandom3 rndgen;

  //efficienze
    float eps1 [3][3] = {{0.7498,0.729,0.725},{0.746,0.713,0.7336},{0.7833,0.7471,0.7786}};
    float eps2 [3][3] = {{0.6204,0.5303,0.5673},{0.6307,0.5626,0.6080},{0.7440,0.6701,0.7241}};
    float eps3 [3][3] = {{0.5743,0.4255,0.6121},{0.6176,0.4701,0.6620},{0.7229,0.6124,0.7621}};
    double  rxmax, rymax, rD12, rD23, reps1[3][3], reps2[3][3], reps3[3][3];
    int cx1, cx2, cx3, cy1, cy2, cy3;
  float s_eps1 = 0.003;
  float s_eps2 = 0.003;
  float s_eps3 = 0.003;
  double theta, W1,W2,W3, phi,x1,x2,x3,y1,y2,y3;
  int j = 0;
  
 TH1F* hacc = new TH1F("a","Distribuzione accettanza; a; # esperimenti", 100, 0.2, 0.3);
 TH1F* haccA = new TH1F("aA","Distribuzione accettanza; aA (cm^2); # esperimenti", 100, 400, 600);

 TFile rfile("accettanza_zone.root","RECREATE");

  for (int a = 1; a <= nexp; a++) { 
    cout << "Experiment n. " << a << ": " << endl;
      rxmax = xmax + rndgen.Uniform(2*s_xmax)-s_xmax;
      rymax = ymax + rndgen.Uniform(2*s_ymax)-s_ymax;
      rD12 = D12 + rndgen.Uniform(2*s_D12)-s_D12;
      rD23 = D23 + rndgen.Uniform(2*s_D23)-s_D23;
      for (int m = 0; m < 3; m++) {
	for (int n = 0; n < 3; n++) {
	  reps1[m][n] = rndgen.Gaus(eps1[m][n],s_eps1); //inserire distribuzione corretta
	  reps2[m][n] = rndgen.Gaus(eps2[m][n],s_eps2);
	  reps3[m][n] = rndgen.Gaus(eps3[m][n],s_eps3);
	}
      }
    for (int i = 1; i <= imax;) {
            
      theta = rndgen.Uniform(2*atan(1.)); 
      W1 = rndgen.Uniform(1);
      if (sin(theta)*pow(cos(theta),2) > W1) { // distribuzione: cos^2(theta) dcos(theta)
	i+=1;
	//	if (i%int(double(imax)/10) == 0) cout << double(i)/double(imax)*100 << "%" << endl;
	phi = rndgen.Uniform(8*atan(1.));
	x2 = (rndgen.Uniform(rxmax)-rxmax/2.);
	y2 = (rndgen.Uniform(rymax)-rymax/2.);
	x1 = tan(theta)*cos(phi)*rD12 + x2;
	y1 = tan(theta)*sin(phi)*rD12 + y2;
	x3 = -tan(theta)*cos(phi)*rD23+x2;
	y3 = -tan(theta)*sin(phi)*rD23 + y2;
	W1 = rndgen.Uniform(1);
	W2 = rndgen.Uniform(1);
	W3 = rndgen.Uniform(1);

	cx1 = cell(x1,rxmax);
	cx2 = cell(x2,rxmax);
	cx3 = cell(x3,rxmax);
	cy1 = cell(y1,rymax);
	cy2 = cell(y2,rymax);
	cy3 = cell(y3,rymax);

	if ((pow(x1,2) <= pow(rxmax,2)/4) && (pow(y1,2) <= pow(rymax,2)/4) && (pow(x3,2) <= pow(rxmax,2)/4) && (pow(y3,2) <= pow(rymax,2)/4) && W1 < reps1[cx1][cy1] && W2 < reps2[cx2][cy2] && W3 < reps3[cx3][cy3]){
	  
	  j+=1;}
      }
    }

    cout << "Generati: " << imax << endl;
    cout << "Accettati: " << j << endl;
    cout << "Accettanza: " << double(j)/double(imax) << endl;
hacc->Fill(double(j)/double(imax));   
haccA->Fill(double(j)/double(imax)*rxmax*rymax); //le moltiplico anche per l'area perché nel flusso accettanza e area compaiono insieme
    j = 0;
  }
  cout << "Accettanza media: " << hacc->GetMean()*xmax*ymax << endl;
  hacc->Write();
  haccA->Write();
}
Example #28
0
Bool_t CheckESD(const char* gAliceFileName = "galice.root", 
		const char* esdFileName = "AliESDs.root")
{
// check the content of the ESD
 
  // check values
  Int_t    checkNGenLow = 1;

  Double_t checkEffLow = 0.5;
  Double_t checkEffSigma = 3;
  Double_t checkFakeHigh = 0.5;
  Double_t checkFakeSigma = 3;

  Double_t checkResPtInvHigh = 5;
  Double_t checkResPtInvSigma = 3;
  Double_t checkResPhiHigh = 10;
  Double_t checkResPhiSigma = 3;
  Double_t checkResThetaHigh = 10;
  Double_t checkResThetaSigma = 3;

  Double_t checkPIDEffLow = 0.5;
  Double_t checkPIDEffSigma = 3;
  Double_t checkResTOFHigh = 500;
  Double_t checkResTOFSigma = 3;

  Double_t checkPHOSNLow = 5;
  Double_t checkPHOSEnergyLow = 0.3;
  Double_t checkPHOSEnergyHigh = 1.0;
  Double_t checkEMCALNLow = 50;
  Double_t checkEMCALEnergyLow = 0.05;
  Double_t checkEMCALEnergyHigh = 1.0;

  Double_t checkMUONNLow = 1;
  Double_t checkMUONPtLow = 0.5;
  Double_t checkMUONPtHigh = 10.;

  Double_t cutPtV0 = 0.3;
  Double_t checkV0EffLow = 0.02;
  Double_t checkV0EffSigma = 3;
  Double_t cutPtCascade = 0.5;
  Double_t checkCascadeEffLow = 0.01;
  Double_t checkCascadeEffSigma = 3;

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

  // open the ESD file
  TFile* esdFile = TFile::Open(esdFileName);
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", esdFileName);
    return kFALSE;
  }
  AliESDEvent * esd = new AliESDEvent;
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return kFALSE;
  }
  esd->ReadFromTree(tree);

  // efficiency and resolution histograms
  Int_t nBinsPt = 15;
  Float_t minPt = 0.1;
  Float_t maxPt = 3.1;
  TH1F* hGen = CreateHisto("hGen", "generated tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  TH1F* hRec = CreateHisto("hRec", "reconstructed tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  Int_t nGen = 0;
  Int_t nRec = 0;
  Int_t nFake = 0;

  TH1F* hResPtInv = CreateHisto("hResPtInv", "", 100, -10, 10, 
           "(p_{t,rec}^{-1}-p_{t,sim}^{-1}) / p_{t,sim}^{-1} [%]", "N");
  TH1F* hResPhi = CreateHisto("hResPhi", "", 100, -20, 20, 
			      "#phi_{rec}-#phi_{sim} [mrad]", "N");
  TH1F* hResTheta = CreateHisto("hResTheta", "", 100, -20, 20, 
				"#theta_{rec}-#theta_{sim} [mrad]", "N");

  // PID
  Int_t partCode[AliPID::kSPECIES] = 
    {kElectron, kMuonMinus, kPiPlus, kKPlus, kProton};
  const char* partName[AliPID::kSPECIES+1] = 
    {"electron", "muon", "pion", "kaon", "proton", "other"};
  Double_t partFrac[AliPID::kSPECIES] = 
    {0.01, 0.01, 0.85, 0.10, 0.05};
  Int_t identified[AliPID::kSPECIES+1][AliPID::kSPECIES];
  for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      identified[iGen][iRec] = 0;
    }
  }
  Int_t nIdentified = 0;

  // dE/dx and TOF
  TH2F* hDEdxRight = new TH2F("hDEdxRight", "", 300, 0, 3, 100, 0, 400);
  hDEdxRight->SetStats(kFALSE);
  hDEdxRight->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxRight->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxRight->SetMarkerStyle(kFullCircle);
  hDEdxRight->SetMarkerSize(0.4);
  TH2F* hDEdxWrong = new TH2F("hDEdxWrong", "", 300, 0, 3, 100, 0, 400);
  hDEdxWrong->SetStats(kFALSE);
  hDEdxWrong->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxWrong->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxWrong->SetMarkerStyle(kFullCircle);
  hDEdxWrong->SetMarkerSize(0.4);
  hDEdxWrong->SetMarkerColor(kRed);
  TH1F* hResTOFRight = CreateHisto("hResTOFRight", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  TH1F* hResTOFWrong = CreateHisto("hResTOFWrong", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  hResTOFWrong->SetLineColor(kRed);

  // calorimeters
  TH1F* hEPHOS = CreateHisto("hEPHOS", "PHOS", 100, 0, 50, "E [GeV]", "N");
  TH1F* hEEMCAL = CreateHisto("hEEMCAL", "EMCAL", 100, 0, 50, "E [GeV]", "N");

  // muons
  TH1F* hPtMUON = CreateHisto("hPtMUON", "MUON", 100, 0, 20, 
			      "p_{t} [GeV/c]", "N");

  // V0s and cascades
  TH1F* hMassK0 = CreateHisto("hMassK0", "K^{0}", 100, 0.4, 0.6, 
			      "M(#pi^{+}#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambda = CreateHisto("hMassLambda", "#Lambda", 100, 1.0, 1.2, 
				  "M(p#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambdaBar = CreateHisto("hMassLambdaBar", "#bar{#Lambda}", 
				     100, 1.0, 1.2, 
				     "M(#bar{p}#pi^{+}) [GeV/c^{2}]", "N");
  Int_t nGenV0s = 0;
  Int_t nRecV0s = 0;
  TH1F* hMassXi = CreateHisto("hMassXi", "#Xi", 100, 1.2, 1.5, 
			      "M(#Lambda#pi) [GeV/c^{2}]", "N");
  TH1F* hMassOmega = CreateHisto("hMassOmega", "#Omega", 100, 1.5, 1.8, 
				 "M(#LambdaK) [GeV/c^{2}]", "N");
  Int_t nGenCascades = 0;
  Int_t nRecCascades = 0;

  // loop over events
  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
    runLoader->GetEvent(iEvent);

    // select simulated primary particles, V0s and cascades
    AliStack* stack = runLoader->Stack();
    Int_t nParticles = stack->GetNtrack();
    TArrayF vertex(3);
    runLoader->GetHeader()->GenEventHeader()->PrimaryVertex(vertex);
    TObjArray selParticles;
    TObjArray selV0s;
    TObjArray selCascades;
    for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
      TParticle* particle = stack->Particle(iParticle);
      if (!particle) continue;
      if (particle->Pt() < 0.001) continue;
      if (TMath::Abs(particle->Eta()) > 0.9) continue;
      TVector3 dVertex(particle->Vx() - vertex[0], 
		       particle->Vy() - vertex[1],
		       particle->Vz() - vertex[2]);
      if (dVertex.Mag() > 0.0001) continue;

      switch (TMath::Abs(particle->GetPdgCode())) {
      case kElectron:
      case kMuonMinus:
      case kPiPlus:
      case kKPlus:
      case kProton: {
	if (particle->Pt() > minPt) {
	  selParticles.Add(particle);
	  nGen++;
	  hGen->Fill(particle->Pt());
	}
	break;
      }
      case kK0Short:
      case kLambda0: {
	if (particle->Pt() > cutPtV0) {
	  nGenV0s++;
	  selV0s.Add(particle);
	}
	break;
      }
      case kXiMinus:
      case kOmegaMinus: {
	if (particle->Pt() > cutPtCascade) {
	  nGenCascades++;
	  selCascades.Add(particle);
	}
	break;
      }
      default: break;
      }
    }

    // get the event summary data
    tree->GetEvent(iEvent);
    if (!esd) {
      Error("CheckESD", "no ESD object found for event %d", iEvent);
      return kFALSE;
    }

    // loop over tracks
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfTracks(); iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);

      // select tracks of selected particles
      Int_t label = TMath::Abs(track->GetLabel());
      if (label > stack->GetNtrack()) continue;     // background
      TParticle* particle = stack->Particle(label);
      if (!selParticles.Contains(particle)) continue;
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;
      if (track->GetConstrainedChi2() > 1e9) continue;
      selParticles.Remove(particle);   // don't count multiple tracks

      nRec++;
      hRec->Fill(particle->Pt());
      if (track->GetLabel() < 0) nFake++;

      // resolutions
      hResPtInv->Fill(100. * (TMath::Abs(track->GetSigned1Pt()) - 1./particle->Pt()) * 
		      particle->Pt());
      hResPhi->Fill(1000. * (track->Phi() - particle->Phi()));
      hResTheta->Fill(1000. * (track->Theta() - particle->Theta()));

      // PID
      if ((track->GetStatus() & AliESDtrack::kESDpid) == 0) continue;
      Int_t iGen = 5;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	if (TMath::Abs(particle->GetPdgCode()) == partCode[i]) iGen = i;
      }
      Double_t probability[AliPID::kSPECIES];
      track->GetESDpid(probability);
      Double_t pMax = 0;
      Int_t iRec = 0;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	probability[i] *= partFrac[i];
	if (probability[i] > pMax) {
	  pMax = probability[i];
	  iRec = i;
	}
      }
      identified[iGen][iRec]++;
      if (iGen == iRec) nIdentified++;

      // dE/dx and TOF
      Double_t time[AliPID::kSPECIES];
      track->GetIntegratedTimes(time);
      if (iGen == iRec) {
	hDEdxRight->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFRight->Fill(track->GetTOFsignal() - time[iRec]);
	}
      } else {
	hDEdxWrong->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFWrong->Fill(track->GetTOFsignal() - time[iRec]);
	}
      }
    }

    // loop over muon tracks
    {
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfMuonTracks(); iTrack++) {
      AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
      Double_t ptInv = TMath::Abs(muonTrack->GetInverseBendingMomentum());
      if (ptInv > 0.001) {
	hPtMUON->Fill(1./ptInv);
      }
    }
    }

    // loop over V0s
    for (Int_t iV0 = 0; iV0 < esd->GetNumberOfV0s(); iV0++) {
      AliESDv0* v0 = esd->GetV0(iV0);
      if (v0->GetOnFlyStatus()) continue;
      v0->ChangeMassHypothesis(kK0Short);
      hMassK0->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0);
      hMassLambda->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0Bar);
      hMassLambdaBar->Fill(v0->GetEffMass());

      Int_t negLabel = TMath::Abs(esd->GetTrack(v0->GetNindex())->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(v0->GetPindex())->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      TParticle* particle = stack->Particle(negMother);
      if (!selV0s.Contains(particle)) continue;
      selV0s.Remove(particle);
      nRecV0s++;
    }

    // loop over Cascades
    for (Int_t iCascade = 0; iCascade < esd->GetNumberOfCascades(); 
	 iCascade++) {
      AliESDcascade* cascade = esd->GetCascade(iCascade);
      Double_t v0q;
      cascade->ChangeMassHypothesis(v0q,kXiMinus);
      hMassXi->Fill(cascade->GetEffMassXi());
      cascade->ChangeMassHypothesis(v0q,kOmegaMinus);
      hMassOmega->Fill(cascade->GetEffMassXi());

      Int_t negLabel = TMath::Abs(esd->GetTrack(cascade->GetNindex())
				  ->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(cascade->GetPindex())
				  ->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      Int_t v0Mother = stack->Particle(negMother)->GetMother(0);
      if (v0Mother < 0) continue;
      Int_t bacLabel = TMath::Abs(esd->GetTrack(cascade->GetBindex())
				  ->GetLabel());
      if (bacLabel > stack->GetNtrack()) continue;     // background
      Int_t bacMother = stack->Particle(bacLabel)->GetMother(0);
      if (v0Mother != bacMother) continue;
      TParticle* particle = stack->Particle(v0Mother);
      if (!selCascades.Contains(particle)) continue;
      selCascades.Remove(particle);
      nRecCascades++;
    }

    // loop over the clusters
    {
      for (Int_t iCluster=0; iCluster<esd->GetNumberOfCaloClusters(); iCluster++) {
	AliESDCaloCluster * clust = esd->GetCaloCluster(iCluster);
	if (clust->IsPHOS()) hEPHOS->Fill(clust->E());
	if (clust->IsEMCAL()) hEEMCAL->Fill(clust->E());
      }
    }

  }

  // perform checks
  if (nGen < checkNGenLow) {
    Warning("CheckESD", "low number of generated particles: %d", Int_t(nGen));
  }

  TH1F* hEff = CreateEffHisto(hGen, hRec);

  Info("CheckESD", "%d out of %d tracks reconstructed including %d "
	 "fake tracks", nRec, nGen, nFake);
  if (nGen > 0) {
    // efficiency
    Double_t eff = nRec*1./nGen;
    Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGen);
    Double_t fake = nFake*1./nGen;
    Double_t fakeError = TMath::Sqrt(fake*(1.-fake) / nGen);
    Info("CheckESD", "eff = (%.1f +- %.1f) %%  fake = (%.1f +- %.1f) %%",
	 100.*eff, 100.*effError, 100.*fake, 100.*fakeError);

    if (eff < checkEffLow - checkEffSigma*effError) {
      Warning("CheckESD", "low efficiency: (%.1f +- %.1f) %%", 
	      100.*eff, 100.*effError);
    }
    if (fake > checkFakeHigh + checkFakeSigma*fakeError) {
      Warning("CheckESD", "high fake: (%.1f +- %.1f) %%", 
	      100.*fake, 100.*fakeError);
    }

    // resolutions
    Double_t res, resError;
    if (FitHisto(hResPtInv, res, resError)) {
      Info("CheckESD", "relative inverse pt resolution = (%.1f +- %.1f) %%",
	   res, resError);
      if (res > checkResPtInvHigh + checkResPtInvSigma*resError) {
	Warning("CheckESD", "bad pt resolution: (%.1f +- %.1f) %%", 
		res, resError);
      }
    }

    if (FitHisto(hResPhi, res, resError)) {
      Info("CheckESD", "phi resolution = (%.1f +- %.1f) mrad", res, resError);
      if (res > checkResPhiHigh + checkResPhiSigma*resError) {
	Warning("CheckESD", "bad phi resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    if (FitHisto(hResTheta, res, resError)) {
      Info("CheckESD", "theta resolution = (%.1f +- %.1f) mrad", 
	   res, resError);
      if (res > checkResThetaHigh + checkResThetaSigma*resError) {
	Warning("CheckESD", "bad theta resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    // PID
    if (nRec > 0) {
      Double_t eff = nIdentified*1./nRec;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nRec);
      Info("CheckESD", "PID eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkPIDEffLow - checkPIDEffSigma*effError) {
	Warning("CheckESD", "low PID efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    printf("%9s:", "gen\\rec");
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      printf("%9s", partName[iRec]);
    }
    printf("\n");
    for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
      printf("%9s:", partName[iGen]);
      for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
	printf("%9d", identified[iGen][iRec]);
      }
      printf("\n");
    }

    if (FitHisto(hResTOFRight, res, resError)) {
      Info("CheckESD", "TOF resolution = (%.1f +- %.1f) ps", res, resError);
      if (res > checkResTOFHigh + checkResTOFSigma*resError) {
	Warning("CheckESD", "bad TOF resolution: (%.1f +- %.1f) ps", 
		res, resError);
      }
    }

    // calorimeters
    if (hEPHOS->Integral() < checkPHOSNLow) {
      Warning("CheckESD", "low number of PHOS particles: %d", 
	      Int_t(hEPHOS->Integral()));
    } else {
      Double_t mean = hEPHOS->GetMean();
      if (mean < checkPHOSEnergyLow) {
	Warning("CheckESD", "low mean PHOS energy: %.1f GeV", mean);
      } else if (mean > checkPHOSEnergyHigh) {
	Warning("CheckESD", "high mean PHOS energy: %.1f GeV", mean);
      }
    }

    if (hEEMCAL->Integral() < checkEMCALNLow) {
      Warning("CheckESD", "low number of EMCAL particles: %d", 
	      Int_t(hEEMCAL->Integral()));
    } else {
      Double_t mean = hEEMCAL->GetMean();
      if (mean < checkEMCALEnergyLow) {
	Warning("CheckESD", "low mean EMCAL energy: %.1f GeV", mean);
      } else if (mean > checkEMCALEnergyHigh) {
	Warning("CheckESD", "high mean EMCAL energy: %.1f GeV", mean);
      }
    }

    // muons
    if (hPtMUON->Integral() < checkMUONNLow) {
      Warning("CheckESD", "low number of MUON particles: %d", 
	      Int_t(hPtMUON->Integral()));
    } else {
      Double_t mean = hPtMUON->GetMean();
      if (mean < checkMUONPtLow) {
	Warning("CheckESD", "low mean MUON pt: %.1f GeV/c", mean);
      } else if (mean > checkMUONPtHigh) {
	Warning("CheckESD", "high mean MUON pt: %.1f GeV/c", mean);
      }
    }

    // V0s
    if (nGenV0s > 0) {
      Double_t eff = nRecV0s*1./nGenV0s;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenV0s);
      if (effError == 0) effError = checkV0EffLow / TMath::Sqrt(1.*nGenV0s);
      Info("CheckESD", "V0 eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkV0EffLow - checkV0EffSigma*effError) {
	Warning("CheckESD", "low V0 efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    // Cascades
    if (nGenCascades > 0) {
      Double_t eff = nRecCascades*1./nGenCascades;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenCascades);
      if (effError == 0) effError = checkV0EffLow / 
			   TMath::Sqrt(1.*nGenCascades);
      Info("CheckESD", "Cascade eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkCascadeEffLow - checkCascadeEffSigma*effError) {
	Warning("CheckESD", "low Cascade efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }
  }

  // draw the histograms if not in batch mode
  if (!gROOT->IsBatch()) {
    new TCanvas;
    hEff->DrawCopy();
    new TCanvas;
    hResPtInv->DrawCopy("E");
    new TCanvas;
    hResPhi->DrawCopy("E");
    new TCanvas;
    hResTheta->DrawCopy("E");
    new TCanvas;
    hDEdxRight->DrawCopy();
    hDEdxWrong->DrawCopy("SAME");
    new TCanvas;
    hResTOFRight->DrawCopy("E");
    hResTOFWrong->DrawCopy("SAME");
    new TCanvas;
    hEPHOS->DrawCopy("E");
    new TCanvas;
    hEEMCAL->DrawCopy("E");
    new TCanvas;
    hPtMUON->DrawCopy("E");
    new TCanvas;
    hMassK0->DrawCopy("E");
    new TCanvas;
    hMassLambda->DrawCopy("E");
    new TCanvas;
    hMassLambdaBar->DrawCopy("E");
    new TCanvas;
    hMassXi->DrawCopy("E");
    new TCanvas;
    hMassOmega->DrawCopy("E");
  }

  // write the output histograms to a file
  TFile* outputFile = TFile::Open("check.root", "recreate");
  if (!outputFile || !outputFile->IsOpen()) {
    Error("CheckESD", "opening output file check.root failed");
    return kFALSE;
  }
  hEff->Write();
  hResPtInv->Write();
  hResPhi->Write();
  hResTheta->Write();
  hDEdxRight->Write();
  hDEdxWrong->Write();
  hResTOFRight->Write();
  hResTOFWrong->Write();
  hEPHOS->Write();
  hEEMCAL->Write();
  hPtMUON->Write();
  hMassK0->Write();
  hMassLambda->Write();
  hMassLambdaBar->Write();
  hMassXi->Write();
  hMassOmega->Write();
  outputFile->Close();
  delete outputFile;

  // clean up
  delete hGen;
  delete hRec;
  delete hEff;
  delete hResPtInv;
  delete hResPhi;
  delete hResTheta;
  delete hDEdxRight;
  delete hDEdxWrong;
  delete hResTOFRight;
  delete hResTOFWrong;
  delete hEPHOS;
  delete hEEMCAL;
  delete hPtMUON;
  delete hMassK0;
  delete hMassLambda;
  delete hMassLambdaBar;
  delete hMassXi;
  delete hMassOmega;

  delete esd;
  esdFile->Close();
  delete esdFile;

  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

  // result of check
  Info("CheckESD", "check of ESD was successfull");
  return kTRUE;
}
void GetRebalanceCorrectionFactor()
{
   gROOT->ProcessLine(".L /afs/desy.de/user/c/csander/xxl-af-cms/CMSSW_7_2_3_patch1/src/macros/PlottingUtils.C+");

   SetPlotStyle();

   // --- define output file for ps ---//
   TString pt = "pt10";
   double x_min = 10.;

   TString outfile = "RebalanceCorrectionFactor/RebalanceCorrectionFactors_madgraph_phys14_withoutPUReweighting_" + pt;

   TH2F* RebCorrection_vsReco = new TH2F("RebCorrection_vsReco", "Jet pt", 1000, 0., 1000., 100, 0., 3.);
   
   string root_file;

   // madgraph
   ifstream myfile ("filelists_phys14/filelist_madgraph_phys14_v1.txt");
   if (myfile.is_open()) {
      while( myfile.good() ) {
         getline (myfile,root_file);
         cout << root_file << endl;
                     
         TH2F* RebCorrection_vsReco_temp; 
               
         TString path = root_file;

         TFile* input_file = TFile::Open(path, "READ");
         input_file->cd("QCDfromSmearing");

         gDirectory->GetObject("RebCorrection_vsReco;1", RebCorrection_vsReco_temp);
         RebCorrection_vsReco->Add(RebCorrection_vsReco_temp);

         input_file->Close();
         
      }
      myfile.close();
   }

   // ---------------------------------------------------- //
   // madgraph
   TH1F* correction_vsReco = new TH1F();
   correction_vsReco = (TH1F*) RebCorrection_vsReco->ProjectionX();
   correction_vsReco->Reset();
   for (int i = 0; i <= RebCorrection_vsReco->GetXaxis()->GetNbins(); ++i) {
      TH1F h = *((TH1F*) RebCorrection_vsReco->ProjectionY("py", i, i));
            
      double mean = h.GetMean();
      double error = h.GetMeanError();

      cout << "i: " << i << " " << "mean: " << mean << " " << "error: " << error << endl;
            
      correction_vsReco->SetBinContent(i, mean);
      correction_vsReco->SetBinError(i, error);
   }

   // ---------------------------------------------------- //

   TCanvas *c = new TCanvas("c", "", CanvasPlot[2], CanvasPlot[3]);
   correction_vsReco->SetAxisRange(x_min, correction_vsReco->GetXaxis()->GetXmax());
   correction_vsReco->SetXTitle("reco jet p_{T} [GeV]");
   correction_vsReco->SetYTitle("reb jet p_{T} / gen jet p_{T} ");
   correction_vsReco->Draw();

   TPaveText* pt1 = CMSLabelMC("4.0");
   pt1->Draw();

   c->Print(outfile + "_vsReco.ps");  
   c->Print(outfile + "_vsReco.png"); 

   // ---------------------------------------------------- //

   TFile* RebalanceCorrection = new TFile(outfile + ".root", "RECREATE");
   correction_vsReco->Write();

   RebalanceCorrection->Write();
}
Example #30
0
int main(int argc, char *argv[]) {

  // make sure command line arguments were supplied
  if (argc != 6) { cerr << "Usage: " << argv[0] << " [reference.root] [new-comparison.root] [root dir] [new-release] [old-release] \n"; return 1; }

  // create the comparison class
  PlotCompareUtility *pc = new PlotCompareUtility(argv[1],argv[2],argv[3],"METTask_");
  HistoData *hd;

  if (pc->GetStatus() != 0) { cout << "Final Result: no_data" << endl; return 0; }

  // add histogram information
  //Type = 0 (Do not rebin or zoom) , 1 (Rebin and Zoom, x-axis > 0 ) , 2 (Rebin and Zoom)
  hd = pc->AddHistoData("MET"); hd->SetType(1);
  hd = pc->AddHistoData("METPhi"); hd->SetType(2);
  hd = pc->AddHistoData("METSig"); hd->SetType(1);
  hd = pc->AddHistoData("MEx"); hd->SetType(2);
  hd = pc->AddHistoData("MEy"); hd->SetType(2);
  hd = pc->AddHistoData("SumET"); hd->SetType(2);

  if (pc->GetStatus() != 0) { cerr << "error encountered, exiting.\n"; return pc->GetStatus(); }

  int num_histos = pc->GetNumHistos();
  bool combinedFailed = false;
  float threshold = KS_TEST ?  pc->GetKSThreshold() : pc->GetChi2Threshold(); 

    // get the reference and comparison histograms
  int Nevents_ref = ((TH1F *)pc->GetRefHisto("Nevents"))->GetEntries();
  int Nevents_new = ((TH1F *)pc->GetNewHisto("Nevents"))->GetEntries();
  int Nevents = -1;
  if (Nevents_ref>Nevents_new) Nevents = Nevents_ref;
  else Nevents = Nevents_new;

  // create summary histograms
  TH1F h1dResults_passed("h1dResults_passed","",num_histos, 1, num_histos + 1);
  TH1F h1dResults_failed("h1dResults_failed","",num_histos, 1, num_histos + 1);

  // loop over the supplied list of histograms for comparison
  for (int index = 0; index < pc->GetNumHistos(); index++) {

    int number = index + 1;
    hd = pc->GetHistoData(number);
    //int type = hd->GetType();
    //types[index] = type;
    string name = hd->GetName();
    //string value = hd->GetValueX();
    cout << name << endl;

    // get the reference and comparison histograms
    TH1F *href = (TH1F *)pc->GetRefHisto(name);
    TH1F *hnew = (TH1F *)pc->GetNewHisto(name);


    // ignore if histogram is empty
    if (hnew->GetEntries() <= 1 || href->GetEntries() <= 1) {
      cerr << name << " error: no entries"; combinedFailed = true; continue;
    }

    // calculate and set range and number of bins
    double h1RMS =  hnew->GetRMS();
    double h2RMS =  href->GetRMS();
    double RMS = TMath::Max(h1RMS, h2RMS);
    double h1Mean =  hnew->GetMean();
    double h2Mean =  href->GetMean();
    double Mean = 0.5 * (h1Mean + h2Mean);
    double Nbins = href->GetNbinsX();
    double min = href->GetXaxis()->GetXmin();
    double max = href->GetXaxis()->GetXmax();
    double dX = max - min;
    double dNdX = 1;
    double NewMin = min;
    double NewMax = max;

    int rebinning = Nbins; 

    if (RMS>0 && hd->GetType() ) 
      {
	dNdX = 100. / ( 10 * RMS);
	NewMin = Mean - 10 * RMS;
	NewMax = Mean + 10 * RMS;
      }
    
    if ((dX * dNdX)>0  && hd->GetType() ) 
      rebinning = (int)(double(Nbins) / (dX * dNdX));
    
    if ( rebinning > 1 && hd->GetType() ) 
      {
	href->Rebin(rebinning);
	hnew->Rebin(rebinning);
      }

    if ( hd->GetType() == 1 )
      { 
	href->GetXaxis()->SetRangeUser(0.0, NewMax);
	hnew->GetXaxis()->SetRangeUser(0.0, NewMax);
      }
    else if ( hd->GetType() == 2 )
      {
	href->GetXaxis()->SetRangeUser(NewMin, NewMax);
	hnew->GetXaxis()->SetRangeUser(NewMin, NewMax);
      }

    // perform statistical tests
    double ks_score = hnew->KolmogorovTest(href,"D");
    double chi2_score = hnew->Chi2Test(href, "p");
    //double result = KS_TEST ? ks_score : chi2_score;
    double result = (ks_score>chi2_score) ? ks_score : chi2_score;
    
      href->SetNormFactor(Nevents_new);     	
      hnew->SetNormFactor(Nevents_new);
    //hnew->SetNormFactor(1);

    // ensure that the peaks of both histograms will be shown by making a dummy histogram
    float Nentries_ref = href->GetEntries();
    float Nentries_new = hnew->GetEntries();
    float XaxisMin_ref = 0, XaxisMax_ref = 0, YaxisMin_ref = 0, YaxisMax_ref = 0;
    float XaxisMin_new = 0, XaxisMax_new = 0, YaxisMin_new = 0, YaxisMax_new = 0;
    if (Nentries_ref>0) YaxisMax_ref = (href->GetMaximum()+TMath::Sqrt(href->GetMaximum()))*(Nentries_new/Nentries_ref);
    if (Nentries_new>0) YaxisMax_new = (hnew->GetMaximum()+TMath::Sqrt(hnew->GetMaximum()));

    XaxisMin_ref = href->GetXaxis()->GetXmin()>NewMin  ? href->GetXaxis()->GetXmin() : NewMin;
    XaxisMax_ref = href->GetXaxis()->GetXmax()<=NewMax ? href->GetXaxis()->GetXmax() : NewMax;
    YaxisMax_ref = (YaxisMax_ref>=YaxisMax_new) ? YaxisMax_ref : YaxisMax_new;

    if (TMath::Abs(XaxisMin_ref - XaxisMax_ref)<1E-6)
      {
	XaxisMin_ref = 0;
	XaxisMax_ref = 1;
      }
    
    TH1F *hdumb = new TH1F("hdumb","", rebinning, XaxisMin_ref, XaxisMax_ref);
    hdumb->SetMinimum(1E-1); //--For Rick
    hdumb->SetMaximum(1.05*YaxisMax_ref);
    //    if (href->GetMaximum() < hnew->GetMaximum())
    //  href->SetAxisRange(0, 1.1 * hnew->GetMaximum(), "Y");
        
    // set drawing options on the reference histogram
    href->SetStats(0);
    href->SetLineWidth(2);
    href->SetLineColor(14);
    href->SetMarkerColor(14);
    href->SetFillColor(17);
    //href->SetFillStyle(3004);
    href->GetXaxis()->SetTitle(name.c_str());
    href->GetYaxis()->SetTitle("Entries");
    href->GetYaxis()->SetTitleOffset(1.5);

    // set drawing options on the new histogram
    hnew->SetStats(0);
    hnew->SetLineWidth(2);
    hnew->SetFillStyle(3001);
    // set drawing options on the dummy histogram
    hdumb->SetStats(0);
    hdumb->GetXaxis()->SetTitle(name.c_str());
    hdumb->GetXaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    hdumb->GetYaxis()->SetTitle("Entries");
    hdumb->GetYaxis()->SetTitleOffset(1.5);
    hdumb->GetYaxis()->SetLabelSize(0.5 * hdumb->GetXaxis()->GetTitleSize());
    
    stringstream ss_title;
    ss_title.precision(5);
    if (ks_score>chi2_score)
      ss_title << "KS Score = " << ks_score;
    else
      ss_title << "Chi^2 Score = " << chi2_score;
    TText canvas_title(0.1,0.97,ss_title.str().c_str());


    // determine if test is a "pass" or a "fail"
    if (result <= threshold) {

      canvas_title.SetTextColor(kRed);

      // make this histogram red to denote failure
      hnew->SetFillColor(kRed);
      hnew->SetLineColor(206);
      hnew->SetMarkerColor(206);

      // mark the entire sample as being 'not-compatible'
      combinedFailed = true;

      // set the summary bin to failed (only need to set titles for passed h1dResults)
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_failed.SetBinContent(number, result);

    } else {

      canvas_title.SetTextColor(kGreen);

      // make this histogram green to denote passing score
      hnew->SetFillColor(kGreen);
      hnew->SetLineColor(103);  
      hnew->SetMarkerColor(103);

      // set the summary bin to passed
      h1dResults_passed.GetXaxis()->SetBinLabel(number, name.c_str());
      h1dResults_passed.SetBinContent(number, result);

    }

    // setup canvas for displaying the compared histograms
    TCanvas histo_c("histo_c","histo_c",785,800);
    histo_c.Draw();

    TPad histo_p("histo_p","histo_p",0,0,1,0.99);
    histo_p.Draw();

    histo_c.cd();
    canvas_title.SetTextSize(0.025);
    canvas_title.Draw();

    histo_p.cd();

    histo_p.SetLogy(1); //--This is just for Dr. Rick
    hdumb->Draw();
    href->Draw("SAME");
    hnew->Draw("SAME");
    hnew->Draw("E1SAME");

      stringstream legend_new;
      stringstream legend_ref;
      legend_new << argv[4] << ": " << Nentries_new << " entries, " << Nevents_new << " events";
      legend_ref << argv[5] << ": " << Nentries_ref << " entries, " << Nevents_ref << " events";		
	
      TLegend l1(0.15,0.001,0.33, 0.06);
      l1.SetTextSize(0.02);
      l1.AddEntry(hnew, legend_new.str().c_str(),"lF");
      l1.AddEntry(href, legend_ref.str().c_str(),"lF");
      l1.SetFillColor(kNone);      
      l1.Draw("SAME");


    // print the result to gif
    string histo_name = name + ".gif";
    histo_c.Print(histo_name.c_str(),"gif");
    cout << "Result of comparison for " << name << ": ks score = " << ks_score << " : chi2 score = " << chi2_score << endl << endl;

  }

  // create summary canvas
  int summary_height = int(780 * float(num_histos) / 11); // 780;
  TCanvas main_c("main_c","main_c",799,summary_height);
  main_c.Draw();

  TPad main_p("main_p","main_p",0.01,0.01,0.99,0.94);
  main_p.SetLeftMargin(0.30);
  main_p.SetBottomMargin(0.15);
  main_p.SetLogx(1);
  main_p.SetGrid();
  main_p.SetFrameFillColor(10);
  main_p.Draw();

  main_c.cd();
  TText summary_title(.01, .95, "");
  summary_title.Draw("SAME");

  main_p.cd();

  // setup the passing test bars
  h1dResults_passed.SetStats(0);
  h1dResults_passed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_passed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_passed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_passed.SetBarWidth(0.7);
  h1dResults_passed.SetBarOffset(0.1);
  h1dResults_passed.SetFillColor(kGreen);
  h1dResults_passed.SetLineColor(1);
  h1dResults_passed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_passed.Draw("hbar0");

  // setup the failing test bars
  h1dResults_failed.SetStats(0);
  h1dResults_failed.GetXaxis()->SetLabelSize(0.06);
  h1dResults_failed.GetYaxis()->SetLabelSize(0.04);
  h1dResults_failed.GetYaxis()->SetTitle("Compatibility");
  h1dResults_failed.SetBarWidth(0.7);
  h1dResults_failed.SetBarOffset(0.1);
  h1dResults_failed.SetFillColor(kRed);
  h1dResults_failed.SetLineColor(1);
  h1dResults_failed.GetYaxis()->SetRangeUser(1E-7,2);
  h1dResults_failed.Draw("hbar0SAME");

  // draw the pass/fail threshold line
  TLine l(threshold, 1, threshold, num_histos+1);
  l.SetLineColor(kRed);
  l.SetLineWidth(2);
  l.SetLineStyle(2);
  l.Draw("SAME"); 

  // print the results
  main_c.Update();
  main_c.Print("AllResults-1dHistoCheck.gif","gif");

  if (combinedFailed) cout << "Final Result: fail" << endl;
  else cout << "Final Result: pass" << endl;

  //delete pc;
  return 0;

}