Ejemplo n.º 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();
    }
  
  
}
Ejemplo n.º 2
0
void GenerateStatErrorMC(double Nt, double Nl, double Nt_err, double Nl_err, double &NtS_err, double &NtZ_err, double Eff, double Fake)
{
  double NtS, NtZ;
  TH1F* htS = new TH1F("htS", "htS", 11000, -100, 1000);
  TH1F* htZ = new TH1F("htZ", "htZ", 11000, -100, 1000);
  
  for(int itest=0; itest<1000; itest++)
  {
    double N_err = 0;
    if(Nt_err<=Nl_err) N_err = sqrt(Nl_err*Nl_err-Nt_err*Nt_err);
    else N_err = sqrt(Nl_err*Nl_err+Nt_err*Nt_err);
    double N_rand=gRandom->Gaus(Nl-Nt, N_err);
    double Nt_rand=gRandom->Gaus(Nt, Nt_err);
    double Nl_rand=N_rand+Nt_rand;
    
    ComputeEstimation(Nt_rand, Nl_rand, NtS, NtZ, Eff, Fake);
    htS->Fill(NtS);
    htZ->Fill(NtZ);
  }
  
  NtS_err = htS->GetRMS();
  NtZ_err = htZ->GetRMS();
  
  cout<<"S MC rms : "<<htS->GetRMS()<<endl;
  cout<<"Z MC rms : "<<htZ->GetRMS()<<endl;

}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
0
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");
}
Ejemplo n.º 5
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
Ejemplo n.º 6
0
void GenerateStatError(double Nt, double Nl, double &NtS_err, double &NtZ_err, double Eff, double Fake)
{
  double NtS, NtZ;
  TH1F* htS = new TH1F("htS", "htS", 11000, -100, 1000);
  TH1F* htZ = new TH1F("htZ", "htZ", 11000, -100, 1000);
  
  for(int itest=0; itest<1000; itest++)
  {
    double N_rand=gRandom->Poisson(Nl-Nt);
    double Nt_rand=gRandom->Poisson(Nt);
    double Nl_rand=N_rand+Nt_rand;
    
    ComputeEstimation(Nt_rand, Nl_rand, NtS, NtZ, Eff, Fake);
    htS->Fill(NtS);
    htZ->Fill(NtZ);
  }
  
  NtS_err = htS->GetRMS();
  NtZ_err = htZ->GetRMS();
  
  cout<<"S rms : "<<htS->GetRMS()<<endl;
  cout<<"Z rms : "<<htZ->GetRMS()<<endl;

}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
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();
    }
}
Ejemplo n.º 9
0
void  PlotAlignmentValidation::plotDMR(const std::string variable, Int_t minHits )
{
 setNiceStyle(); 
 gStyle->SetOptStat(0);

 // TList treeList=getTreeList();

 TCanvas *c = new TCanvas("canv", "canv", 600, 600);
 setCanvasStyle( *c );
 //loop over sub-detectors 
 for (int i=1;i<7;++i){
 
   int histo_Counter=1;
   TLegend *leg_hist = new TLegend(0.17,0.8,0.85,0.88);
   setLegendStyle(*leg_hist);
   //loop over file list
   //TTree *tree= (TTree*)treeList.First();
   //binning
   int nbinsX=100;
   double xmin=0;
   double xmax=0;
   float maxY=0;
   bool isHisto = false;
   std::string plotVar=variable;
   THStack *hstack=new THStack("hstack","hstack");

   for(std::vector<TkOfflineVariables*>::iterator it = sourceList.begin();
       it != sourceList.end(); ++it){
      
     //while ( tree ){
     plotVar=variable;
     TString subdet = "entries>=";
     subdet+=minHits; 
     subdet+=" && subDetId==";
     subdet+=i;
      
     char binning [50]="";
     sprintf (binning, ">>myhisto(%d,  %f , %f)", nbinsX, xmin, xmax);
     TH1F *h = 0;
     
     if (histo_Counter==1&&plotVar=="meanX")(*it)->getTree()->Draw( (plotVar+=">>myhisto(50,-0.001,0.001)").c_str(),subdet,"goff");
     else if (histo_Counter==1&&plotVar=="meanY")(*it)->getTree()->Draw( (plotVar+=">>myhisto(50,-0.005,0.005)").c_str(),subdet,"goff");
     else if (histo_Counter==1&&plotVar=="medianX")(*it)->getTree()->Draw( (plotVar+=">>myhisto(50,-0.005,0.005)").c_str(),subdet,"goff");
     else if (histo_Counter==1&&plotVar=="medianY")(*it)->getTree()->Draw( (plotVar+=">>myhisto(50,-0.005,0.005)").c_str(),subdet,"goff");
     else if (histo_Counter==1&&plotVar=="meanNormX")(*it)->getTree()->Draw( (plotVar+=">>myhisto(100,-2,2)").c_str(),subdet,"goff");
     else if (histo_Counter==1&&plotVar=="rmsX")(*it)->getTree()->Draw( (plotVar+=">>myhisto(100,0.,0.1)").c_str(),subdet,"goff");
     else if (histo_Counter!=1)(*it)->getTree()->Draw( (plotVar+=binning).c_str(),subdet,"goff");

     if (gDirectory) gDirectory->GetObject("myhisto", h);
     std::pair<float,float> fitResults(9999., 9999.);
     if (h){
       if (h->GetEntries()>0) {
	 isHisto = true;
	 h->SetDirectory(0);
	 //general draw options
	 h->SetLineWidth(2);
	 //first histo only, setting optStat...
	 if (histo_Counter==1)
	   setHistStyle(*h,plotVar.c_str() ,"#modules", 1 ); //set color later

	 h->SetLineColor( (*it)->getLineColor() );
	 h->SetLineStyle( (*it)->getLineStyle() );
	   //h->SetMarkerStyle(20+file_Counter);
      
	 //draw options
	 
	 if (maxY<h->GetMaximum()){
	   maxY=h->GetMaximum();
	 }
      
	 //fit histogram for median and mean
	 if (variable=="medianX"||variable =="meanX")fitResults=fitGauss(h, (*it)->getLineColor() );

	 if (histo_Counter==1){
	   //get mean and sigma from fit: gauss for 2sigma range
	   hstack->Add(h);
	   nbinsX=h->GetXaxis()->GetNbins();
	   xmin=h->GetXaxis()->GetXmin();
	   xmax=h->GetXaxis()->GetXmax();
	  
	 }else if (histo_Counter!=1 &&  h->GetEntries()>0)hstack->Add(h);
     
	 char legend [50]="";
	 std::string legEntry = (*it)->getName();
	 if ( (variable=="medianX"||variable =="meanX") && useFit_)
	   sprintf (legend, "%s: #mu = %4.2f#mum, #sigma = %4.2f#mum ",legEntry.c_str(),fitResults.first ,fitResults.second);
	 if ( (variable=="medianX"||variable =="meanX"||variable=="medianY"||variable =="meanY" )&&useFit_ == false)
	   sprintf (legend, "%s: #mu = %4.2f#mum, rms = %4.2f#mum ",legEntry.c_str(),h->GetMean(1)*10000 ,h->GetRMS(1)*10000);
	 else sprintf (legend, "%s ",legEntry.c_str());
	 if(h)
	   leg_hist->AddEntry(h,legend,"l");
	 else
	   std::cerr<< "histogram did not exist!";
       }
     }
     //     tree= (TTree*)treeList.After( tree );
     //     file_Counter++;
     histo_Counter++;
        
   }
    
   if (isHisto){
     hstack->Draw("nostack");
     hstack->SetMaximum(maxY*1.3);
     setTitleStyle(*hstack,plotVar.c_str() ,"#modules",i);
     setHistStyle(*hstack->GetHistogram(),plotVar.c_str() ,"#modules", 1 );
     leg_hist->Draw(); 

     std::string histName="D";
     if (variable=="medianX") histName+="medianR_";
     else if (variable=="medianY") histName+="medianYR_";
     else if (variable=="meanX") histName+="meanR_";
     else if (variable=="meanY") histName+="meanYR_";
     else if (variable=="rmsX") histName+="rmsR_";
     std::string subDetector ="";
     switch (i){
     case 1 : subDetector+="TPB";break;
     case 2 : subDetector+="TPE";break;
     case 3 : subDetector+="TIB";break;
     case 4 : subDetector+="TID";break;
     case 5 : subDetector+="TOB";break;
     case 6 : subDetector+="TEC";break;
     }
 
     char PlotName[100];
     sprintf( PlotName, "%s/%s%s.eps",outputDir.c_str(), histName.c_str(), subDetector.c_str() );
     c->Update(); 
     c->Print(PlotName);
     //c->Update();
     //c->Close();
    
   }
   delete hstack;
   hstack=0; 
  
 }
 
 delete c;
 c=0;
}
Ejemplo n.º 10
0
TCanvas *PlotDataMCMC(TChain *data, TChain *mc, TChain *mc2,
		      TString branchname, TString binning, 
		      TString category, TString selection, 
		      TString dataLabel, TString mcLabel, TString mc2Label,
		      TString xLabel, TString yLabelUnit, 
		      bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, true,0);
  selection_MC+=selection;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  data->Draw(branchNameData+">>data_hist"+binning, selection_data);
  if(mc!=NULL){
    if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  }
  if(mc2!=NULL){
    if(usePU)  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data *"puWeight");
    else  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data);
  }
  

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  TH1F *s2 = (TH1F *) gROOT->FindObject("mc2_hist");
  if(s==NULL){
    std::cerr << "[WARNING] no mc" << std::endl;
    s=d;
  }
  if(s2==NULL){
    std::cerr << "[WARNING] no mc2" << std::endl;
    s2=s;
  }
  std::cout << s->GetEntries() << "\t" << s2->GetEntries() << "\t" << d->GetEntries() << std::endl;

  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  s2->SaveAs("tmp/s2_hist.root");


  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  std::cout << "nEvents signal2: " << s2->Integral() << "\t" << s2->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    s2->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
    s2->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  s2->GetYaxis()->SetTitle(yLabel);
  s2->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }
  if(s2 != s){
    //s2->SetMarkerStyle(1);
    //s2->SetMarkerSize(0);
    //s->SetFillStyle(0);
    //s->SetFillColor(kB);
    s2->SetLineWidth(3);
    s2->SetLineColor(kBlack);
  }


  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  TH1F* s2_norm = (TH1F *) (s2->DrawNormalized("hist same", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation & Simulation2 \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() 
	    << " & " << s2_norm->GetMean() <<  " " << s2_norm->GetMeanError() 
	    << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() 
	    << " & " << s2_norm->GetRMS() << " " << s2_norm->GetRMSError() 
	    << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  if(mc2Label   !="") leg->AddEntry(s2,mc2Label, "l");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.23,0.95,0.6,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Ejemplo n.º 11
0
TCanvas *PlotDataMC(TChain *data, TChain *mc, TString branchname, TString binning, 
		    TString category, TString selection, 
		    TString dataLabel, TString mcLabel, TString xLabel, TString yLabelUnit, 
		    bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  std::cout<<"entering"<<std::endl;
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;

  std::cout<<"entering2"<<std::endl;

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,true);
  selection_data.Print();
  //  return NULL;
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  std::cout<<"qui"<<std::endl;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele ","(energySCEle_regrCorr_ele*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[0]","(energySCEle_regrCorr_ele[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[1]","(energySCEle_regrCorr_ele[1]*corrEle[1])");

  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  if(branchname=="HLT"){
    TH1F *hlt_data = new TH1F("data_hist","",500,0,500);
    TH1F *hlt_mc = new TH1F("mc_hist","",500,0,500);
    
    
    std::vector< std::string > *HLTNames = new std::vector<std::string>; ///< List of HLT names
    std::vector<Bool_t> *HLTResults = new std::vector<Bool_t>;      ///< 0=fail, 1=fire
    
    data->SetBranchAddress("HLTNames", &HLTNames);
    data->SetBranchAddress("HLTResults", &HLTResults);
    
    data->GetEntries();
    for(Long64_t jentry=0; jentry < data->GetEntriesFast(); jentry++){
      data->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_data->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }
    data->ResetBranchAddresses();

    mc->SetBranchAddress("HLTNames", &HLTNames);
    mc->SetBranchAddress("HLTResults", &HLTResults);
    
    mc->GetEntries();
    for(Long64_t jentry=0; jentry < mc->GetEntriesFast(); jentry++){
      mc->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_mc->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }

    for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	hlt_itr!=HLTNames->end();
	hlt_itr++){
      int index=hlt_itr-HLTNames->begin()+1;
      if(hlt_mc->GetBinContent(index)>0)
      hlt_mc->GetXaxis()->SetBinLabel(index,(*hlt_itr).c_str());
    }
  } else {

  std::cout<<"qui"<<std::endl;
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(mc!=NULL){
      if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  std::cout<<"qui"<<std::endl;
    }
  }

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  if(s==NULL) s=d;
  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  std::cout<<"qui"<<std::endl;

  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }

  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.2,0.95,0.7,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Ejemplo n.º 12
0
void drawNoisePlotsMC(TString InputFileName, TString suffix)
{
  TFile* f = TFile::Open(InputFileName.Data(),"READ");
  f -> cd();
  
  
  TH1F* h_occupancy_vsNvtx   = (TH1F*)( f->Get("h_occupancy_vsNvtx_EB") );
  TH1F* h_occupancy_vsNavgPU = (TH1F*)( f->Get("h_occupancy_vsNavgPU_EB") );
  TH1F* h_occupancy_vsIeta   = (TH1F*)( f->Get("h_occupancy_vsIeta_EB") );
  TH1F* h_occupancy_vsIring  = (TH1F*)( f->Get("h_occupancy_vsIring_EE") );
  
  
    
  TGraphErrors* g_RMSNoise_vsNvtx_EB = new TGraphErrors();
  TGraphErrors* g_RMSNoise_vsNvtx_EE = new TGraphErrors();

  TGraphErrors* g_RMSNoise_vsNavgPU_EB = new TGraphErrors();
  TGraphErrors* g_RMSNoise_vsNavgPU_EE = new TGraphErrors();
  
  int point = 0;
  for(int bin = 1; bin <= nBins_nVtx; ++bin)
  {  
    TH1F* histo;
    char histoName[50];
    
    float binCenter  = h_occupancy_vsNvtx -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNvtx -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNvtx -> GetBinLowEdge(bin) + h_occupancy_vsNvtx_EB->GetBinWidth(bin);
    
    if( binCenter < 5. ) continue;
    if( binCenter > 30. ) continue;
        
    sprintf(histoName,"hEB_recHitE_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    histo = (TH1F*)( f->Get(histoName) );
    g_RMSNoise_vsNvtx_EB -> SetPoint(point,binCenter,histo->GetRMS());
    g_RMSNoise_vsNvtx_EB -> SetPointError(point,0.,histo->GetRMSError());
    
    sprintf(histoName,"hEE_recHitE_nVtx%02.1f-%02.1f",binLowEdge,binHigEdge);
    histo = (TH1F*)( f->Get(histoName) );
    g_RMSNoise_vsNvtx_EE -> SetPoint(point,binCenter,histo->GetRMS());
    g_RMSNoise_vsNvtx_EE -> SetPointError(point,0.,histo->GetRMSError());    
    
    ++point;
  }
  
  g_RMSNoise_vsNvtx_EB -> SetPoint(g_RMSNoise_vsNvtx_EB->GetN(),-1.,-1.);
  g_RMSNoise_vsNvtx_EE -> SetPoint(g_RMSNoise_vsNvtx_EE->GetN(),-1.,-1.);
  
  
  
  point = 0;
  for(int bin = 1; bin <= nBins_nAvgPU; ++bin)
  {  
    TH1F* histo;
    char histoName[50];
    
    float binCenter  = h_occupancy_vsNavgPU -> GetBinCenter(bin);
    float binLowEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin);
    float binHigEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin) + h_occupancy_vsNavgPU_EB->GetBinWidth(bin);
    
    if( binCenter < 8. ) continue;
    if( binCenter > 30. ) continue;
        
    sprintf(histoName,"hEB_recHitE_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    histo = (TH1F*)( f->Get(histoName) );
    g_RMSNoise_vsNavgPU_EB -> SetPoint(point,binCenter,histo->GetRMS());
    g_RMSNoise_vsNavgPU_EB -> SetPointError(bin-1,0.,histo->GetRMSError());
    
    sprintf(histoName,"hEE_recHitE_nAvgPU%02.1f-%02.1f",binLowEdge,binHigEdge);
    histo = (TH1F*)( f->Get(histoName) );
    g_RMSNoise_vsNavgPU_EE -> SetPoint(point,binCenter,histo->GetRMS());
    g_RMSNoise_vsNavgPU_EE -> SetPointError(bin-1,0.,histo->GetRMSError());    
    
    ++point;
  }
  
  
  
  
  
  
  TCanvas* c1_RMSNoise_EB = new TCanvas("c1_RMSNoise_EB","EB RMS noise");
  c1_RMSNoise_EB -> cd();
  c1_RMSNoise_EB -> SetGridx();
  c1_RMSNoise_EB -> SetGridy();
  
  g_RMSNoise_vsNvtx_EB -> SetMarkerColor(kRed+2);
  g_RMSNoise_vsNavgPU_EB -> SetMarkerColor(kGreen+2);
  
  g_RMSNoise_vsNvtx_EB -> GetXaxis() -> SetTitle("N_{vtx} or Num^{Int}_{True}");
  g_RMSNoise_vsNvtx_EB -> GetYaxis() -> SetTitle("noise RMS (GeV)");
  g_RMSNoise_vsNvtx_EB -> GetXaxis() -> SetRangeUser(0.,35.);
  g_RMSNoise_vsNvtx_EB -> GetYaxis() -> SetRangeUser(0.040,0.080);
  
  g_RMSNoise_vsNvtx_EB -> Draw("AP");
  g_RMSNoise_vsNavgPU_EB -> Draw("P,same");
  
  TF1* f_pol1_vsNvtx_EB   = new TF1("f_pol1_vsNvtx_EB","[0]+[1]*x",0.,35.);
  f_pol1_vsNvtx_EB -> SetLineColor(kRed+2);
  TF1* f_pol1_vsNavgPU_EB = new TF1("f_pol1_vsNavgPU_EB","[0]+[1]*x",0.,35.);
  f_pol1_vsNavgPU_EB -> SetLineColor(kGreen+2);  
  g_RMSNoise_vsNvtx_EB -> Fit("f_pol1_vsNvtx_EB","QS+","",5.,25.);
  g_RMSNoise_vsNavgPU_EB -> Fit("f_pol1_vsNavgPU_EB","QS+","",10.,25.);
  f_pol1_vsNvtx_EB -> Draw("same");
  f_pol1_vsNavgPU_EB -> Draw("same");
  
  TLegend* legend = new TLegend(0.14, 0.70, 0.60, 0.94);
  legend -> SetFillColor(kWhite);
  legend -> SetFillStyle(0);
  legend -> SetLineWidth(0);
  legend -> SetLineColor(kWhite);
  legend -> SetTextFont(42);  
  legend -> SetTextSize(0.04);
  legend -> AddEntry(g_RMSNoise_vsNvtx_EB,"noise vs N_{vtx}","P");
  legend -> AddEntry(g_RMSNoise_vsNavgPU_EB,"noise vs Num^{Int}_{True}","P");
  legend -> Draw("same");
  
  TString NamePlot = Form("c1_RMSNoise_EB_%s.png",suffix.Data());
  c1_RMSNoise_EB -> SaveAs(NamePlot.Data(),"png");
  
  
  
  TCanvas* c1_RMSNoise_EE = new TCanvas("c1_RMSNoise_EE","EE RMS noise");
  c1_RMSNoise_EE -> cd();
  c1_RMSNoise_EE -> SetGridx();
  c1_RMSNoise_EE -> SetGridy();
  
  g_RMSNoise_vsNvtx_EE -> SetMarkerColor(kRed+2);
  g_RMSNoise_vsNavgPU_EE -> SetMarkerColor(kGreen+2);
    
  g_RMSNoise_vsNvtx_EE -> GetXaxis() -> SetTitle("N_{vtx} or Num^{Int}_{True}");
  g_RMSNoise_vsNvtx_EE -> GetYaxis() -> SetTitle("noise RMS (GeV)");
  g_RMSNoise_vsNvtx_EE -> GetXaxis() -> SetRangeUser(0.,35.);
  g_RMSNoise_vsNvtx_EE -> GetYaxis() -> SetRangeUser(0.20,0.35);
      
  g_RMSNoise_vsNvtx_EE -> Draw("AP");
  g_RMSNoise_vsNavgPU_EE -> Draw("P,same");
  
  TF1* f_pol1_vsNvtx_EE   = new TF1("f_pol1_vsNvtx_EE","[0]+[1]*x",0.,35.);
  f_pol1_vsNvtx_EE -> SetLineColor(kRed+2);
  TF1* f_pol1_vsNavgPU_EE = new TF1("f_pol1_vsNavgPU_EE","[0]+[1]*x",0.,35.);
  f_pol1_vsNavgPU_EE -> SetLineColor(kGreen+2);  
  g_RMSNoise_vsNvtx_EE -> Fit("f_pol1_vsNvtx_EE","QS+","",5.,25.);
  g_RMSNoise_vsNavgPU_EE -> Fit("f_pol1_vsNavgPU_EE","QS+","",10.,25.);
  f_pol1_vsNvtx_EE -> Draw("same");
  f_pol1_vsNavgPU_EE -> Draw("same");
  
  legend -> Draw("same");
 
  NamePlot = Form("c1_RMSNoise_EE_%s.png",suffix.Data());
  c1_RMSNoise_EE -> SaveAs(NamePlot.Data(),"png");
  
  
  
  
  
  
  TGraphErrors* g_noiseAtZero_vsIeta_EB = new TGraphErrors();
  TGraphErrors* g_noiseSlope_vsIeta_EB = new TGraphErrors();
  TGraphErrors* g_addNoise_vsIeta_EB = new TGraphErrors();
  
  for(int iEtaBin = 1; iEtaBin <= nBins_iEta; ++iEtaBin)
  {
    float iEtaBinCenter  = h_occupancy_vsIeta -> GetBinCenter(iEtaBin);
    float iEtaBinLowEdge = h_occupancy_vsIeta -> GetBinLowEdge(iEtaBin);
    float iEtaBinHigEdge = h_occupancy_vsIeta -> GetBinLowEdge(iEtaBin) + h_occupancy_vsIeta_EB->GetBinWidth(bin);
    
    TGraphErrors* g_RMSNoise_vsNavgPU_vsIeta_EB = new TGraphErrors();
    
    int point = 0;
    for(int bin = 1; bin <= nBins_nAvgPU; ++bin)
    {  
      TH1F* histo;
      char histoName[50];
      
      float binCenter  = h_occupancy_vsNavgPU -> GetBinCenter(bin);
      float binLowEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin);
      float binHigEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin) + h_occupancy_vsNavgPU_EB->GetBinWidth(bin);
      
      if( binCenter < 8. ) continue;
      if( binCenter > 30. ) continue;    
      sprintf(histoName,"hEB_recHitE_nAvgPU%02.1f-%02.1f_iEta%02.1f-%02.1f",binLowEdge,binHigEdge,iEtaBinLowEdge,iEtaBinHigEdge);
      histo = (TH1F*)( f->Get(histoName) );
      
      g_RMSNoise_vsNavgPU_vsIeta_EB -> SetPoint(point,binCenter,histo->GetRMS());
      g_RMSNoise_vsNavgPU_vsIeta_EB -> SetPointError(point,0.,histo->GetRMSError());
      
      ++point;
    }
    
    char funcName[50];
    sprintf(funcName,"f_pol1_iEta%02.1f-%02.1f_EB",iEtaBinLowEdge,iEtaBinHigEdge);
    TF1* f_pol1_vsNavgPU_vsIeta_EB = new TF1(funcName,"[0]+[1]*x",0.,35.);
    g_RMSNoise_vsNavgPU_vsIeta_EB -> Fit(funcName,"QS+","",10.,25.);
    
    g_noiseAtZero_vsIeta_EB -> SetPoint(iEtaBin-1,iEtaBinCenter,f_pol1_vsNavgPU_vsIeta_EB->GetParameter(0.));
    g_noiseAtZero_vsIeta_EB -> SetPointError(iEtaBin-1,0.,f_pol1_vsNavgPU_vsIeta_EB->GetParError(0.));
    g_noiseSlope_vsIeta_EB -> SetPoint(iEtaBin-1,iEtaBinCenter,f_pol1_vsNavgPU_vsIeta_EB->GetParameter(1.));
    g_noiseSlope_vsIeta_EB -> SetPointError(iEtaBin-1,0.,f_pol1_vsNavgPU_vsIeta_EB->GetParError(1.));
    
    g_addNoise_vsIeta_EB -> SetPoint(iEtaBin-1,iEtaBinCenter,sqrt(pow(f_pol1_vsNavgPU_vsIeta_EB->GetParameter(0.)+20.*f_pol1_vsNavgPU_vsIeta_EB->GetParameter(1.),2)-pow(f_pol1_vsNavgPU_vsIeta_EB->GetParameter(0.),2)));
  }
  
  
  
  TCanvas* c1_noiseAtZero_vsIeta_EB = new TCanvas("c1_noiseAtZero_vsIeta_EB","EB noise at 0 PU vs iEta");
  c1_noiseAtZero_vsIeta_EB -> cd();
  c1_noiseAtZero_vsIeta_EB -> SetGridx();
  c1_noiseAtZero_vsIeta_EB -> SetGridy();
  
  g_noiseAtZero_vsIeta_EB -> GetXaxis() -> SetTitle("i#eta");
  g_noiseAtZero_vsIeta_EB -> GetYaxis() -> SetTitle("RMS noise at N_{PU}=0 (GeV)");
  g_noiseAtZero_vsIeta_EB -> Draw("AP");
  
  NamePlot = Form("c1_noiseAtZero_vsIeta_EB_%s.png",suffix.Data());
  c1_noiseAtZero_vsIeta_EB -> SaveAs(NamePlot.Data(),"png");

  
  
  TCanvas* c1_noiseSlope_vsIeta_EB = new TCanvas("c1_noiseSlope_vsIeta_EB","EB noise slope vs iEta");
  c1_noiseSlope_vsIeta_EB -> cd();
  c1_noiseSlope_vsIeta_EB -> SetGridx();
  c1_noiseSlope_vsIeta_EB -> SetGridy();
  
  g_noiseSlope_vsIeta_EB -> GetXaxis() -> SetTitle("i#eta");
  g_noiseSlope_vsIeta_EB -> GetYaxis() -> SetTitle("RMS noise slope wrt N_{PU} (GeV/N_{PU})");
  g_noiseSlope_vsIeta_EB -> Draw("AP");
  
  NamePlot = Form("c1_noiseSlope_vsIeta_EB_%s.png",suffix.Data());
  c1_noiseSlope_vsIeta_EB -> SaveAs(NamePlot.Data(),"png");
  
  TCanvas* c1_addNoise_vsIeta_EB = new TCanvas("c1_addNoise_vsIeta_EB","EB additional noise vs iEta");
  c1_addNoise_vsIeta_EB -> cd();
  c1_addNoise_vsIeta_EB -> SetGridx();
  c1_addNoise_vsIeta_EB -> SetGridy();
  
  g_addNoise_vsIeta_EB -> GetXaxis() -> SetTitle("i#eta");
  g_addNoise_vsIeta_EB -> GetYaxis() -> SetTitle("additional quad. noise at N_{PU}=20 (GeV)");
  g_addNoise_vsIeta_EB -> Draw("AP");


  NamePlot = Form("c1_addNoise_vsIeta_EB_%s.png",suffix.Data());
  c1_addNoise_vsIeta_EB -> SaveAs(NamePlot.Data(),"png");
  
 
  
  TGraphErrors* g_noiseAtZero_vsIring_EE = new TGraphErrors();
  TGraphErrors* g_noiseSlope_vsIring_EE = new TGraphErrors();
  TGraphErrors* g_addNoise_vsIring_EE = new TGraphErrors();
    
  for(int iRingBin = 1; iRingBin <= nBins_iRing; ++iRingBin)
  {
    float iRingBinCenter  = h_occupancy_vsIring -> GetBinCenter(iRingBin);
    float iRingBinLowEdge = h_occupancy_vsIring -> GetBinLowEdge(iRingBin);
    float iRingBinHigEdge = h_occupancy_vsIring -> GetBinLowEdge(iRingBin) + h_occupancy_vsIring_EE->GetBinWidth(bin);
    
    if( iRingBinCenter > 33 ) continue;
    
    TGraphErrors* g_RMSNoise_vsNavgPU_vsIring_EE = new TGraphErrors();
    
    int point = 0;
    for(int bin = 1; bin <= nBins_nAvgPU; ++bin)
    {  
      TH1F* histo;
      char histoName[50];
      
      float binCenter  = h_occupancy_vsNavgPU -> GetBinCenter(bin);
      float binLowEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin);
      float binHigEdge = h_occupancy_vsNavgPU -> GetBinLowEdge(bin) + h_occupancy_vsNavgPU_EE->GetBinWidth(bin);
      
      if( binCenter < 8. ) continue;
      if( binCenter > 30. ) continue;    
      sprintf(histoName,"hEE_recHitE_nAvgPU%02.1f-%02.1f_iRing%02.1f-%02.1f",binLowEdge,binHigEdge,iRingBinLowEdge,iRingBinHigEdge);
      histo = (TH1F*)( f->Get(histoName) );
      
      g_RMSNoise_vsNavgPU_vsIring_EE -> SetPoint(point,binCenter,histo->GetRMS());
      g_RMSNoise_vsNavgPU_vsIring_EE -> SetPointError(point,0.,histo->GetRMSError());
      
      ++point;
    }
    
    char funcName[50];
    sprintf(funcName,"f_pol1_iRing%02.1f-%02.1f_EE",iRingBinLowEdge,iRingBinHigEdge);
    TF1* f_pol1_vsNavgPU_vsIring_EE = new TF1(funcName,"[0]+[1]*x",0.,35.);
    g_RMSNoise_vsNavgPU_vsIring_EE -> Fit(funcName,"QS+","",10.,25.);
    
    g_noiseAtZero_vsIring_EE -> SetPoint(iRingBin-1,iRingBinCenter,f_pol1_vsNavgPU_vsIring_EE->GetParameter(0.));
    g_noiseAtZero_vsIring_EE -> SetPointError(iRingBin-1,0.,f_pol1_vsNavgPU_vsIring_EE->GetParError(0.));
    g_noiseSlope_vsIring_EE -> SetPoint(iRingBin-1,iRingBinCenter,f_pol1_vsNavgPU_vsIring_EE->GetParameter(1.));
    g_noiseSlope_vsIring_EE -> SetPointError(iRingBin-1,0.,f_pol1_vsNavgPU_vsIring_EE->GetParError(1.));
    
    g_addNoise_vsIring_EE -> SetPoint(iRingBin-1,iRingBinCenter,sqrt(pow(f_pol1_vsNavgPU_vsIring_EE->GetParameter(0.)+20.*f_pol1_vsNavgPU_vsIring_EE->GetParameter(1.),2)-pow(f_pol1_vsNavgPU_vsIring_EE->GetParameter(0.),2)));    
  }
  
  
  
  TCanvas* c1_noiseAtZero_vsIring_EE = new TCanvas("c1_noiseAtZero_vsIring_EE","EE noise at 0 PU vs iRing");
  c1_noiseAtZero_vsIring_EE -> cd();
  c1_noiseAtZero_vsIring_EE -> SetGridx();
  c1_noiseAtZero_vsIring_EE -> SetGridy();
  
  g_noiseAtZero_vsIring_EE -> GetXaxis() -> SetTitle("ring");
  g_noiseAtZero_vsIring_EE -> GetYaxis() -> SetTitle("RMS noise at N_{PU}=0 (GeV)");
  g_noiseAtZero_vsIring_EE -> Draw("AP");
  
  NamePlot = Form("c1_noiseAtZero_vsIring_EE_%s.png",suffix.Data());
  c1_noiseAtZero_vsIring_EE -> SaveAs(NamePlot.Data(),"png"); 
  
  
  TCanvas* c1_noiseSlope_vsIring_EE = new TCanvas("c1_noiseSlope_vsIring_EE","EE noise slope vs iRing");
  c1_noiseSlope_vsIring_EE -> cd();
  c1_noiseSlope_vsIring_EE -> SetGridx();
  c1_noiseSlope_vsIring_EE -> SetGridy();
  
  g_noiseSlope_vsIring_EE -> GetXaxis() -> SetTitle("ring");
  g_noiseSlope_vsIring_EE -> GetYaxis() -> SetTitle("RMS noise slope wrt N_{PU} (GeV/N_{PU})");
  g_noiseSlope_vsIring_EE -> Draw("AP");  
  
  NamePlot = Form("c1_noiseSlope_vsIring_EE _%s.png",suffix.Data());
  c1_noiseSlope_vsIring_EE  -> SaveAs(NamePlot.Data(),"png");
  
  
  
  TCanvas* c1_addNoise_vsIring_EE = new TCanvas("c1_addNoise_vsIring_EE","EE additional noise vs iEta");
  c1_addNoise_vsIring_EE -> cd();
  c1_addNoise_vsIring_EE -> SetGridx();
  c1_addNoise_vsIring_EE -> SetGridy();
  
  g_addNoise_vsIring_EE -> GetXaxis() -> SetTitle("ring");
  g_addNoise_vsIring_EE -> GetYaxis() -> SetTitle("additional quad. noise at N_{PU}=20 (GeV)");
  g_addNoise_vsIring_EE -> Draw("AP");

  NamePlot = Form("c1_addNoise_vsIring_EE_%s.png",suffix.Data());
  c1_addNoise_vsIring_EE-> SaveAs(NamePlot.Data(),"png");
}
Ejemplo n.º 13
0
double runGraphicHistos(TString ifile = "tmpfitdirc.root", bool verbose_out=true, double ienergy = 5, int iupdown = 0)
{
	TCanvas *c1 = new TCanvas("myc1","myc1",1000,1200);

	if (verbose_out == false)
	{
		//supresses canvas message 
		//gErrorIgnoreLevl=kInfo;
		gROOT->ProcessLine( "gErrorIgnoreLevel = kWarning;");
	}

	double hmin = -100;
	double hmax = 100;

	hmin = -25;
	hmax = 25;

	double energy = ienergy;

	double pi_mass = .13957;
	double k_mass = .49367;

	double pi_beta = sqrt(1-pi_mass*pi_mass/(energy*energy));
	double k_beta = sqrt(1-k_mass*k_mass/(energy*energy));

	double quartz_index = 1.47;

	double pi_mrad = 1000*acos(1/(pi_beta*quartz_index));
	double k_mrad = 1000*acos(1/(k_beta*quartz_index));

	//double seperation = 5.2;
	double seperation = pi_mrad - k_mrad;
	double mean_pion = 0;
	double mean_kaon = mean_pion + seperation;
	if (verbose_out == true)
	{
		printf("Energy: %4.02f\n",energy);
		printf("Mrad Seperation: %8.03f\n",seperation);
	}
	//denominator pf spread

	TRandom3* randgen = new TRandom3();

	TFile *f1 = new TFile(ifile);
	TH1F *hpion;
	TH1F *hkaon;
	TH1F *phots_pion;
	if (iupdown == 0)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon");
		phots_pion = (TH1F*) f1->Get("phot_found_pion");
	}
	else if (iupdown == 1)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion_up");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon_up");
		phots_pion = (TH1F*) f1->Get("phot_found_pion_up");
	}
	else if (iupdown == -1)
	{
		hpion = (TH1F*) f1->Get("ll_diff_pion_down");
		hkaon = (TH1F*) f1->Get("ll_diff_kaon_down");
		phots_pion = (TH1F*) f1->Get("phot_found_pion_down");
	}
	else
	{
		printf("Unrecognize updown arguement: %d \nFailing....\n",iupdown);
		return -1;
	}
	if (verbose_out == true)
	{
		printf("pion_ll mean, spread: %12.04f, %12.04f\n",hpion->GetMean(),hpion->GetRMS());
		printf("kaon_ll mean, spread: %12.04f, %12.04f\n",hkaon->GetMean(),hkaon->GetRMS());
	}
	double spread = seperation/2;
	double spreadsq2 = 2*spread*spread;
	//Swap kaon and pion numbers

	for (int i = 1; i < hpion->GetNbinsX()/2; i++)
	{
		double t_swap = hpion->GetBinContent(i);
		hpion->SetBinContent(i,hpion->GetBinContent(hpion->GetNbinsX() - i + 1));
		hpion->SetBinContent(hpion->GetNbinsX() - i + 1, t_swap);
	}
	for (int i = 1; i < hkaon->GetNbinsX()/2; i++)
	{
		double t_swap = hkaon->GetBinContent(i);
		hkaon->SetBinContent(i,hkaon->GetBinContent(hkaon->GetNbinsX() - i + 1));
		hkaon->SetBinContent(hkaon->GetNbinsX() - i + 1, t_swap);
	}

	double titlesize=1.2*.04;

	int rebin = 20;
	rebin = 160;
	hpion->Rebin(rebin);
	hkaon->Rebin(rebin);

	hpion->SetAxisRange(hmin,hmax);
	hkaon->SetAxisRange(hmin,hmax);

	hkaon->GetXaxis()->SetTitle("Loglikelihood difference");
	hkaon->GetYaxis()->SetTitle("A.U.");
	hkaon->GetXaxis()->SetTitleSize(titlesize);
	hkaon->GetYaxis()->SetTitleSize(titlesize);

	hpion->SetStats(false);
	hkaon->SetStats(false);

	hpion->SetLineColor(kCyan);
	//hpion->SetFillColorAlpha(kRed,.5);

	hkaon->SetLineColor(kBlue);
	//hkaon->SetFillColorAlpha(kBlue,.5);

	TLegend *leg_ll = new TLegend(.6,.6,.8,.8);
	leg_ll->AddEntry(hpion,"Pion");
	leg_ll->AddEntry(hkaon,"Kaon");
	leg_ll->SetBorderSize(0);


	hkaon->SetTitle("log(P(Pi)/P(K)) for actual Pi (red) and K (blue) at 5 GeV");



	TH1F *pion_veto_eff = new TH1F(*hpion);
	TH1F *kaon_missid = new TH1F(*hkaon);

	pion_veto_eff->SetName("pion_veto_eff");
	pion_veto_eff->SetTitle("");

	kaon_missid->SetName("kaon_missid");
	kaon_missid->SetTitle("");



	for (int i = 0; i < pion_veto_eff->GetNbinsX(); i++)
	{
		pion_veto_eff->SetBinContent(i,hpion->Integral(0,i));
		kaon_missid->SetBinContent(i,hkaon->Integral(i,kaon_missid->GetNbinsX()));
		//	printf("%12.04f %12.04f %d\n",1,1,i);
	}

	pion_veto_eff->SetAxisRange(0,10000,"Y");

	double scale_int = 1/hpion->Integral(0,pion_veto_eff->GetNbinsX());
	pion_veto_eff->Scale(scale_int);
	scale_int = 1/hkaon->Integral(0,kaon_missid->GetNbinsX());
	kaon_missid->Scale(scale_int);

	hkaon->SetTitle("");
	hpion->SetTitle("");


	if (verbose_out == true)
	{
		hkaon->Draw();
		hpion->Draw("SAME H");
		leg_ll->Draw("SAME");
		c1->SetWindowSize(1000,800);

		c1->Print("overlap.pdf");
	}

	if (verbose_out == true)
	{
		pion_veto_eff->Draw("");
		kaon_missid->Draw("SAME H");

		c1->SetWindowSize(1000,800);
		c1->Print("overlap_integral.pdf");
	}

	double linewidth=6;
	TGraph* roc_graph;
	int roc_n = pion_veto_eff->GetNbinsX();
	TVectorF xr(roc_n);//gross
	TVectorF yr(roc_n);
	double ival = 0;

	for (int i = 0; i < pion_veto_eff->GetNbinsX(); i++)
	{
		xr[i] = pion_veto_eff->GetBinContent(i);
		yr[i] = kaon_missid->GetBinContent(i);

		//	printf("%8.04f %8.04f\n",xr[i],yr[i]);	
	}

	double y1,y2,x1,x2;
	x1 = pion_veto_eff->GetBinContent(0);
	double last_x = pion_veto_eff->GetBinContent(0);
	double last_y = kaon_missid->GetBinContent(0);

	for (int i = 0; i < pion_veto_eff->GetNbinsX()-1; i++)
	{
		ival += (yr[i]+last_y)*(xr[i] - last_x)/2;
                //printf("%6d %12.09f %12.04f %12.04f %12.04f %12.04f\n",i,ival,xr[i],yr[i],last_x,last_y);
		last_x = xr[i];
		last_y = yr[i];
		
	}

	if (verbose_out == true)
	{
		printf("ROC integral: %12.04f\n",ival);
	}

	roc_graph = new TGraph(xr,yr);
	roc_graph->SetLineColor(2);
	roc_graph->SetLineWidth(4);
	//roc_graph->SetMarkerColor(4);
	//roc_graph->SetMarkerStyle(21);
	roc_graph->SetTitle("");
	roc_graph->GetXaxis()->SetTitle("Kaon Efficiency");
	roc_graph->GetYaxis()->SetTitle("Pion Rejection");
	roc_graph->GetXaxis()->SetTitleSize(titlesize);
	roc_graph->GetYaxis()->SetTitleSize(titlesize);
	roc_graph->GetXaxis()->SetLimits(0,1.01);
	roc_graph->SetMinimum(0);
	roc_graph->SetMaximum(1.01);
	roc_graph->SetLineWidth(linewidth);

	if (verbose_out == true)
	{
		roc_graph->Draw("ACP");
		c1->Print("roc_curve.gif");
	}
	spread = find_sig_val(seperation,ival,spread); 


	//FAKE version stuff below
	/*---------------------------------------------------------------------------------------------------------------------------*/




	TH1F *fhpion = (TH1F*) f1->Get("ll_diff_pion");
	TH1F *fhkaon = (TH1F*) f1->Get("ll_diff_kaon");

	fhpion->Reset();
	fhkaon->Reset();

	fhpion->SetBins(1000,hmin,hmax);
	fhkaon->SetBins(1000,hmin,hmax);

	double pion_obs, kaon_obs;
	double pion_ll_diff, kaon_ll_diff;

	for (int ii = 0; ii < 10000; ii++)
	{
		pion_obs = randgen->Gaus(mean_pion,spread);
		kaon_obs = randgen->Gaus(mean_kaon,spread);

		pion_ll_diff = -1*(pion_obs - mean_pion)*(pion_obs - mean_pion);
		pion_ll_diff += (pion_obs - mean_kaon)*(pion_obs - mean_kaon);
		pion_ll_diff /= spreadsq2;

		kaon_ll_diff = - (kaon_obs - mean_pion)*(kaon_obs - mean_pion);
		kaon_ll_diff += (kaon_obs - mean_kaon)*(kaon_obs - mean_kaon);
		kaon_ll_diff /= spreadsq2;

		fhpion->Fill(pion_ll_diff);
		fhkaon->Fill(kaon_ll_diff);
	}


	fhpion->SetAxisRange(hmin,hmax);
	fhkaon->SetAxisRange(hmin,hmax);

	fhpion->SetLineColor(kRed);
	//hpion->SetFillColorAlpha(kRed,.5);

	fhkaon->SetLineColor(kBlue);
	//hkaon->SetFillColorAlpha(kBlue,.5);

	fhkaon->SetTitle("");

	TH1F *fpion_veto_eff = new TH1F(*fhpion);
	TH1F *fkaon_missid = new TH1F(*fhkaon);

	fpion_veto_eff->SetName("pion_veto_eff");
	fpion_veto_eff->SetTitle("");

	fkaon_missid->SetName("kaon_missid");
	fkaon_missid->SetTitle("");

	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{
		fpion_veto_eff->SetBinContent(i,fhpion->Integral(i,fpion_veto_eff->GetNbinsX()));
		fkaon_missid->SetBinContent(i,fhkaon->Integral(0,i));
	}

	fpion_veto_eff->SetAxisRange(0,10000,"Y");

	double fscale_int = 1/fhpion->Integral(0,fpion_veto_eff->GetNbinsX());
	fpion_veto_eff->Scale(fscale_int);
	fscale_int = 1/fhkaon->Integral(0,fkaon_missid->GetNbinsX());
	fkaon_missid->Scale(fscale_int);




	TGraph* froc_graph;
	int froc_n = fpion_veto_eff->GetNbinsX();
	TVectorF fxr(froc_n);
	TVectorF fyr(froc_n);

	double fival = 0;
	double flast_x = fpion_veto_eff->GetBinContent(0);
	double flast_y = fkaon_missid->GetBinContent(0);
	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{
		fxr[i] = fpion_veto_eff->GetBinContent(i);
		fyr[i] = fkaon_missid->GetBinContent(i);


		fival -= (fyr[i]+flast_y)*(fxr[i] - flast_x)/2;
		flast_x = fxr[i];
		flast_y = fyr[i];
	}
	ival = 0;
	flast_x = fpion_veto_eff->GetBinContent(0);
	flast_y = fkaon_missid->GetBinContent(0);
	for (int i = 0; i < fpion_veto_eff->GetNbinsX(); i++)
	{

		//Why oh why is Erf not the standard definition
		double t = hmin + i*(hmax-hmin)/fpion_veto_eff->GetNbinsX();
		fxr[i] = .5 + TMath::Erf(t/(sqrt(2)*spread))/2;
		fyr[i] = .5 - TMath::Erf((t-seperation)/(sqrt(2)*spread))/2;

		fival -= (fyr[i]+flast_y)*(fxr[i] - flast_x)/2;
		flast_x = fxr[i];
		flast_y = fyr[i];
	}	
	//printf("Fake ROC integral: %12.04f\n",fival);


	froc_graph = new TGraph(fxr,fyr);
	if (verbose_out == true)
	{
		froc_graph->SetLineColor(4);
		froc_graph->SetLineWidth(linewidth);
		froc_graph->SetLineStyle(2);
		froc_graph->SetTitle("");
		froc_graph->GetXaxis()->SetTitle("\"Kaon Efficiency\"");
		froc_graph->GetYaxis()->SetTitle("\"Pion Rejection\"");
		froc_graph->GetXaxis()->SetTitleSize(titlesize);
		froc_graph->GetYaxis()->SetTitleSize(titlesize);
		froc_graph->GetXaxis()->SetLimits(0,1.01);
		froc_graph->SetMinimum(0);
		froc_graph->SetMaximum(1.01);


		roc_graph->SetFillColorAlpha(kWhite,1);
		froc_graph->SetFillColorAlpha(kWhite,1);
		TLegend *leg_roc = new TLegend(.3,.5,.7,.7);
		leg_roc->AddEntry(roc_graph,"ROC Curve");
		leg_roc->AddEntry(froc_graph,"Matched Gaussian ROC Curve");
		leg_roc->SetBorderSize(0);
		leg_roc->SetTextSize(0.04*1.1);

		froc_graph->Draw("SAME");
		leg_roc->Draw("SAME");
		c1->Print("roc_curve_overlay.pdf");
	}



	if (verbose_out == true)
	{
		printf("Matching resolution: %6.03f\n",spread);
		printf("Matching resolution per photon: %6.03f\n",spread*sqrt(phots_pion->GetMean()));
	}
	else
	{
		printf("%6.04f\n",spread);
	}
	return spread;

}
Ejemplo n.º 14
0
int main(int argc, char** argv)
{
  setTDRStyle();
  gStyle -> SetOptFit(0000);
  
  int nFib = 64;
  int nCryst = 9;
  
  std::string inFileName(argv[1]);
  
  
  //----------
  // open file
  
  TFile* inFile = TFile::Open(Form("ntuples/tot_capture_%s.root",inFileName.c_str()));
  TTree* tree = (TTree*)( inFile->Get("tree") );
  
  
  //---------------------
  // set branch addresses
  
  std::map<int,std::vector<int>*> t_waveform;
  std::map<int,std::vector<int>*> t_crystWaveform;
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    t_waveform[fibIt] = new std::vector<int>;
    tree -> SetBranchAddress(Form("fib%02d_waveform",fibIt),&t_waveform[fibIt]);
  }
  for(int crystIt = 0; crystIt < nCryst; ++crystIt)
  {
    t_crystWaveform[crystIt] = new std::vector<int>;
    tree -> SetBranchAddress(Form("cryst%01d_waveform",crystIt),&t_crystWaveform[crystIt]);
  }
  
  
  
  //-------------
  // define plots
  
  std::map<int,int> n_waveform_fib;
  TGraph** g_waveform_fib = new TGraph*[nFib];
  
  std::map<int,int> n_waveform_cut_fib;
  TGraph** g_waveform_cut_fib = new TGraph*[nFib];
  
  TH1F** h_ped_fib = new TH1F*[nFib];
  TH1F* h_ped_fib_all = new TH1F("h_ped_fib_all","",100,80.,120.);
  
  TH1F** h_maximum_fib = new TH1F*[nFib];
  TH1F* h_maximum_fib_all = new TH1F("h_maximum_fib_all","",1000,0.,2500.);
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    g_waveform_fib[fibIt] = new TGraph();
    g_waveform_cut_fib[fibIt] = new TGraph();
    
    h_ped_fib[fibIt] = new TH1F(Form("h_ped_fib%02d",fibIt),"",100,80.,120.);
    h_maximum_fib[fibIt] = new TH1F(Form("h_maximum_fib%02d",fibIt),"",1000,0.,2500.);
  }
  
  TProfile2D* p_fibAveInt = new TProfile2D("p_fibAveInt","",17,-0.5,16.5,18,-0.5,17.5);
  TProfile2D* p_fibAveMax = new TProfile2D("p_fibAveMax","",17,-0.5,16.5,18,-0.5,17.5);
  TProfile2D* p_crystAveMax = new TProfile2D("p_crystAveMax","",3,-0.5,2.5,3,-0.5,2.5);
  
  TH1F* h_tot_integral = new TH1F("h_tot_integral","",1000,0.,100000.);
  TH1F* h_tot_maximum  = new TH1F("h_tot_maximum", "",1000,0.,1000.);
  
  
  //------------------
  // loop over entries
  
  for(int entry = 0; entry < tree->GetEntries(); ++entry)
  {
    std::cout << ">>> reading entry " << entry << " / " << tree->GetEntries() << "\r" << std::flush;
    tree -> GetEntry(entry);
    
    float tot_integral = 0.;
    float tot_maximum = 0.;
    
    for(int fibIt = 0; fibIt < nFib; ++fibIt)
    {
      ++n_waveform_fib[fibIt];
      AddWaveform(g_waveform_fib[fibIt],t_waveform[fibIt]);
      
      float ped, integral, maximum;
      CalculateAmplitude(t_waveform[fibIt],ped,integral,maximum);
      
      h_ped_fib[fibIt] -> Fill(ped);
      h_ped_fib_all -> Fill(ped);
      h_maximum_fib[fibIt] -> Fill(maximum);
      h_maximum_fib_all -> Fill(maximum);
      
      int x = 16-2*int(fibIt/8);
      int y = (x/2)%2 == 0 ? 16-2*(fibIt%8) : 16-2*(fibIt%8)-1;
      p_fibAveInt -> Fill(x,y,integral);
      p_fibAveMax -> Fill(x,y,maximum);
      
      if( maximum+ped > 120. )
      {
        tot_integral += integral;
        tot_maximum += maximum;
        
        ++n_waveform_cut_fib[fibIt];
        AddWaveform(g_waveform_cut_fib[fibIt],t_waveform[fibIt]);
      }
    }
    
    for(int crystIt = 0; crystIt < nCryst; ++crystIt)
    {
      float ped, integral, maximum;
      CalculateAmplitude(t_waveform[crystIt],ped,integral,maximum);
      p_crystAveMax -> Fill(crystIt%3,2-crystIt/3,maximum);
    }
    
    h_tot_integral -> Fill(tot_integral);
    h_tot_maximum -> Fill(tot_maximum);
  }
  
  
  
  TCanvas* c_waveform_fib_all = new TCanvas();
  
  int plotIt = 0;
  float min = +999999.;
  float max = -999999.;
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    TGraph* g = g_waveform_fib[fibIt];
    if( g->GetN() == 0 ) continue;
    
    NormalizeGraph(g,n_waveform_fib[fibIt]);
    
    if( GetMinimum(g) < min ) min = GetMinimum(g);
    if( GetMaximum(g) > max ) max = GetMaximum(g);
  }
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    TGraph* g = g_waveform_fib[fibIt];
    if( g->GetN() == 0 ) continue;
    
    TCanvas* c_waveform_fib = new TCanvas();
    
    g -> SetMinimum(min-0.05*fabs(max-min));
    g -> SetMaximum(max+0.05*fabs(max-min));
    g -> SetLineWidth(2);
    g -> SetLineColor(fibIt+1);
    g -> SetMarkerSize(0.2);
    g -> GetXaxis() -> SetTitle("sample time (ns)");
    g -> Draw("APL");
    
    c_waveform_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/waveform_fib%02d.png",inFileName.c_str(),fibIt),"png");
    
    c_waveform_fib_all -> cd();
    
    if( plotIt == 0 ) g -> Draw("APL");
    else              g -> Draw("PL,same");
    
    ++plotIt;
  }
  
  c_waveform_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/waveform_fib_all.png",inFileName.c_str()),"png");
  
  
  
  TCanvas* c_waveform_cut_fib_all = new TCanvas();
  
  plotIt = 0;
  min = +999999.;
  max = -999999.;
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    TGraph* g = g_waveform_cut_fib[fibIt];
    if( g->GetN() == 0 ) continue;
    
    NormalizeGraph(g,n_waveform_cut_fib[fibIt]);
    
    if( GetMinimum(g) < min ) min = GetMinimum(g);
    if( GetMaximum(g) > max ) max = GetMaximum(g);
  }
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    TGraph* g = g_waveform_cut_fib[fibIt];
    if( g->GetN() == 0 ) continue;
    
    //g -> SetMinimum(min-0.05*fabs(max-min));
    //g -> SetMaximum(max+0.05*fabs(max-min));
    g -> SetLineWidth(2);
    g -> SetLineColor(fibIt+1);
    g -> SetMarkerSize(0.2);
    g -> GetXaxis() -> SetTitle("sample time (ns)");
    g -> Draw("APL");
    
    c_waveform_cut_fib_all -> cd();
    
    if( plotIt == 0 ) g -> Draw("APL");
    else              g -> Draw("PL,same");
    
    ++plotIt;
  }
  
  c_waveform_cut_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/waveform_cut_fib_all.png",inFileName.c_str()),"png");
  
  
  
  for(int fibIt = 0; fibIt < nFib; ++fibIt)
  {
    TH1F* h = h_ped_fib[fibIt];
    
    TCanvas* c_ped_fib = new TCanvas();
    c_ped_fib -> SetLogy();
    
    h -> SetLineWidth(2);
    h -> GetXaxis() -> SetTitle("max sample");
    h -> Draw();
    h -> Fit("gaus","Q");
    
    TLatex* latex1 = new TLatex(0.60,0.90,Form("RMS = %.1f",h->GetRMS()));
    latex1 -> SetNDC();
    latex1 -> SetTextFont(42);
    latex1 -> SetTextSize(0.04);
    latex1 -> Draw("same");
    
    TLatex* latex2 = new TLatex(0.60,0.85,Form("#sigma = %.1f",h->GetFunction("gaus")->GetParameter(2)));
    latex2 -> SetNDC();
    latex2 -> SetTextFont(42);
    latex2 -> SetTextSize(0.04);
    latex2 -> Draw("same");
    
    c_ped_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/ped_fib%02d.png",inFileName.c_str(),fibIt),"png");
    
    h = h_maximum_fib[fibIt];
    
    TCanvas* c_maximum_fib = new TCanvas();
    c_maximum_fib -> SetLogy();
    
    h -> SetLineWidth(2);
    h -> GetXaxis() -> SetTitle("max sample");
    h -> Draw();
    
    c_maximum_fib -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/plotsPerFib/maximum_fib%02d.png",inFileName.c_str(),fibIt),"png");
  }
  
  TCanvas* c_ped_fib_all = new TCanvas();
  c_ped_fib_all -> SetLogy();
  
  h_ped_fib_all -> SetLineWidth(2);
  h_ped_fib_all -> GetXaxis() -> SetTitle("pedestal");
  h_ped_fib_all -> Draw();
  h_ped_fib_all -> Fit("gaus","Q");
  
  TLatex* latex1 = new TLatex(0.60,0.90,Form("RMS = %.1f",h_ped_fib_all->GetRMS()));
  latex1 -> SetNDC();
  latex1 -> SetTextFont(42);
  latex1 -> SetTextSize(0.04);
  latex1 -> Draw("same");
  
  TLatex* latex2 = new TLatex(0.60,0.85,Form("#sigma = %.1f",h_ped_fib_all->GetFunction("gaus")->GetParameter(2)));
  latex2 -> SetNDC();
  latex2 -> SetTextFont(42);
  latex2 -> SetTextSize(0.04);
  latex2 -> Draw("same");
  c_ped_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/ped_fib_all.png",inFileName.c_str()),"png");
  
  TCanvas* c_maximum_fib_all = new TCanvas();
  c_maximum_fib_all -> SetLogy();
  
  h_maximum_fib_all -> SetLineWidth(2);
  h_maximum_fib_all -> GetXaxis() -> SetTitle("max sample");
  h_maximum_fib_all -> Draw();
  
  c_maximum_fib_all -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/maximum_fib_all.png",inFileName.c_str()),"png");
  
  
  
  TCanvas* c_fibAveInt = new TCanvas();
  
  p_fibAveInt -> Draw("COLZ");
  c_fibAveInt -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/fibAveInt.png",inFileName.c_str()),"png");
  
  TCanvas* c_fibAveMax = new TCanvas();
  
  p_fibAveMax -> Draw("COLZ");
  c_fibAveMax -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/fibAveMax.png",inFileName.c_str()),"png");
  
  
  TCanvas* c_crystAveMax = new TCanvas();
  
  p_crystAveMax -> Draw("COLZ");
  c_crystAveMax -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/crystAveMax.png",inFileName.c_str()),"png");
  
  
  
  TCanvas* c_tot_integral = new TCanvas();
  c_tot_integral -> SetLogy();
  
  h_tot_integral -> Draw();
  c_tot_integral -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/tot_integral.png",inFileName.c_str()),"png");
  
  TCanvas* c_tot_maximum = new TCanvas();
  c_tot_maximum -> SetLogy();
  
  h_tot_maximum -> Draw();
  c_tot_maximum -> Print(Form("/afs/cern.ch/user/a/abenagli/www/TBatFNAL/%s/tot_maximum.png",inFileName.c_str()),"png");
}
Ejemplo n.º 15
0
void cetaflatHFP12(int nIterN=1, double Ethr1=10, double Ethr2=150) {
  
  gStyle->SetOptLogz(0);
  gStyle->SetMarkerSize(0.7);
  gStyle->SetMarkerStyle(20);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);
  gStyle->SetTitleOffset(1.7,"Y");
  gStyle->SetTitleOffset(0.9,"X");
  //gStyle->SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  gStyle->SetPadLeftMargin(0.18);
  //gStyle->SetNdivisions(516);
  gStyle->SetStatH(0.025);
  gStyle->SetStatW(0.3);
  gStyle->SetTitleW(0.4);
  gStyle->SetTitleX(0.28);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  sprintf(ctit,"HFPo_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
  TFile *histf = new TFile(ctit,"RECREATE");
  hLcorr1D->Write(); 
  hScorr1D->Write();  
  hLmapP->Write(); 
  hLmapP0->Write(); 
  hLmapPc->Write(); 
  hSmapP->Write(); 
  hSmapP0->Write(); 
  hSmapPc->Write(); 
  grL->Write();
  grS->Write();
  histf->Close();
}
Ejemplo n.º 16
0
void readMCPerform(TString filename="QAresults_AOD.root", Int_t drawOnlyDzerDplus = 1, Int_t runNumber=-1)
{

  const Int_t totTrending=5;
  Float_t vecForTrend[totTrending];
  TString varForTrending[totTrending]={"nDzeroCandperEv","nDplusCandperEv","nDsCandperEv","nLcCandperEv","nDstarCandperEv"};

  

  TTree* trtree=new TTree("trendingHF","tree of trending variables");
  trtree->Branch("nrun",&runNumber,"nrun/I");
  for(Int_t j=0; j<totTrending; j++){
    trtree->Branch(varForTrending[j].Data(),&vecForTrend[j],Form("%s/F",varForTrending[j].Data()));
    vecForTrend[j]=-99.;
  }

  TFile *ff = new TFile(filename.Data());

  Int_t color[5] = {kBlack, kRed, kGreen, kBlue, kOrange};

  TDirectoryFile *dirD2H = (TDirectoryFile *)ff->Get("PWG3_D2H_QA");
  if(!dirD2H){
    printf("Directory PWG3_D2H_QA not found in file %s\n",filename.Data());
    return;
  }
  TList *listD2H = (TList *)dirD2H->Get("nEntriesQA");
  if(!listD2H){
    printf("TList nEntriesQA not found in file %s\n",filename.Data());
    return;  
  }
  TH1F *hNentries = (TH1F *)listD2H->FindObject("hNentries");
  TH2F *hHasSelBit = (TH2F *)listD2H->FindObject("HasSelBit");

  TCanvas *cqa = new TCanvas("cqa", "cqa", 800, 500);
  cqa->Divide(2, 1);
  cqa->cd(1);
  hNentries->Draw();
  cqa->cd(2);
  hHasSelBit->Draw("colz");
  cqa->SaveAs("plot_D2HQA.png");

  Double_t nEv=hNentries->GetBinContent(10);
  vecForTrend[0]=hHasSelBit->GetBinContent(1)/nEv;
  vecForTrend[1]=hHasSelBit->GetBinContent(2)/nEv;
  vecForTrend[2]=hHasSelBit->GetBinContent(3)/nEv;
  vecForTrend[3]=hHasSelBit->GetBinContent(4)/nEv;
  vecForTrend[4]=hHasSelBit->GetBinContent(5)/nEv;


  TDirectoryFile *dir = (TDirectoryFile *)ff->Get("PWGHF_D2H_MCPerform");
  TList* list = 0x0;
  if (dir)
  {
    list = (TList *)dir->Get("coutputDperfQA");
    if(list){
    
      TH1F *hn = (TH1F *)list->FindObject("fHistNEvents");
      TH1F *hnGenD = (TH1F *)list->FindObject("fHistNGenD");
      Int_t entries = hn->GetBinContent(3);
      
      TH2F *fHistNCand = (TH2F *)list->FindObject("fHistNCand");
      TH1F *fHistNCandDzero = (TH1F *)fHistNCand->ProjectionY("fHistNCandDzero", 1, 1);
      TH1F *fHistNCandDplus = (TH1F *)fHistNCand->ProjectionY("fHistNCandDplus", 2, 2);
      TH1F *fHistNCandDstar = (TH1F *)fHistNCand->ProjectionY("fHistNCandDstar", 3, 3);
      TH1F *fHistNCandDs = (TH1F *)fHistNCand->ProjectionY("fHistNCandDs", 4, 4);
      TH1F *fHistNCandLc = (TH1F *)fHistNCand->ProjectionY("fHistNCandLc", 5, 5);
      
      TString names[5] = {"Dzero", "Dplus", "Dstar", "Ds", "Lc2pkpi"};
      TString type[2] = {"Prompt", "Feeddown"};
      const Int_t nDecays = 5;
      TH2F *fHistXvtxResVsPt[2 * nDecays];
      TH2F *fHistYvtxResVsPt[2 * nDecays];
      TH2F *fHistZvtxResVsPt[2 * nDecays];
      TH2F *fHistInvMassVsPt[2 * nDecays];
      TH2F *fHistDecLenVsPt[2 * nDecays];
      TH2F *fHistNormDLxyVsPt[2 * nDecays];
      TH2F *fHistCosPointVsPt[2 * nDecays];
      
      TH3F *fHistPtYMultGenDauInAcc[2 * nDecays];
      TH3F *fHistPtYMultRecoFilt[2 * nDecays];
      
      TProfile *fHistXvtxRes[2 * nDecays];
      TProfile *fHistYvtxRes[2 * nDecays];
      TProfile *fHistZvtxRes[2 * nDecays];
      TProfile *fHistXvtxMean[2 * nDecays];
      TProfile *fHistYvtxMean[2 * nDecays];
      TProfile *fHistZvtxMean[2 * nDecays];
      
      TH1F *fHistXvtxRes2[2 * nDecays];
      TH1F *fHistYvtxRes2[2 * nDecays];
      TH1F *fHistZvtxRes2[2 * nDecays];
      
      TProfile *fHistInvMass[2 * nDecays];
      TProfile *fHistDecLen[2 * nDecays];
      TProfile *fHistCosp[2 * nDecays];
      
      TH1F *fHistInvMassRes[2 * nDecays];
      
      TH1F *hEffPt[2 * nDecays];
      TH1F *htemp;
      
      for (Int_t j = 0; j < 5; j++)
	{ //decays
	  for (Int_t i = 0; i < 2; i++)
	    { //prompt and fd
	      Int_t index = j * 2 + i;
	      fHistXvtxResVsPt[index] = (TH2F *)list->FindObject(Form("hXvtxResVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistYvtxResVsPt[index] = (TH2F *)list->FindObject(Form("hYvtxResVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistZvtxResVsPt[index] = (TH2F *)list->FindObject(Form("hZvtxResVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistInvMassVsPt[index] = (TH2F *)list->FindObject(Form("hInvMassVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistDecLenVsPt[index] = (TH2F *)list->FindObject(Form("hDecLenVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistCosPointVsPt[index] = (TH2F *)list->FindObject(Form("hCosPointVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistPtYMultGenDauInAcc[index] = (TH3F *)list->FindObject(Form("hPtYMult%sGenDauInAcc%s", type[i].Data(), names[j].Data()));
	      fHistPtYMultRecoFilt[index] = (TH3F *)list->FindObject(Form("hPtYMult%sRecoFilt%s", type[i].Data(), names[j].Data()));
	      
	      fHistXvtxMean[index] = (TProfile *)fHistXvtxResVsPt[index]->ProfileX(Form("hXvtxMean%s%s", type[i].Data(), names[j].Data()));
	      fHistXvtxMean[index]->SetLineColor(color[j]);
	      fHistXvtxMean[index]->SetLineWidth(2);
	      fHistXvtxMean[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistXvtxMean[index]->GetYaxis()->SetTitle("Xvtx (reco-true) mean (#mum)");
	      fHistXvtxMean[index]->SetTitle("Xvtx residual vs pT");

	      fHistYvtxMean[index] = (TProfile *)fHistYvtxResVsPt[index]->ProfileX(Form("hYvtxMean%s%s", type[i].Data(), names[j].Data()));
	      fHistYvtxMean[index]->SetLineColor(color[j]);
	      fHistYvtxMean[index]->SetLineWidth(2);
	      fHistYvtxMean[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistYvtxMean[index]->GetYaxis()->SetTitle("Yvtx (reco-true) mean (#mum)");
	      fHistYvtxMean[index]->SetTitle("Yvtx residual vs pT");

	      fHistZvtxMean[index] = (TProfile *)fHistZvtxResVsPt[index]->ProfileX(Form("hZvtxMean%s%s", type[i].Data(), names[j].Data()));
	      fHistZvtxMean[index]->SetLineColor(color[j]);
	      fHistZvtxMean[index]->SetLineWidth(2);
	      fHistZvtxMean[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistZvtxMean[index]->GetYaxis()->SetTitle("Zvtx (reco-true) mean (#mum)");
	      fHistZvtxMean[index]->SetTitle("Zvtx residual vs pT");

	      fHistXvtxRes[index] = (TProfile *)fHistXvtxResVsPt[index]->ProfileX(Form("hXvtxRes%s%s", type[i].Data(), names[j].Data()), 1, -1, "s");
	      fHistYvtxRes[index] = (TProfile *)fHistYvtxResVsPt[index]->ProfileX(Form("hYvtxRes%s%s", type[i].Data(), names[j].Data()), 1, -1, "s");
	      fHistZvtxRes[index] = (TProfile *)fHistZvtxResVsPt[index]->ProfileX(Form("hZvtxRes%s%s", type[i].Data(), names[j].Data()), 1, -1, "s");
	      fHistXvtxRes2[index] = (TH1F *)fHistXvtxResVsPt[index]->ProjectionX(Form("hXvtxRes2%s%s", type[i].Data(), names[j].Data()));
	      fHistYvtxRes2[index] = (TH1F *)fHistYvtxResVsPt[index]->ProjectionX(Form("hYvtxRes2%s%s", type[i].Data(), names[j].Data()));
	      fHistZvtxRes2[index] = (TH1F *)fHistZvtxResVsPt[index]->ProjectionX(Form("hZvtxRes2%s%s", type[i].Data(), names[j].Data()));
	      fHistXvtxRes[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistXvtxRes[index]->GetYaxis()->SetTitle("Xvtx (reco-true) RMS (#mum)");
	      fHistXvtxRes[index]->SetTitle("Xvtx resolution vs pT");
	      fHistYvtxRes[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistYvtxRes[index]->GetYaxis()->SetTitle("Yvtx (reco-true) RMS (#mum)");
	      fHistYvtxRes[index]->SetTitle("Yvtx resolution vs pT");
	      fHistZvtxRes[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistZvtxRes[index]->GetYaxis()->SetTitle("Zvtx (reco-true) RMS (#mum)");
	      fHistZvtxRes[index]->SetTitle("Zvtx resolution vs pT");

	      fHistXvtxRes2[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistXvtxRes2[index]->GetYaxis()->SetTitle("Xvtx (reco-true) RMS (#mum)");
	      fHistXvtxRes2[index]->SetTitle("Xvtx resolution vs pT");
	      fHistYvtxRes2[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistYvtxRes2[index]->GetYaxis()->SetTitle("Yvtx (reco-true) RMS (#mum)");
	      fHistYvtxRes2[index]->SetTitle("Yvtx resolution vs pT");
	      fHistZvtxRes2[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistZvtxRes2[index]->GetYaxis()->SetTitle("Zvtx (reco-true) RMS (#mum)");
	      fHistZvtxRes2[index]->SetTitle("Zvtx resolution vs pT");

	      fHistXvtxRes2[index]->SetLineColor(color[j]);
	      fHistYvtxRes2[index]->SetLineColor(color[j]);
	      fHistZvtxRes2[index]->SetLineColor(color[j]);
	      fHistXvtxRes2[index]->SetMarkerColor(color[j]);
	      fHistXvtxRes2[index]->SetMarkerStyle(20);
	      fHistYvtxRes2[index]->SetMarkerColor(color[j]);
	      fHistYvtxRes2[index]->SetMarkerStyle(20);
	      fHistZvtxRes2[index]->SetMarkerColor(color[j]);
	      fHistZvtxRes2[index]->SetMarkerStyle(20);
	      fHistXvtxRes2[index]->SetLineWidth(2);
	      fHistYvtxRes2[index]->SetLineWidth(2);
	      fHistZvtxRes2[index]->SetLineWidth(2);
	      fHistXvtxRes2[index]->Sumw2();
	      fHistYvtxRes2[index]->Sumw2();
	      fHistZvtxRes2[index]->Sumw2();

	      fHistInvMass[index] = (TProfile *)fHistInvMassVsPt[index]->ProfileX(Form("hInvMassVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistInvMass[index]->SetLineColor(color[j]);
	      fHistInvMass[index]->SetLineWidth(2);
	      fHistInvMass[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistInvMass[index]->GetYaxis()->SetTitle("Inv Mass (GeV/c2)");
	      fHistInvMass[index]->SetTitle("Inv Mass vs pT");

	      fHistDecLen[index] = (TProfile *)fHistDecLenVsPt[index]->ProfileX(Form("hDecLenVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistDecLen[index]->SetLineColor(color[j]);
	      fHistDecLen[index]->SetLineWidth(2);
	      fHistDecLen[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistDecLen[index]->GetYaxis()->SetTitle("Dec Len (#mum)");
	      fHistDecLen[index]->SetTitle("Prompt Dec Len vs pT");

	      fHistCosp[index] = (TProfile *)fHistCosPointVsPt[index]->ProfileX(Form("hCosPVsPt%s%s", type[i].Data(), names[j].Data()));
	      fHistCosp[index]->SetLineColor(color[j]);
	      fHistCosp[index]->SetLineWidth(2);
	      fHistCosp[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      fHistCosp[index]->GetYaxis()->SetTitle("Cos Point");
	      fHistCosp[index]->SetTitle("Prompt CosPoint vs pT");

	      if (index % 2 == 1)
		fHistDecLen[index]->SetTitle("FeedDown Dec Len vs pT");

	      htemp = (TH1F *)fHistPtYMultGenDauInAcc[index]->ProjectionX(Form("hPtDen%s%s", type[i].Data(), names[j].Data()));
	      hEffPt[index] = (TH1F *)fHistPtYMultRecoFilt[index]->ProjectionX(Form("hPtNum%s%s", type[i].Data(), names[j].Data()));
	      fHistPtYMultGenDauInAcc[index]->Sumw2();
	      fHistPtYMultRecoFilt[index]->Sumw2();
	      hEffPt[index]->Sumw2();
	      hEffPt[index]->Divide(htemp);
	      hEffPt[index]->SetLineColor(color[j]);
	      hEffPt[index]->SetLineWidth(2);
	      hEffPt[index]->GetXaxis()->SetTitle("pT (GeV/c)");
	      hEffPt[index]->GetYaxis()->SetTitle("Prompt Efficiency");
	      hEffPt[index]->SetTitle("Prompt Efficiency");
	      hEffPt[index]->SetStats(0);
	      fHistCosp[index]->SetStats(0);
	      fHistDecLen[index]->SetStats(0);

	      if (index % 2 == 1)
		{
		  hEffPt[index]->GetYaxis()->SetTitle("Feeddown Efficiency");
		  hEffPt[index]->SetTitle("Feeddown Efficiency");
		}

	      fHistInvMassRes[index] = new TH1F(*hEffPt[index]);
	      for (Int_t jj = 1; jj < hEffPt[index]->GetNbinsX() + 1; jj++)
		{
		  TH1F *hTemp = (TH1F *)fHistInvMassVsPt[index]->ProjectionY("htemp", jj, jj);
		  fHistInvMassRes[index]->SetBinContent(jj, hTemp->GetRMS());
		  fHistInvMassRes[index]->SetBinError(jj, hTemp->GetRMSError());
		  fHistInvMassRes[index]->SetLineColor(color[j]);
		  fHistInvMassRes[index]->SetLineWidth(2);
		  fHistInvMassRes[index]->GetXaxis()->SetTitle("pT (GeV/c)");
		  fHistInvMassRes[index]->GetYaxis()->SetTitle("Inv Mass RMS (GeV/c2)");
		  fHistInvMassRes[index]->SetTitle("Inv Mass RMS vs pT");
		  if (index == 0)
		    printf("D0: pt=%f, res=%f \n", fHistInvMassRes[index]->GetBinCenter(jj), fHistInvMassRes[index]->GetBinContent(jj));
		  TH1F *hTempX = (TH1F *)fHistXvtxResVsPt[index]->ProjectionY("htempX", jj, jj);
		  TH1F *hTempY = (TH1F *)fHistYvtxResVsPt[index]->ProjectionY("htempY", jj, jj);
		  TH1F *hTempZ = (TH1F *)fHistZvtxResVsPt[index]->ProjectionY("htempZ", jj, jj);

		  fHistXvtxRes2[index]->SetBinContent(jj, hTempX->GetRMS());
		  fHistXvtxRes2[index]->SetBinError(jj, hTempX->GetRMSError());

		  fHistYvtxRes2[index]->SetBinContent(jj, hTempY->GetRMS());
		  fHistYvtxRes2[index]->SetBinError(jj, hTempY->GetRMSError());

		  fHistZvtxRes2[index]->SetBinContent(jj, hTempZ->GetRMS());
		  fHistZvtxRes2[index]->SetBinError(jj, hTempZ->GetRMSError());
		}
	    }
	}

      fHistNCandDplus->SetLineColor(2);
      fHistNCandDstar->SetLineColor(3);
      fHistNCandDs->SetLineColor(4);
      fHistNCandLc->SetLineColor(kOrange);
      fHistNCandDplus->SetLineWidth(2);
      fHistNCandDstar->SetLineWidth(2);
      fHistNCandDs->SetLineWidth(2);
      fHistNCandLc->SetLineWidth(2);

      fHistNCandDzero->GetXaxis()->SetTitle("pT (GeV/c)");
      fHistNCandDzero->GetYaxis()->SetTitle("counts");
      TLegend *leg = new TLegend(0.6, 0.7, 0.8, 0.9);
      leg->AddEntry(fHistNCandDzero, "Dzero", "l");
      leg->AddEntry(fHistNCandDplus, "Dplus", "l");
      leg->AddEntry(fHistNCandDstar, "Dstar", "l");
      leg->AddEntry(fHistNCandDs, "Ds", "l");
      leg->AddEntry(fHistNCandLc, "Lc", "l");

      TLegend *leg1 = new TLegend(0.5, 0.7, 0.7, 0.9);
      leg1->AddEntry(fHistYvtxRes2[0], "Dzero", "pl");
      leg1->AddEntry(fHistYvtxRes2[2], "Dplus", "pl");
      if (drawOnlyDzerDplus == 0)
	leg1->AddEntry(fHistYvtxRes2[6], "Ds", "pl");
      if (drawOnlyDzerDplus == 0)
	leg1->AddEntry(fHistYvtxRes2[8], "Lc", "pl");

      TLegend *leg2 = new TLegend(0.5, 0.7, 0.7, 0.9);
      leg2->AddEntry(fHistYvtxMean[0], "Dzero", "l");
      leg2->AddEntry(fHistYvtxMean[2], "Dplus", "l");
      if (drawOnlyDzerDplus == 0)
	leg2->AddEntry(fHistYvtxMean[6], "Ds", "l");
      if (drawOnlyDzerDplus == 0)
	leg2->AddEntry(fHistYvtxMean[8], "Lc", "l");

      TLegend *leg3 = new TLegend(0.2, 0.7, 0.4, 0.9);
      leg3->AddEntry(fHistNCandDzero, "Dzero", "l");
      leg3->AddEntry(fHistNCandDplus, "Dplus", "l");
      if (drawOnlyDzerDplus == 0)
	leg3->AddEntry(fHistNCandDstar, "Dstar", "l");
      if (drawOnlyDzerDplus == 0)
	leg3->AddEntry(fHistNCandDs, "Ds", "l");
      if (drawOnlyDzerDplus == 0)
	leg3->AddEntry(fHistNCandLc, "Lc", "l");

      TLegend *leg4 = new TLegend(0.7, 0.7, 0.9, 0.9);
      leg4->AddEntry(fHistNCandDzero, "Dzero", "l");
      leg4->AddEntry(fHistNCandDplus, "Dplus", "l");
      if (drawOnlyDzerDplus == 0)
	leg4->AddEntry(fHistNCandDstar, "Dstar", "l");
      if (drawOnlyDzerDplus == 0)
	leg4->AddEntry(fHistNCandDs, "Ds", "l");
      if (drawOnlyDzerDplus == 0)
	leg4->AddEntry(fHistNCandLc, "Lc", "l");

      TCanvas *c0_1 = new TCanvas("c0_1", "c0_1", 500, 500);
      hnGenD->SetTitle("number of generated D mesons");
      hnGenD->Draw();
      c0_1->SaveAs("plotDgen.png");

      TCanvas *c0_2 = new TCanvas("c0_2", "c0_2", 500, 500);
      c0_2->SetLogy();

      fHistNCandDs->SetTitle("Candidates passing filtering cuts");
      fHistNCandDs->Draw("");
      c0_2->Update();
      TPaveStats *stats = (TPaveStats *)c0_2->GetPrimitive("stats");
      stats->SetName("h1stats");
      stats->SetY1NDC(0.5);
      stats->SetY2NDC(0.35);
      c0_2->Update();

      fHistNCandDplus->Draw("sames");
      c0_2->Update();
      TPaveStats *stats2 = (TPaveStats *)c0_2->GetPrimitive("stats");
      stats2->SetName("h2stats");
      stats2->SetY1NDC(0.8);
      stats2->SetY2NDC(.65);
      c0_2->Update();

      fHistNCandDstar->Draw("sames");
      c0_2->Update();
      TPaveStats *stats3 = (TPaveStats *)c0_2->GetPrimitive("stats");
      stats3->SetName("h3stats");
      stats3->SetY1NDC(0.65);
      stats3->SetY2NDC(.5);
      c0_2->Update();

      fHistNCandDzero->Draw("sames");
      c0_2->Update();
      TPaveStats *stats4 = (TPaveStats *)c0_2->GetPrimitive("stats");
      stats4->SetName("h4stats");
      stats4->SetY1NDC(0.95);
      stats4->SetY2NDC(.8);
      c0_2->Update();

      fHistNCandLc->Draw("sames");
      c0_2->Update();
      TPaveStats *stats5 = (TPaveStats *)c0_2->GetPrimitive("stats");
      stats5->SetName("h1stats");
      stats5->SetY1NDC(0.35);
      stats5->SetY2NDC(.2);
      c0_2->Update();
      leg->Draw();
      c0_2->SaveAs("plotDcandpt.png");

      TCanvas *c0_3 = new TCanvas("c0_3", "c0_3", 500, 500);
      fHistInvMass[0]->SetMinimum(1.6);
      fHistInvMass[0]->SetMaximum(2.4);
      fHistInvMass[0]->Draw();
      fHistInvMass[2]->Draw("sames");
      fHistInvMass[4]->Draw("sames");
      fHistInvMass[6]->Draw("sames");
      fHistInvMass[8]->Draw("sames");
      leg->Draw();
      c0_3->SaveAs("plotDcandInvMass.png");

      TCanvas *c0_4 = new TCanvas("c0_4", "c0_4", 500, 500);
      //fHistInvMassRes[0]->SetMinimum(1.6);
      //fHistInvMassRes[0]->SetMaximum(2.4);

      fHistInvMassRes[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistInvMassRes[0]->SetTitle("D0 Inv Mass RMS vs pT");
      fHistInvMassRes[0]->Draw("");
      //  fHistInvMassRes[2]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistInvMassRes[4]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistInvMassRes[6]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistInvMassRes[8]->Draw("sames");
      //leg->Draw();
      c0_4->SaveAs("plotD0candInvMassWidth.png");

      fHistXvtxMean[0]->SetStats(0);
      fHistYvtxMean[0]->SetStats(0);
      fHistZvtxMean[0]->SetStats(0);
      fHistXvtxMean[2]->SetStats(0);
      fHistYvtxMean[2]->SetStats(0);
      fHistZvtxMean[2]->SetStats(0);
      fHistXvtxRes2[0]->SetStats(0);
      fHistYvtxRes2[0]->SetStats(0);
      fHistZvtxRes2[0]->SetStats(0);
      fHistXvtxRes2[2]->SetStats(0);
      fHistYvtxRes2[2]->SetStats(0);
      fHistZvtxRes2[2]->SetStats(0);

      TCanvas *cc = new TCanvas("cc", "cc", 1200, 500);
      cc->Divide(3, 1);
      cc->cd(1);
      fHistXvtxMean[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistXvtxMean[0]->SetMinimum(-300.);
      fHistXvtxMean[0]->SetMaximum(300.);
      fHistXvtxMean[0]->Draw();

      fHistXvtxMean[2]->Draw("sames");
      leg2->Draw();

      cc->cd(2);

      fHistYvtxMean[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistYvtxMean[0]->SetMinimum(-300.);
      fHistYvtxMean[0]->SetMaximum(300.);
      fHistYvtxMean[0]->Draw();
      fHistYvtxMean[2]->Draw("sames");
      leg2->Draw();

      cc->cd(3);
      fHistZvtxMean[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistZvtxMean[0]->SetMinimum(-300.);
      fHistZvtxMean[0]->SetMaximum(300.);
      fHistZvtxMean[0]->Draw();
      fHistZvtxMean[2]->Draw("sames");
      leg2->Draw();
      cc->SaveAs("plotXYZVtxMean.png");
      /////////

      TCanvas *ccr = new TCanvas("ccr", "ccr", 1200, 500);
      ccr->Divide(3, 1);
      ccr->cd(1);
      fHistXvtxRes2[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistXvtxRes2[0]->SetMinimum(0.);
      fHistXvtxRes2[0]->SetMaximum(500.);
      fHistXvtxRes2[0]->Draw();
      fHistXvtxRes2[2]->Draw("sames");
      leg2->Draw();

      ccr->cd(2);
      fHistYvtxRes2[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistYvtxRes2[0]->SetMinimum(0.);
      fHistYvtxRes2[0]->SetMaximum(500.);
      fHistYvtxRes2[0]->Draw();
      fHistYvtxRes2[2]->Draw("sames");
      leg2->Draw();

      ccr->cd(3);
      fHistZvtxRes2[0]->GetYaxis()->SetTitleOffset(1.4);
      fHistZvtxRes2[0]->SetMinimum(0.);
      fHistZvtxRes2[0]->SetMaximum(500.);
      fHistZvtxRes2[0]->Draw();
      fHistZvtxRes2[2]->Draw("sames");
      leg2->Draw();
      ccr->SaveAs("plotXYZVtxRMS.png");

      TCanvas *ccc = new TCanvas("ccc", "ccc", 1200, 800);
      ccc->Divide(3, 2);
      ccc->cd(1);
      fHistDecLen[0]->GetYaxis()->SetTitleOffset(1.45);
      fHistDecLen[0]->Draw();
      fHistDecLen[2]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[4]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[6]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[8]->Draw("sames");
      leg3->Draw();

      ccc->cd(2);
      fHistCosp[0]->GetYaxis()->SetTitleOffset(1.45);
      fHistCosp[0]->Draw();
      fHistCosp[2]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[4]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[6]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[8]->Draw("sames");
      leg4->Draw();

      ccc->cd(3);
      hEffPt[0]->GetYaxis()->SetTitleOffset(1.45);
      hEffPt[0]->Draw();
      hEffPt[2]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[4]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[6]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[8]->Draw("sames");
      leg3->Draw();

      ccc->cd(4);
      fHistDecLen[1]->GetYaxis()->SetTitleOffset(1.45);
      fHistDecLen[1]->Draw();
      fHistDecLen[3]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[5]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[7]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistDecLen[9]->Draw("sames");
      leg3->Draw();

      ccc->cd(5);
      fHistCosp[1]->GetYaxis()->SetTitleOffset(1.45);
      fHistCosp[1]->Draw();
      fHistCosp[3]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[5]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[7]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	fHistCosp[9]->Draw("sames");
      leg4->Draw();

      ccc->cd(6);
      hEffPt[1]->GetYaxis()->SetTitleOffset(1.45);
      hEffPt[1]->Draw();
      hEffPt[3]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[5]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[7]->Draw("sames");
      if (drawOnlyDzerDplus == 0)
	hEffPt[9]->Draw("sames");
      leg3->Draw();

      ccc->SaveAs("plot_DL_cosp_Eff_prompt_fd.png");
    }
  }

  trtree->Fill();

  if(runNumber>0){
    TFile* foutfile=new TFile("trendingHF.root","recreate");
    trtree->Write();
    TDirectory* outdir=foutfile->mkdir(dirD2H->GetName());
    outdir->cd();
    listD2H->Write(listD2H->GetName(),1);
    foutfile->cd();
    if(dir && list){
      TDirectory* outdir2=foutfile->mkdir(dir->GetName());
      outdir2->cd();
      list->Write(list->GetName(),1);
    }
    foutfile->Close();
    delete foutfile;
  }
}
Ejemplo n.º 17
0
void cetaflatHEM3t(int nIterN=1, double Ethr1=4, double Ethr2=150) {

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

    char ctit[145];

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

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

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

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

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

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

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

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


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

    TCanvas *cx[400];
    TSpline5 *tt;

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}
Ejemplo n.º 18
0
void DrawMLPoutputMovie( TFile* file, const TString& methodType, const TString& methodTitle )
{
   gROOT->SetBatch( 1 );

   // define Canvas layout here!
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas* c = 0;

   Float_t nrms = 4;
   Float_t xmin = -1.2;
   Float_t xmax = 1.2;
   Float_t ymin = 0;
   Float_t ymax = 0;
   Float_t maxMult = 6.0;
   Int_t   countCanvas = 0;
   Bool_t  first = kTRUE;
            
   TString     dirname  = methodType + "/" + methodTitle + "/" + "EpochMonitoring";
   TDirectory *epochDir = (TDirectory*)file->Get( dirname );
   if (!epochDir) {
      cout << "Big troubles: could not find directory \"" << dirname << "\"" << endl;
      exit(1);
   }

   // now read all evolution histograms
   TIter keyItTit(epochDir->GetListOfKeys());
   TKey *titkeyTit;
   while ((titkeyTit = (TKey*)keyItTit())) {
      
      if (!gROOT->GetClass(titkeyTit->GetClassName())->InheritsFrom("TH1F")) continue;
      TString name = titkeyTit->GetName();
      
      if (!name.BeginsWith("convergencetest___")) continue;
      if (!name.Contains("_train_"))              continue; // only for training so far
      if (name.EndsWith( "_B"))                   continue;
      
      // must be signal histogram
      if (!name.EndsWith( "_S")) {
         cout << "Big troubles with histogram: " << name << " -> should end with _S" << endl;
         exit(1);
      }
      
      // create canvas
      countCanvas++;
      TString ctitle = Form("TMVA response %s",methodTitle.Data());
      c = new TCanvas( Form("canvas%d", countCanvas), ctitle, 0, 0, width, (Int_t)width*0.78 ); 
      
      TH1F* sig = (TH1F*)titkeyTit->ReadObj();
      sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
      
      TString dataType = (name.Contains("_train_") ? "(training sample)" : "(test sample)");
      
      // find background
      TString nbn = sig->GetName(); nbn[nbn.Length()-1] = 'B';            
      TH1F* bgd = dynamic_cast<TH1F*>(epochDir->Get( nbn ));
      if (bgd == 0) {
         cout << "Big troubles with histogram: " << bgd << " -> cannot find!" << endl;
         exit(1);
      }
      
      cout << "sig = " << sig->GetName() << endl;
      cout << "bgd = " << bgd->GetName() << endl;
      
      // set the histogram style
      TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
      
      // normalise both signal and background
      TMVAGlob::NormalizeHists( sig, bgd );
      
      // set only first time, then same for all plots
      if (first) {
         if (xmin == 0 && xmax == 0) {
            xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                          bgd->GetMean() - nrms*bgd->GetRMS() ),
                               sig->GetXaxis()->GetXmin() );
            xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                          bgd->GetMean() + nrms*bgd->GetRMS() ),
                               sig->GetXaxis()->GetXmax() );
         }
         ymin = 0;
         ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
         first = kFALSE;
      }
      
      // build a frame
      Int_t nb = 100;
      TString hFrameName(TString("frame") + methodTitle);
      TObject *o = gROOT->FindObject(hFrameName);
      if(o) delete o;
      TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                              nb, xmin, xmax, nb, ymin, ymax );
      frame->GetXaxis()->SetTitle( methodTitle + " response" );
      frame->GetYaxis()->SetTitle("(1/N) dN^{ }/^{ }dx");
      TMVAGlob::SetFrameStyle( frame );
      
      // find epoch number (4th token)
      TObjArray* tokens = name.Tokenize("_");
      TString es = ((TObjString*)tokens->At(4))->GetString();
      if (!es.IsFloat()) {
         cout << "Big troubles in epoch parsing: \"" << es << "\" is not float" << endl;
         exit(1);
      }
      Int_t epoch = es.Atoi();
      
      // eventually: draw the frame
      frame->Draw();  
      
      c->GetPad(0)->SetLeftMargin( 0.105 );
      frame->GetYaxis()->SetTitleOffset( 1.2 );
      
      // Draw legend               
      TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                    c->GetLeftMargin() + 0.5, 1 - c->GetTopMargin() );
      legend->SetFillStyle( 1 );
      legend->AddEntry(sig,TString("Signal ")     + dataType, "F");
      legend->AddEntry(bgd,TString("Background ") + dataType, "F");
      legend->SetBorderSize(1);
      legend->SetMargin( 0.15 );
      legend->Draw("same");
      
      TText* t = new TText();            
      t->SetTextSize( 0.04 );
      t->SetTextColor( 1 );
      t->SetTextAlign( 31 );
      t->DrawTextNDC( 1 - c->GetRightMargin(), 1 - c->GetTopMargin() + 0.015, Form( "Epoch: %i", epoch) );
      
      // overlay signal and background histograms
      sig->Draw("samehist");
      bgd->Draw("samehist");
      
      // save to file
      TString dirname  = "movieplots";
      TString foutname = dirname + "/" + name;
      foutname.Resize( foutname.Length()-2 );
      foutname.ReplaceAll("convergencetest___","");
      foutname += ".gif";
      
      cout << "storing file: " << foutname << endl;
      
      c->Update();
      c->Print(foutname);            
   }
}
void plotPedestalAnalysis(string inputFileName, string outputDIR, bool testDoubleGaussianChannels){

  system(("mkdir -p "+outputDIR).c_str());

  setTDRStyle();
  gROOT->SetBatch(kTRUE);

  TFile* inputFile = TFile::Open(inputFileName.c_str(),"READ");
  inputFile->cd();
  TTree* tree = (TTree*) inputFile->Get("pedestalFullNoise");

  uint32_t detid,fedKey;
  uint16_t fecCrate,fecSlot, fecRing, ccuAdd, ccuChan, lldChannel, fedId, fedCh, apvId, stripId;
  float    fitChi2Probab, kSProbab, jBProbab, aDProbab, fitChi2;
  float    noiseSkewness, noiseKurtosis;
  float    fitGausMean, fitGausSigma, fitGausNormalization;
  float    fitGausMeanError, fitGausSigmaError, fitGausNormalizationError;
  vector<float>* noiseDistribution = 0;
  vector<float>* noiseDistributionError = 0;
  float    nBin, xMin, xMax;

  tree->SetBranchStatus("*",kFALSE);
  tree->SetBranchStatus("detid",kTRUE);
  tree->SetBranchStatus("fedKey",kTRUE);
  tree->SetBranchStatus("fecCrate",kTRUE);
  tree->SetBranchStatus("fecSlot",kTRUE);
  tree->SetBranchStatus("fecRing",kTRUE);
  tree->SetBranchStatus("ccuAdd",kTRUE);
  tree->SetBranchStatus("ccuChan",kTRUE);
  tree->SetBranchStatus("lldChannel",kTRUE);
  tree->SetBranchStatus("fedId",kTRUE);
  tree->SetBranchStatus("fedCh",kTRUE);
  tree->SetBranchStatus("apvId",kTRUE);
  tree->SetBranchStatus("stripId",kTRUE);
  tree->SetBranchStatus("fitChi2",kTRUE);
  tree->SetBranchStatus("fitChi2Probab",kTRUE);
  tree->SetBranchStatus("kSProbab",kTRUE);
  tree->SetBranchStatus("jBProbab",kTRUE);
  tree->SetBranchStatus("aDProbab",kTRUE);
  tree->SetBranchStatus("fitGausNormalization",kTRUE);
  tree->SetBranchStatus("fitGausMean",kTRUE);
  tree->SetBranchStatus("fitGausSigma",kTRUE);
  tree->SetBranchStatus("fitGausNormalizationError",kTRUE);
  tree->SetBranchStatus("fitGausMeanError",kTRUE);
  tree->SetBranchStatus("fitGausSigmaError",kTRUE);
  tree->SetBranchStatus("noiseSkewness",kTRUE);
  tree->SetBranchStatus("noiseKurtosis",kTRUE);
  tree->SetBranchStatus("noiseDistribution",kTRUE);
  tree->SetBranchStatus("noiseDistributionError",kTRUE);
  tree->SetBranchStatus("nBin",kTRUE);
  tree->SetBranchStatus("xMin",kTRUE);
  tree->SetBranchStatus("xMax",kTRUE);

  tree->SetBranchAddress("detid",&detid);
  tree->SetBranchAddress("fedKey",&fedKey);
  tree->SetBranchAddress("fecCrate",&fecCrate);
  tree->SetBranchAddress("fecSlot",&fecSlot);
  tree->SetBranchAddress("fecRing",&fecRing);
  tree->SetBranchAddress("ccuAdd",&ccuAdd);
  tree->SetBranchAddress("ccuChan",&ccuChan);
  tree->SetBranchAddress("lldChannel",&lldChannel);
  tree->SetBranchAddress("fedId",&fedId);
  tree->SetBranchAddress("fedCh",&fedCh);
  tree->SetBranchAddress("apvId",&apvId);
  tree->SetBranchAddress("stripId",&stripId);
  tree->SetBranchAddress("fitGausNormalization",&fitGausNormalization);
  tree->SetBranchAddress("fitGausMean",&fitGausMean);
  tree->SetBranchAddress("fitGausSigma",&fitGausSigma);
  tree->SetBranchAddress("fitGausNormalizationError",&fitGausNormalizationError);
  tree->SetBranchAddress("fitGausMeanError",&fitGausMeanError);
  tree->SetBranchAddress("fitGausSigmaError",&fitGausSigmaError);
  tree->SetBranchAddress("fitChi2",&fitChi2);
  tree->SetBranchAddress("fitChi2Probab",&fitChi2Probab);
  tree->SetBranchAddress("noiseSkewness",&noiseSkewness);
  tree->SetBranchAddress("noiseKurtosis",&noiseKurtosis);
  tree->SetBranchAddress("kSProbab",&kSProbab);
  tree->SetBranchAddress("aDProbab",&aDProbab);
  tree->SetBranchAddress("jBProbab",&jBProbab);
  tree->SetBranchAddress("noiseDistribution",&noiseDistribution);
  tree->SetBranchAddress("noiseDistributionError",&noiseDistributionError);
  tree->SetBranchAddress("nBin",&nBin);
  tree->SetBranchAddress("xMin",&xMin);
  tree->SetBranchAddress("xMax",&xMax);

  TFile* badStripsNFilledBins = new TFile((outputDIR+"/badStripsNFilledBins.root").c_str(),"RECREATE");
  TFile* badKsTest = new TFile((outputDIR+"/badStripsKsTest.root").c_str(),"RECREATE");
  TFile* badjBTest = new TFile((outputDIR+"/badStripsjBTest.root").c_str(),"RECREATE");
  TFile* badChi2Test = new TFile((outputDIR+"/badStripsChi2Test.root").c_str(),"RECREATE");
  TFile* badaDTest = new TFile((outputDIR+"/badStripsaDTest.root").c_str(),"RECREATE");
  TFile* badCombinedTest = new TFile((outputDIR+"/badStripsCombined.root").c_str(),"RECREATE");
  TFile* badJBNotKSTest = new TFile((outputDIR+"/badStripsjBNotKS.root").c_str(),"RECREATE");
  TFile* badaDNotKSandjBTest = new TFile((outputDIR+"/badStripaDNotKSNotjB.root").c_str(),"RECREATE");
  TFile* badChi2NotKSandjBandaDTest = new TFile((outputDIR+"/badStripsChi2NotKsandjBandaD.root").c_str(),"RECREATE");

  long int nbadNFilledBins = 0;
  long int nbadKsTest = 0;
  long int nbadjBTest = 0;
  long int nbadaDTest = 0;
  long int nbadChi2Test = 0;
  long int nbadCombinedTest = 0;
  long int nbadJBNotKSTest = 0;
  long int nbadaDNotKSandjBTest = 0;
  long int nbadChi2NotKSandjBandaDTest = 0;

  long int nbadDoublePeakDistance = 0;
  long int nbadDoublePeakAshman = 0;
  long int nbadDoublePeakChi2 = 0;
  long int nbadDoublePeakAmplitude = 0;
  long int nbadDoublePeakBimodality = 0;
  long int nbadDoublePeakCombined = 0;

  TCanvas* canvas = new TCanvas("canvas","canvas",600,650);

  map<uint32_t,uint32_t> moduleDenominator;
  map<uint32_t,uint32_t> moduleNumerator;
  //  map<uint32_t,uint32_t> moduleNonEdgeNumerator;
  //  map<uint32_t,uint32_t> moduleAPVEdgeNumerator;

  map<uint32_t,uint32_t> moduleNumeratorFilledBins;
  map<uint32_t,uint32_t> moduleNumeratorKS;
  map<uint32_t,uint32_t> moduleNumeratorJB;
  map<uint32_t,uint32_t> moduleNumeratorDoublePeak;

  vector<TrackerStrip> badStrip;

  TH1F* noiseHist = NULL;
  TF1*  noiseFit  = NULL;
  TF1*  noiseFit2Gaus  = NULL;
  TFitResultPtr result;

  TH1F* chi2Distance       = new TH1F("chi2Distance","",100,0,1);
  chi2Distance->Sumw2();
  TH1F* peakDistance    = new TH1F("peakDistance","",100,0,3);
  peakDistance->Sumw2();
  TH1F* ashmanDistance  = new TH1F("ashmanDistance","",100,0,5);
  ashmanDistance->Sumw2();
  TH1F* bimodalityDistance = new TH1F("bimodalityDistance","",100,0,1);
  bimodalityDistance->Sumw2();
  TH1F* amplitudeRatioDistance = new TH1F("amplitudeRatioDistance","",100,0,3);
  amplitudeRatioDistance->Sumw2();

  TFile* multiPeakChannelsChi2       = new TFile((outputDIR+"/multiPeakChannelsChi2.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsDistance   = new TFile((outputDIR+"/multiPeakChannelsDistance.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsAshman     = new TFile((outputDIR+"/multiPeakChannelsAshman.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsAmplitude  = new TFile((outputDIR+"/multiPeakChannelsAmplitude.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsBimodality = new TFile((outputDIR+"/multiPeakChannelsBimodality.root").c_str(),"RECREATE");
  TFile* multiPeakChannelsCombined   = new TFile((outputDIR+"/multiPeakChannelsCombined.root").c_str(),"RECREATE");

  int nonNullBins = 0;
  float chi2Ratio = 0;
  float distance  = 0;
  float ashman    = 0;
  float bimodality = 0;
  float amplitudeRatio = 0;

  bool isfound = false;
  string fedKeyStr ;
  TString name ;
  std::map<string,string> fitParam;
 
  for(long int iChannel = 0; iChannel < tree->GetEntries(); iChannel++){
    tree->GetEntry(iChannel);
    cout.flush();
    if(iChannel %10000 == 0) cout<<"\r"<<"iChannel "<<100*double(iChannel)/(tree->GetEntries()/reductionFactor)<<" % ";
    if(iChannel > double(tree->GetEntries())/reductionFactor) break;

    // skip problematic fed id
    isfound = false;
    for(auto skipfed : skipFEDid){
      if(fedId == skipfed) isfound = true;
    }
    if(isfound) continue;

    // make selections to identify bad noisy channels (not gaussian ones)
    std::stringstream stream;
    stream << std::hex << fedKey;
    fedKeyStr = stream.str();
    if(fedKeyStr.size() == 4)
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x0000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);
    else if(fedKeyStr.size() == 5)
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);
  
    fitParam.clear();
    stringstream sMean;
    sMean << std::scientific << fitGausMean;
    fitParam["fitGausMean"]   = sMean.str();
    stringstream sSigma;
    sSigma << std::scientific << fitGausSigma;
    fitParam["fitGausSigma"]  = sSigma.str();
    stringstream sSkew;
    sSkew << std::scientific << noiseSkewness;
    fitParam["noiseSkewness"] = sSkew.str();
    stringstream sKurt;
    sKurt << std::scientific << noiseKurtosis;
    fitParam["noiseKurtosis"] = sKurt.str();
    stringstream sKS;
    sKS << std::scientific << kSProbab;
    fitParam["kSProbab"] = sKS.str();
    stringstream sJB;
    sJB << std::scientific << jBProbab;
    fitParam["jBProbab"] = sJB.str();
    stringstream sChi2;
    sChi2 << std::scientific << fitChi2Probab;
    fitParam["fitChi2Probab"] = sChi2.str();
    stringstream sAD;
    sAD << std::scientific << aDProbab;
    fitParam["aDProbab"] = sAD.str();

    moduleDenominator[detid] = moduleDenominator[detid]+1;
    if(noiseHist == NULL){
      noiseHist = new TH1F ("noiseHist","",nBin,xMin,xMax);
      noiseHist->Sumw2();
    }
    noiseHist->Reset();
    
    for(int iBin = 0; iBin < noiseDistribution->size(); iBin++){
      noiseHist->SetBinContent(iBin+1,noiseDistribution->at(iBin));
      noiseHist->SetBinError(iBin+1,noiseDistributionError->at(iBin));
    }

    if(noiseFit == NULL)
      noiseFit = new TF1 ("noiseFist","gaus(0)",xMin,xMax);
    
    noiseFit->SetRange(xMin,xMax);
    noiseFit->SetParameters(fitGausNormalization,fitGausMean,fitGausSigma);
    noiseFit->SetParError(0,fitGausNormalizationError);
    noiseFit->SetParError(1,fitGausMeanError);
    noiseFit->SetParError(2,fitGausSigmaError);

    nonNullBins = 0;
    for(int iBin = 0; iBin < noiseHist->GetNbinsX(); iBin++){
      if(noiseHist->GetBinContent(iBin+1) != 0) nonNullBins++;
    }

    if(nonNullBins < nFilledBinSelection or noiseHist->GetRMS() < minimumRMS){
      badStripsNFilledBins->cd();
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);
      nbadNFilledBins++;
      moduleNumeratorFilledBins[detid] +=1;
      continue;
    }


    if(kSProbab < quantile3sigma){
      badKsTest->cd();
      nbadKsTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      moduleNumeratorKS[detid] += 1;
    }
    
    if(jBProbab < quantile5sigma){
      badjBTest->cd();
      nbadjBTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(fitChi2Probab < quantile4sigma){
      badChi2Test->cd();
      nbadChi2Test++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(aDProbab < quantile3sigma){
      badaDTest->cd();
      nbadaDTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);
    }
    if(jBProbab < quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile){
      badJBNotKSTest->cd();
      nbadJBNotKSTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      moduleNumeratorJB[detid] += 1;
    }

    if(aDProbab < quantile3sigma and jBProbab > quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile){
      badaDNotKSandjBTest->cd();
      nbadaDNotKSandjBTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }


    if(fitChi2Probab < quantile4sigma and jBProbab > quantile5sigma and kSProbab > quantile3sigma and kSProbab < quantile and aDProbab > quantile3sigma){
      badChi2NotKSandjBandaDTest->cd();
      nbadChi2NotKSandjBandaDTest++;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
    }

    if(kSProbab < quantile3sigma or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab < quantile5sigma) or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab > quantile5sigma and aDProbab < quantile3sigma)  or (kSProbab > quantile3sigma and kSProbab < quantile and jBProbab > quantile5sigma and aDProbab > quantile3sigma and fitChi2Probab < quantile4sigma)){
      badCombinedTest->cd();
      nbadCombinedTest++;
      moduleNumerator[detid] = moduleNumerator[detid]+1;
      //if(stripId == 1 or stripId == 128)
      //  moduleAPVEdgeNumerator[detid] = moduleAPVEdgeNumerator[detid]+1;
      //else
      //  moduleNonEdgeNumerator[detid] = moduleNonEdgeNumerator[detid]+1;
      storeOutputCanvas(canvas,noiseHist,noiseFit,name,fitParam);      
      name = Form("fecCrate%d_fecSlot%d_fecRing%d_ccuAdd%d_ccuCh%d_fedKey0x0000%s_lldCh%d_apv%d_strip%d",fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,fedKeyStr.c_str(),lldChannel,apvId,stripId);      
      badStrip.push_back(TrackerStrip(fecCrate,fecSlot,fecRing,ccuAdd,ccuChan,uint32_t(atoi(fedKeyStr.c_str())),lldChannel,apvId,stripId));

      //try to identify double peaked channels
      if(testDoubleGaussianChannels){
	if(noiseFit2Gaus == NULL)
	  // double gaussian in which the sigma is constrained to be the same --> identifing clear two peak channels
	  noiseFit2Gaus = new TF1("dgaus","[0]*exp(-((x-[1])*(x-[1]))/(2*[2]*[2]))+[3]*exp(-((x-[4])*(x-[4]))/(2*[5]*[5]))",xMin,xMax);

	noiseFit2Gaus->SetRange(xMin,xMax);
	noiseFit2Gaus->SetParameter(0,fitGausNormalization/2);
	noiseFit2Gaus->SetParameter(3,fitGausNormalization/2);
	noiseFit2Gaus->SetParameter(1,1.);
	noiseFit2Gaus->SetParameter(4,-1.);
	noiseFit2Gaus->SetParameter(2,fitGausSigma);
	noiseFit2Gaus->SetParameter(5,fitGausSigma);
	noiseFit2Gaus->SetParLimits(1,0.,xMax);
	noiseFit2Gaus->SetParLimits(4,xMin,0);
	result = noiseHist->Fit(noiseFit2Gaus,"QSR");

	chi2Ratio = 0;
	distance  = 0;
	ashman    = 0;
	bimodality = 0;
	amplitudeRatio = 0;
	if(result.Get() or noiseHist->Integral() == 0){

	  //compute the chi2 ratio
	  chi2Ratio = 0.5*ROOT::Math::chisquared_cdf_c((fitChi2/(result->Ndf()+3))/(result->Chi2()/result->Ndf()),1);
	  chi2Distance->Fill(chi2Ratio);			
	  distance = fabs(noiseFit2Gaus->GetParameter(1)-noiseFit2Gaus->GetParameter(4))/(2*sqrt(noiseFit2Gaus->GetParameter(2)*noiseFit2Gaus->GetParameter(5)));
	  peakDistance->Fill(distance);
	  ashman   = TMath::Power(2,0.5)*abs(noiseFit2Gaus->GetParameter(1)-noiseFit2Gaus->GetParameter(4))/(sqrt(pow(noiseFit2Gaus->GetParameter(2),2)+pow(noiseFit2Gaus->GetParameter(5),2)));
	  ashmanDistance->Fill(ashman);	 
	  if(nonNullBins > 3)
	    bimodality = (noiseHist->GetSkewness()*noiseHist->GetSkewness()+1)/(noiseHist->GetKurtosis()+3*(nonNullBins-1)*(nonNullBins-1)/((nonNullBins-2)*(nonNullBins-3)));
	  else
	    bimodality = (noiseHist->GetSkewness()*noiseHist->GetSkewness()+1)/(noiseHist->GetKurtosis());
	  bimodalityDistance->Fill(bimodality);	  
	  amplitudeRatio = std::min(noiseFit2Gaus->GetParameter(0),noiseFit2Gaus->GetParameter(3))/std::max(noiseFit2Gaus->GetParameter(0),noiseFit2Gaus->GetParameter(3));
	  amplitudeRatioDistance->Fill(amplitudeRatio);	
	  
	  if(distance > 1){
	    multiPeakChannelsDistance->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakDistance++;
	}
	  
	  if(ashman > 2){
	    multiPeakChannelsAshman->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakAshman++;
	  }
	  
	  if(chi2Ratio < 0.05){
	    multiPeakChannelsChi2->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakChi2++;
	  }
	  
	  if(amplitudeRatio > 0.85){
	    multiPeakChannelsAmplitude->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakAmplitude++;
	}
	  
	  if(bimodality > 0.55){
	    multiPeakChannelsBimodality->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakBimodality++;
	  }
	  
	  if(ashman > 2 && amplitudeRatio > 0.85){
	    multiPeakChannelsCombined->cd();
	    storeOutputCanvas(canvas,noiseHist,noiseFit,noiseFit2Gaus,name);
	    nbadDoublePeakCombined++;
	    moduleNumeratorDoublePeak[detid]++;
	  }
	}
      }
    }
  }

  // plot the chi2 and peak distance
  if(testDoubleGaussianChannels){
    storeOutputCanvas(canvas,chi2Distance,"chi2TestStatistics",outputDIR);
    storeOutputCanvas(canvas,peakDistance,"peakDistanceTestStatistics",outputDIR);
    storeOutputCanvas(canvas,ashmanDistance,"ashmanTestStatistics",outputDIR);
    storeOutputCanvas(canvas,amplitudeRatioDistance,"amplitudeRatioDistance",outputDIR);
    storeOutputCanvas(canvas,bimodalityDistance,"bimodalityDistance",outputDIR);
  }
  
  std::cout<<std::endl;
  badStripsNFilledBins->Close();
  badKsTest->Close();
  badaDTest->Close();
  badjBTest->Close();
  badChi2Test->Close();
  badCombinedTest->Close();
  badJBNotKSTest->Close();
  badaDNotKSandjBTest->Close();
  badChi2NotKSandjBandaDTest->Close();
  multiPeakChannelsCombined->Close();
  //////
  multiPeakChannelsChi2->Close();
  multiPeakChannelsDistance->Close();
  multiPeakChannelsAshman->Close();
  multiPeakChannelsAmplitude->Close();
  multiPeakChannelsBimodality->Close();

  cout<<"#### Bad Nfilled bins "<<nbadNFilledBins<<" --> "<<double(nbadNFilledBins)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad KS Test Channels "<<nbadKsTest<<" ---> "<<double(nbadKsTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad JB Test Channels "<<nbadjBTest<<" ---> "<<double(nbadjBTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad AD Test Channels "<<nbadaDTest<<" ---> "<<double(nbadaDTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Chi2 Test Channels "<<nbadChi2Test<<" ---> "<<double(nbadChi2Test)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad JB but not KS Test Channels "<<nbadJBNotKSTest<<" ---> "<<double(nbadJBNotKSTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad AD but not KS and not JB Test Channels "<<nbadaDNotKSandjBTest<<" ---> "<<double(nbadaDNotKSandjBTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Chi2 but not KS and JB and AD Test Channels "<<nbadChi2NotKSandjBandaDTest<<" ---> "<<double(nbadChi2NotKSandjBandaDTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  cout<<"#### Bad Combined Test Channels "<<nbadCombinedTest<<" ---> "<<double(nbadCombinedTest)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;

  if(testDoubleGaussianChannels){
    cout<<"###############################"<<endl;
    cout<<"#### Multiple peak finder ####"<<endl;
    cout<<"##############################"<<endl;
    cout<<"Two peak by Chi2 "<<nbadDoublePeakChi2<<" --> "<<double(nbadDoublePeakChi2)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Distance "<<nbadDoublePeakDistance<<" --> "<<double(nbadDoublePeakDistance)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Ashman "<<nbadDoublePeakAshman<<" --> "<<double(nbadDoublePeakAshman)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Amplitude "<<nbadDoublePeakAmplitude<<" --> "<<double(nbadDoublePeakAmplitude)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Bimodality "<<nbadDoublePeakBimodality<<" --> "<<double(nbadDoublePeakBimodality)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
    cout<<"Two peak by Combibed "<<nbadDoublePeakCombined<<" ---> "<<double(nbadDoublePeakCombined)/(tree->GetEntries()/reductionFactor)<<" % "<<endl;
  }

  /// -------> 
  ofstream channelMap ((outputDIR+"/fractionOfGoodChannels.txt").c_str());
  for(auto module : moduleDenominator)
    channelMap << module.first <<"  "<< 1. - double(moduleNumerator[module.first])/double(moduleDenominator[module.first]) << "\n";
  channelMap.close();

  /// -------> 
  ofstream nchannelMapFilledBins ((outputDIR+"/numberBadChannelsFilledBins.txt").c_str());
  for(auto module : moduleNumeratorFilledBins)
    nchannelMapFilledBins << module.first <<"  "<< moduleNumeratorFilledBins[module.first] << "\n";
  nchannelMapFilledBins.close();

  /// -------> 
  ofstream nchannelMap ((outputDIR+"/numberBadChannels.txt").c_str());
  for(auto module : moduleNumerator)
    nchannelMap << module.first <<"  "<< moduleNumerator[module.first] << "\n";
  nchannelMap.close();

  /// -------> 
  //  ofstream nNonEdgechannelMap ((outputDIR+"/numberBadChannelsNonEdge.txt").c_str());
  //  for(auto module : moduleNonEdgeNumerator)
  //    nNonEdgechannelMap << module.first <<"  "<< moduleNonEdgeNumerator[module.first] << "\n";
  //  nNonEdgechannelMap.close();

  /// -------> 
  //  ofstream nAPVEdgechannelMap ((outputDIR+"/numberBadChannelsAPVEdge.txt").c_str());
  //  for(auto module : moduleAPVEdgeNumerator)
  //    nAPVEdgechannelMap << module.first <<"  "<< moduleAPVEdgeNumerator[module.first] << "\n";
  //  nAPVEdgechannelMap.close();

  /// -------> 
  ofstream nchannelMapKS ((outputDIR+"/numberBadChannelsKS.txt").c_str());
  for(auto module : moduleNumeratorKS)
    nchannelMapKS << module.first <<"  "<< moduleNumeratorKS[module.first] << "\n";
  nchannelMapKS.close();

  /// -------> 
  ofstream nchannelMapJB ((outputDIR+"/numberBadChannelsJB.txt").c_str());
  for(auto module : moduleNumeratorJB)
    nchannelMapJB << module.first <<"  "<< moduleNumeratorKS[module.first] << "\n";
  nchannelMapJB.close();

  /// -------> 
  ofstream nchannelMapDoublePeak ((outputDIR+"/numberBadChannelsDoublePeak.txt").c_str());
  for(auto module : moduleNumeratorDoublePeak)
    nchannelMapDoublePeak << module.first <<"  "<< moduleNumeratorDoublePeak[module.first] << "\n";
  nchannelMapDoublePeak.close();
  
  // ------> detailed info of bad strips
  ofstream badStripDump ((outputDIR+"/badStripDump.txt").c_str());
  for(auto badstrip : badStrip){
    badStripDump<< badstrip.fecCrate_<<" "<<badstrip.fecSlot_<<" "<<badstrip.fecRing_<<" "<<badstrip.ccuAdd_<<" "<<badstrip.ccuCh_<<" "<<badstrip.fedKey_<<" "<<badstrip.lldCh_<<" "<<badstrip.apvid_<<" "<<badstrip.stripid_<<" \n";
  }
  badStripDump.close();

}
Ejemplo n.º 20
0
void fitPtOverMCJLST(int mass = 125, int LHCsqrts = 7, int whichtype = 1, 
		     bool correctErrors = false, /* string changeParName = "", */
		     bool showErrorPDFs = false, string systString = "Default")

// whichtype
// 0 - gg Signal
// 1 - VBF Signal
// 2 - ZZ
// 3 - ZX
// 4 - ggZZ
// 5 - WH
// 6 - ZH
// 7 - ttH

{

  string changeParName = "";
  if (systString == "Default") changeParName = "up";

  string nameSample[8] = {"gg","vbf","zz","zx","ggzz","wh","zh","tth"};
  float maxType[8] = {2.4,3.2,1.6,1.6,1.6,3.2,3.2,3.2};   
  float rebinType[8] = {1,2,1,1,4,10,10,40};
  
  for (int t = 0; t < 8; t++) {
    if (mass > 150) maxType[t] = int(117.90*maxType[t]/sqrt(mass-10.91))/10.;
  }

  char fileToOpen[200];
  sprintf(fileToOpen,"selRootFiles/PToverM_%s%d_SEL_%dTeV.root",nameSample[whichtype].c_str(),mass,LHCsqrts);
  // if (whichtype == 3) sprintf(fileToOpen,"PTOVERM_%s_SEL_allTeV.root",nameSample[whichtype].c_str());

  RooRealVar* ptoverm = new RooRealVar("ptoverm","p_{T}/M^{4l}",0.,maxType[whichtype],"GeV/c");
 
  TFile input(fileToOpen);
  // if (systString == "Mass" || systString == "Mela") {
  //  sprintf(fileToOpen,"ptovermH_%sUp",systString.c_str());
  // } else {
  sprintf(fileToOpen,"ptovermH_%s",systString.c_str());
  //}
  TH1F* ptovermH = (TH1F*)input.Get(fileToOpen);
  
  if (rebinType[whichtype] > 1) ptovermH->Rebin(rebinType[whichtype]);
  if (maxType[whichtype] < ptovermH->GetBinLowEdge(ptovermH->GetNbinsX() + 1) - ptovermH->GetBinWidth(1)) {
    int theBin = ptovermH->FindBin(maxType[whichtype]);
    ptovermH->GetXaxis()->SetRange(1,theBin-1);
  }

  gROOT->ProcessLine(".L mytdrstyle.C");
  gROOT->ProcessLine("setTDRStyle()");
  
  // cout << endl << "Signal " << endl;   
  ptoverm->setBins(ptovermH->GetNbinsX());

  RooDataHist* rdh = new RooDataHist("rdh","Some dataset",RooArgList(*ptoverm),Import(*ptovermH,kFALSE));
 
  // fit definitions
  // RooWorkspace *ws = new RooWorkspace("ws");

  RooRealVar m("m","emme", 1.,0.01, 40.);
  RooRealVar n("n","enne", 0.93, 0.05, 15.);
  RooRealVar n2("n2","enne2", 0.75, 0.5, 15.);
  RooRealVar bb("bb","bibi",0.02, 0.000005, 20.0);
  RooRealVar T("T","tti",0.2,0.00000005,1.);
  RooRealVar bb2("bb2","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexp("fexp","f_exp",0.02, 0.0, 1.0);
  if (whichtype == 0) {
    if (LHCsqrts == 8) {
      m.setVal(3.319);   // m.setConstant(kTRUE);
      n.setVal(0.7606);    if (systString != "Default" || mass != 125) n.setConstant(kTRUE); 
      n2.setVal(0.8061);   n2.setConstant(kTRUE);
      bb.setVal(3.728);   // bb.setConstant(kTRUE);
      T.setVal(0.00333);   // T.setConstant(kTRUE);
      bb2.setVal(1.7172);    // bb2.setConstant(kTRUE);
      fexp.setVal(0.002144);   if (systString != "Default" || mass != 125) fexp.setConstant(kTRUE);
    } else {
      m.setVal(0.061);   // m.setConstant(kTRUE);
      n.setVal(1.6141);   if (systString == "Resummation" || systString == "TopMass")  n.setConstant(kTRUE);
      n2.setVal(1.3294);   n2.setConstant(kTRUE);
      bb.setVal(4.2761);   // bb.setConstant(kTRUE);
      T.setVal(0.0361);   // T.setConstant(kTRUE);
      bb2.setVal(1.6643);   bb2.setConstant(kTRUE);
      fexp.setVal(0.0004);   // fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 1) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);   n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.02048);   bb.setConstant(kTRUE);
    T.setVal(0.16115);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE); // T.setConstant(kTRUE);
    bb2.setVal(1.0024);   bb2.setConstant(kTRUE);
    fexp.setVal(0.005);   fexp.setConstant(kTRUE);
    if (mass > 300) {
      fexp.setVal(0.0);   fexp.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb2.setVal(5.0);  //  bb2.setConstant(kFALSE);
    }
    if (mass > 500) {
      bb.setVal(15.0);  //  bb.setConstant(kFALSE);
    }
  } else if (whichtype == 2) {
    if (LHCsqrts == 8) {
      m.setVal(1.0476);   // m.setConstant(kTRUE);    
      bb.setVal(3.3088);  // if (mass != 140) bb.setConstant(kTRUE);
      n2.setVal(0.7146);   n2.setConstant(kTRUE);
      n.setVal(0.9518);      n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.0021889);    if (systString.find("Mela") != string::npos || mass != 140) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    } else {
      m.setVal(1.028);   // m.setConstant(kTRUE);    
      bb.setVal(2.91); // bb.setConstant(kTRUE);
      n2.setVal(0.7146);  n2.setConstant(kTRUE);
      n.setVal(0.9518);     n.setConstant(kTRUE);
      bb2.setVal(100000.);  bb2.setConstant(kTRUE);
      T.setVal(0.002248);   if (systString.find("Mela") != string::npos) T.setConstant(kTRUE);
      fexp.setVal(0.0);    fexp.setConstant(kTRUE);
    }
  } else if (whichtype == 3) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(3.4523);     n.setConstant(kTRUE);
    n2.setVal(0.6910);    n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 4) {
    m.setVal(1.411);   // m.setConstant(kTRUE);
    n.setVal(5.756);    // n.setConstant(kTRUE);
    n2.setVal(0.8738);   // n2.setConstant(kTRUE);
    bb.setVal(0.00039);  // bb.setConstant(kTRUE);
    T.setVal(0.118);   // T.setConstant(kTRUE);
    bb2.setVal(0.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.0);   fexp.setConstant(kTRUE);
  } else if (whichtype == 5 && LHCsqrts == 8) {
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(3.897);   bb.setConstant(kTRUE);
    T.setVal(0.1009);  // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  } else {
    // cout << "Entro qui" << endl;
    m.setVal(1.006);   // m.setConstant(kTRUE);
    n.setVal(10.939);    n.setConstant(kTRUE);
    n2.setVal(1.1448);   n2.setConstant(kTRUE);
    bb.setVal(0.0129);  bb.setConstant(kTRUE);
    T.setVal(0.1009);    // T.setConstant(kTRUE);
    bb2.setVal(1.0224);   bb2.setConstant(kTRUE);
    fexp.setVal(0.01);   fexp.setConstant(kTRUE);
  }
 
  
  RooModifTsallis* rt3 = new RooModifTsallis("rt3","rt3",*ptoverm,m,n,n2,bb,bb2,T,fexp);
  // ws->import(*rt3);

  // fit
  RooFitResult* fit = rt3->fitTo(*rdh,Minos(0),Save(1),SumW2Error(kTRUE),NumCPU(1));  

  float mVal = m.getVal();   
  float nVal = n.getVal();
  float n2Val = n2.getVal();
  float bbVal = bb.getVal();
  float bb2Val = bb2.getVal();
  float fexpVal = fexp.getVal();
  float TVal = T.getVal();

  if (correctErrors) {
    // Tsallis errors not reliable, use toy MC

    TH1F* mHist = new TH1F("mHist","m",21,-0.5*mVal,0.5*mVal);
    TH1F* nHist = new TH1F("nHist","n",21,-0.2*nVal,0.2*nVal);
    TH1F* n2Hist = new TH1F("n2Hist","n2",21,-0.2*n2Val,0.2*n2Val);
    TH1F* bbHist = new TH1F("bbHist","bb",21,-0.2*bbVal,0.2*bbVal);
    TH1F* bb2Hist = new TH1F("bb2Hist","bb2",21,-0.2*bb2Val,0.2*bb2Val);
    TH1F* fexpHist = new TH1F("fexpHist","fexp",21,-0.2*fexpVal-0.000001,0.2*fexpVal+0.000001);
    TH1F* THist = new TH1F("THist","T",21,-0.5*TVal,0.5*TVal);
    mHist->GetXaxis()->SetTitle("m-m_{gen}");
    nHist->GetXaxis()->SetTitle("n-n_{gen}");
    n2Hist->GetXaxis()->SetTitle("n2-n2_{gen}");
    bbHist->GetXaxis()->SetTitle("bb-bb_{gen}");
    bb2Hist->GetXaxis()->SetTitle("bb2-bb2_{gen}");
    THist->GetXaxis()->SetTitle("T-T_{gen}");
    fexpHist->GetXaxis()->SetTitle("fexp-fexp_{gen}");

    for (unsigned int iToy = 0; iToy < 200; iToy++) {

      cout << endl << "####" << endl;
      cout << "Generating toy experiment n. " << iToy+1 << endl;

      m.setVal(mVal);
      n.setVal(nVal);
      n2.setVal(n2Val);
      bb.setVal(bbVal);
      bb2.setVal(bb2Val);
      fexp.setVal(fexpVal);
      T.setVal(TVal);

      TDatime *now = new TDatime();
      Int_t seed = now->GetDate() + now->GetTime();
      cout << "RooFit Generation Seed = " << seed+iToy << endl;
      RooRandom::randomGenerator()->SetSeed(seed+iToy);
      cout << "####" << endl << endl;

      RooDataSet *dataToy = rt3->generate(RooArgSet(*ptoverm),ptovermH->GetEntries());
      RooDataHist *dataToyH = new RooDataHist("dataToyH","toy",RooArgSet(*ptoverm),*dataToy);
      
      rt3->fitTo(*dataToyH,Minos(0),SumW2Error(kTRUE),NumCPU(1));  
  
      if (fit->floatParsFinal().find("m")) mHist->Fill(m.getVal()-mVal);
      if (fit->floatParsFinal().find("n")) nHist->Fill(n.getVal()-nVal);
      if (fit->floatParsFinal().find("n2")) n2Hist->Fill(n2.getVal()-n2Val);
      if (fit->floatParsFinal().find("bb")) bbHist->Fill(bb.getVal()-bbVal);
      if (fit->floatParsFinal().find("bb2")) bb2Hist->Fill(bb2.getVal()-bb2Val);
      if (fit->floatParsFinal().find("fexp")) fexpHist->Fill(fexp.getVal()-fexpVal);
      if (fit->floatParsFinal().find("T")) THist->Fill(T.getVal()-TVal);
    }

    TCanvas cant("cant","Test canvas",5.,5.,900.,500.);
    cant.Divide(4,2);
    cant.cd(1);   mHist->Draw();
    cant.cd(2);   nHist->Draw();
    cant.cd(3);   n2Hist->Draw();
    cant.cd(4);   bbHist->Draw();
    cant.cd(5);   bb2Hist->Draw();
    cant.cd(6);   fexpHist->Draw();
    cant.cd(7);   THist->Draw();
    // cant.SaveAs("figs/testToys.pdf");
    cant.SaveAs("newfigs/testToys.pdf");

    if (fit->floatParsFinal().find("m")) m.setError(mHist->GetRMS());
    if (fit->floatParsFinal().find("n")) n.setError(nHist->GetRMS());
    if (fit->floatParsFinal().find("n2")) n2.setError(n2Hist->GetRMS());
    if (fit->floatParsFinal().find("bb")) bb.setError(bbHist->GetRMS());
    if (fit->floatParsFinal().find("bb2")) bb2.setError(bb2Hist->GetRMS());
    if (fit->floatParsFinal().find("fexp")) fexp.setError(fexpHist->GetRMS());
    if (fit->floatParsFinal().find("T")) T.setError(THist->GetRMS());
  }

  m.setVal(mVal);
  n.setVal(nVal);
  n2.setVal(n2Val);
  bb.setVal(bbVal);
  bb2.setVal(bb2Val);
  fexp.setVal(fexpVal);
  T.setVal(TVal);

  char fileToSave[200];
  // if (changeParName != "") 
  //  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s_%dTeV_%s_%s.txt",nameSample[whichtype].c_str(),LHCsqrts,systString.c_str(),changeParName.c_str()); 
  // else 
  sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_%s.txt",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  ofstream os1(fileToSave);
  if (changeParName != "") {
    sprintf(fileToSave,"m%s",changeParName.c_str());  m.SetName(fileToSave);
    sprintf(fileToSave,"n%s",changeParName.c_str());  n.SetName(fileToSave);
    sprintf(fileToSave,"n2%s",changeParName.c_str());  n2.SetName(fileToSave);
    sprintf(fileToSave,"bb%s",changeParName.c_str());  bb.SetName(fileToSave);
    sprintf(fileToSave,"bb2%s",changeParName.c_str());  bb2.SetName(fileToSave);
    sprintf(fileToSave,"fexp%s",changeParName.c_str());  fexp.SetName(fileToSave);
    sprintf(fileToSave,"T%s",changeParName.c_str());  T.SetName(fileToSave);
  }
  (RooArgSet(m,n,n2,bb,bb2,fexp,T)).writeToStream(os1,false);
  os1.close();

  RooRealVar mup("mup","emme", 1.,0.01, 30.);
  RooRealVar nup("nup","enne", 0.93, 0.5, 15.);
  RooRealVar n2up("n2up","enne2", 0.75, 0.5, 15.);
  RooRealVar bbup("bbup","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tup("Tup","tti",0.2,0.00000005,1.);
  RooRealVar bb2up("bb2up","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpup("fexpup","f_exp",0.02, 0.0, 1.0);
 
  RooModifTsallis* rt3up = new RooModifTsallis("rt3up","rt3up",*ptoverm,mup,nup,n2up,bbup,bb2up,Tup,fexpup);
  // ws->import(*rt3up);
 
  RooRealVar mdown("mdown","emme", 1.,0.01, 30.);
  RooRealVar ndown("ndown","enne", 0.93, 0.5, 15.);
  RooRealVar n2down("n2down","enne2", 0.75, 0.5, 15.);
  RooRealVar bbdown("bbdown","bibi",0.02, 0.00005, 20.0);
  RooRealVar Tdown("Tdown","tti",0.2,0.00000005,1.);
  RooRealVar bb2down("bb2down","bibi2",0.02, 0.0005, 10.0);
  RooRealVar fexpdown("fexpdown","f_exp",0.02, 0.0, 1.0);

  RooModifTsallis* rt3down = new RooModifTsallis("rt3down","rt3down",*ptoverm,mdown,ndown,n2down,bbdown,bb2down,Tdown,fexpdown);
  // ws->import(*rt3down);

  RooPlot *frame = ptoverm->frame();

  char reducestr[300];
  sprintf(reducestr,"ptoverm > %f && ptoverm < %f",ptoverm->getMin(),ptoverm->getMax());
  
  rdh->plotOn(frame,DataError(RooAbsData::SumW2),Cut(reducestr));
  static RooHist *hpull;
  float chi2 = 0.;

  if (changeParName == "") {
    sprintf(fileToSave,"text/paramsPTOverMCJLST_%s%d_%dTeV_Default.txt",nameSample[whichtype].c_str(),mass,LHCsqrts);
    ifstream is1(fileToSave);
    (RooArgSet(mup,nup,n2up,bbup,bb2up,fexpup,Tup)).readFromStream(is1,false);

    mdown.setVal(fabs(3*mup.getVal() - 2*m.getVal()));
    ndown.setVal(fabs(3*nup.getVal() - 2*n.getVal()));
    n2down.setVal(fabs(3*n2up.getVal() - 2*n2.getVal()));
    bbdown.setVal(fabs(3*bbup.getVal() - 2*bb.getVal()));
    Tdown.setVal(fabs(3*Tup.getVal() - 2*T.getVal()));
    bb2down.setVal(fabs(3*bb2up.getVal() - 2*bb2.getVal()));
    fexpdown.setVal(fabs(3*fexpup.getVal() - 2*fexp.getVal()));

    if (showErrorPDFs) {
      rt3->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
      rt3up->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      if (systString.find("Mela") == string::npos) rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    } else {
      rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      hpull = frame->pullHist();
    }
  } else {
    mup.setVal(m.getVal() + m.getError());   cout << "mup = " << mup.getVal() << endl;
    nup.setVal(n.getVal() + n.getError());
    n2up.setVal(n2.getVal() + n2.getError());
    bbup.setVal(bb.getVal() + bb.getError());
    Tup.setVal(T.getVal() + T.getError());
    bb2up.setVal(bb2.getVal() + bb2.getError());
    fexpup.setVal(fexp.getVal() + fexp.getError());

    mdown.setVal(m.getVal() - m.getError());  cout << "mdown = " << mdown.getVal() << endl;
    ndown.setVal(n.getVal() - n.getError());
    n2down.setVal(n2.getVal() - n2.getError());
    bbdown.setVal(bb.getVal() - bb.getError());
    Tdown.setVal(T.getVal() - T.getError());
    bb2down.setVal(bb2.getVal() - bb2.getError());
    fexpdown.setVal(fexp.getVal() - fexp.getError());

    rt3->plotOn(frame,LineColor(kBlue),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    hpull = frame->pullHist();
    if (showErrorPDFs) {
      rt3up->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
      rt3down->plotOn(frame,LineColor(kRed),LineStyle(kDashed),Normalization(rdh->sumEntries(),RooAbsReal::NumEvent));
    }
  }

  double *ypulls = hpull->GetY();
  unsigned int nBins = rdh->numEntries();
  unsigned int nFullBins = 0;
  for (unsigned int i = 0; i < nBins; i++) {
    cout << "Pull of bin " << i << " = " << ypulls[i] << endl;
    if (fabs(ypulls[i]) < 5.0) chi2 += ypulls[i]*ypulls[i]; 
    cout << "Partial chi2 = " << chi2 << endl;
    if (fabs(ypulls[i]) > 0.0001 && fabs(ypulls[i]) < 5.0) nFullBins++;
  }
  for (unsigned int i = 0; i < nBins; i++) {
    if (fabs(ypulls[i]) < 0.0001) ypulls[i] = 999.; 
    hpull->SetPointError(i,0.,0.,0.,0.);
  } 
  int nFitPar = fit->floatParsFinal().getSize() - 1;

  TCanvas can("can","The canvas",5.,5.,500.,900.); 
  can.Divide(1,3);

  TLatex *t = new TLatex();
  t->SetNDC();
  t->SetTextAlign(22);
  t->SetTextSize(0.06);

  can.cd(1);
  gPad->SetBottomMargin(0.0);
  frame->Draw();
  // gPad->SetLogy(); 
  // Htest->Draw();
  sprintf(fileToSave,"%s %d GeV at %d TeV",nameSample[whichtype].c_str(),mass,LHCsqrts);
  t->DrawLatex(0.6,0.8,fileToSave); 

  can.cd(2);
  gPad->SetLogy(); 
  gPad->SetTopMargin(0.0);
  frame->Draw();
 
  RooPlot* pull = ptoverm->frame(Title("Pull Distribution")) ;
  pull->GetYaxis()->SetTitle("Pull");
  /* pull->SetLabelSize(0.08,"XYZ");
  pull->SetTitleSize(0.08,"XYZ");
  pull->SetTitleOffset(0.6,"Y");
  pull->SetTitleOffset(1.0,"X"); */
  pull->addPlotable(hpull,"P") ; 
  pull->SetMinimum(-6.); 
  pull->SetMaximum(6.); 

  can.cd(3);
  gPad->SetGridy();
  pull->Draw();
  sprintf(fileToSave,"#chi^{2}/n_{DoF} = %4.1f/%d",chi2,nFullBins - nFitPar);
  if (chi2 < 1000.) t->DrawLatex(0.80,0.86,fileToSave);

  // sprintf(fileToSave,"figs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  sprintf(fileToSave,"newfigs/fitPTOverMCJLST_%s%d_%dTeV_%s.pdf",nameSample[whichtype].c_str(),mass,LHCsqrts,systString.c_str());
  can.SaveAs(fileToSave);

}
Ejemplo n.º 21
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;

}
Ejemplo n.º 22
0
void Getvn2D(bool usingCNTEP=0){
    TString str;
    TFile *fin;
    int nrun = GetTotalRun();
    std::cout<<"Totally we have "<<nrun<<" runs/segments!"<<std::endl;
    FillGoodRun();
    std::cout<<"Filling Good run finished!"<<std::endl;

    if(nrun<0) exit(1);

     ofstream fout, foutraw, fout1, fout2;
     int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
     for(int icent=0;icent<ncent;icent++){
      for(int ihar=0;ihar<nhar;ihar++){
          if(icent!=0) continue;
       for(int isub=0;isub<nsub;isub++){
        int n = ihar+1.0+iharE;
        str = choosesub(isub);
        TString UseCNTEP;
        if(str=="ABORT") continue;
        if(usingCNTEP)
         UseCNTEP = "UseCNTEP";
        else
         UseCNTEP = "NoUseCNTEP";
        std::cout<<UseCNTEP<<std::endl;
        std::cout<<"starting doing "<<str<<" v"<<n<<" analysis!"<<std::endl;
        cout<<Form("Result/%s/res%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())<<endl;
         fout1.open(Form("Result/%s/res%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())); //using str as event plane detector
         fout2.open(Form("Result/%s/psi%d_%d_%s.dat",UseCNTEP.Data(),n,icent,str.Data())); //using str as event plane detector
         float reso = GetReso(icent,ihar,isub,usingCNTEP);
         fout1<<reso<<std::endl;
         if(reso<0) {std::cout<<"resolution is wrong!"<<std::endl; reso = -9999;}
        for(int irun=0;irun<nrun;irun++){
         fout2<<GetRun(irun)<<" "<<GoodRunFit[icent][ihar][isub][irun]<<std::endl;
        }
         TH2F* hvobsall = 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* hvobsallsq = 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 iphi=0;iphi<nphi+1;iphi++){
         TH2F* hvobs = new TH2F(Form("hvobs_%d_%d_%d_%d",icent,ihar,isub,iphi),Form("hvobs_%d_%d_%d_%d",icent,ihar,isub,iphi),60,0,6,220,-1.1,1.1);
        // TH2F* hvobssq = new TH2F(Form("hvobssq_%d_%d_%d_%d",icent,ihar,isub,iphi),Form("hvobssq_%d_%d_%d_%d",icent,ihar,isub,iphi),60,0,6,220,-1.1,1.1);
         string phistr = (iphi==0)?"_east":"_west";
         if(iphi==nphi) phistr = "";
         cout<<"open v2 file"<<endl;
         fout.open(Form("Result/%s/v%d_%d%s_%s.dat",UseCNTEP.Data(),n,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         cout<<"open v2raw file"<<endl;
         foutraw.open(Form("Result/%s/v%draw_%d%s_%s.dat",UseCNTEP.Data(),n,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         if(iphi<nphi){
        for(int irun=0;irun<nrun;irun++){
         //std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<irun<<" "<<phistr<<std::endl;
         //fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/%s%s/%d/data/%s.root",dataset.Data(),pro.Data(),taxi,GetRun(irun).Data()));
         //fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/39GeV/output/%s",GetRun(irun).Data()));
         fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/39GeV/treeout/%s",GetRun(irun).Data()));
         if(!(GoodRunFit[icent][ihar][isub][irun]>0.2 && GoodRunFit[icent][ihar][isub][irun]<3.0)){
         std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<GetRun(irun)<<" is bad run!"<<std::endl;
         fin->Close();
        continue;
         }
         TH2F* hvobstemp = (TH2F*)fin->Get(Form("vobs%s_0_0_%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();
        }
         }
        hvobsall->Add(hvobs);
        //hvobsallsq->Add(hvobssq);
        if(iphi==nphi){
        hvobs = hvobsall;
        //hvobssq = hvobsallsq;
        }
            TH1F* ptProj = (TH1F*)hvobs->ProjectionX(Form("hptProj"),0,-1);
         for(int ipt=0;ipt<npt-1;ipt++){
             int xbinmin = hvobs->GetXaxis()->FindBin(ptbin[ipt]+eps);
             int xbinmax = hvobs->GetXaxis()->FindBin(ptbin[ipt+1]-eps);
           //  std::cout<<xbinmin<<" "<<xbinmax<<std::endl;
           //  std::cout<<ptbin[ipt]<<" "<<ptbin[ipt+1]<<std::endl;
            TH1F* hvobsProj = (TH1F*)hvobs->ProjectionY(Form("hvobsProj_%d",ipt),xbinmin,xbinmax);
           // TH1F* hvobssqProj = (TH1F*)hvobssq->ProjectionY(Form("hvobssqProj_%d",ipt),xbinmin,xbinmax);
            float vobs = hvobsProj->GetMean();
            float Ntracks = hvobsProj->Integral();
           // float vobssq = hvobssqProj->GetMean();
            float v = vobs/reso;
            if(Ntracks>0)
            float verr = hvobsProj->GetRMS()/reso/sqrt(Ntracks);
            else verr = -9999;
           // float verr = sqrt(vobssq/reso/reso-(v*v))/sqrt(Ntracks);
            ptProj->GetXaxis()->SetRangeUser(ptbin[ipt]+eps,ptbin[ipt+1]-eps);
            float pt = ptProj->GetMean();
            fout<<pt<<" "<<v<<" "<<verr<<" "<<std::endl;
            foutraw<<pt<<" "<<vobs<<" "<<verr*reso<<" "<<std::endl;
         }
        fout.close();
        foutraw.close();
         }
        fout1.close();
        fout2.close();
        }
        }
     }
}
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;
}
void draw_centEff_fitResults(string cutname = "hiHF_hfCoinc3_pVtx") {

    ifstream in;
    //in.open("temp.txt");
    in.open(Form("centEff_fitResults_%s.txt",cutname.data()));

    string run;
    int runtemp;
    Float_t eff, chi2;
    Int_t nlines = 0;
    //TFile *f = new TFile("hist_effcon_runDep.root","RECREATE");
    TCanvas *c1 = new TCanvas("c1","",10,10,900,500);
    c1->SetGrid();
    TH1F *h = new TH1F("h1","Eff+Contamination vs. run",1,0,1);
    h->SetStats(0);
    h->SetTitle("Eff+Contamination vs. run; Run number;Efficiency+Contamination (%)");
    h->SetAxisRange(95,105,"Y");
    h->SetCanExtend(TH1::kAllAxes);
    h->SetLineColor(2);
    TH1F *hgaus = new TH1F("hgaus","Eff+Contamination",20,99,101);

    while (1) {
        in >> run>> eff >> chi2;
        //run = itoa(runtemp);
        if (!in.good()) break;
        if (nlines < 5) printf("run=%s, eff+contamination=%3f, reduced chi2=%3f\n",run.data(),eff,chi2);
        h->Fill(run.data(),eff);
        hgaus->Fill(eff);
        nlines++;
    }
    in.close();
    printf(" found %d points\n",nlines);
    c1->cd();
    h->LabelsDeflate();
    h->Draw("hist");
    c1->SaveAs(Form("figures/centEff_runDep_%s.png",cutname.data()));
 
    TCanvas *c2 = new TCanvas("c2","",500,500);
    double gausMean, gausResol;
    double histMean, histResol;
    TF1* fgaus = cleverGaus(hgaus);
    gausMean = fgaus->GetParameter(1);
    gausResol = fgaus->GetParameter(2);
    hgaus->SetTitle(";Efficiency+Contamination (%);");
    hgaus->SetNdivisions(504);
    hgaus->Draw("hist");
    fgaus->Draw("same");
    histMean = hgaus->GetMean();
    histResol= hgaus->GetRMS();// GetRMS()=GetStdDev() only in ROOT!
    float xpos(0.62), ypos(0.76);
    float dy=0.05;
    drawText(Form("from historgam"),xpos,ypos,kBlack,18);
    drawText(Form("mean = %.3f",histMean),xpos,ypos-dy,kBlack,18);
    drawText(Form("sigma = %.3f",histResol),xpos,ypos-2*dy,kBlack,18);
    ypos=0.55;
    drawText(Form("from gaus fit"),xpos,ypos,kBlack,18);
    drawText(Form("mean = %.3f",gausMean),xpos,ypos-dy,kBlack,18);
    drawText(Form("sigma = %.3f",gausResol),xpos,ypos-2*dy,kBlack,18);
    xpos=0.62-0.21;
    drawText("Dataset : HIMinimumBias2", xpos, 0.18+2*dy);
    drawText("Trig : HLT_HIL1MinimumBiasHF1AND_v1", xpos, 0.18+dy);
    drawText("Evt. sel. filter : hfCoinc3 && pVtx", xpos, 0.18);
    c2->SaveAs(Form("figures/centEff_runDep_gaus_%s.png",cutname.data()));

}
Ejemplo n.º 25
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( );
} 
void ClusterWidthAnalysisTreeMaker::FitHistos(std::map<ULong64_t , std::vector<TH1F*> > &HistSoN, string output_file, 
 std::vector< TH1F* > commonHistos, std::map<ULong64_t, TProfile* > Monitors){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Mean;
  double errMean;
  double RMS;
  double errRMS;
  int index;
  int nhits;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Mean",&Mean,"Mean/D");
  tree->Branch("errMean",&errMean,"errMean/D");
  tree->Branch("RMS",&RMS,"RMS/D");
  tree->Branch("errRMS",&errRMS,"errRMS/D");
  tree->Branch("Nhits",&nhits,"Nhits/I");


  //TCanvas* c1 = new TCanvas();
  TH1F* hNhits = new TH1F("hNhits", "hNhits", 1000, 0,1000); // N hits per module
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TH1F*> >::iterator iter = HistSoN.begin(); iter != HistSoN.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_%u",iter->first,i);
 	  
	  
      //std::cout << "searching for " << thestring.Data() << std::endl;
      //TH1F*  SoNHisto= (TH1F*)gROOT->FindObject( thestring.Data() );
	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TH1F*  Histo = iter->second[i];
	  
	  if(!Histo) 
       { std::cout<<" Histo "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}
 
	  
	  detid = iter->first;

	  bool rmfit=false;

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Histo->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Mean = Histo->GetMean();
	  errMean = Histo->GetMeanError();
	  RMS = Histo->GetRMS();
	  errRMS = Histo->GetRMSError();
	  nhits = (int) Histo->Integral();
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  hNhits->Write();
  

  for(unsigned int ih=0; ih<commonHistos.size(); ih++) commonHistos[ih]->Write();

  std::map<ULong64_t, TProfile* >::iterator itMon;
  for(itMon=Monitors.begin(); itMon!=Monitors.end(); itMon++)
  {
    itMon->second->GetXaxis()->SetTimeDisplay(1);
	itMon->second->GetXaxis()->SetTimeFormat("%H:%M");
	itMon->second->GetXaxis()->SetTimeOffset(t_monitor_start);
	itMon->second->Write();
  }
  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
Ejemplo n.º 27
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();
}
Ejemplo n.º 28
0
void estimate_uncertainty(int N=1000)
{
  double a,b,c,d;
  TRandom3 rand;
  double mean = 0.0;
  double sigma = 0.25;
  double sigma1 = 0.22;

  TH1F *hA = new TH1F("hA","numerator 1;A;counts", 200,0,2);
  TH1F *hB = new TH1F("hB","denominator 1;B;counts", 200,0,2);
  TH1F *hC = new TH1F("hC","numerator 2;C;counts", 200,0,2);
  TH1F *hD = new TH1F("hD","denominator 2;D;counts", 200,0,2);
  TH1F *hR1 = new TH1F("hR1","ratio 1;single ratio;counts",200,0,2);
  TH1F *hR2 = new TH1F("hR2","ratio 2;single raito;counts",200,0,2);
  TH1F *hDR = new TH1F("hDR","double ratio;double ratio;counts",200,0,2);

  hA->Sumw2();
  hB->Sumw2();
  hC->Sumw2();
  hD->Sumw2();
  hR1->Sumw2();
  hR2->Sumw2();
  hDR->Sumw2();

  hA->SetMarkerColor(kBlack);
  hB->SetMarkerColor(kRed);
  hC->SetMarkerColor(kBlue);
  hD->SetMarkerColor(kGreen+2);

  hB->SetMarkerStyle(21);
  hC->SetMarkerStyle(24);
  hD->SetMarkerStyle(25);

  hR2->SetMarkerColor(kRed);
  hR2->SetMarkerStyle(24);

  hA->GetXaxis()->CenterTitle(1);
  hR1->GetXaxis()->CenterTitle(1);
  hDR->GetXaxis()->CenterTitle(1);

  rand.SetSeed(0);

  for (int i=0; i<N; ++i) {
    // a = rand.Gaus(mean, sigma1);
    // b = a;
    a = rand.Gaus(mean, sigma1);
    a *= rand.Gaus(mean, sigma);
    b = rand.Gaus(mean, sigma1);
    b *= rand.Gaus(mean, sigma);

    // c = rand.Gaus(mean, sigma1);
    // d = c;
    c = rand.Gaus(mean, sigma1);
    c *= rand.Gaus(mean, sigma);
    d = rand.Gaus(mean, sigma1);
    d *= rand.Gaus(mean, sigma);

    a += 1;
    b += 1;
    c += 1;
    d += 1;

    hA->Fill(a);
    hB->Fill(b);
    hC->Fill(c);
    hD->Fill(d);

    hR1->Fill( (a/b) );
    hR2->Fill( (c/d) );

    hDR->Fill( (a/b) / (c/d) );
  }

  TCanvas *c1 = new TCanvas("c1","c1",1200,600);
  c1->Divide(3,1);
  c1->cd(1);
  hA->Draw();
  hB->Draw("same");
  hC->Draw("same");
  hD->Draw("same");
  c1->cd(2);
  hR1->Draw();
  hR2->Draw("same");
  c1->cd(3);
  hDR->Draw();

  cout << "Mean = " << hDR->GetMean() << " RMS = " << hDR->GetRMS() << endl;

  return;
}
Ejemplo n.º 29
0
void fitSignalShapeW(int massBin,int id, int channels,int categ, int sample, 
		     /* float lumi, bool doSfLepton, */double rangeLow, double rangeHigh,
		     double bwSigma,
		     double fitValues[9], double fitErrors[9], double covQual[1]){
 // ------ root settings ---------
  gROOT->Reset();  
  gROOT->SetStyle("Plain");
  gStyle->SetPadGridX(kFALSE);
  gStyle->SetPadGridY(kFALSE);
  //gStyle->SetOptStat("kKsSiourRmMen");
  gStyle->SetOptStat("iourme");
  //gStyle->SetOptStat("rme");
  //gStyle->SetOptStat("");
  gStyle->SetOptFit(11);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetPadRightMargin(0.06);
  // ------------------------------ 

  ROOT::Math::MinimizerOptions::SetDefaultTolerance( 1.E-7);

  stringstream FileName;
  //Insert the file here
  if(sample==1) FileName <<"root://lxcms03//data3/Higgs/150915/ZH125/ZZ4lAnalysis.root" ;
  else if(sample==2) FileName << "root://lxcms03//data3/Higgs/150915/WplusH125/ZZ4lAnalysis.root";
  else if(sample==3) FileName << "root://lxcms03//data3/Higgs/150915/WminusH125/ZZ4lAnalysis.root";
  else if(sample==4) FileName << "root://lxcms03//data3/Higgs/150915/ttH125/ZZ4lAnalysis.root";
  else {
    cout << "Wrong sample." << endl;
    return;
  }
    

  cout << "Using " << FileName.str() << endl;
  
 
  TFile* ggFile = TFile::Open(FileName.str().c_str()); 

  TTree* ggTree = (TTree*) ggFile->Get("ZZTree/candTree");

  float m4l;
  
  Short_t z1flav, z2flav; 
  float weight;

  Short_t nExtraLeptons;   
  float ZZPt;
  Short_t nJets;
  Short_t nBTaggedJets;
  std::vector<float> * jetpt = 0;
  std::vector<float> * jeteta = 0;
  std::vector<float> * jetphi = 0;
  std::vector<float> * jetmass = 0;
  float jet30pt[10];
  float jet30eta[10];
  float jet30phi[10];
  float jet30mass[10];
  float Fisher;
  
  int  nentries = ggTree->GetEntries();
 
  //--- ggTree part
  ggTree->SetBranchAddress("ZZMass",&m4l);
  ggTree->SetBranchAddress("Z1Flav",&z1flav);
  ggTree->SetBranchAddress("Z2Flav",&z2flav);
  ggTree->SetBranchAddress("genHEPMCweight",&weight);
  ggTree->SetBranchAddress("nExtraLep",&nExtraLeptons);
  ggTree->SetBranchAddress("nCleanedJets",&nJets);
  ggTree->SetBranchAddress("nCleanedJetsPt30BTagged",&nBTaggedJets);
  ggTree->SetBranchAddress("DiJetFisher",&Fisher);
  
  ggTree->SetBranchAddress("JetPt",&jetpt);
  ggTree->SetBranchAddress("JetEta",&jeteta);
  ggTree->SetBranchAddress("JetPhi",&jetphi);
  ggTree->SetBranchAddress("JetMass",&jetmass);
  ggTree->SetBranchAddress("ZZPt",&ZZPt);

  //--- rooFit part
  double xMin,xMax,xInit;
  xInit = (double) massBin;
  xMin = rangeLow;
  xMax = rangeHigh ;
  cout << "Fit range: [" << xMin << " , " << xMax << "]. Init value = " << xInit << endl;
  
  TH1F *hmass = new TH1F("hmass","hmass",200,xMin,xMax);
  //---------  
  RooRealVar x("mass","m_{4l}",xInit,xMin,xMax,"GeV");
  RooRealVar w("myW","myW",1.0,0.,1000.);
  RooArgSet ntupleVarSet(x,w);
  RooDataSet dataset("mass4l","mass4l",ntupleVarSet,WeightVar("myW"));

  for(int k=0; k<nentries; k++){
    ggTree->GetEvent(k);

    int njet30 = 0;
    for (unsigned int ijet = 0; ijet < jetpt->size(); ijet++) { 
      if ( (*jetpt)[ijet] > 30. ) {
	jet30pt[njet30] = (*jetpt)[ijet];      
	jet30eta[njet30] = (*jeteta)[ijet];
	jet30phi[njet30] = (*jetphi)[ijet];
	jet30mass[njet30] = (*jetmass)[ijet];
	njet30++;
      }
    }  
    int Cat = category(nExtraLeptons, ZZPt, m4l, njet30, nBTaggedJets, jet30pt, jet30eta, jet30phi,jet30mass, Fisher); 
    if (categ >= 0 && categ != Cat ) continue;

 
    if(channels==0 && z1flav*z2flav != 28561) continue;
    if(channels==1 && z1flav*z2flav != 14641) continue;
    if (weight <= 0 ) cout << "Warning! Negative weight events" << endl;
    if(channels==2 && z1flav*z2flav != 20449) continue;
    

    ntupleVarSet.setRealValue("mass",m4l);
    ntupleVarSet.setRealValue("myW",weight);
    if(x.getVal()>xMin && x.getVal()<xMax)
      dataset.add(ntupleVarSet, weight);
    hmass->Fill(m4l);

  }
  //---------

  cout << "dataset n entries: " << dataset.sumEntries() << endl;


  TCanvas *c1 = new TCanvas("c1","c1",725,725);


  c1->cd();

  TPad *pad1 = new TPad("pad1","This is pad1",0.05,0.35,0.95,0.97);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","This is pad2",0.05,0.02,0.95,0.35);
  pad2->Draw();

  //--- double CrystalBall
  RooRealVar mean("bias","mean of gaussian",0,-5.,5.) ;
  RooRealVar sigma("sigma","width of gaussian",1.5,0.,30.); 
  RooRealVar a1("a1","a1",1.46,0.5,5.);
  RooRealVar n1("n1","n1",1.92,0.,10.);   
  RooRealVar a2("a2","a2",1.46,1.,10.);
  RooRealVar n2("n2","n2",20,1.,50.);   
  RooDoubleCB DCBall("DCBall","Double Crystal ball",x,mean,sigma,a1,n1,a2,n2);
  if (channels== 1) mean.setVal(-1.);
  //--- Breit-Wigner
  float bwSigmaMax,bwSigmaMin;
  if(massBin<400) bwSigmaMin=bwSigmaMax=bwSigma;
  else { 
    bwSigmaMin=bwSigma-20.; 
    bwSigmaMax=bwSigma+20.; 
  }
  RooRealVar mean3("mean3","mean3",xInit) ;
  RooRealVar sigma3("sigma3","width3",bwSigma,bwSigmaMin,bwSigmaMax); 
  RooRealVar scale3("scale3","scale3 ",1.); 

  RooRelBWUFParam bw("bw","bw",x,mean3,scale3);
  //Chebyshev-Polynomial
  RooRealVar A1("A1","A1",-1,-3,3.);
  RooRealVar A2("A2","A2",0.5,-3.,3.);
  RooChebychev BkgPDF("BkgPDF","BkgPDF",x ,RooArgList(A1,A2));
  //Fraction
  RooRealVar frac("frac","Fraction for PDF",0.5,0.,1.);

  x.setBins(10000,"fft");
  RooFFTConvPdf model("model","model",x,bw,DCBall);
  

  RooAddPdf totPDF("totPDF","Total PDF ",RooArgList(model,BkgPDF),RooArgList(frac));
  
  RooArgSet* params = totPDF.getParameters(x);
  
  if(sample!=1 && categ!=0 && id!=125){
  if(channels==0 ){params->readFromFile("Ch0_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev) 

  if(channels==1 ){params->readFromFile("Ch1_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev)

  if(channels==2 ){params->readFromFile("Ch2_Cat0_paraT.txt");}//  Read the Parameter for the Resonance + Bkg(ChebyChev)
  }
  
  RooFitResult *fitres = (RooFitResult*)totPDF.fitTo(dataset,SumW2Error(1),Range(xMin,xMax),Strategy(2),NumCPU(8),Save(true));

  if (sample==1 && categ==0 && id==125){
 
  mean.setConstant(kTRUE);
  sigma.setConstant(kTRUE);
  a1.setConstant(kTRUE);
  n1.setConstant(kTRUE);
  a2.setConstant(kTRUE);
  n2.setConstant(kTRUE);
  mean3.setConstant(kTRUE);
  sigma3.setConstant(kTRUE);
  scale3.setConstant(kTRUE);
  A1.setConstant(kTRUE);
  A2.setConstant(kTRUE);
  frac.setConstant(kTRUE);

  if(channels==0 ){
  params->readFromFile("Ch0_Cat0_para.txt");  // Read the Parameter for the Resonance as ggH sample
  params->writeToFile("Ch0_Cat0_paraT.txt");} // Writing the Parameter for Full PDF including the Chebyshev-Polynomial

  if(channels==1 )
  {params->readFromFile("Ch1_Cat0_para.txt"); // Read the Parameter for the Resonance as in ggH sample
   params->writeToFile("Ch1_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial

  if(channels==2 ){
  params->readFromFile("Ch2_Cat0_para.txt"); // Read the Parameter for the Resonance as ggH sample
  params->writeToFile("Ch2_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial
  }
  
  stringstream frameTitle;
  if(channels==0){frameTitle << "4#mu, m_{H} = "; }
  if(channels==1){frameTitle << "4e, m_{H} = ";}
  if(channels==2){frameTitle << "2e2#mu, m_{H} = ";}
  frameTitle << massBin << " GeV";

  stringstream nameFileRoot;
  nameFileRoot << "fitM" << massBin << ".root";
  TFile *fileplot = TFile::Open(nameFileRoot.str().c_str(), "recreate");

  RooPlot* xframe = x.frame() ;
  xframe->SetTitle("");
  xframe->SetName("m4lplot");
  dataset.plotOn(xframe,DataError(RooAbsData::SumW2), MarkerStyle(kOpenCircle), MarkerSize(1.1) );
  int col;
  if(channels==0) col=kOrange+7;
  if(channels==1) col=kAzure+2;
  if(channels==2) col=kGreen+3;
  totPDF.plotOn(xframe,LineColor(col));


  RooHist* hpull = xframe->pullHist();

  RooPlot* frame3 = x.frame(Title("Pull Distribution")) ;
  frame3->addPlotable(hpull,"P");
  
  // cosmetics
  TLegend *legend = new TLegend(0.20,0.45,0.45,0.60,NULL,"brNDC");
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetTextAlign(12);
  legend->SetTextFont (42);
  legend->SetTextSize (0.03);

  TH1F *dummyPoints = new TH1F("dummyP","dummyP",1,0,1);
  TH1F *dummyLine = new TH1F("dummyL","dummyL",1,0,1);
  dummyPoints->SetMarkerStyle(kOpenCircle);
  dummyPoints->SetMarkerSize(1.1);
  dummyLine->SetLineColor(col);
  
  legend->AddEntry(dummyPoints, "Simulation", "pe");
  legend->AddEntry(dummyLine, "Parametric Model", "l");
  
  TPaveText *text = new TPaveText(0.15,0.90,0.77,0.98,"brNDC");
  text->AddText("CMS Simulation");
  text->SetBorderSize(0);
  text->SetFillStyle(0);
  text->SetTextAlign(12);
  text->SetTextFont(42);
  text->SetTextSize(0.03);

  TPaveText *titlet = new TPaveText(0.15,0.80,0.60,0.85,"brNDC");
  titlet->AddText(frameTitle.str().c_str());
  titlet->SetBorderSize(0);
  titlet->SetFillStyle(0);
  titlet->SetTextAlign(12);
  titlet->SetTextFont(132);
  titlet->SetTextSize(0.045);

  TPaveText *sigmat = new TPaveText(0.15,0.65,0.77,0.78,"brNDC");
  stringstream sigmaval0, sigmaval1, sigmaval2;
  sigmaval0 << fixed;
  sigmaval0 << setprecision(1);
  sigmaval0 << "m_{dCB} = " << mean.getVal() + massBin << " GeV";
  sigmaval1 << fixed;
  sigmaval1 << setprecision(1);
  sigmaval1 << "#sigma_{dCB} = " << sigma.getVal() << " GeV";
  sigmaval2 << fixed;
  sigmaval2 << setprecision(1);
  sigmaval2 << "RMS_{eff} = " << effSigma(hmass) << " GeV";
  
  sigmat->AddText(sigmaval1.str().c_str());
  sigmat->AddText(sigmaval2.str().c_str());
  sigmat->SetBorderSize(0);
  sigmat->SetFillStyle(0);
  sigmat->SetTextAlign(12);
  sigmat->SetTextFont(132);
  sigmat->SetTextSize(0.04);
  
  xframe->GetYaxis()->SetTitleOffset(1.5);

  cout << "EFF RMS = " << effSigma(hmass) << "    RMS = " << hmass->GetRMS() << endl;

  pad1->cd();
  stringstream nameFile, nameFileC, nameFilePng;
  nameFile << "fitM" << massBin << "_channel" << channels<< "_category"<< categ << ".pdf";
  nameFileC << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".C";
  nameFilePng << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".png";

  xframe->Draw(); 
  gPad->Update(); legend->Draw(); text->Draw(); sigmat->Draw(); titlet->Draw();

  pad2->cd() ;
  frame3->Draw() ;
  frame3->SetMinimum(-3);
  frame3->SetMaximum(3);

  TLine *line1 = new TLine(105,0,140,0);
  line1->SetLineColor(kRed);
  line1->Draw();
  

  c1->Print(nameFile.str().c_str());
  c1->SaveAs(nameFileC.str().c_str());
  c1->SaveAs(nameFilePng.str().c_str());

  fileplot->cd();
  xframe->Write();
  sigmat->Write();
  hmass->Write();

  fileplot->Close();

  if(fitValues!=0){
    fitValues[0] = a1.getVal();
    fitValues[1] = a2.getVal();
    fitValues[2] = mean.getVal();
    fitValues[3] = mean3.getVal();
    fitValues[4] = n1.getVal();
    fitValues[5] = n2.getVal();
    fitValues[6] = sigma.getVal();
    fitValues[7] = A1.getVal();
    fitValues[8] = A2.getVal();

  }  

  if(fitErrors!=0){
    fitErrors[0] = a1.getError();
    fitErrors[1] = a2.getError();
    fitErrors[2] = mean.getError();
    fitErrors[3] = mean3.getError();
    fitErrors[4] = n1.getError();
    fitErrors[5] = n2.getError();
    fitErrors[6] = sigma.getError();
    fitErrors[7] = A1.getError();
    fitErrors[8] = A2.getError();

  }

  covQual[0] = fitres->covQual();
  
}
void fullPedestalAnalysis(string inputDIR, string outputDIR, string inputCablingMap, string outputFileName){

  gROOT->ProcessLine("gErrorIgnoreLevel = 1");
  
  // open the file and prepare the cluster tree, adding the other trees as frined --> memory consuming                                                                                                
  std::cout<<"##################################"<<std::endl;
  std::cout<<"###### fullPedestalAnalysis ######"<<std::endl;
  std::cout<<"##################################"<<std::endl;

  clock_t tStart = clock();

  // prepare style and load macros                                                                                                                                                                    
  setTDRStyle();
  gROOT->SetBatch(kTRUE);

  system(("mkdir -p "+outputDIR).c_str());
  ifstream file;

  std::cout<<"### Make input file list"<<std::endl;
  system(("find "+inputDIR+" -name \"*.root\" > file.temp").c_str());
  std::ifstream infile;
  string line;
  vector<string> fileList;
  infile.open("file.temp",ifstream::in);
  if(infile.is_open()){
    while(!infile.eof()){
      getline(infile,line);
      if(line != "" and TString(line).Contains(".root") and line !="\n"){
        fileList.push_back(line);
      }
    }
  }
  system("rm file.temp");
  std::sort(fileList.begin(),fileList.end());

  TFile* cablingFile = TFile::Open(inputCablingMap.c_str(),"READ");
  cablingFile->cd();
  TTree* readoutMap = (TTree*) cablingFile->FindObjectAny("readoutMap");
  TTreeReader reader(readoutMap);
  TTreeReaderValue<uint32_t> detid    (reader,"detid");
  TTreeReaderValue<uint16_t> fecCrate (reader,"fecCrate");
  TTreeReaderValue<uint16_t> fecSlot  (reader,"fecSlot");
  TTreeReaderValue<uint16_t> fecRing  (reader,"fecRing");
  TTreeReaderValue<uint16_t> ccuAdd   (reader,"ccuAdd");
  TTreeReaderValue<uint16_t> ccuChan  (reader,"ccuChan");
  TTreeReaderValue<uint16_t> lldChannel  (reader,"lldChannel");
  TTreeReaderValue<uint16_t> fedId  (reader,"fedId");
  TTreeReaderValue<uint16_t> fedCh  (reader,"fedCh");

  // output tree
  TFile* ouputTreeFile = new TFile((outputDIR+"/"+outputFileName).c_str(),"RECREATE");
  ouputTreeFile->cd();
  ouputTreeFile->SetCompressionLevel(0);
  TTree* outputTree = new TTree("pedestalFullNoise","pedestalFullNoise");
  
  // branches
  uint32_t detid_,fedKey_;
  uint16_t fecCrate_,fecSlot_, fecRing_, ccuAdd_, ccuChan_, lldChannel_, fedId_, fedCh_, apvId_, stripId_;
  float    noiseMean_,noiseRMS_, noiseSkewness_, noiseKurtosis_;
  float    fitChi2_, fitChi2Probab_, fitStatus_;
  float    fitGausMean_, fitGausSigma_, fitGausNormalization_;
  float    fitGausMeanError_, fitGausSigmaError_, fitGausNormalizationError_;
  float    noiseIntegral3Sigma_, noiseIntegral3SigmaFromFit_;
  float    noiseIntegral4Sigma_, noiseIntegral4SigmaFromFit_;
  float    noiseIntegral5Sigma_, noiseIntegral5SigmaFromFit_;
  float    kSValue_, kSProbab_, jBValue_, jBProbab_, aDValue_, aDProbab_;
  vector<float> noiseDistribution_, noiseDistributionError_;
  float xMin_, xMax_, nBin_ ;

  outputTree->Branch("detid",&detid_,"detid/i");
  outputTree->Branch("fedKey",&fedKey_,"fedKey/i");
  outputTree->Branch("fecCrate",&fecCrate_,"fecCrate/s");
  outputTree->Branch("fecSlot",&fecSlot_,"fecSlot/s");
  outputTree->Branch("fecRing",&fecRing_,"fecRing/s");
  outputTree->Branch("ccuAdd",&ccuAdd_,"ccuAdd/s");
  outputTree->Branch("ccuChan",&ccuChan_,"ccuChan/s");
  outputTree->Branch("lldChannel",&lldChannel_,"lldChannel/s");
  outputTree->Branch("fedId",&fedId_,"fedId/s");
  outputTree->Branch("fedCh",&fedCh_,"fedCh/s");
  outputTree->Branch("apvId",&apvId_,"apvId/s");
  outputTree->Branch("stripId",&stripId_,"stripId/s");

  outputTree->Branch("noiseMean",&noiseMean_,"noiseMean/F");
  outputTree->Branch("noiseRMS",&noiseRMS_,"noiseRMS/F");
  outputTree->Branch("noiseSkewness",&noiseSkewness_,"noiseSkewness/F");
  outputTree->Branch("noiseKurtosis",&noiseKurtosis_,"noiseKurtosis/F");
  outputTree->Branch("fitGausNormalization",&fitGausNormalization_,"fitGausNormalization/F");
  outputTree->Branch("fitGausMean",&fitGausMean_,"fitGausMean/F");
  outputTree->Branch("fitGausSigma",&fitGausSigma_,"fitGausSigma/F");
  outputTree->Branch("fitGausNormalizationError",&fitGausNormalizationError_,"fitGausNormalizationError/F");
  outputTree->Branch("fitGausMeanError",&fitGausMeanError_,"fitGausMeanError/F");
  outputTree->Branch("fitGausSigmaError",&fitGausSigmaError_,"fitGausSigmaError/F");
  outputTree->Branch("fitChi2",&fitChi2_,"fitChi2/F");
  outputTree->Branch("fitChi2Probab",&fitChi2Probab_,"fitChi2Probab/F");
  outputTree->Branch("fitStatus",&fitStatus_,"fitStatus_F");
  outputTree->Branch("noiseIntegral3Sigma",&noiseIntegral3Sigma_,"noiseIntegral3Sigma/F");
  outputTree->Branch("noiseIntegral3SigmaFromFit",&noiseIntegral3SigmaFromFit_,"noiseIntegral3SigmaFromFit/F");
  outputTree->Branch("noiseIntegral4Sigma",&noiseIntegral4Sigma_,"noiseIntegral4Sigma/F");
  outputTree->Branch("noiseIntegral4SigmaFromFit",&noiseIntegral4SigmaFromFit_,"noiseIntegral4SigmaFromFit/F");
  outputTree->Branch("noiseIntegral5Sigma",&noiseIntegral4Sigma_,"noiseIntegral5Sigma/F");
  outputTree->Branch("noiseIntegral5SigmaFromFit",&noiseIntegral4SigmaFromFit_,"noiseIntegral5SigmaFromFit/F");
  outputTree->Branch("kSValue",&kSValue_,"kSValue/F");
  outputTree->Branch("jBValue",&jBValue_,"jBValue/F");
  outputTree->Branch("aDValue",&aDValue_,"aDValue/F");
  outputTree->Branch("kSProbab",&kSProbab_,"kSProbab/F");
  outputTree->Branch("jBProbab",&jBProbab_,"jBProbab/F");
  outputTree->Branch("aDProbab",&aDProbab_,"aDProbab/F");
  outputTree->Branch("xMin",&xMin_,"xMin/F");
  outputTree->Branch("xMax",&xMax_,"xMax/F");
  outputTree->Branch("nBin",&nBin_,"nBin/F");

  bool histoBranches = false;

  // Loop on the file list to extract each histogram 2D DQM histo with full noise distribution  
  TH1F* histoNoiseStrip = NULL;
  TF1*  fitFunc = NULL;
  TH1F* randomHisto = NULL;
  TFitResultPtr result;
  for(auto file : fileList){
    cout<<"input file: "<<file<<endl;
    TFile* inputFile = TFile::Open(file.c_str(),"READ");
    inputFile->cd();
    // take into account that the DQM file structure for strips is always the same --> use cabling map to browse the histograms
    reader.SetEntry(0);
    TH2* histoNoise = NULL;
    long int iChannel = 0;
    int noFitResult = 0;
    while(reader.Next()){
      cout.flush();
      if(iChannel %10 == 0) cout<<"\r"<<"iChannel "<<100*double(iChannel)/(readoutMap->GetEntries()/reductionFactor)<<" % ";
      if(iChannel > double(readoutMap->GetEntries())/reductionFactor) break;
      iChannel++;
      TString objName;
      uint32_t fedKey =  SiStripFedKey(*fedId,SiStripFedKey::feUnit(*fedCh),SiStripFedKey::feChan(*fedCh)).key();
      std::stringstream stream;
      stream << std::hex << fedKey;
      string fedKeyStr = stream.str();
      if(fedKeyStr.size() == 4)
	objName = Form("DQMData/SiStrip/ControlView/FecCrate%d/FecSlot%d/FecRing%d/CcuAddr%d/CcuChan%d/ExpertHisto_PedsFullNoise_FedKey0x0000%s_LldChannel%d_Noise2D",*fecCrate,*fecSlot,*fecRing,*ccuAdd,*ccuChan,fedKeyStr.c_str(),*lldChannel);      
      else if(fedKeyStr.size() == 5)
	objName = Form("DQMData/SiStrip/ControlView/FecCrate%d/FecSlot%d/FecRing%d/CcuAddr%d/CcuChan%d/ExpertHisto_PedsFullNoise_FedKey0x000%s_LldChannel%d_Noise2D",*fecCrate,*fecSlot,*fecRing,*ccuAdd,*ccuChan,fedKeyStr.c_str(),*lldChannel);      
      else
	cerr<<"hex number to short "<<fedKeyStr<<" --> please check "<<endl;

      inputFile->GetObject(objName.Data(),histoNoise);
      // extract single strip noise histogram --> loop on the y-axis
      uint16_t apvID = 0;
      uint16_t stripID = 0;       
      if(histoNoiseStrip == 0 or histoNoiseStrip == NULL){
	histoNoiseStrip = new TH1F ("histoNoiseStrip","",histoNoise->GetNbinsX(),histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	histoNoiseStrip->Sumw2();
      }
      for(int iBinY = 0; iBinY < histoNoise->GetNbinsY(); iBinY++){
	histoNoiseStrip->Reset();
	histoNoiseStrip->SetDirectory(0);
	// two multiplexed APV per line
	if(iBinY < histoNoise->GetNbinsY()/2) apvID = 1;
	else apvID = 2;
	// strip id
	stripID++;
	if(stripID > 128) stripID = 1;
	// loop on x-axis bin
	for(int iBinX = 0; iBinX < histoNoise->GetNbinsX(); iBinX++){
	  histoNoiseStrip->SetBinContent(iBinX+1,histoNoise->GetBinContent(iBinX+1,iBinY+1));
	  histoNoiseStrip->SetBinError(iBinX+1,histoNoise->GetBinError(iBinX+1,iBinY+1));	    
	}
     	
	// to initialize branches
	detid_ = 0; fedKey_ = 0; fecCrate_ = 0; fecSlot_ = 0; fecRing_ = 0; ccuAdd_ = 0; ccuChan_ = 0; lldChannel_ = 0; fedId_ = 0; fedCh_ = 0; apvId_ = 0; stripId_ = 0; 
	noiseMean_ = 0.; noiseRMS_ =  0.; noiseSkewness_ = 0.; noiseKurtosis_ = 0.; 
	fitGausMean_ = 0.; fitGausSigma_ = 0.;fitGausNormalization_ = 0.;
	fitGausMeanError_ = 0.; fitGausSigmaError_ = 0.;fitGausNormalizationError_ = 0.;	  	  
	fitChi2_ = 0.; fitChi2Probab_ = 0.; fitStatus_ = -1.; 
	noiseIntegral3Sigma_ = 0.; noiseIntegral3SigmaFromFit_ = 0.; 
	noiseIntegral4Sigma_ = 0.; noiseIntegral4SigmaFromFit_ = 0.; 
	noiseIntegral5Sigma_ = 0.; noiseIntegral5SigmaFromFit_ = 0.; 
	kSProbab_ = 0.; jBProbab_ = 0.;
	kSValue_ = 0.; jBValue_ = 0.; 
	aDValue_= 0.; aDProbab_ = 0.;
	nBin_ = 0.; xMin_ = 0.; xMax_ = 0.;
	
	// basic info
	detid_ = *detid;
	fedKey_ = fedKey;
	fecCrate_ = *fecCrate;
	fecSlot_ = *fecSlot;
	fecRing_ = *fecRing;
	ccuAdd_  = *ccuAdd;
	ccuChan_ = *ccuChan;
	lldChannel_ = *lldChannel;
	fedId_   = *fedId;
	fedCh_   = *fedCh;
	apvId_   = apvID;
	stripId_ = stripID;
	
	// basic info of nioise distribution
	noiseMean_ = histoNoiseStrip->GetMean();
	noiseRMS_  = histoNoiseStrip->GetRMS();
	noiseSkewness_ = histoNoiseStrip->GetSkewness();
	noiseKurtosis_ = histoNoiseStrip->GetKurtosis();
	float integral = histoNoiseStrip->Integral();	
	noiseIntegral3Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*3),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*3)))/integral;
	noiseIntegral4Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*4),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*4)))/integral;
	noiseIntegral5Sigma_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+noiseRMS_*5),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-noiseRMS_*5)))/integral;
	
	// make a gaussian fit	  	
	if(fitFunc == NULL or fitFunc == 0){
	  fitFunc = new TF1 ("fitFunc","gaus(0)",histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	}
	fitFunc->SetRange(histoNoise->GetXaxis()->GetXmin(),histoNoise->GetXaxis()->GetXmax());
	fitFunc->SetParameters(histoNoiseStrip->Integral(),noiseMean_,noiseRMS_);
	result = histoNoiseStrip->Fit(fitFunc,"QSR");

	if(result.Get()){
	    fitStatus_     = result->Status();
	    fitGausNormalization_  = fitFunc->GetParameter(0);
	    fitGausMean_   = fitFunc->GetParameter(1);
	    fitGausSigma_  = fitFunc->GetParameter(2);
	    fitGausNormalizationError_  = fitFunc->GetParError(0);
	    fitGausMeanError_  = fitFunc->GetParError(1);
	    fitGausSigmaError_ = fitFunc->GetParError(2);
	    fitChi2_           = result->Chi2();
	    fitChi2Probab_     = result->Prob();

	    noiseIntegral3SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*3),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*3)))/histoNoiseStrip->Integral();
	    noiseIntegral4SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*4),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*4)))/histoNoiseStrip->Integral();
	    noiseIntegral5SigmaFromFit_ = (histoNoiseStrip->Integral(histoNoiseStrip->FindBin(noiseMean_+fitGausSigma_*5),histoNoiseStrip->GetNbinsX()+1) + histoNoiseStrip->Integral(0,histoNoiseStrip->FindBin(noiseMean_-fitGausSigma_*5)))/histoNoiseStrip->Integral();
	    
	    jBValue_   = (histoNoiseStrip->Integral()/6)*(noiseSkewness_*noiseSkewness_+(noiseKurtosis_*noiseKurtosis_)/4);	  
	    jBProbab_  = ROOT::Math::chisquared_cdf_c(jBValue_,2);

	    if(randomHisto == 0 or randomHisto == NULL)
	      randomHisto = (TH1F*) histoNoiseStrip->Clone("randomHisto");	    	    
	    randomHisto->Reset();
	    randomHisto->SetDirectory(0);     
	
      
	    if(integral != 0){	      
	      if(generateRandomDistribution){
		randomHisto->FillRandom("fitFunc",histoNoiseStrip->Integral());	    
		kSValue_  = histoNoiseStrip->KolmogorovTest(randomHisto,"MN");
		kSProbab_ = histoNoiseStrip->KolmogorovTest(randomHisto,"N");	    
		aDValue_  = histoNoiseStrip->AndersonDarlingTest(randomHisto,"T");
		aDProbab_ = histoNoiseStrip->AndersonDarlingTest(randomHisto);
	      }
	      else{
		
		randomHisto->Add(fitFunc);		
		kSValue_  = histoNoiseStrip->KolmogorovTest(randomHisto,"MN"); 
		kSProbab_ = histoNoiseStrip->KolmogorovTest(randomHisto,"N");
		// AD test
		ROOT::Fit::BinData data1;
		ROOT::Fit::BinData data2;
		ROOT::Fit::FillData(data1,histoNoiseStrip,0);
		data2.Initialize(randomHisto->GetNbinsX()+1,1);
		for(int ibin = 0; ibin < randomHisto->GetNbinsX(); ibin++){ 
		  if(histoNoiseStrip->GetBinContent(ibin+1) != 0 or randomHisto->GetBinContent(ibin+1) >= 1)
		    data2.Add(randomHisto->GetBinCenter(ibin+1),randomHisto->GetBinContent(ibin+1),randomHisto->GetBinError(ibin+1));
		}
	  
		double probab;
		double value;
		ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2,probab,value);
		aDValue_ = value;
		aDProbab_ = probab;
	      }
	    }
	}
	else
	  noFitResult++;
	
	if(not histoBranches){
	  noiseDistribution_.clear();
	  noiseDistributionError_.clear();
	  outputTree->Branch("noiseDistribution","vector<float>",&noiseDistribution_);
	  outputTree->Branch("noiseDistributionError","vector<float>",&noiseDistributionError_);
	  histoBranches = true;
	}
    
	// set histogram
	noiseDistribution_.clear();
	noiseDistributionError_.clear();
	for(int iBin = 0; iBin < histoNoiseStrip->GetNbinsX(); iBin++){
	  noiseDistribution_.push_back(histoNoiseStrip->GetBinContent(iBin+1));
	  noiseDistributionError_.push_back(histoNoiseStrip->GetBinError(iBin+1));	      
	}
    
	nBin_ = histoNoiseStrip->GetNbinsX();
	xMin_ = histoNoise->GetXaxis()->GetBinLowEdge(1);
	xMax_ = histoNoise->GetXaxis()->GetBinLowEdge(histoNoise->GetNbinsX()+1);

	// fill all branches for each strip
	ouputTreeFile->cd();
	outputTree->Fill();
      }
    }
    inputFile->Close();
    std::cout<<std::endl;
    cout<<"No fit results found for "<<100*double(noFitResult)/iChannel<<endl;
  }
  outputTree->BuildIndex("detid");
  outputTree->Write(outputTree->GetName(),TObject::kOverwrite);
  ouputTreeFile->Close();
  cablingFile->Close();

  /* Do your stuff here */
  cout<<"Time taken: "<<(double)(clock() - tStart)/CLOCKS_PER_SEC<<endl;  
}