Ejemplo n.º 1
0
TProfile* plotIsoPerformance( TFile* ftt, 
			      const char* signal,     // histogram name
			      const char* background, // histogram name
			      const char* name,       // unique name
			      bool reverse = false,   // normally signal near zero bin, reverse means signal is around max bin
			      double bkg_eff_min = 0,
			      double bkg_eff_max = 1,
			      double sig_eff_min = 0,
			      double sig_eff_max = 0
			      )
{ 
  TH1F* S = dynamic_cast<TH1F*>(ftt->Get(signal));
  if ( ! S ) {
    std::cout << "Error: histogram not found " << signal << std::endl;
    return 0;
  }
  TH1F* B = dynamic_cast<TH1F*>(ftt->Get(background));
  if ( ! B ) {
    std::cout << "Error: histogram not found " << background << std::endl;
    return 0;
  }
  char buf[1024];
  sprintf(buf,"c_%s",name);
  // TCanvas* c = new TCanvas(buf,buf,500,500);
  sprintf(buf,"p_%s",name);
  TProfile* p = new TProfile(buf,buf,50,bkg_eff_min,bkg_eff_max,sig_eff_min,sig_eff_max);
  p->SetLineColor(kBlue);
  p->SetLineWidth(2);
  p->SetMarkerStyle(20);
  p->SetMarkerSize(1);
  p->GetXaxis()->SetTitle("Background Efficiency");
  p->GetYaxis()->SetTitle("Signal Efficiency");
  p->SetStats(kFALSE);
  for( int i=0;i<=S->GetNbinsX()+1; ++i )
    if ( reverse ) 
      p->Fill(B->Integral(i,B->GetNbinsX()+1)/B->Integral(0,B->GetNbinsX()+1),
	      S->Integral(i,S->GetNbinsX()+1)/S->Integral(0,S->GetNbinsX()+1));
    else
      p->Fill(B->Integral(0,i)/B->Integral(0,B->GetNbinsX()+1),
	      S->Integral(0,i)/S->Integral(0,S->GetNbinsX()+1));
  // p->Draw();
  return p;
}
Ejemplo n.º 2
0
void Fake100PeVShower(int opt)
{

  // opt == 0 implies save to root file
  // opt == 1 implies plot and save to canvas
  TFile* file = NULL;
  TCanvas* c  = NULL;

  if(opt == 0)
    file = new TFile("fake100PeVShower.root","recreate");
  if(opt == 1)
    c = makeCanvas("c");

  TString gaus = "1.5e7*TMath::Exp(-(pow(x-10,2)/9))";
  TString bump = "5e6*TMath::Exp(-(pow(x-17,2)/20))";
  TF1* f = new TF1("f",(gaus+"+"+bump).Data(),0,30);

  int nbins = 3000;
  float xmin  = 0;
  float xmax  = 30;
  TProfile* prof = new TProfile("prof","",nbins,xmin,xmax);
  prof->SetStats(0);
  prof->SetTitle("");
  prof->GetYaxis()->SetTitle("Charge excess / 1e7");
  prof->GetXaxis()->SetTitle("z [m]");

  float step = xmax / nbins;
  for(int i =0; i<nbins; ++i){
    float x = step * i;
    if(opt == 1 ) prof->Fill(x, f->Eval(x)/1e7);
    else          prof->Fill(x, f->Eval(x));
  }
    
  if(opt == 1){
    prof->Draw();
    c->SaveAs("JaimeCheck/FakeProfile100PeV.png");
  }
  if(opt == 0){
    file->Write();
    file->Close();
  }
}
Ejemplo n.º 3
0
void profile()
{
  TCanvas* c1 = new TCanvas("canvas","nhitac",1200,600);
  c1->Divide(2,1);
  c1->cd(1);
  TFile *file1 = new TFile("test_nhitac_modified.root");
  //TH1F  *histo1 = new TH1F("nhitac1","nhitac1",60,0,300);
  TProfile *profile1 = new TProfile("profile","nhitac profile",100,0,100,0,300);

  TFile *file2 = new TFile("test_nhitac_unmodified.root");
  //TH1F  *histo2 = new TH1F("nhitac","nhitac",60,0,300);
  TProfile *profile2 = new TProfile("profile2","nhitac profile2",100,0,100,0,300);
  TProfile *ratio = new TProfile("ratio","nhitac ratio", 100,0,100,0,2);
  //histo2->SetMarkerStyle(31);
  TLegend *l1 = new TLegend(0.20, 0.60, 0.3, 0.7);
  l1->SetBorderSize(0);

  TTree* nhitac_modified = (TTree*)file1->Get("testnhitac");
  TTree* nhitac_unmodified = (TTree*)file2->Get("testnhitac");
  int testnhitac1, testnhitac2;
  nhitac_modified->SetBranchAddress("nhitac",&testnhitac1);
  nhitac_unmodified->SetBranchAddress("nhitac",&testnhitac2);
  for(int i= 0; i < nhitac_modified->GetEntries(); i++)
  {
    nhitac_modified->GetEntry(i);
    nhitac_unmodified->GetEntry(i);
    profile1->Fill(i,testnhitac1);
    profile2->Fill(i,testnhitac2);
    double temp = testnhitac2;
    ratio->Fill(i,testnhitac1/temp);
    //histo1->Fill(testnhitac1);
    //histo2->Fill(testnhitac2);
  }
  //histo1->SetMarkerColor(kRed);
  //histo1->SetLineColor(kRed);
  profile1->SetMarkerColor(kRed);
  profile1->SetMarkerStyle(5);
  profile2->SetMarkerColor(kBlue);
  l1->AddEntry(profile1,"modified od bad channel","P");
  l1->AddEntry(profile2,"old od bad channel","l");
  l1->SetTextSize(0.04);
  profile1->Draw("e1p");
  profile1->GetXaxis()->SetTitle("event #");
  profile1->GetYaxis()->SetTitle("nhitac");
  profile2->Draw("same");
  l1->Draw();
  c1->cd(2);
  ratio->GetXaxis()->SetTitle("event #");
  ratio->GetYaxis()->SetTitle("new/old");
  //ratio->SetMarkerStyle(5);
  //ratio->SetMarkerColor(kRed);
  ratio->Draw();
}
Ejemplo n.º 4
0
// Report cut flow findings to screen
void DileptonAnalyzer::reportCutFlow( TFile & outputFile ) {

  // Store in a TProfile
  TProfile *cutFlow = new TProfile("cutFlow","Cut flow for final set of analysis cuts",20,0.5,20.5,-9.9e9,9.9e9);
  TAxis *cutFlowAxis = cutFlow->GetXaxis();

  for ( unsigned int iCut = 0; iCut < cutNamesInOrder_.size(); iCut++ ) {
    cutFlow->Fill( iCut+1, cutFlowMap_[cutNamesInOrder_[iCut]]);
    cutFlowAxis->SetBinLabel( iCut+1, cutNamesInOrder_[iCut]);
  }

  outputFile.cd();
  cutFlow->Write();
}
Ejemplo n.º 5
0
//----------------------------------------//
// Get profile from all events mixed
//----------------------------------------//
TProfile* getMixProfile(TFile* file, int nbins,
			float xmin, float xmax,
			int color, int marker)
{

  // Histograms all have same base name
  string base = "h_evt";
  
  // String stream easy for manipulation
  stringstream ss;
  
  // Create Profile
  TProfile* p = new TProfile("mixed","",nbins,xmin,xmax);
  p->SetMarkerSize(0.75);
  p->SetMarkerStyle(marker);
  p->SetMarkerColor(color);
  p->SetLineColor(color);

  // Now loop over events and get result
  TH1F* h = NULL;
  for(int i=0; i<m_nEvent; ++i){
    ss.str("");
    ss << base << i;
    h = (TH1F*) file->Get(ss.str().c_str());

    // Loop over bin content
    for(int bin=1; bin<=h->GetNbinsX(); ++bin){
      float content = h->GetBinContent(bin);
      float center  = h->GetBinCenter(bin);
      p->Fill(center, content);
    }
    
    h = NULL;

  }// end loop events

  return p;

}
Ejemplo n.º 6
0
void AnalysisBase::getTDC(){
  TProfile *hb = new TProfile("hb","Cluster Charge vs TDC time",12,0,12,100,1000);
  Long64_t nentries = fChain->GetEntriesFast();
  float lo = 0, hi = 0;
  int istrip;

  Long64_t nbytes = 0, nb = 0;
  std::cout << "============================================" << std::endl;
  std::cout << "getTDC(): Determining Optimal TDC time range" << std::endl;
  std::cout << "============================================" << std::endl;   
  for (Long64_t jentry=0; jentry<max(50000,(int)nentries);jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    for(int j=0; j<min((int)clusterNumberPerEvent,10); j++){
      //std::cout << "j: " << ", clustersTDC: " << clustersTDC << ", clustersCharge[j]: " << clustersCharge[j] << ", clustersPosition[j]: " << clustersPosition[j] << std::endl; 
      istrip = clustersSeedPosition[j];
      if(badStrips[istrip]==0) continue; // exclude bad strips
      if(clustersPosition[j] < 0.1) continue;
      if(polarity*clustersCharge[j] < kClusterChargeMin) continue;
      if(clustersPosition[j]>=iLo && clustersPosition[j]<=iHi && clustersTDC>1.0 && 
         polarity*clustersCharge[j]>150 && polarity*clustersCharge[j]<500) hb->Fill(clustersTDC+0.1,polarity*clustersCharge[j]);
    }
  }

  getTDCBins(hb,lo,hi);
  tdcLo = lo;
  tdcHi = hi;
  std::cout << "====> TDC Range determined to be from " << tdcLo << " -- " << tdcHi << std::endl;
  hb->Draw();
  //delete hb;
  

  return;
}
Ejemplo n.º 7
0
void DileptonAnalyzer::storeSignalEfficiencies( TFile & outputFile ) {
  // Store in a TProfile
  TProfile *sigEffOne = new TProfile("SignalEfficOneDecay","Signal efficiencies when one exotic decays in this channel",10,0.5,10.5,-9.9e9,9.9e9);
  TAxis *sigEffOneAxis = sigEffOne->GetXaxis();

  TProfile *sigEffTwo = new TProfile("SignalEfficTwoDecay","Signal efficiencies when two exotic decays in this channel",10,0.5,10.5,-9.9e9,9.9e9);
  TAxis *sigEffTwoAxis = sigEffTwo->GetXaxis();

  // Fill set of 3 bins in each TProfile for each exotic
  for ( int iExotic = 0; iExotic < nSignalParticles_; iExotic++ ) {

    TString axisTitle;

    sigEffOne->Fill( iExotic*nSignalParticles_+1, numEvents_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of events coming into macro for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+1, axisTitle.Data());

    sigEffOne->Fill( iExotic*nSignalParticles_+2, numExoticsRECO_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of candidates RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+2, axisTitle.Data());

    sigEffOne->Fill( iExotic*nSignalParticles_+3, numExoticsCorrectRECO_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of exotics correctly RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+3, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+1, numEvents_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of events coming into macro for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+1, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+2, numExoticsRECO_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of candidates RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+2, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+3, numExoticsCorrectRECO_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of exotics correctly RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+3, axisTitle.Data());
  }
  outputFile.cd();
  sigEffOne->Write();
  sigEffTwo->Write();
}
Ejemplo n.º 8
0
void RunPidGetterQAEff()
{
        
    TString PidFrameworkDir = "/lustre/nyx/cbm/users/klochkov/soft/PidFramework/";
    gSystem->Load( PidFrameworkDir + "build/libPid");  
    
    gStyle->SetOptStat(0000);

    TFile *f2 = new TFile("pid_0.root");    
    TTree *PidTree = (TTree*) f2->Get("PidTree");

    TofPidGetter *getter = new TofPidGetter();
    TBranch *PidGet = PidTree->GetBranch("TofPidGetter");
    PidGet->SetAddress(&getter);

    PidGet->GetEntry(0);
    Float_t ret[3];
        
    TProfile *hEffP  = new  TProfile ("hEffP", "", 100, 0, 10);
    TProfile *hEffPi = new  TProfile ("hEffPi", "", 100, 0, 6);
    TProfile *hEffK  = new  TProfile ("hEffK", "", 100, 0, 5);

    TProfile *hEffPSigma  = new  TProfile ("hEffPSigma", "", 100, 0, 10);
    TProfile *hEffPiSigma = new  TProfile ("hEffPiSigma", "", 100, 0, 6);
    TProfile *hEffKSigma  = new  TProfile ("hEffKSigma", "", 100, 0, 5);

    TProfile2D *hEffPtYP  = new  TProfile2D ("hEffPtYP", "", 100,   -2.5, 2.5, 100, 0, 4);
    TProfile2D *hEffPtYK  = new  TProfile2D ("hEffPtYK", "", 100,   -2.5, 2.5, 100, 0, 4);
    TProfile2D *hEffPtYPi  = new  TProfile2D ("hEffPtYPi", "", 100, -2.5, 2.5, 100, 0, 4);

    TString InTreeFileName = "/lustre/nyx/cbm/users/dblau/cbm/mc/UrQMD/AuAu/10AGeV/sis100_electron/SC_ON/2016_09_01/tree/11111.root";
    TFile *InFile = new TFile(InTreeFileName);    
    TTree *InTree = (TTree*) InFile->Get("fDataTree");
    DataTreeEvent* DTEvent;
    InTree -> SetBranchAddress("DTEvent",&DTEvent);

    int nevents = 100000;//InTree->GetEntries();
    int outputstep = 100;
    std::cout << "Entries = " << nevents << std::endl;

    for (int j=0;j<nevents;j++)
    {
        if ( (j+1) % outputstep == 0) std::cout << j+1 << "/" << nevents <<  "\r" << std::flush;
        InTree->GetEntry(j);
        
        Int_t Nmc[3] = {100,100,100};
        Int_t Ntof[3] = {0,0,0};
        Int_t PdgCode[3] = {2212, 212, 211};
        Double_t sigmas [3] = {0,0,0};
                
        for (int i=0;i<DTEvent->GetNTracks(); i++)
        {
            
            TLorentzVector v;
            
            DataTreeTrack* track = DTEvent -> GetTrack(i);
            DataTreeMCTrack* mctrack = DTEvent -> GetMCTrack(i);
            Double_t p = mctrack->GetPt() * TMath::CosH( mctrack->GetEta() );
            if (track->GetTOFHitId() < 0)
            {
                if (mctrack->GetPdgId() == 2212  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.9386);
                    hEffP->Fill ( p, 0 );
                    hEffPSigma->Fill ( p, 0 );
                    hEffPtYP -> Fill( v.Rapidity() - 1.52, v.Pt(), 0 );
                }
                
                if (mctrack->GetPdgId() == 321  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.5);
                    hEffK->Fill ( p, 0 );
                    hEffKSigma->Fill ( p,  0 ); 
                    hEffPtYK -> Fill( v.Rapidity() - 1.52, v.Pt(), 0 );
                }
                
                if (mctrack->GetPdgId() == 211  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.14);
                    hEffPi->Fill ( p, 0 );
                    hEffPiSigma->Fill ( p,  0);  
                    hEffPtYPi -> Fill( v.Rapidity() - 1.52, v.Pt(),  0 );
                }
                continue;
            }
//             
            DataTreeTOFHit* toftrack = DTEvent -> GetTOFHit(track->GetTOFHitId());
            p = toftrack->GetP();
            Double_t m2 = toftrack->GetMass2 ();
            
            Bool_t cut = toftrack->GetBeta() > 0.1 && ( track->GetChiSq(0)/track->GetNDF(0) < 3 ) && p > 1.0 ;
            if ( !cut ) continue;
            
            getter->GetBayesProbability (m2, p, ret);
            sigmas[0] = getter->GetSigmaProton (m2, p);
            sigmas[1] = getter->GetSigmaKaon (m2, p);
            sigmas[2] = getter->GetSigmaPion (m2, p);
            
    //             std::cout << "pdg = " << mctrack->GetPdgId() << " p = " << p << " Sp = " << sigmas[0] << " Sk = " << sigmas[1]<< " Spi = " << sigmas[2] << std::endl;
            
            if (mctrack->GetPdgId() == 2212  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.9386);
                hEffP->Fill ( p, ret[0] > 0.9 );
                hEffPSigma->Fill ( p,  sigmas[0] < 3&& sigmas[1] > 2 && sigmas[2] > 2 );
                hEffPtYP -> Fill( v.Rapidity() - 1.52, v.Pt(),  ret[0] > 0.9 );
            }
            
            if (mctrack->GetPdgId() == 321  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.5);
                hEffK->Fill ( p, ret[1] > 0.9 );
                hEffKSigma->Fill ( p,  sigmas[1] < 3&& sigmas[2] > 2 && sigmas[0] > 2 ); 
                hEffPtYK -> Fill(  v.Rapidity() - 1.52, v.Pt(),  ret[1] > 0.9 );
            }
            
            if (mctrack->GetPdgId() == 211  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.14);
                hEffPi->Fill ( p, ret[2] > 0.9 );
                hEffPiSigma->Fill ( p, sigmas[2] < 3&& sigmas[0] > 2 && sigmas[1] > 2 );  
                hEffPtYPi -> Fill( v.Rapidity() - 1.52, v.Pt(),  ret[2] > 0.9  );
            }
        }
    }

    hEffP       -> SetMarkerStyle(21);      hEffP       -> SetMarkerColor(kRed);     hEffP       -> SetLineColor(kRed); 
    hEffPi      -> SetMarkerStyle(21);      hEffPi      -> SetMarkerColor(kRed);     hEffPi      -> SetLineColor(kRed); 
    hEffK       -> SetMarkerStyle(21);      hEffK       -> SetMarkerColor(kRed);     hEffK       -> SetLineColor(kRed); 
    hEffPSigma  -> SetMarkerStyle(22);      hEffPSigma  -> SetMarkerColor(kBlue);    hEffPSigma  -> SetLineColor(kBlue);
    hEffPiSigma -> SetMarkerStyle(22);      hEffPiSigma -> SetMarkerColor(kBlue);    hEffPiSigma -> SetLineColor(kBlue);
    hEffKSigma  -> SetMarkerStyle(22);      hEffKSigma  -> SetMarkerColor(kBlue);    hEffKSigma  -> SetLineColor(kBlue);

    hEffP->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffP->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffP->GetYaxis()->SetRangeUser(0.0, 1.);

    hEffK->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffK->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffK->GetYaxis()->SetRangeUser(0.0, 1.);

    hEffPi->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffPi->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffPi->GetYaxis()->SetRangeUser(0.0, 1.);
    
    hEffPtYP->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYP->GetXaxis()->SetTitle(  "Rapidity"  );
    hEffPtYK->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYK->GetXaxis()->SetTitle(  "Rapidity"  );
    hEffPtYPi->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYPi->GetXaxis()->SetTitle(  "Rapidity"  );
    
    TCanvas *c1 = new TCanvas ("c1", "c1", 1400, 700);
    c1->Divide(3,1);

    c1->cd(1);
    hEffP->Draw();
    hEffPSigma->Draw("same");
    c1->cd(2);
    hEffK->Draw();
    hEffKSigma->Draw("same");
    c1->cd(3);
    hEffPi->Draw();
    hEffPiSigma->Draw("same");

//     c1->cd(4);
//     getter->GetProtonSigma()->Draw();
//     getter->GetKaonSigma()->Draw("same");
//     getter->GetPionSigma()->Draw("same");
// 
//     c1->cd(5);
//     getter->GetProtonA()->Draw();
//     getter->GetKaonA()->Draw("same");
//     getter->GetPionA()->Draw("same");
// 
//     c1->cd(6);
//     getter->GetProtonM2()->Draw();
//     getter->GetKaonM2()->Draw("same");
//     getter->GetPionM2()->Draw("same");    
    
    TCanvas *c2 = new TCanvas ("c2", "c2", 1400, 700);
    
    c2->Divide(3,1);
    c2->cd(1);
    hEffPtYP->Draw("colz");

    c2->cd(2);
    hEffPtYK->Draw("colz");
    
    c2->cd(3);
    hEffPtYPi->Draw("colz");
    
   
    c1->SaveAs("Canvas_Eff_p_all.root");
    c1->SaveAs("Canvas_Eff_p_all.C");
    c1->SaveAs("Canvas_Eff_p_all.png");
   
    c2->SaveAs("Canvas_Eff_pT_Y_all.root");
    c2->SaveAs("Canvas_Eff_pT_Y_all.C");
    c2->SaveAs("Canvas_Eff_pT_Y_all.png");
   
}
Ejemplo n.º 9
0
void calibrateEM()
{

  // FIXME: There are two possibilities to execute the script:
  // i) root run_hadron_g4.C
  //    root[] .L calibrateEM.C
  //    root[] calibrateEM()
  // or ii) Include the basics from run_hadron_g4.C here and
  //    execute simply:
  //    root calibrateEM.C
  // Load basic libraries
   // Load basic libraries
  gROOT->LoadMacro("/opt/geant4_vmc.2.15a/examples/macro/basiclibs.C");
  basiclibs();

  // Load Geant4 libraries
  gROOT->LoadMacro("/opt/geant4_vmc.2.15a/examples/macro/g4libs.C");
  g4libs();
  
  // Load the tutorial application library
  gSystem->Load("libTutorialApplication");
  
  // MC application
  TutorialApplication* app 
    = new TutorialApplication("TutorialApplication",
			      "Tutorial Application for HEP Lecture @EKP");
  
  // configure Geant4
  gROOT->LoadMacro("g4Config.C");
  Config();

 // instantiate graphical user interface for tutorial application
 new TutorialMainFrame(app);
  //FIXME: Load "CountChargedinScint.C"
  gROOT->ProcessLine(".L CountChargedinScint.C");

  //FIXME: Initialize the geometry
  app->InitMC("geometry/calor(1,0.2)");
  //FIXME: Set the primary particle to photon
  app->SetPrimaryPDG(22);
  // Profile histogram - will show us the mean numbers of counts in bins of the energy.
  // The given binning refers to the energy, the other binning will be inferred automatically.
  TProfile* hcounts = new TProfile("hcounts","Counts per particle energy",
				   10,0,10);
  hcounts->SetXTitle("energy [GeV]");
  hcounts->SetYTitle("mean number of counts");

  // FIXME loop over different particle momenta, and for each momentum simulate several events (e.g. 10)
  for(Int_t i = 0 ; i < 10 ; ++i) {
    for(Int_t k = 0 ; k < 10; k ++) {
    //FIXME: Set the momentum of the primary particle to p
      Double_t p = i;
      app->SetPrimaryMomentum(p);
    //FIXME: Run the simulation
      app->RunMC();
    //FIXME: Fill both the momentum and the output from CountChargedinScint
    //        into the profile histogram hcounts
      Double_t x = CountChargedinScint();
      hcounts->Fill(p,x);
    }
  }

  TCanvas* c = new TCanvas();
  c->cd();
  hcounts->Draw();

  TF1 *fitter = new TF1("fitf","[0]*x", 0,10);
  fitter->SetParameter(0,1.0);
  fitter->SetParNames("calibration factor");
  //FIXME: Fit the histogram to get the calibration factor
  hcounts->Fit("fitf");
}
Ejemplo n.º 10
0
int main (int argc, char* argv[]) 
{
   
    int EEradStart = 15 ;
    int EEradEnd = 50 ;
    int EEphiStart = 0 ;
    int EEphiEnd = 360 ;

    std::string filename = "coeffcompareEE.root" ;
     
//     std::string NameDBOracle1 = "oracle://cms_orcoff_int2r/CMS_COND_ECAL";
//     std::string TagDBOracle1 = "EcalIntercalibConstants_startup_csa08_mc";  
//     
//     std::string NameDBOracle2 = "oracle://cms_orcoff_int2r/CMS_COND_ECAL";
//     std::string TagDBOracle2 = "EcalIntercalibConstants_inv_startup_csa08_mc";  

    std::string NameDBOracle1 = "oracle://cms_orcoff_prod/CMS_COND_20X_ECAL";
    std::string TagDBOracle1 = "EcalIntercalibConstants_phi_Zee_csa08_s156_mc";  
    
    std::string NameDBOracle2 = "oracle://cms_orcoff_prod/CMS_COND_20X_ECAL";
    std::string TagDBOracle2 = "EcalIntercalibConstants_startup_csa08_mc";  
    
    
    
    //---- location of the xml file ----
    std::string calibFile = "/afs/cern.ch/user/a/amassiro/scratch0/CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml";
 
    
    
    
    if (argc == 1) {
        std::cout << "Help:"<<std::endl;
        std::cout << " 0-> Help"<< std::endl;
        std::cout << " 1-> Name of 1st Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 2-> Name of 1st Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 3-> Location of the xml file, e.g. /afs/cern.ch/user/.../CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml. Make sure it is on your afs."<< std::endl;
        std::cout << " 4-> Name of 2nd Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 5-> Name of 2nd Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 6-> EEradStart"<< std::endl;
        std::cout << " 7-> EEradEnd"<< std::endl;
        std::cout << " 8-> EEphiStart"<< std::endl;
        std::cout << " 9-> EEphiEnd"<< std::endl;
        std::cout << " 10-> filename output"<< std::endl;
        
        std::cout << std::endl << std::endl << "Now working with default values" << std::endl;
    }
      
    if (argc == 2) {
        //---- Help option ----
        std::string testName = "--help";
        std::string testNameLoad = argv[1];
        if (argv[1] == testName){
        std::cout << "Help:"<<std::endl;
        std::cout << " 0-> Help. --help option"<< std::endl;
        std::cout << " 1-> Name of 1st Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 2-> Name of 1st Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 3-> Location of the xml file, e.g. /afs/cern.ch/user/.../CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml. Make sure it is on your afs."<< std::endl;
        std::cout << " 4-> Name of 2nd Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 5-> Name of 2nd Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 6-> EEradStart"<< std::endl;
        std::cout << " 7-> EEradEnd"<< std::endl;
        std::cout << " 8-> EEphiStart"<< std::endl;
        std::cout << " 9-> EEphiEnd"<< std::endl;
        std::cout << " 10-> filename output"<< std::endl;
        exit (1);
        }
    }
    if (argc > 1){
        NameDBOracle1 = argv[1];
        TagDBOracle1 = argv[2];
        std::cout << "NameDBOracle1 = " << NameDBOracle1 << std::endl;
        std::cout << "TagDBOracle1 = " << TagDBOracle1 << std::endl;
        if (argc > 3){
            calibFile = argv[3];
            std::cout << "calibFile = " << calibFile << std::endl;
            if (argc > 4){
                NameDBOracle2 = argv[4];
                TagDBOracle2 = argv[5];
                std::cout << "NameDBOracle2 = " << NameDBOracle2 << std::endl;
                std::cout << "TagDBOracle2 = " << TagDBOracle2 << std::endl;
            }
        }
    }
  
    
    if (argc > 6)
    {
        if (argc < 10)
        {
            std::cerr << "Too few (or too many) arguments passed" << std::endl ;
            exit (1) ;
        }
        EEradStart = atoi (argv[6]) ;
        EEradEnd = atoi (argv[7]) ;
        EEphiStart = atoi (argv[8]) ;
        EEphiEnd = atoi (argv[9]) ;
    }
    if (argc == 11) filename = argv[10] ;

    
    
    
    //---- export of the DB from oracle to sqlite db ----
  
    
    std::string Command2LineStr1 = "cmscond_export_iov -s " + NameDBOracle1 + " -d sqlite_file:Uno.db -D CondFormatsEcalObjects -t " + TagDBOracle1 + " -P /afs/cern.ch/cms/DB/conddb/";
   
    std::string Command2LineStr2 = "cmscond_export_iov -s " + NameDBOracle2 + " -d sqlite_file:Due.db -D CondFormatsEcalObjects -t " + TagDBOracle2 + " -P /afs/cern.ch/cms/DB/conddb/";
            

    gSystem->Exec(Command2LineStr1.c_str());

    //---- now the second set analysed through xml file ----
        gSystem->Exec(Command2LineStr2.c_str());
   
    
    
   
  
  std::string NameDB;
  std::string FileData;

  //----------------------------------
  //---- First Database Analyzed -----
  //----------------------------------

  NameDB = "sqlite_file:Uno.db";
  FileData = TagDBOracle1;
  CondIter<EcalIntercalibConstants> Iterator1;
  Iterator1.create(NameDB,FileData);
  
  
  
  //-----------------------------------
  //---- Second Database Analyzed -----
  //-----------------------------------
  
  NameDB = "sqlite_file:Due.db";
  FileData = TagDBOracle2;
  CondIter<EcalIntercalibConstants> Iterator2;
  Iterator2.create(NameDB,FileData);

  //---------------------------------------------------------------------
  
  
      
  
  
  //-------------------------------------------------
  //---- Ottengo Mappe da entrambi gli Iterators ----
  //-------------------------------------------------
  
  const EcalIntercalibConstants* EEconstants1;
  EEconstants1 = Iterator1.next();
  EcalIntercalibConstantMap iEEcalibMap = EEconstants1->getMap () ;
 
  
  
  const EcalIntercalibConstants* EEconstants2;
  EEconstants2 = Iterator2.next();
  EcalIntercalibConstantMap iEEscalibMap = EEconstants2->getMap () ;

  
  
  
  
  
  
  
  
  
  //---- load form xml file ----
  //---- name of the xml file defined at the beginning ----
  
//   CaloMiscalibMapEcal EEscalibMap ;
//   EEscalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap endcapreader (EEscalibMap) ;
//   if (!calibFile.empty ()) endcapreader.parseXMLMiscalibFile (calibFile) ;
//   EcalIntercalibConstants* EEconstants = new EcalIntercalibConstants (EEscalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEscalibMap = EEconstants->getMap () ;  //MF prende i vecchi coeff
    
  
  
  
  
  
  
  //---- Xml way ----  

  
  
//   CaloMiscalibMapEcal EEscalibMap ;
//   EEscalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap endcapreader (EEscalibMap) ;
//   if (!endcapfile.empty ()) endcapreader.parseXMLMiscalibFile (endcapfile) ;
//   EcalIntercalibConstants* EEconstants = 
//           new EcalIntercalibConstants (EEscalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEscalibMap = EEconstants->getMap () ;  //MF prende i vecchi coeff
// 
//   //PG get the recalibration files for EB and EE
//   //PG -----------------------------------------
// 
//   CaloMiscalibMapEcal EEcalibMap ;
//   EEcalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap calibEndcapreader (EEcalibMap) ;
//   if (!calibEndcapfile.empty ()) calibEndcapreader.parseXMLMiscalibFile (calibEndcapfile) ;
//   EcalIntercalibConstants* EECconstants = 
//           new EcalIntercalibConstants (EEcalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEcalibMap = EECconstants->getMap () ;  //MF prende i vecchi coeff
  
  
  
  
  
  
  
  
  //PG fill the histograms
  //PG -------------------
  
  TH1F EEPCompareCoeffDistr ("EEPCompareCoeffDistr","EEPCompareCoeffDistr",5000,0,2) ;
  TH2F EEPCompareCoeffMap ("EEPCompareCoeffMap","EEPCompareCoeffMap",101,0,101,101,0,101) ;
  TH2F EEPCompareCoeffEtaTrend ("EEPCompareCoeffEtaTrend",
                                "EEPCompareCoeffEtaTrend",
                                51,0,50,500,0,2) ;
  TProfile EEPCompareCoeffEtaProfile ("EEPCompareCoeffEtaProfile",
                                      "EEPCompareCoeffEtaProfile",
                                      51,0,50,0,2) ;
   
  TH1F EEPCompareCoeffDistr_R1 ("EEPCompareCoeff_R1","EEPCompareCoeff_R1",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R2 ("EEPCompareCoeff_R2","EEPCompareCoeff_R2",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R3 ("EEPCompareCoeff_R3","EEPCompareCoeff_R3",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R4 ("EEPCompareCoeff_R4","EEPCompareCoeff_R4",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R5 ("EEPCompareCoeff_R5","EEPCompareCoeff_R5",1000,0,2) ;

  // ECAL endcap +
  for (int ix = 1 ; ix <= 100 ; ++ix)
      for (int iy = 1 ; iy <= 100 ; ++iy)
  {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
              (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      int phi = static_cast<int> ( phiTemp * 180 / PI_GRECO) ;
      if (phi < EEphiStart || phi > EEphiEnd) continue ;
      if (!EEDetId::validDetId (ix,iy,1)) continue ;
      EEDetId det = EEDetId (ix, iy, 1, EEDetId::XYMODE) ;
      double factor = *(iEEcalibMap.find (det.rawId ())) / 
                  *(iEEscalibMap.find (det.rawId ())) ;
      
//       std::cout << " iEEcalibMap rad = " << rad << " --> " << *(iEEcalibMap.find (det.rawId ()));
//       std::cout << " iEEscalibMap --> " << *(iEEscalibMap.find (det.rawId ())) << std::endl;  
      
      EEPCompareCoeffDistr.Fill (factor) ;
      EEPCompareCoeffMap.Fill (ix,iy,factor) ;
      EEPCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEPCompareCoeffEtaProfile.Fill (rad,factor) ;
      if (abs(rad) < 22) continue ;
      else if (abs(rad) < 27) EEPCompareCoeffDistr_R1.Fill (factor) ;
      else if (abs(rad) < 32) EEPCompareCoeffDistr_R2.Fill (factor) ;
      else if (abs(rad) < 37) EEPCompareCoeffDistr_R3.Fill (factor) ;
      else if (abs(rad) < 42) EEPCompareCoeffDistr_R4.Fill (factor) ;
      else EEPCompareCoeffDistr_R5.Fill (factor) ;

  } // ECAL endcap +

  // ECAL endcap-
  TH1F EEMCompareCoeffDistr ("EEMCompareCoeffDistr","EEMCompareCoeffDistr",200,0,2) ;
  TH2F EEMCompareCoeffMap ("EEMCompareCoeffMap","EEMCompareCoeffMap",100,0,100,100,0,100) ;
  TH2F EEMCompareCoeffEtaTrend ("EEMCompareCoeffEtaTrend",
                                "EEMCompareCoeffEtaTrend",
                                51,0,50,500,0,2) ;
  TProfile EEMCompareCoeffEtaProfile ("EEMCompareCoeffEtaProfile",
                                      "EEMCompareCoeffEtaProfile",
                                      51,0,50,0,2) ;
   
  // ECAL endcap -
  for (int ix = 1 ; ix <= 100 ; ++ix)
      for (int iy = 1 ; iy <= 100 ; ++iy)
  {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
              (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      if (!EEDetId::validDetId (ix,iy,-1)) continue ;
      EEDetId det = EEDetId (ix, iy, -1, EEDetId::XYMODE) ;
      double factor = *(iEEcalibMap.find (det.rawId ())) *
                  *(iEEscalibMap.find (det.rawId ())) ;
      EEMCompareCoeffDistr.Fill (factor) ;
      EEMCompareCoeffMap.Fill (ix,iy,factor) ;
      EEMCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEMCompareCoeffEtaProfile.Fill (rad,factor) ;
  } // ECAL endcap -
    
  TFile out (filename.c_str (),"recreate") ;
  EEMCompareCoeffMap.Write() ;
  EEMCompareCoeffDistr.Write() ;
  EEMCompareCoeffEtaTrend.Write () ;
  EEMCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffMap.Write() ;
  EEPCompareCoeffDistr.Write() ;
  EEPCompareCoeffEtaTrend.Write () ;
  EEPCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffDistr_R1.Write () ;
  EEPCompareCoeffDistr_R2.Write () ;
  EEPCompareCoeffDistr_R3.Write () ;
  EEPCompareCoeffDistr_R4.Write () ;
  EEPCompareCoeffDistr_R5.Write () ;
  out.Close() ;
  
  
  
  
  
  
  
  
  //---- remove local database ----
  
  gSystem->Exec("rm Uno.db");
  gSystem->Exec("rm Due.db");

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

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

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

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

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

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

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

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

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

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

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

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

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

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

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

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

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

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

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

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

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

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

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

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


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

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

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

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

      }
    }
  }
  else{
    telC = NULL;
  }

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

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

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

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

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

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

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


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

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

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

    neventsGR++;

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

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

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

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

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

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

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


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

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

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

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

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

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

  h->SetStats(0);

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

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


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

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

  h->Draw();
  
  new TCanvas;

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

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

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

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

  return nsecGR*1./86400;
  
}
Ejemplo n.º 12
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad
Ejemplo n.º 13
0
void tauStudy(const TString inputfile = "/afs/cern.ch/work/k/klawhorn/HHToBBTT/Conf4_10GeV/HHToBBTT_10GeVJets_14TeV.root") {

  // set up input tree

  LorentzVector *genTau1=0, *genTau2=0, *genJetTau1=0, *genJetTau2=0, *jetTau1=0, *jetTau2=0;

  Float_t genTau1pt, genTau2pt, genJetTau1pt, genJetTau2pt, jetTau1pt, jetTau2pt, corrJetTau1pt, corrJetTau2pt;
  Float_t genTau1eta, genTau2eta, genJetTau1eta, genJetTau2eta, jetTau1eta, jetTau2eta;

  TFile *infile = new TFile(inputfile, "READ"); assert(infile);
  TTree *intree = (TTree*) infile->Get("Events"); assert(intree);

  intree->SetBranchAddress("genTau1",        &genTau1);
  intree->SetBranchAddress("genTau2",        &genTau2);
  intree->SetBranchAddress("genJetTau1",     &genJetTau1);
  intree->SetBranchAddress("genJetTau2",     &genJetTau2);
  intree->SetBranchAddress("jetTau1",        &jetTau1);
  intree->SetBranchAddress("jetTau2",        &jetTau2);

  const Float_t PT_MAX = 500;
  const Float_t PT_MIN = 0;
  const Int_t PT_BINS = 50;
  const Float_t ETA_MAX = 2.4;
  const Float_t ETA_MIN = -2.4;
  const Int_t ETA_BINS = 16;
  
  TProfile *tauTagEffWithPT = new TProfile("tauTagEffWithPT", "Tau Tagging Efficiency", PT_BINS, PT_MIN, PT_MAX);
  TProfile *tauTagEffWithEta = new TProfile("tauTagEffWithEta", "Tau Tagging Efficiency", ETA_BINS, ETA_MIN, ETA_MAX);

  //TProfile *ptScaleWithPT = new TProfile("ptScaleWithPT", "P_{T} Scale Factor between gen Tau and reco Jet", PT_BINS, PT_MIN, PT_MAX);
  //TProfile *ptJetScaleWithPT = new TProfile("ptJetScaleWithPT", "P_{T} Scale Factor between gen Jet and reco Jet", PT_BINS, PT_MIN, PT_MAX);

  //TProfile *ptScaleWithEta = new TProfile("ptScaleWithEta", "P_{T} Scale Factor between gen Tau and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);
  //TProfile *ptJetScaleWithEta = new TProfile("ptJetScaleWithEta", "P_{T} Scale Factor between gen Jet and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);

  //TProfile *ptResWithPT = new TProfile("ptResWithPT", "P_{T} Resolution between gen Tau and reco Jet", PT_BINS, PT_MIN, PT_MAX);
  TProfile *ptJetResWithPT = new TProfile("ptJetResWithPT", "P_{T} Resolution: (genJet-recoJet)/(genJet)", PT_BINS, PT_MIN, PT_MAX);
  TProfile *ptJetResCorrWithPT = new TProfile("ptJetResCorrWithPT", "P_{T} Resolution: (genJet-recoJet)/(genJet)", PT_BINS, PT_MIN, PT_MAX);

  //TProfile *ptResWithEta = new TProfile("ptResWithEta", "P_{T} Resolution between gen Tau and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);
  TProfile *ptJetResWithEta = new TProfile("ptJetResWithEta", "P_{T} Resolution: (genJet-recoJet)/(genJet)", ETA_BINS, ETA_MIN, ETA_MAX);
  TProfile *ptJetResCorrWithEta = new TProfile("ptJetResCorrWithEta", "P_{T} Resolution: (genJet-recoJet)/(genJet)", ETA_BINS, ETA_MIN, ETA_MAX);
  
  for (Int_t iEntry=0; iEntry<intree->GetEntries(); iEntry++) {
    intree->GetEntry(iEntry);

    genTau1pt = genTau1->Pt();       genTau1eta = genTau1->Eta();
    genTau2pt = genTau2->Pt();       genTau2eta = genTau2->Eta();
    genJetTau1pt = genJetTau1->Pt(); genJetTau1eta = genJetTau1->Eta();
    genJetTau2pt = genJetTau2->Pt(); genJetTau2eta = genJetTau2->Eta();
    jetTau1pt = jetTau1->Pt();       jetTau1eta = jetTau1->Eta();
    jetTau2pt = jetTau2->Pt();       jetTau2eta = jetTau2->Eta();

    // jet corrections
    //if ( (jetTau1pt != 999) ) cout << "eta " << jetTau1eta << " pt " << jetTau1pt << " scaleCorr " << getJetScaleFactor(jetTau1pt, jetTau1eta) << endl;
    corrJetTau1pt = jetTau1pt*getJetScaleFactor(jetTau1pt, jetTau1eta);
    corrJetTau2pt = jetTau2pt*getJetScaleFactor(jetTau2pt, jetTau2eta);

    if ( (genTau1pt != 999) && (jetTau1pt != 999) ) {
      tauTagEffWithPT->Fill(genTau1pt, 1);
      //ptScaleWithPT->Fill(genTau1pt, jetTau1pt/genTau1pt);
      //ptJetScaleWithPT->Fill(genJetTau1pt, jetTau1pt/genJetTau1pt);
      //ptResWithPT->Fill(genTau1pt, (genTau1pt-jetTau1pt)/genTau1pt);
      ptJetResWithPT->Fill(genJetTau1pt, (genJetTau1pt-jetTau1pt)/genJetTau1pt);
      ptJetResCorrWithPT->Fill(genJetTau1pt, (genJetTau1pt-corrJetTau1pt)/genJetTau1pt);

      tauTagEffWithEta->Fill(genTau1eta, 1);
      //ptScaleWithEta->Fill(genTau1eta, jetTau1pt/genTau1pt);
      //ptJetScaleWithEta->Fill(genJetTau1eta, jetTau1pt/genJetTau1pt);
      //ptResWithEta->Fill(genTau1eta, (genTau1pt-jetTau1pt)/genTau1pt);
      ptJetResWithEta->Fill(genJetTau1eta, (genJetTau1pt-jetTau1pt)/genJetTau1pt);
      ptJetResCorrWithEta->Fill(genJetTau1eta, (genJetTau1pt-corrJetTau1pt)/genJetTau1pt);

    }
    else if ( (genTau1pt != 999) && (jetTau1pt == 999) ) {
      tauTagEffWithPT->Fill(genTau1pt, 0);
      tauTagEffWithEta->Fill(genTau1eta, 0);
    }
    if ( (genTau2pt != 999) && (jetTau2pt != 999) ) {
      tauTagEffWithPT->Fill(genTau2pt, 1);
      //ptScaleWithPT->Fill(genTau2pt, jetTau2pt/genTau2pt);
      //ptJetScaleWithPT->Fill(genJetTau2pt, jetTau2pt/genJetTau2pt);
      //ptResWithPT->Fill(genTau2pt, (genTau2pt-jetTau2pt)/genTau2pt);
      ptJetResWithPT->Fill(genJetTau2pt, (genJetTau2pt-jetTau2pt)/genJetTau2pt);
      ptJetResCorrWithPT->Fill(genJetTau2pt, (genJetTau2pt-corrJetTau2pt)/genJetTau2pt);

      tauTagEffWithEta->Fill(genTau2eta, 1);
      //ptScaleWithEta->Fill(genTau2eta, jetTau2pt/genTau2pt);
      //ptJetScaleWithEta->Fill(genJetTau2eta, jetTau2pt/genJetTau2pt);
      //ptResWithEta->Fill(genTau2eta, (genTau2pt-jetTau2pt)/genTau2pt);
      ptJetResWithEta->Fill(genJetTau2eta, (genJetTau2pt-jetTau2pt)/genJetTau2pt);
      ptJetResCorrWithEta->Fill(genJetTau2eta, (genJetTau2pt-corrJetTau2pt)/genJetTau2pt);

    }
    else if ( (genTau2pt != 999) && (jetTau2pt == 999) ) {
      tauTagEffWithPT->Fill(genTau2pt, 0);
      tauTagEffWithEta->Fill(genTau2eta, 0);
    }

  }

  TCanvas *c1 = MakeCanvas("c1", "Tau Tagging Efficiency", 800, 600);
  tauTagEffWithPT->SetMarkerStyle(1);
  tauTagEffWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  tauTagEffWithPT->GetYaxis()->SetTitle("Efficiency");
  tauTagEffWithPT->Draw();
  
  c1->SaveAs("tauTagEffWithPT.png");

  TCanvas *c2 = MakeCanvas("c2", "Tau Tagging Efficiency", 800, 600);
  tauTagEffWithEta->SetMarkerStyle(1);
  tauTagEffWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  tauTagEffWithEta->GetYaxis()->SetTitle("Efficiency");
  tauTagEffWithEta->Draw();

  c2->SaveAs("tauTagEffWithEta.png");
  /*  
  TCanvas *c3 = MakeCanvas("c3", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau P_{T})", 800, 600);
  ptScaleWithPT->SetMarkerStyle(1);
  ptScaleWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  ptScaleWithPT->GetYaxis()->SetTitle("P_{T} Scale");
  ptScaleWithPT->Draw();

  c3->SaveAs("ptScaleWithPT.png");

  TCanvas *c4 = MakeCanvas("c4", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau P_{T})", 800, 600);
  ptScaleWithEta->SetMarkerStyle(1);
  ptScaleWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  ptScaleWithEta->GetYaxis()->SetTitle("P_{T} Scale");
  ptScaleWithEta->Draw();

  c4->SaveAs("ptScaleWithEta.png");

  TCanvas *c5 = MakeCanvas("c5", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau Jet P_{T})", 800, 600);
  ptJetScaleWithPT->SetMarkerStyle(1);
  ptJetScaleWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau Jet");
  ptJetScaleWithPT->GetYaxis()->SetTitle("P_{T} Scale");
  ptJetScaleWithPT->Draw();

  c5->SaveAs("ptJetScaleWithPT.png");

  TCanvas *c6 = MakeCanvas("c6", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau Jet P_{T})", 800, 600);
  ptJetScaleWithEta->SetMarkerStyle(1);
  ptJetScaleWithEta->GetXaxis()->SetTitle("Eta of Generator Tau Jet");
  ptJetScaleWithEta->GetYaxis()->SetTitle("P_{T} Scale");
  ptJetScaleWithEta->Draw();

  c6->SaveAs("ptJetScaleWithEta.png");

  TCanvas *c7 = MakeCanvas("c7", "Tau P_{T} Resolution ((reco Tau Jet P_{T} - gen Tau P_{T})/gen Tau P_{T})", 800, 600);
  ptResWithPT->SetMarkerStyle(1);
  ptResWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  ptResWithPT->GetYaxis()->SetTitle("P_{T} Resolution");
  ptResWithPT->Draw();

  c7->SaveAs("ptResWithPT.png");

  TCanvas *c8 = MakeCanvas("c8", "Tau P_{T} Resolution", 800, 600);
  ptResWithEta->SetMarkerStyle(1);
  ptResWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  ptResWithEta->GetYaxis()->SetTitle("P_{T} Resolution");
  ptResWithEta->Draw();
  
  c8->SaveAs("ptResWithEta.png");

  TCanvas *c9 = MakeCanvas("c9", "Tau P_{T} Resolution", 800, 600);
  ptJetResWithPT->SetMarkerStyle(1);
  ptJetResWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau Jet");
  ptJetResWithPT->GetYaxis()->SetTitle("P_{T} Resolution");
  ptJetResWithPT->Draw();
  ptJetResCorrWithPT->SetMarkerStyle(1);
  ptJetResCorrWithPT->SetLineColor(2);
  ptJetResCorrWithPT->Draw("same");

  c9->SaveAs("ptJetResWithPT.png");

  TCanvas *c10 = MakeCanvas("c10", "Tau P_{T} Resolution ((reco Tau Jet P_{T} - gen Tau Jet P_{T})/gen Tau Jet P_{T})", 800, 600);
  ptJetResWithEta->SetMarkerStyle(1);
  ptJetResWithEta->GetXaxis()->SetTitle("Eta of Generator Tau Jet");
  ptJetResWithEta->GetYaxis()->SetTitle("P_{T} Resolution");
  ptJetResWithEta->Draw();
  ptJetResCorrWithEta->SetMarkerStyle(1);
  ptJetResCorrWithEta->SetLineColor(2);
  ptJetResCorrWithEta->Draw("same");

  c10->SaveAs("ptJetResWithEta.png");
  */  
}
Ejemplo n.º 14
0
void fitBjetJES(int ppPbPb=1, int cbinlo=12, int cbinhi=40){

  if(!ppPbPb){
    cbinlo=0;
    cbinhi=40;
  }

  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);

  TFile *fL;
  
  if(!ppPbPb)fL=new TFile("histos/ppMC_hiReco_jetTrig_highPurity_JEC.root");
  else     fL=new TFile("histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight.root");

  // these are dummy files for pp
  TFile *fB=new TFile("histos/PbPbBMC_pt30by3_ipHICalibCentWeight.root");
  TFile *fC=new TFile("histos/PbPbCMC_pt30by3_ipHICalibCentWeight.root");


  TNtuple *tL = (TNtuple*) fL->Get("nt");
  TNtuple *tB = (TNtuple*) fB->Get("nt");
  TNtuple *tC = (TNtuple*) fC->Get("nt");
  
  float jtptL, refptL, jtetaL, weightL, refparton_flavorForBL, binL;

  tL->SetBranchAddress("jtpt",&jtptL);
  tL->SetBranchAddress("jteta",&jtetaL);
  tL->SetBranchAddress("refpt",&refptL);
  tL->SetBranchAddress("weight",&weightL);
  if(ppPbPb)tL->SetBranchAddress("bin",&binL);
  tL->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBL);

  float jtptB, refptB, jtetaB, weightB, refparton_flavorForBB, binB;

  tB->SetBranchAddress("jtpt",&jtptB);
  tB->SetBranchAddress("jteta",&jtetaB);
  tB->SetBranchAddress("refpt",&refptB);
  tB->SetBranchAddress("weight",&weightB);
  if(ppPbPb)tB->SetBranchAddress("bin",&binB);
  tB->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBB);

  float jtptC, refptC, jtetaC, weightC, refparton_flavorForBC, binC;

  tC->SetBranchAddress("jtpt",&jtptC);
  tC->SetBranchAddress("jteta",&jtetaC);
  tC->SetBranchAddress("refpt",&refptC);
  tC->SetBranchAddress("weight",&weightC);
  if(ppPbPb)tC->SetBranchAddress("bin",&binC);
  tC->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBC);

  TProfile  *hL = new TProfile("hL","hL",250,50,300,0,10);
  TProfile  *hB = new TProfile("hB","hB",250,50,300,0,10);
  TProfile  *hC = new TProfile("hC","hC",250,50,300,0,10);
  hL->Sumw2(),hB->Sumw2(),hC->Sumw2();


  for(int i=0;i<tL->GetEntries();i++){
    tL->GetEntry(i);
    if(!ppPbPb) binL=39;

    if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi)
      hL->Fill(refptL,jtptL/refptL,weightL); 


    if(!ppPbPb){
      if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi && abs(refparton_flavorForBL)==5)
	hB->Fill(refptL,jtptL/refptL,weightL);
      
      if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi && abs(refparton_flavorForBL)==4)
	hC->Fill(refptL,jtptL/refptL,weightL);      
    }
  }

  if(ppPbPb){
    for(int i=0;i<tB->GetEntries();i++){
      tB->GetEntry(i);
      if(fabs(jtetaB)<2 && binB>=cbinlo && binB<cbinhi && abs(refparton_flavorForBB)==5)
	hB->Fill(refptB,jtptB/refptB,weightB);
    }
    for(int i=0;i<tC->GetEntries();i++){
      tC->GetEntry(i);
      if(fabs(jtetaC)<2 && binC>=cbinlo && binC<cbinhi && abs(refparton_flavorForBC)==4)
	hC->Fill(refptC,jtptC/refptC,weightC);
    }
  }

  
 
  hL->SetMinimum(0.);
  
  hL->SetLineColor(kBlue);
  hB->SetLineColor(kRed);
  hC->SetLineColor(kGreen);

  hL->SetMarkerColor(kBlue);
  hB->SetMarkerColor(kRed);
  hC->SetMarkerColor(kGreen);
  
  //hL->SetMarkerStyle(4);
  //hB->SetMarkerStyle(4);
  //hC->SetMarkerStyle(4);
  
  hL->SetXTitle("genJet p_{T} (GeV/c)");
  hL->SetYTitle("<reco p_{T} / gen p_{T} >");

  hL->GetXaxis()->SetRangeUser(50.,199.999);
  hL->GetYaxis()->SetRangeUser(0.5,1.05);
  
  TCanvas *c1=new TCanvas("c1","c1",800,600);
  c1->SetGridx(1);
  c1->SetGridy(1);

  hL->Draw("e1");
  hB->Draw("e1,same");
  hC->Draw("e1,same");

  TLegend *leg=new TLegend(0.4,0.15,0.9,0.45);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  if(ppPbPb&&cbinlo==0&&cbinhi==40)leg->SetHeader("Pythia+Hydjet, 0-100%");
  leg->AddEntry(hL,"Inclusive jets","pl");
  leg->AddEntry(hC,"c-jets","pl");
  leg->AddEntry(hB,"b-jets","pl");
  leg->Draw();

  TCanvas *c2=new TCanvas("c2","c2",1);
  /*
  TH1F *hL2 = (TH1F*)hL->Clone("hL2");
  TH1F *hB2 = (TH1F*)hB->Clone("hB2");
  hL2->Add(hB2,-1);
  hL2->Draw();
  */

  TH1F  *hcorr = new TH1F("hcorr","hcorr",250,50,300);
  hcorr->Sumw2();

  for(int i=0;i<hL->GetNbinsX();i++){
    cout<<" b resp "<<hB->GetBinContent(i+1)<<endl;
    cout<<" l resp "<<hL->GetBinContent(i+1)<<endl;
    cout<<" l offset "<<1.-hL->GetBinContent(i+1)<<endl;
    cout<<" corrected b resp "<<hB->GetBinContent(i+1)+1.-hL->GetBinContent(i+1)<<endl;
    float jesOffset = 1.-hL->GetBinContent(i+1);

    hcorr->SetBinContent(i+1,hB->GetBinContent(i+1)+jesOffset);

    hcorr->SetBinError(i+1,sqrt(hB->GetBinError(i+1)*hB->GetBinError(i+1)+hL->GetBinError(i+1)*hL->GetBinError(i+1)));


  }

  hcorr->SetMinimum(0.5);
  hcorr->SetMaximum(1.1);
      
  hcorr->SetLineColor(kRed);
  hcorr->SetMarkerColor(kRed);
  hcorr->SetMarkerStyle(4);
  hcorr->Draw();

  TF1 *fCorr = new TF1("fCorr","[0]+[1]*log(x)+[2]*log(x)*log(x)",50,300);
  fCorr->SetLineWidth(1);
  fCorr->SetLineColor(kBlue);
  hcorr->Fit(fCorr);

  TFile *fout;
  if(ppPbPb) fout =new TFile(Form("bJEShistos/bJetScale_PbPb_Cent_fineBin_%d_%d.root",cbinlo,cbinhi),"recreate");
  else fout =new TFile("bJEShistos/bJetScale_PP_fineBin.root","recreate");
  hcorr->Write();
  fCorr->Write();
  fout->Close();

}
Ejemplo n.º 15
0
void Analyzer(string MODE="COMPILE")
{
    if(MODE=="COMPILE") return;

    system("mkdir pictures");

    setTDRStyle();
    gStyle->SetPadTopMargin   (0.06);
    gStyle->SetPadBottomMargin(0.15);
    gStyle->SetPadRightMargin (0.03);
    gStyle->SetPadLeftMargin  (0.07);
    gStyle->SetTitleSize(0.04, "XYZ");
    gStyle->SetTitleXOffset(1.1);
    gStyle->SetTitleYOffset(1.35);
    gStyle->SetPalette(1);
    gStyle->SetNdivisions(505,"X");
    TH1::AddDirectory(kTRUE);

    system("mkdir pictures/");
    string saveName = "dedx";
    TFile* OutputHisto = new TFile((string("pictures/") + "/Histos.root").c_str(),"RECREATE");
    TH1D* HdedxMIP          = new TH1D(    (saveName + "_MIP"    ).c_str(), "MIP"    ,  1000, 0, 10);
    TH2D* HdedxVsP          = new TH2D(    (saveName + "_dedxVsP").c_str(), "dedxVsP", 3000, 0, 30,1500,0,15);
    TH2D* HdedxVsPM         = new TH2D(    (saveName + "_dedxVsPM").c_str(), "dedxVsPM", 3000, 0, 30,1500,0,15);
    TH2D* HdedxVsQP         = new TH2D(    (saveName + "_dedxVsQP").c_str(), "dedxVsQP", 6000, -30, 30,1500,0,25);
    TProfile* HdedxVsPProfile   = new TProfile((saveName + "_Profile").c_str(), "Profile",  100, 0,100);
    TProfile* HdedxVsEtaProfile = new TProfile((saveName + "_Eta"    ).c_str(), "Eta"    ,  100,-3,  3);
    TH2D* HdedxVsEta        = new TH2D    ((saveName + "_Eta2D"  ).c_str(), "Eta"    ,  100,-3,  3, 1000,0,5);
    TProfile* HNOSVsEtaProfile  = new TProfile((saveName + "_NOS"    ).c_str(), "NOS"    ,  100,-3,  3);
    TProfile* HNOMVsEtaProfile  = new TProfile((saveName + "_NOM"    ).c_str(), "NOM"    ,  100,-3,  3);
    TProfile* HNOMSVsEtaProfile = new TProfile((saveName + "_NOMS"    ).c_str(), "NOMS"    ,  100,-3,  3);
    TH1D* HMass             = new TH1D(    (saveName + "_Mass"   ).c_str(), "Mass"   ,  500, 0, 10);
    TH1D* HP                = new TH1D(    (saveName + "_P"      ).c_str(), "P"      ,  500, 0, 100);

    TH1D* HHit          = new TH1D(    (saveName + "_Hit"      ).c_str(), "P"      ,  600, 0, 6);

    TH2D* HIasVsP          = new TH2D(    (saveName + "_IasVsP").c_str(), "IasVsP", 3000, 0, 30,1500,0,1);
    TH2D* HIasVsPM         = new TH2D(    (saveName + "_IasVsPM").c_str(), "IasVsPM", 3000, 0, 30,1500,0,1);
    TH1D* HIasMIP          = new TH1D(    (saveName + "_IasMIP"    ).c_str(), "IasMIP"    ,  1000, 0, 1);

    reco::DeDxData* emptyDeDx = new reco::DeDxData(0,0,0);
//   TH3F* dEdxTemplates = loadDeDxTemplate("../../../data/Data7TeV_Deco_SiStripDeDxMip_3D_Rcd.root");
//   TH3F* dEdxTemplates = loadDeDxTemplate("../../../data/MC7TeV_Deco_SiStripDeDxMip_3D_Rcd.root");
//   TH3F* dEdxTemplates = loadDeDxTemplate("../../../data/Discrim_Templates_MC_2012b.root");
    TH3F* dEdxTemplates = loadDeDxTemplate("../../../data/Discrim_Templates_MC_2012_new2.root");
    double SF = 1.05; //0.9;

    std::vector<string> FileName;
//   FileName.push_back("root://eoscms//eos/cms/store/cmst3/user/querten/12_11_19_MC_dEdx/dedx_data_2012.root");
    FileName.push_back("root://eoscms//eos/cms/store/cmst3/user/querten/12_11_19_MC_dEdx/dedx_mc_2012.root");
    fwlite::ChainEvent ev(FileName);

    printf("Progressing Bar              :0%%       20%%       40%%       60%%       80%%       100%%\n");
    printf("Looping on Tree              :");
    int TreeStep = ev.size()/50;
    if(TreeStep==0)TreeStep=1;
    for(Long64_t e=0; e<ev.size(); e++) {
//      if(e>5000)break;
        ev.to(e);
        if(e%TreeStep==0) {
            printf(".");
            fflush(stdout);
        }

        fwlite::Handle< std::vector<reco::Track> > trackCollHandle;
        trackCollHandle.getByLabel(ev,"TrackRefitter");
        if(!trackCollHandle.isValid()) {
            printf("Invalid trackCollHandle\n");
            continue;
        }

        for(unsigned int c=0; c<trackCollHandle->size(); c++) {
            reco::TrackRef track = reco::TrackRef( trackCollHandle.product(), c );

            if(track->chi2()/track->ndof()>5 )continue;  //WAS >1
            if(track->found()<8)continue;
///////////////

            fwlite::Handle<HSCPDeDxInfoValueMap> dEdxHitsH;
            dEdxHitsH.getByLabel(ev, "dedxHitInfo");
            if(!dEdxHitsH.isValid()) {
                printf("Invalid dEdxHitInfo\n");
                return;
            }
            const ValueMap<HSCPDeDxInfo>& dEdxHitMap = *dEdxHitsH.product();
            const HSCPDeDxInfo& hscpHitsInfo = dEdxHitMap.get((size_t)track.key());

            for(unsigned int h=0; h<hscpHitsInfo.charge.size(); h++) {
                DetId detid(hscpHitsInfo.detIds[h]);
                if(detid.subdetId()<3)continue; // skip pixels
                if(!hscpHitsInfo.shapetest[h])continue;

                double Norm = (detid.subdetId()<3)?3.61e-06:3.61e-06*265;
                Norm*=10.0; //mm --> cm
                Norm*=SF;
                HHit->Fill(Norm * hscpHitsInfo.charge[h]/hscpHitsInfo.pathlength[h]);

//        vect_charge.push_back(Norm*hscpHitsInfo.charge[h]/hscpHitsInfo.pathlength[h]);
            }
//////////////

            reco::DeDxData* dedxObj = dEdxEstimOnTheFly(ev, track, emptyDeDx, SF);
            reco::DeDxData* dedxIasObj = dEdxOnTheFly(ev, track, emptyDeDx, SF, dEdxTemplates, false);


            if(track->pt()>20 && track->pt()<40 && dedxObj->numberOfMeasurements()>6 ) {
                HdedxVsEtaProfile->Fill(track->eta(), dedxObj->dEdx() );
                HdedxVsEta->Fill(track->eta(), dedxObj->dEdx() );
                HNOMVsEtaProfile->Fill(track->eta(),dedxObj->numberOfMeasurements() );
                HNOSVsEtaProfile->Fill(track->eta(),dedxObj->numberOfSaturatedMeasurements() );
                HNOMSVsEtaProfile->Fill(track->eta(),dedxObj->numberOfMeasurements() - dedxObj->numberOfSaturatedMeasurements() );
            }
            if(fabs(track->eta())>2.1)continue;
            if((int)dedxObj->numberOfMeasurements()<10)continue;
            if(track->p()>5 && track->p()<40) {
                HdedxMIP->Fill(dedxObj->dEdx());
                HP->Fill(track->p());
                HIasMIP->Fill(dedxIasObj->dEdx());
            }
            HdedxVsP ->Fill(track->p(), dedxObj->dEdx() );
            HdedxVsQP->Fill(track->p()*track->charge(), dedxObj->dEdx() );
            HIasVsP ->Fill(track->p(), dedxIasObj->dEdx() );

            if(fabs(track->eta())<0.4)HdedxVsPProfile->Fill(track->p(), dedxObj->dEdx() );
            double Mass = GetMass(track->p(),dedxObj->dEdx(), false);
            if(dedxObj->dEdx()>4.0 && track->p()<3.0) {
                HMass->Fill(Mass);
                if(isnan((float)Mass) || Mass<0.94-0.3 || Mass>0.94+0.3)continue;
                HdedxVsPM ->Fill(track->p(), dedxObj->dEdx() );
                HIasVsPM ->Fill(track->p(), dedxIasObj->dEdx() );
            }


        }


    }


    OutputHisto->Write();
    OutputHisto->Close();
}
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEE fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  timeCorrectionEE_ = new TF1("timeCorrectionEE_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Low eta region < 2.2, run 144011
  timeCorrectionEE_->SetParameters(-0.461192,0.0876435,-0.234752,0.143774,-0.051990);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxE1E9, maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEE, minHitTimeEE;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEE = 15; // ns
  minHitTimeEE = -15; // ns
  maxE1E9 = 0.95; // EB only
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-e1e9max") && argc>i+1) maxE1E9 = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemax") && argc>i+1) maxHitTimeEE = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemin") && argc>i+1) minHitTimeEE = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxHitTimeEE: " << maxHitTimeEE << " minHitTimeEE: " << minHitTimeEE
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEE";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEE = new TH1F("timingCalibsEE","timingCalibs EE [ns]",2000,-100,100);
  TH1F* calibErrorHistEE = new TH1F("timingCalibErrorEE","timingCalibError EE [ns]",500,0,5);
  calibHistEE->Sumw2();
  calibErrorHistEE->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  //TH2F* calibMapEE = new TH2F("calibMapEE","time calib map EE",360,1,361,170,-86,86);
  //TH2F* calibMapEEFlip = new TH2F("calibMapEEFlip","time calib map EE",170,-86,86,360,1,361);
  //TH2F* calibMapEEPhase = new TH2F("calibMapEEPhase","time calib map EE (phase of Tmax)",360,1,361,170,-86,86);
  
  //TH2F* calibMapEtaAvgEE = new TH2F("calibMapEtaAvgEE","time calibs raw eta avg map EE",360,1,361,170,-86,86);
  //TH1F* calibHistEtaAvgEE = new TH1F("timingCalibsEtaAvgEE","EtaAvgTimingCalibs EE [ns]",2000,-100,100);

  TH2F* hitsPerCryMapEEM = new TH2F("hitsPerCryMapEEM","Hits per cry EEM;ix;iy",100,1,101,100,1,101);
  TH2F* hitsPerCryMapEEP = new TH2F("hitsPerCryMapEEP","Hits per cry EEP;ix;iy",100,1,101,100,1,101);
  TH1F* hitsPerCryHistEEM = new TH1F("hitsPerCryHistEEM","Hits per cry EEM;hashedIndex",14648,0,14648);
  TH1F* hitsPerCryHistEEP = new TH1F("hitsPerCryHistEEP","Hits per cry EEP;hashedIndex",14648,0,14648);
  //TH1C* eventsEEMHist = new TH1C("numEventsEEM","Number of events, EEM",100,0,100);
  //TH1C* eventsEEPHist = new TH1C("numEventsEEP","Number of events, EEP",100,0,100);
  TProfile* ampProfileEEM = new TProfile("ampProfileEEM","Amp. profile EEM;hashedIndex",14648,0,14648);
  TProfile* ampProfileEEP = new TProfile("ampProfileEEP","Amp. profile EEP;hashedIndex",14648,0,14648);
  TProfile2D* ampProfileMapEEP = new TProfile2D("ampProfileMapEEP","Amp. profile EEP;ix;iy",100,1,101,100,1,101);
  TProfile2D* ampProfileMapEEM = new TProfile2D("ampProfileMapEEM","Amp. profile EEM;ix;iy",100,1,101,100,1,101);

  //TH1F* eventsEEHist = new TH1F("numEventsEE","Number of events, EE",100,0,100);
  //TH1F* calibSigmaHist = new TH1F("timingSpreadEE","Crystal timing spread [ns]",1000,-5,5);

  TH1F* sigmaHistEE = new TH1F("sigmaCalibsEE"," Sigma of calib distributions EE [ns]",100,0,1);

  //TH1F* chiSquaredEachEventHist = new TH1F("chi2eachEvent","Chi2 of each event",500,0,500);
  //TH2F* chiSquaredVsAmpEachEventHist = new TH2F("chi2VsAmpEachEvent","Chi2 vs. amplitude of each event",500,0,500,750,0,750);
  //TH2F* chiSquaredHighMap = new TH2F("chi2HighMap","Channels with event #Chi^{2} > 100",360,1,361,170,-86,86);
  //TH1F* chiSquaredTotalHist = new TH1F("chi2Total","Total chi2 of all events in each crystal",500,0,500);
  //TH1F* chiSquaredSingleOverTotalHist = new TH1F("chi2SingleOverTotal","Chi2 of each event over total chi2",100,0,1);
  //TH1F* ampEachEventHist = new TH1F("energyEachEvent","Energy of all events [GeV]",1000,0,10);
  //TH1F* numPointsErasedHist = new TH1F("numPointsErased","Number of points erased per crystal",25,0,25);
  
  //TProfile2D* myAmpProfile = (TProfile2D*)EBampProfile->Clone();
  //myAmpProfile->Write();
  TH1F* expectedStatPresHistEEM = new TH1F("expectedStatPresEEM","Avg. expected statistical precision EEM [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEM = new TH2F("expectedStatPresVsObsEEM","Expected stat. pres. vs. obs. error on mean each event EEM [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEM = new TH1F("expectedStatPresSingleEventEEM","Expected stat. pres. each event EEM [ns]",200,0,2);
  TH1F* expectedStatPresHistEEP = new TH1F("expectedStatPresEEP","Avg. expected statistical precision EEP [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEP = new TH2F("expectedStatPresVsObsEEP","Expected stat. pres. vs. obs. error on mean each event [ns] EEP",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEP = new TH1F("expectedStatPresSingleEventEEP","Expected stat. pres. each event EEP [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();
  
  TH1F* calibHistEEM = new TH1F("timingCalibsEEM","timingCalibs EEM [ns]",500,-25,25);
  TH1F* calibHistEEP = new TH1F("timingCalibsEEP","timingCalibs EEP [ns]",500,-25,25);
  TH1F* calibErrorHistEEM = new TH1F("calibErrorEEM","timingCalibError EEM [ns]",250,0,5);
  TH1F* calibErrorHistEEP = new TH1F("calibErrorEEP","timingCalibError EEP [ns]",250,0,5);
  calibHistEEM->Sumw2();
  calibHistEEP->Sumw2();
  calibErrorHistEEM->Sumw2();
  calibErrorHistEEP->Sumw2();

  TH2F* calibMapEEM = new TH2F("calibMapEEM","time calib map EEM",100,1,101,100,1,101);
  TH2F* calibMapEEP = new TH2F("calibMapEEP","time calib map EEP",100,1,101,100,1,101);
  calibMapEEM->Sumw2();
  calibMapEEP->Sumw2();

  TH2F* sigmaMapEEM = new TH2F("sigmaMapEEM","Sigma of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* sigmaMapEEP = new TH2F("sigmaMapEEP","Sigma of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEM = new TH2F("calibErrorMapEEM","Error of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEP = new TH2F("calibErrorMapEEP","Error of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);

  TDirectory* cryDirEEP = gDirectory->mkdir("crystalTimingHistsEEP");
  cryDirEEP->cd();
  TH1C* cryTimingHistsEEP[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,1))
        continue;
      string histname = "EEP_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEP[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEP[x][y]->Sumw2();
    }
  }
  outfile->cd();
  TDirectory* cryDirEEM = gDirectory->mkdir("crystalTimingHistsEEM");
  cryDirEEM->cd();
  TH1C* cryTimingHistsEEM[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,-1))
        continue;
      string histname = "EEM_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEM[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEM[x][y]->Sumw2();
    }
  }
  outfile->cd();
  
  cout << "Making calibs..." << endl;

  CrystalCalibration* eeCryCalibs[14648];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 14648; ++i)
    eeCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //eeCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  cout << "Looping over TTree...";

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEE = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEE++;
      }
    }
    //debug
    //cout << "Number of EE crys in event: " << numEEcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEE > avgTimeMax || sumTime/numCrysEE < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEE  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EE crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEE;
	float AoLog = log10(Ao/25);

        EEDetId det = EEDetId::unhashIndex(hashedIndex);
        if(det==EEDetId()) // make sure DetId is valid
          continue;

        int ix = det.ix();
        int iy = det.iy();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEE
          && cryTime > minHitTimeEE
          && cryTime < maxHitTimeEE
	  && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

	// Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEE_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        eeCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);

        //SIC Use when we don't have time_error available
        //eeCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        if(det.zside() < 0)
        {
          ampProfileEEM->Fill(hashedIndex,cryAmp);
          ampProfileMapEEM->Fill(ix,iy,cryAmp);
        }
        else
        {
          ampProfileEEP->Fill(hashedIndex,cryAmp);
          ampProfileMapEEP->Fill(ix,iy,cryAmp);
        }
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 14648; ++hashedIndex)
  {
    EEDetId det = EEDetId::unhashIndex(hashedIndex);
    if(det==EEDetId())
      continue;
    CrystalCalibration cryCalib = *(eeCryCalibs[hashedIndex]);
    int x = det.ix();
    int y = det.iy();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      if(det.zside() < 0)
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEM[x-1][y-1]->Fill(timeItr->time,weight);
      }
      else
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEP[x-1][y-1]->Fill(timeItr->time,weight);
      }
    }
    if(det.zside() < 0)
    {
      cryDirEEM->cd();
      cryTimingHistsEEM[x-1][y-1]->Write();
    }
    else
    {
      cryDirEEP->cd();
      cryTimingHistsEEP[x-1][y-1]->Write();
    }
    outfile->cd();

    if(det.zside() < 0)
    {
      hitsPerCryHistEEM->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEM->Fill(x,y,cryCalib.timingEvents.size());
    }
    else
    {
      hitsPerCryHistEEP->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEP->Fill(x,y,cryCalib.timingEvents.size());
    }
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << det.zside() << ", "
                                                                                        << x <<", " << y << ", hash: "
                                                                        << hashedIndex
                                                                          << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EE\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      if(det.zside() < 0)
      {
        calibHistEEM->Fill(p1);
        //calibMapEEMFlip->Fill(y-85,x+1,p1);
        calibMapEEM->Fill(x,y,p1);
        //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      else
      {
        calibHistEEP->Fill(p1);
        //calibMapEEPFlip->Fill(y-85,x+1,p1);
        calibMapEEP->Fill(x,y,p1);
        //calibMapEEPPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EEDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << y <<", " << x << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << x <<", " << y << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
    }

    sigmaHistEE->Fill(cryCalib.stdDev);
    if(det.zside() < 0)
    {
      //calibsVsErrorsEEM->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEM->Fill(p1err);
      calibErrorMapEEM->Fill(x,y,p1err);
      sigmaMapEEM->Fill(x,y,cryCalib.stdDev);
    }
    else
    {
      //calibsVsErrorsEEP->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEP->Fill(p1err);
      calibErrorMapEEP->Fill(x,y,p1err);
      sigmaMapEEP->Fill(x,y,cryCalib.stdDev);
    }
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EEDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEE.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEE.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EBDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEEM->SetXTitle("timingCalib [ns]");
  calibHistEEM->Write();
  calibHistEEP->SetXTitle("timingCalib [ns]");
  calibHistEEP->Write();
  calibErrorHistEEP->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEP->Write();
  calibErrorHistEEM->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEM->Write();
  calibErrorMapEEP->Write();
  calibErrorMapEEM->Write();
  sigmaHistEE->Write();
  sigmaMapEEM->Write();
  sigmaMapEEP->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //Move empty bins out of the way
  int nxbins = calibMapEEM->GetNbinsX();
  int nybins = calibMapEEM->GetNbinsY();
  for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  {
    double binentsM = calibMapEEM->GetBinContent(i);
    if(binentsM==0)
    {
      calibMapEEM->SetBinContent(i,-1000);
    }
    double binentsP = calibMapEEP->GetBinContent(i);
    if(binentsP==0)
    {
      calibMapEEP->SetBinContent(i,-1000);
    }
  }
  calibMapEEM->SetXTitle("ix");
  calibMapEEM->SetYTitle("iy");
  calibMapEEM->Write();
  calibMapEEP->SetXTitle("ix");
  calibMapEEP->SetYTitle("iy");
  calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEEM->Write();
  expectedStatPresVsObservedMeanErrHistEEM->Write();
  expectedStatPresEachEventHistEEM->Write();
  expectedStatPresHistEEP->Write();
  expectedStatPresVsObservedMeanErrHistEEP->Write();
  expectedStatPresEachEventHistEEP->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();
  hitsPerCryHistEEP->Write();
  hitsPerCryMapEEP->Write();
  hitsPerCryHistEEM->Write();
  hitsPerCryMapEEM->Write();
  ampProfileEEP->Write();
  ampProfileMapEEP->Write();
  ampProfileEEM->Write();
  ampProfileMapEEM->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
Ejemplo n.º 17
0
int main(int argc,char **argv){


   //======================================================================
      printf("z1: gROOT Reset \n");
       // gROOT->Reset();
       // gROOT->SetStyle("Plain");
        gStyle->SetTitleFont(42);           // title font
        gStyle->SetTitleFontSize(0.07);     // title font size
        gStyle->SetLabelSize(0.05,"xy");     // 
        gStyle->SetStatFontSize(0.05);     //for box size 
        gStyle->SetStatX(0.97);     // for box x position
        gStyle->SetStatW(0.25);     // for box width
        gStyle->SetOptFit(1111); // pcev

// for several root files:
//ifstream fnames("fileList");
ifstream fnames("../fileListV3");
TList* trList=new TList();
const int N=58;
const int n=N; // for 1st N files from fileList  

 TChain muon("prom/Muon/muonHB");
string fname;
char tmp[100];
for (int i=0; i<N; i++)
        {
        fnames>>fname;
        fnames.getline(tmp,100,'\n');
        cout<<fname<<"\n";
        muon.Add(fname.c_str());
        }
//muon.Print(); 
/*
 TChain muon("prom/Muon/muonHB");
 muon.Add("/afs/cern.ch/user/k/kropiv/scratch0/CosmicMuons/CosmicMuons43410_01.root");
 muon.Add("/afs/cern.ch/user/k/kropiv/scratch0/CosmicMuons/CosmicMuons43410_02.root");
 muon.Add("/afs/cern.ch/user/k/kropiv/scratch0/CosmicMuons/CosmicMuons43410_03.root");
*/
// creat root-file with histo
   TH1::AddDirectory(true);  // automatic add histograms (for latest versions of ROOT)
   TFile *theFile    =new TFile("Golden.root", "RECREATE");
   theFile->cd();

/////////////////////////////////////////////////////////
//Declaration of leaves types
// ntuple creation:
//     TFile*      hOutputFile ;
     Int_t run, event, NumMuonHBphiPlane, NumHBTowersMuon[50];
     Int_t IdTowerPhiMuonIn[50], IdTowerPhiMuonOut[50], IdTowerEtaMuonIn[50], IdTowerEtaMuonOut[50];
     Float_t TimeAvMuonHB[50];
     Float_t PHIoutMuonHB[50], PHIinMuonHB[50],  ETAoutMuonHB[50], ETAinMuonHB[50];
     Float_t ImpXYmuonHB[50], ZImpXYmuonHB[50];
//     Float_t ImpXYmuon[50], ZImpXYmuon[50],
     Float_t PHIinTowerHB[50];
     Float_t EmuonHB[50];
//
     Float_t XinPosMuonDT[50], YinPosMuonDT[50], ZinPosMuonDT[50];
     Float_t XoutPosMuonDT[50], YoutPosMuonDT[50], ZoutPosMuonDT[50];
     Float_t LengthMuonHB[50], LengthMuonDT[50];
     Int_t NumHitsMuonDT[50], NumHitsMuonDTall[50];
//
     //int  NumHBTowersMuon2[50];
     Int_t IdTowerPhiMuonIn2[50], IdTowerPhiMuonOut2[50], IdTowerEtaMuonIn2[50], IdTowerEtaMuonOut2[50];
     Float_t TimeAvMuonHB2[50],  TimeAvMuonHBcut2[50], TimeAvMuonHBcutwide2[50], LengthMuonHB2[50];
     Float_t EmuonHB2[50], EmuonHBcut2[50], EmuonHBcutwide2[50];
// make initialisation of Muons that not belong to the same Phi Plane in HB
     Int_t NumMuonHBnoPhiPlane;
     Int_t IdTowerMuonNoPlanePhiIn[50], IdTowerMuonNoPlanePhiOut[50];
     Int_t IdTowerMuonNoPlaneEtaIn[50], IdTowerMuonNoPlaneEtaOut[50];
     Float_t XinPosMuonNoPlaneDT[50], YinPosMuonNoPlaneDT[50], ZinPosMuonNoPlaneDT[50];
     Float_t XoutPosMuonNoPlaneDT[50], YoutPosMuonNoPlaneDT[50], ZoutPosMuonNoPlaneDT[50];
     Float_t ImpXYmuonNoPlaneDT[50], ZImpXYmuonNoPlaneDT[50], LengthMuonNoPlaneDT[50];
     Int_t NumHitsMuonNoPlaneDTall[50];
// end ntuple creation

   // Set branch addresses.
   muon.SetBranchAddress("run",&run);
   muon.SetBranchAddress("event",&event);
   muon.SetBranchAddress("NumMuonHBphiPlane",&NumMuonHBphiPlane);
   muon.SetBranchAddress("NumHBTowersMuon",NumHBTowersMuon);
   muon.SetBranchAddress("TimeAvMuonHB",TimeAvMuonHB);
   muon.SetBranchAddress("PHIoutMuonHB",PHIoutMuonHB);
   muon.SetBranchAddress("ETAoutMuonHB",ETAoutMuonHB);
   muon.SetBranchAddress("PHIinMuonHB",PHIinMuonHB);
   muon.SetBranchAddress("ETAinMuonHB",ETAinMuonHB);
   muon.SetBranchAddress("IdTowerPhiMuonIn",IdTowerPhiMuonIn);
   muon.SetBranchAddress("IdTowerPhiMuonOut",IdTowerPhiMuonOut);
   muon.SetBranchAddress("IdTowerEtaMuonIn",IdTowerEtaMuonIn);
   muon.SetBranchAddress("IdTowerEtaMuonOut",IdTowerEtaMuonOut);
   muon.SetBranchAddress("LengthMuonHB",LengthMuonHB);
   muon.SetBranchAddress("ImpXYmuonHB",ImpXYmuonHB);
   muon.SetBranchAddress("ZImpXYmuonHB",ZImpXYmuonHB);
   muon.SetBranchAddress("EmuonHB",EmuonHB);
   muon.SetBranchAddress("PHIinTowerHB",PHIinTowerHB);
   muon.SetBranchAddress("IdTowerPhiMuonIn2",IdTowerPhiMuonIn2);
   muon.SetBranchAddress("IdTowerPhiMuonOut2",IdTowerPhiMuonOut2);
   muon.SetBranchAddress("IdTowerEtaMuonIn2",IdTowerEtaMuonIn2);
   muon.SetBranchAddress("IdTowerEtaMuonOut2",IdTowerEtaMuonOut2);
   muon.SetBranchAddress("LengthMuonHB2",LengthMuonHB2);
   muon.SetBranchAddress("TimeAvMuonHB2",TimeAvMuonHB2);
   muon.SetBranchAddress("TimeAvMuonHBcut2",TimeAvMuonHBcut2);
   muon.SetBranchAddress("TimeAvMuonHBcutwide2",TimeAvMuonHBcutwide2);
   muon.SetBranchAddress("EmuonHB2",EmuonHB2);
   muon.SetBranchAddress("EmuonHBcut2",EmuonHBcut2);
   muon.SetBranchAddress("EmuonHBcutwide2",EmuonHBcutwide2);
   muon.SetBranchAddress("LengthMuonDT",LengthMuonDT);
   muon.SetBranchAddress("NumHitsMuonDTall",NumHitsMuonDTall);
   muon.SetBranchAddress("NumHitsMuonDT",NumHitsMuonDT);
   muon.SetBranchAddress("XinPosMuonDT",XinPosMuonDT);
   muon.SetBranchAddress("YinPosMuonDT",YinPosMuonDT);
   muon.SetBranchAddress("ZinPosMuonDT",ZinPosMuonDT);
   muon.SetBranchAddress("XoutPosMuonDT",XoutPosMuonDT);
   muon.SetBranchAddress("YoutPosMuonDT",YoutPosMuonDT);
   muon.SetBranchAddress("ZoutPosMuonDT",ZoutPosMuonDT);
   //
   muon.SetBranchAddress("NumMuonHBnoPhiPlane",&NumMuonHBnoPhiPlane);
   muon.SetBranchAddress("IdTowerMuonNoPlanePhiIn",IdTowerMuonNoPlanePhiIn);
   muon.SetBranchAddress("IdTowerMuonNoPlanePhiOut",IdTowerMuonNoPlanePhiOut);
   muon.SetBranchAddress("IdTowerMuonNoPlaneEtaIn",IdTowerMuonNoPlaneEtaIn);
   muon.SetBranchAddress("IdTowerMuonNoPlaneEtaOut",IdTowerMuonNoPlaneEtaOut);
   muon.SetBranchAddress("XinPosMuonNoPlaneDT",XinPosMuonNoPlaneDT);
   muon.SetBranchAddress("YinPosMuonNoPlaneDT",YinPosMuonNoPlaneDT);
   muon.SetBranchAddress("ZinPosMuonNoPlaneDT",ZinPosMuonNoPlaneDT);
   muon.SetBranchAddress("XoutPosMuonNoPlaneDT",XoutPosMuonNoPlaneDT);
   muon.SetBranchAddress("YoutPosMuonNoPlaneDT",YoutPosMuonNoPlaneDT);
   muon.SetBranchAddress("ZoutPosMuonNoPlaneDT",ZoutPosMuonNoPlaneDT);
   muon.SetBranchAddress("ImpXYmuonNoPlaneDT",ImpXYmuonNoPlaneDT);
   muon.SetBranchAddress("ZImpXYmuonNoPlaneDT",ZImpXYmuonNoPlaneDT);
   muon.SetBranchAddress("LengthMuonNoPlaneDT",LengthMuonNoPlaneDT);
   muon.SetBranchAddress("NumHitsMuonNoPlaneDTall",NumHitsMuonNoPlaneDTall);

// Create histo
//***************************************************************************************************
// 2nd (Partner) Muon is good: in one Phi Plane in HB
   //matching between 2 muons
   TH1F *hAngleMuonHB2DT = new TH1F("hAngleMuonHB2DT","Cos Angle between two muons, 2nd muon in one phi plane ", 100, 0.95, 1.02);
   TH1F *hDeltaImpXYHB2DT = new TH1F("hDeltaImpXYHB2DT","delta ImpXY between two muons, 2nd muon in one phi plane ", 30, 0., 30.);
   TH1F *hDeltaZImpXYHB2DT = new TH1F("hDeltaZImpXYHB2DT","delta ZImpXY between two muons, 2nd muon in one phi plane ", 50, 0., 100.);
   TH1F *hPhiDeltaTowerHB2DT = new TH1F("hPhiDeltaTowerHB2DT","diviation from PhiTower center, 2nd muon in one phi plane ", 50, 0., 1.);
   //Energy
   TH1F *hEmuonHB2DTTopPlus = new TH1F("hEmuonHB2DTTopPlus","Emoun, Top+, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTTopMinus = new TH1F("hEmuonHB2DTTopMinus","Emoun, Top-, 2nd muon in one phi plane", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlus = new TH1F("hEmuonHB2DTBotPlus","Emoun, Bottom+, 2nd muon in one phi plane", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotMinus = new TH1F("hEmuonHB2DTBotMinus","Emoun, Bottom-, 2nd muon in one phi plane", 60, -2., 10.);
   //Time
   TH1F *hTimeMuonHB2DTTopPlus = new TH1F("hTimeMuonHB2DTTopPlus","TimeMoun, Top+, 2nd muon in one phi plane ", 60, -150., 150.);
   TH1F *hTimeMuonHB2DTTopMinus = new TH1F("hTimeMuonHB2DTTopMinus","TimeMoun, Top-, 2nd muon in one phi plane ", 60, -150., 150.);
   TH1F *hTimeMuonHB2DTBotPlus = new TH1F("hTimeMuonHB2DTBotPlus","TimeMoun, Bottom+, 2nd muon in one phi plane ", 60, -150., 150.);
   TH1F *hTimeMuonHB2DTBotMinus = new TH1F("hTimeMuonHB2DTBotMinus","TimeMoun, Bottom-, 2nd muon in one phi plane ", 60, -150., 150.);
   //Number Towers in Eta Plane passing by good muon
   TH1F *hNumTowerMuonHB2DTTopPlus = 
        new TH1F("hNumTowerMuonHB2DTTopPlus","Number Towers of Moun, Top+, 2nd muon in one phi plane ", 11, -0.5, 10.5);
   TH1F *hNumTowerMuonHB2DTTopMinus = 
        new TH1F("hNumTowerMuonHB2DTTopMinus","Number Towers of Moun, Top+, 2nd muon in one phi plane ", 11, -0.5, 10.5);
   TH1F *hNumTowerMuonHB2DTBotPlus = 
        new TH1F("hNumTowerMuonHB2DTBotPlus","Number Towers of Moun, Bottom+, 2nd muon in one phi plane ", 11, -0.5, 10.5);
   TH1F *hNumTowerMuonHB2DTBotMinus = 
        new TH1F("hNumTowerMuonHB2DTBotMinus","Number Towers of Moun, Bottom+, 2nd muon in one phi plane ", 11, -0.5, 10.5);
   //idPhiTower for eta+ and eta-
   TH1F *hIdPhiTowerHB2DTMinus = new TH1F("hIdPhiTowerHB2DTMinus", "IdPhiTower for eta-, 2nd muon in one phi plane ", 74, -0.5, 73.5);
   TH1F *hIdPhiTowerHB2DTPlus = new TH1F("hIdPhiTowerHB2DTPlus", "IdPhiTower for eta+, 2nd muon in one phi plane ", 74, -0.5, 73.5);
   // Muon Track quality in DT
   TH1F *hNumHitsHB2DT = new TH1F("hNumHitsHB2DT", "Number Hits for analysing muon, 2nd muon in one phi plane ",61 , -0.5, 60.5);
   TH1F *hNumHitsHB2DT2 = new TH1F("hNumHitsHB2DT2", "Number Hits for partner of analysing muon, 2nd muon in one phi plane ",61 , -0.5, 60.5);
   TH1F *hLengthMuonDTHB2DT = new TH1F("hLengthMuonDTHB2DT", "Length of analysing muon in DT, 2nd muon in one phi plane ",100 , 0, 600);
   TH1F *hLengthMuonDTHB2DT2 = new TH1F("hLengthMuonDTHB2DT2", "Length of partner of analysing muon in DT, 2nd muon in one phi plane ",100 , 0, 600);
   // energy for time- and time+
   TH1F *hEmuonHB2DTTopPlusTimePlus = new TH1F("hEmuonHB2DTTopPlusTimePlus","Emoun, Top+, Time+, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTTopMinusTimePlus = new TH1F("hEmuonHB2DTTopMinusTimePlus","Emoun, Top-, Time+, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimePlus = new TH1F("hEmuonHB2DTBotPlusTimePlus","Emoun, Bot+, Time+, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotMinusTimePlus = new TH1F("hEmuonHB2DTBotMinusTimePlus","Emoun, Bot-, Time+, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTTopPlusTimeMinus = new TH1F("hEmuonHB2DTTopPlusTimeMinus","Emoun, Top+, Time-, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTTopMinusTimeMinus = new TH1F("hEmuonHB2DTTopMinusTimeMinus","Emoun, Top-, Time-, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimeMinus = new TH1F("hEmuonHB2DTBotPlusTimeMinus","Emoun, Bot+, Time-, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotMinusTimeMinus = new TH1F("hEmuonHB2DTBotMinusTimeMinus","Emoun, Bot-, Time-, 2nd muon in one phi plane ", 60, -2., 10.);
   // in different time:
   TH1F *hEmuonHB2DTBotPlusTimePlus1 = new TH1F("hEmuonHB2DTBotPlusTimePlus1","Emoun, Bot+, Time+1, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimePlus2 = new TH1F("hEmuonHB2DTBotPlusTimePlus2","Emoun, Bot+, Time+2, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimePlus3 = new TH1F("hEmuonHB2DTBotPlusTimePlus3","Emoun, Bot+, Time+3, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimePlus4 = new TH1F("hEmuonHB2DTBotPlusTimePlus4","Emoun, Bot+, Time+4, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimeMinus1 = new TH1F("hEmuonHB2DTBotPlusTimeMinus1","Emoun, Bot+, Time-1, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimeMinus2 = new TH1F("hEmuonHB2DTBotPlusTimeMinus2","Emoun, Bot+, Time-2, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimeMinus3 = new TH1F("hEmuonHB2DTBotPlusTimeMinus3","Emoun, Bot+, Time-3, 2nd muon in one phi plane ", 60, -2., 10.);
   TH1F *hEmuonHB2DTBotPlusTimeMinus4 = new TH1F("hEmuonHB2DTBotPlusTimeMinus4","Emoun, Bot+, Time-4, 2nd muon in one phi plane ", 60, -2., 10.);
   // IdPhi vs Emuon
   TH2F *hIdPhiPlusVsE = new TH2F("hIdPhiPlusVsE","IdPhiTower vs Emuon, HB+",  60, -2, 10, 74, -0.5, 73.5); // x, y coordiants
   TH2F *hIdPhiMinusVsE = new TH2F("hIdPhiMinusVsE","IdPhiTower vs Emuon, HB-",  60, -2, 10, 74, -0.5, 73.5); // x, y coordiants
   // IdEta vs Emuon
   TH2F *hIdEtaTopVsE = new TH2F("hIdEtaTopVsE","IdEtaTower vs Emuon, Top HB",  60, -2, 10, 57, -14.25, 14.25); // x, y coordiants
   TH2F *hIdEtaBotVsE = new TH2F("hIdEtaBotVsE","IdEtaTower vs Emuon, Bottom HB",  60, -2, 10, 57, -14.25, 14.25); // x, y coordiants
  
   // contral plots
   TH1F *hImpXYHB2DT = new TH1F("hImpXYHB2DT","ImpXY of analyzing muon, 2nd muon in one phi plane ", 50, 0., 50.);
   TH1F *hZImpXYHB2DT = new TH1F("hZImpXYHB2DT","ZImpXY of analyzing muon, 2nd muon in one phi plane ", 100, -500., 500.);
   TH2F *hLmuonDTImpXY = new TH2F("hLmuonDTImpXY","ImpXT vs Muon Length", 100, 0, 600, 40, 0, 40); // x, y coordiants
   TH2F *hImpXYvsZ = new TH2F("hImpXYvsZ","ImpXY vs ZImpXY for muon", 40, 0, 40, 100, -500, 500); // x, y coordiants

   //energy of selected muon in different part of phi Towers
   TH1F *hEmuonPhiDetaTower1 = new TH1F("hEmuonPhiDetaTower1","Emoun in 1st:0-0.2 part of phi Towers ", 60, -2., 10.);
   TH1F *hEmuonPhiDetaTower2 = new TH1F("hEmuonPhiDetaTower2","Emoun in 2nd:0.2-0.4 part of phi Towers ", 60, -2., 10.);
   TH1F *hEmuonPhiDetaTower3 = new TH1F("hEmuonPhiDetaTower3","Emoun in 3th:0.4-0.6 part of phi Towers ", 60, -2., 10.);
   TH1F *hEmuonPhiDetaTower4 = new TH1F("hEmuonPhiDetaTower4","Emoun in 4th:0.6-0.8 part of phi Towers ", 60, -2., 10.);
   TH1F *hEmuonPhiDetaTower5 = new TH1F("hEmuonPhiDetaTower5","Emoun in 5th:0.8-0.9 part of phi Towers ", 60, -2., 10.);
   TH1F *hEmuonPhiDetaTower6 = new TH1F("hEmuonPhiDetaTower6","Emoun in 6th:0.9-1. part of phi Towers ", 60, -2., 10.);

   // fill TProfile for Time as iphi
   TProfile *hProfTimeAsIdPhiMinus = new TProfile("hProfTimeAsIdPhiMinus","mean Time as IdPhi for ETA-",72,0.5,72.5,-150,150);
   TProfile *hProfTimeAsIdPhiPlus = new TProfile("hProfTimeAsIdPhiPlus","mean Time as IdPhi for ETA+",72,0.5,72.5,-150,150);
   TProfile *hProfTimeAsIdEtaTop = new TProfile("hProfTimeAsIdEtaTop","mean Time as IdEta for Top",57,-14.25,14.25,-150,150);
   TProfile *hProfTimeAsIdEtaBot = new TProfile("hProfTimeAsIdEtaBot","mean Time as IdEta for Bot",57,-14.25,14.25,-150,150);
  
//***************************************************************************************************

//   Start main loop on all events
//   Event *eveall = new Event(); 
   Int_t nevent = muon.GetEntries();
// calculate pi:
   //float piG=acos(-1.);
   float DeltaPhiTower = 0.08726646; // width of PhiTower 
   for (Int_t i=0;i<nevent;i++) {
       muon.GetEntry(i);
// calculate anlge between good moun in one PhiPlane and other muons (could be also good or bad) 

        if(NumMuonHBphiPlane>0){ 
            for(Int_t ik = 0; ik<NumMuonHBphiPlane;ik++){
               int IsecondMuonDT = 0; // check if pair in DT to moun exists
               //int IsecondMuonHB = 0; // check if pair in HB to moun exists
               int maxTowerEta = 40; // maximal number of Towers crossing in eta 
               int minTowerEta = 0; // minimal number of Towers crossing in eta 
               // select muoun for wich we looking partner with |in and out IdTower|<=14, 
               // for partner it dosn't importent because we are not going to calculate it energy
               if(fabs(IdTowerEtaMuonIn[ik])>14 || fabs(IdTowerEtaMuonOut[ik])>14)continue;
               // check quality of muon
               if(NumHitsMuonDTall[ik]<25)continue; 
               // calculate angle between good muons
               for(Int_t jk = 0; jk<NumMuonHBphiPlane;jk++){
                  // check that this is not the same muon
                  if(ik==jk) continue;
                  // check quality of muon
                  //if(NumHitsMuonDTall[jk]<25)continue; 
                  //check that both muons from different place of DT R(inDT1,inDT2)>600 cm
                  float R12;
                  R12=pow((XinPosMuonDT[ik]-XinPosMuonDT[jk]),2)+pow((YinPosMuonDT[ik]-YinPosMuonDT[jk]),2);
                  R12=sqrt(R12+pow((ZinPosMuonDT[ik]-ZinPosMuonDT[jk]),2));
                  if(R12<600)continue;
                  // calculate cos angle
                  float CosAngle;
                  float r1;
                  float r2;
                  float deltaIm; 
                  float deltaZIm; 
                  r1 = pow((XinPosMuonDT[ik]-XoutPosMuonDT[ik]),2)+pow((YinPosMuonDT[ik]-YoutPosMuonDT[ik]),2);
                  r1 = sqrt(r1+pow((ZinPosMuonDT[ik]-ZoutPosMuonDT[ik]),2));
                  r2 = pow((XinPosMuonDT[jk]-XoutPosMuonDT[jk]),2)+pow((YinPosMuonDT[jk]-YoutPosMuonDT[jk]),2);
                  r2 = sqrt(r2+pow((ZinPosMuonDT[jk]-ZoutPosMuonDT[jk]),2));
                  CosAngle = -0.1;
                  if(r1*r2>0){
                      CosAngle = (XinPosMuonDT[ik]-XoutPosMuonDT[ik])*(XinPosMuonDT[jk]-XoutPosMuonDT[jk]);
                      CosAngle = CosAngle+(YinPosMuonDT[ik]-YoutPosMuonDT[ik])*(YinPosMuonDT[jk]-YoutPosMuonDT[jk]);
                      CosAngle = CosAngle+(ZinPosMuonDT[ik]-ZoutPosMuonDT[ik])*(ZinPosMuonDT[jk]-ZoutPosMuonDT[jk]);
                      CosAngle = CosAngle/r1/r2;
                      deltaIm = fabs(ImpXYmuonHB[ik]-ImpXYmuonHB[jk]);
                      deltaZIm = fabs(ZImpXYmuonHB[ik]-ZImpXYmuonHB[jk]);
                      hAngleMuonHB2DT->Fill(CosAngle);
                      hDeltaImpXYHB2DT->Fill(deltaIm); 
                      hDeltaZImpXYHB2DT->Fill(deltaZIm);
                      // make cut that 2nd muon in DT exists, do not make doulbe counting for histo filling
                      if(CosAngle>0.99&&deltaIm<10&&deltaZIm<20&&IsecondMuonDT==0){
                           IsecondMuonDT=1;
                           //calculate quality of Phi crossing:
                           float phiR;
                           phiR = fabs((PHIinMuonHB[ik]+PHIoutMuonHB[ik])/2-PHIinTowerHB[ik])/(DeltaPhiTower/2);
                           hPhiDeltaTowerHB2DT -> Fill(phiR);
                           if(phiR>0.8)continue;
                           float dLHB= 287.65-177.7;
               
                           // Top: 1<=iphi<=36, Bottom: 37<=iphi<=72 
                           // +: ieta>0, -: ieta<0
                           // number crossing towers in eta < 5 for quolity energy  
                           float eHB;
                           eHB = EmuonHB[ik]/LengthMuonHB[ik]*dLHB;
                           float tmuon;
                           tmuon = TimeAvMuonHB[ik]; 
                           float meanB=0; // difined mean time for top and bot
                           float rmsB=0; // difined mean time for top and but
                           // select that analized muon has good Time (+-1RMS) and belong to one part: Top+,Top-,Bot+ or Bot-  
                           if(IdTowerPhiMuonIn[ik]>0&&IdTowerPhiMuonIn[ik]<37&&NumHBTowersMuon[ik]<=maxTowerEta&&NumHBTowersMuon[ik]>=minTowerEta){ 
                             // cout << " *** check *** " << std::endl;
                              if(IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                                 //meanB=24.04;
                                 //rmsB=23.02;
                                 meanB=23.77;
                                 rmsB=22.74;
                                 if(fabs(tmuon-meanB)<=rmsB){
                                    hEmuonHB2DTTopPlus ->Fill(eHB);
                                    hNumTowerMuonHB2DTTopPlus->Fill(NumHBTowersMuon[ik]);
                                 }
                                 hTimeMuonHB2DTTopPlus ->Fill(tmuon); 
                                 if((tmuon-meanB)<0&&(tmuon-meanB)>(-rmsB))hEmuonHB2DTTopPlusTimeMinus->Fill(eHB); //cut on the tail one RMS
                                 if((tmuon-meanB)>=0&&(tmuon-meanB)<rmsB)hEmuonHB2DTTopPlusTimePlus->Fill(eHB);
                              } 
                              if(IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                                 //meanB=22.01;
                                 //rmsB=22.99;
                                 meanB=22.02;
                                 rmsB=22.8;
                                 if(fabs(tmuon-meanB)<=rmsB){
                                    hEmuonHB2DTTopMinus ->Fill(eHB);
                                    hNumTowerMuonHB2DTTopMinus->Fill(NumHBTowersMuon[ik]); 
                                 } 
                                 hTimeMuonHB2DTTopMinus ->Fill(tmuon);
                                 if((tmuon-meanB)<0&&(tmuon-meanB)>(-rmsB))hEmuonHB2DTTopMinusTimeMinus->Fill(eHB);
                                 if((tmuon-meanB)>=0&&(tmuon-meanB)<rmsB)hEmuonHB2DTTopMinusTimePlus->Fill(eHB);
                              } 
                           }
                           if(IdTowerPhiMuonIn[ik]>36&&IdTowerPhiMuonIn[ik]<73&&NumHBTowersMuon[ik]<=maxTowerEta&&NumHBTowersMuon[ik]>=minTowerEta){
                              if(IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                                 //meanB=37.99;
                                 //rmsB=23.7;
                                 meanB=39.56;
                                 rmsB=24.02;
                                 if(fabs(tmuon-meanB)<=rmsB){
                                    hEmuonHB2DTBotPlus ->Fill(eHB);
                                    hNumTowerMuonHB2DTBotPlus->Fill(NumHBTowersMuon[ik]); 
                                 } 
                                 hTimeMuonHB2DTBotPlus ->Fill(tmuon);
                                 if((tmuon-meanB)<0&&(tmuon-meanB)>(-rmsB))hEmuonHB2DTBotPlusTimeMinus->Fill(eHB);
                                 if((tmuon-meanB)>=0&&(tmuon-meanB)<rmsB)hEmuonHB2DTBotPlusTimePlus->Fill(eHB);
                                 // fill Emuon in different time:
                                 if((tmuon-meanB)>=0&&(tmuon-meanB)<rmsB/2)hEmuonHB2DTBotPlusTimePlus1->Fill(eHB);
                                 if((tmuon-meanB)>=rmsB/2&&(tmuon-meanB)<rmsB)hEmuonHB2DTBotPlusTimePlus2->Fill(eHB);
                                 if((tmuon-meanB)>=rmsB&&(tmuon-meanB)<rmsB*1.5)hEmuonHB2DTBotPlusTimePlus3->Fill(eHB);
                                 if((tmuon-meanB)>=rmsB*1.5)hEmuonHB2DTBotPlusTimePlus4->Fill(eHB);
                                 if((tmuon-meanB)<0&&(tmuon-meanB)>=(-rmsB/2))hEmuonHB2DTBotPlusTimeMinus1->Fill(eHB);
                                 if((tmuon-meanB)<(-rmsB/2)&&(tmuon-meanB)>=(-rmsB))hEmuonHB2DTBotPlusTimeMinus2->Fill(eHB);
                                 if((tmuon-meanB)<(-rmsB)&&(tmuon-meanB)>=(-1.5*rmsB))hEmuonHB2DTBotPlusTimeMinus3->Fill(eHB);
                                 if((tmuon-meanB)<(-rmsB*1.5))hEmuonHB2DTBotPlusTimeMinus4->Fill(eHB);
                              }
                              if(IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                                 //meanB=33.51;
                                 //rmsB=27.35;
                                 meanB=34.84;
                                 rmsB=27.31;
                                 if(fabs(tmuon-meanB)<=rmsB){
                                    hEmuonHB2DTBotMinus ->Fill(eHB);
                                    hNumTowerMuonHB2DTBotMinus->Fill(NumHBTowersMuon[ik]); 
                                 } 
                                 hTimeMuonHB2DTBotMinus ->Fill(tmuon);
                                 if((tmuon-meanB)<0&&(tmuon-meanB)>(-rmsB))hEmuonHB2DTBotMinusTimeMinus->Fill(eHB);
                                 if((tmuon-meanB)>=0&&(tmuon-meanB)<rmsB)hEmuonHB2DTBotMinusTimePlus->Fill(eHB);
                              }
                           }
                          // if(IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                          //       hProfTimeAsIdPhiMinus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                          // }  
                          // if(IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                          //       hProfTimeAsIdPhiPlus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                          // }  
                           if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=28&&IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                              hProfTimeAsIdPhiPlus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                           }
                           if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=27&&IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                              hProfTimeAsIdPhiMinus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                           }
                           if(IdTowerPhiMuonIn[ik]>=43&&IdTowerPhiMuonIn[ik]<=65&&IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                              hProfTimeAsIdPhiPlus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                           }
                           if(IdTowerPhiMuonIn[ik]>=47&&IdTowerPhiMuonIn[ik]<=64&&IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                              hProfTimeAsIdPhiMinus->Fill(IdTowerPhiMuonIn[ik],tmuon);
                           }
                           if(abs(IdTowerEtaMuonIn[ik]-IdTowerEtaMuonOut[ik])<=3){
                              float ideta = float(IdTowerEtaMuonIn[ik]+IdTowerEtaMuonOut[ik])/2;
                              if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=28&&IdTowerEtaMuonIn[ik]>0){
                                    hProfTimeAsIdEtaTop->Fill(ideta,tmuon);
                              }
                              if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=27&&IdTowerEtaMuonIn[ik]<0&&IdTowerPhiMuonIn[ik]!=24){
                                    hProfTimeAsIdEtaTop->Fill(ideta,tmuon);
                              }
                              if(IdTowerPhiMuonIn[ik]>=43&&IdTowerPhiMuonIn[ik]<=65&&IdTowerEtaMuonIn[ik]>0){
                                    hProfTimeAsIdEtaBot->Fill(ideta,tmuon);
                              }
                              if(IdTowerPhiMuonIn[ik]>=47&&IdTowerPhiMuonIn[ik]<=64&&IdTowerEtaMuonIn[ik]<0){
                                    hProfTimeAsIdEtaBot->Fill(ideta,tmuon);
                              }
                           }

// this cut is also means that ower muon belong only to one from 4 HB Parts
                           if(fabs(tmuon-meanB)<=rmsB&&meanB!=0){
                              // fill energy in different id Phi
                              if(IdTowerEtaMuonIn[ik]<0&&IdTowerEtaMuonOut[ik]<0){
                                    hIdPhiTowerHB2DTMinus->Fill(float(IdTowerPhiMuonIn[ik]));
                                    hIdPhiMinusVsE->Fill(eHB,float(IdTowerPhiMuonIn[ik]));
                              }  
                              if(IdTowerEtaMuonIn[ik]>0&&IdTowerEtaMuonOut[ik]>0){
                                    hIdPhiTowerHB2DTPlus->Fill(float(IdTowerPhiMuonIn[ik]));
                                    hIdPhiPlusVsE->Fill(eHB,float(IdTowerPhiMuonIn[ik]));
                              }  
                              // fill energy in different id Eta Tower, max Eta Tower crossing by muon <= 4 
                              if(abs(IdTowerEtaMuonIn[ik]-IdTowerEtaMuonOut[ik])<=3){
                                 float ideta = float(IdTowerEtaMuonIn[ik]+IdTowerEtaMuonOut[ik])/2;
                                 if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=28&&IdTowerEtaMuonIn[ik]>0){
                                       hIdEtaTopVsE->Fill(eHB,ideta);
                                       //hProfTimeAsIdEtaTop->Fill(ideta,tmuon);
                                 }  
                                 if(IdTowerPhiMuonIn[ik]>=8&&IdTowerPhiMuonIn[ik]<=27&&IdTowerEtaMuonIn[ik]<0&&IdTowerPhiMuonIn[ik]!=24){
                                       hIdEtaTopVsE->Fill(eHB,ideta);
                                       //hProfTimeAsIdEtaTop->Fill(ideta,tmuon);
                                 }  
                                 if(IdTowerPhiMuonIn[ik]>=43&&IdTowerPhiMuonIn[ik]<=65&&IdTowerEtaMuonIn[ik]>0){
                                       hIdEtaBotVsE->Fill(eHB,ideta);
                                       //hProfTimeAsIdEtaBot->Fill(ideta,tmuon);
                                 }  
                                 if(IdTowerPhiMuonIn[ik]>=47&&IdTowerPhiMuonIn[ik]<=64&&IdTowerEtaMuonIn[ik]<0){
                                       hIdEtaBotVsE->Fill(eHB,ideta);
                                       //hProfTimeAsIdEtaBot->Fill(ideta,tmuon);
                                 }  
                              }  

                              // fill energy of muon in different phiR
                              if(phiR<=0.2)hEmuonPhiDetaTower1->Fill(eHB);
                              if(phiR>0.2&&phiR<=0.4)hEmuonPhiDetaTower2->Fill(eHB);
                              if(phiR>0.4&&phiR<=0.6)hEmuonPhiDetaTower3->Fill(eHB);
                              if(phiR>0.6&&phiR<=0.8)hEmuonPhiDetaTower4->Fill(eHB);
                              if(phiR>0.8&&phiR<=0.9)hEmuonPhiDetaTower5->Fill(eHB);
                              if(phiR>0.9&&phiR<=1.0)hEmuonPhiDetaTower6->Fill(eHB);
                              hNumHitsHB2DT->Fill(NumHitsMuonDTall[ik]);
                              hLengthMuonDTHB2DT->Fill(LengthMuonDT[ik]);  
                              hNumHitsHB2DT2->Fill(NumHitsMuonDTall[jk]);
                              hLengthMuonDTHB2DT2->Fill(LengthMuonDT[jk]); 
                              float XY;
                              XY = ImpXYmuonHB[ik];  
                              hImpXYHB2DT -> Fill(XY); 
                              XY = ZImpXYmuonHB[ik];  
                              hZImpXYHB2DT -> Fill(XY); 
                              hLmuonDTImpXY->Fill(LengthMuonDT[ik],ImpXYmuonHB[ik]);
                              hImpXYvsZ->Fill(ImpXYmuonHB[ik],ZImpXYmuonHB[ik]);
                           }
                      } // end check for muon in 2 DT exists
                  }
               } //end for for 2nd good muon
            } //end for for interested muon 
        } // end check if good moun exists
   } //end event loop
/////////////////////////////////////////////////
// write histo to file
   theFile->Write();
   theFile->Close();
/////////////////////////////////////////////////
/*
   TCanvas *c1 = new TCanvas("c1","Check that Muon passes though DT in 2 places");
   c1->Divide(2,2);
   c1->cd(1);
   gPad -> SetLogy();
   //     TAxis *axis = histo->GetXaxis();
   //     axis->SetLabelSize(0.06);   
   hAngleMuonHB2DT ->Draw();
   c1->cd(2);
   hDeltaImpXYHB2DT->Draw();
   c1->cd(3);
   hDeltaZImpXYHB2DT->Draw();
   c1->cd(4);
   hPhiDeltaTowerHB2DT->Draw();
   c1->Print("pic1.gif");
// wait
   c1->WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c2 = new TCanvas("c2","E of Muon passes though DT in 2 places, NTowerEta<5");
   c2->Divide(2,2);
   c2->cd(1);
   hEmuonHB2DTTopMinus.Fit("gaus","E","",0.8.,2.4);
   c2->cd(2);
   hEmuonHB2DTTopPlus.Fit("gaus","E","",0.8.,2.4);
   c2->cd(3);
   hEmuonHB2DTBotMinus.Fit("gaus","E","",0.8.,2.4);
   c2->cd(4);
   hEmuonHB2DTBotPlus.Fit("gaus","E","",0.8.,2.4);
   c2->Print("pic2.gif");
// wait
   c2.WaitPrimitive();

/////////////////////////////////////////////////
   TCanvas *c21 = new TCanvas("c21","Time of Muon passes though DT in 2 places, NTowerEta<5");
   c21->Divide(2,2);
   c21->cd(1);
   hTimeMuonHB2DTTopMinus->Draw();
   c21->cd(2);
   hTimeMuonHB2DTTopPlus->Draw();
   c21->cd(3);
   hTimeMuonHB2DTBotMinus->Draw();
   c21->cd(4);
   hTimeMuonHB2DTBotPlus->Draw();
   c21->Print("pic21.gif");
  c21.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c22 = new TCanvas("c22","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c22->Divide(2,2);
   c22->cd(1);
   hNumTowerMuonHB2DTTopMinus ->Draw();
   c22->cd(2);
   hNumTowerMuonHB2DTTopPlus->Draw();
   c22->cd(3);
   hNumTowerMuonHB2DTBotMinus->Draw();
   c22->cd(4);
   hNumTowerMuonHB2DTBotPlus->Draw();
   c22->Print("pic22.gif");
// wait
  c22.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c4 = new TCanvas("c4","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c4->Divide(2,2);
   c4->cd(1);
   hIdPhiTowerHB2DTMinus->Draw();
   c4->cd(2);
   hIdPhiTowerHB2DTPlus->Draw();

   c4->cd(3);
//   hIdPhiTowerHB2DTsevMinus->Draw();
   c4->cd(4);
//   hIdPhiTowerHB2DTsevPlus->Draw();
   c4->Print("pic4.gif");
// wait
  c4.WaitPrimitive();

/////////////////////////////////////////////////
   TCanvas *c51 = new TCanvas("c51","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c51->Divide(2,2);
   c51->cd(1);
   hNumHitsHB2DT->Draw();
   c51->cd(2);
   hLengthMuonDTHB2DT->Draw();
   c51->cd(3);
   hNumHitsHB2DT2->Draw();
   c51->cd(4);
   hLengthMuonDTHB2DT2->Draw();
   c51->Print("pic51.gif");
// wait
  c51.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c61 = new TCanvas("c61","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c61->Divide(2,2);
   c61->cd(1);
   //hEmuonHB2DTTopMinusTimeMinus->Draw();
   hEmuonHB2DTTopMinusTimeMinus.Fit("gaus","E","",0.8.,2.4);
   c61->cd(2);
   hEmuonHB2DTTopPlusTimeMinus.Fit("gaus","E","",0.8.,2.4);
   c61->cd(3);
   hEmuonHB2DTBotMinusTimeMinus.Fit("gaus","E","",0.8.,2.4);
   c61->cd(4);
   hEmuonHB2DTBotPlusTimeMinus.Fit("gaus","E","",0.8.,2.4);
   c61->Print("pic61.gif");
// wait
  c61.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c62 = new TCanvas("c62","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c62->Divide(2,2);
   c62->cd(1);
   hEmuonHB2DTTopMinusTimePlus->Fit("gaus","E","",0.8.,2.4);
   c62->cd(2);
   hEmuonHB2DTTopPlusTimePlus->Fit("gaus","E","",0.8.,2.4);
   c62->cd(3);
   hEmuonHB2DTBotMinusTimePlus->Fit("gaus","E","",0.8.,2.4);
   c62->cd(4);
   hEmuonHB2DTBotPlusTimePlus->Fit("gaus","E","",0.8.,2.4);
   c62->Print("pic62.gif");
// wait
  c62.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c63 = new TCanvas("c63","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c63->Divide(2,2);
   c63->cd(1);
   hEmuonHB2DTBotPlusTimeMinus1->Fit("gaus","E","",0.8.,2.4);
   c63->cd(2);
   hEmuonHB2DTBotPlusTimeMinus2->Fit("gaus","E","",0.8.,2.4);
   c63->cd(3);
   hEmuonHB2DTBotPlusTimeMinus3->Fit("gaus","E","",0.8.,2.4);
   c63->cd(4);
   hEmuonHB2DTBotPlusTimeMinus4->Fit("gaus","E","",0.8.,2.4);
   c63->Print("pic63.gif");
// wait
  c63.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c64 = new TCanvas("c64","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c64->Divide(2,2);
   c64->cd(1);
   hEmuonHB2DTBotPlusTimePlus1->Fit("gaus","E","",0.8.,2.4);
   c64->cd(2);
   hEmuonHB2DTBotPlusTimePlus2->Fit("gaus","E","",0.8.,2.4);
   c64->cd(3);
   hEmuonHB2DTBotPlusTimePlus3->Fit("gaus","E","",0.8.,2.4);
   c64->cd(4);
   hEmuonHB2DTBotPlusTimePlus4->Fit("gaus","E","",0.8.,2.4);
   c64->Print("pic64.gif");
// wait
  c64.WaitPrimitive();
/////////////////////////////////////////////////
   TCanvas *c65 = new TCanvas("c65","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c65->Divide(3,2);
   c65->cd(1);
   hEmuonPhiDetaTower1->Fit("gaus","E","",0.8.,2.4);
   c65->cd(2);
   hEmuonPhiDetaTower2->Fit("gaus","E","",0.8.,2.4);
   c65->cd(3);
   hEmuonPhiDetaTower3->Fit("gaus","E","",0.8.,2.4);
   c65->cd(4);
   hEmuonPhiDetaTower4->Fit("gaus","E","",0.8.,2.4);
   c65->cd(5);
   hEmuonPhiDetaTower5->Fit("gaus","E","",0.8.,2.4);
   c65->cd(6);
   hEmuonPhiDetaTower6->Fit("gaus","E","",0.8.,2.4);
   c65->Print("pic65.gif");
// wait
  c65.WaitPrimitive();

////////////////////////////////////////////////
   TCanvas *c7 = new TCanvas("c7","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c7->Divide(2,2);
   c7->cd(1);
   hImpXYHB2DT->Draw();
   c7->cd(2);
   hZImpXYHB2DT->Draw();
   c7->cd(3);
   hLmuonDTImpXY->Draw();
   c7->cd(4);
   hImpXYvsZ->Draw();
   c7->Print("pic7.gif");
// wait
  c7.WaitPrimitive();
////////////////////////////////////////////////
   TCanvas *c8 = new TCanvas("c8","Number Eta Towers of Muon passes though DT in 2 places, NTowerEta<5");
   c8->Divide(2,2);
   c8->cd(1);
   hProfTimeAsIdPhiMinus->Draw();
   c8->cd(2);
   hProfTimeAsIdPhiPlus->Draw();
   c8->Print("pic8.gif");
// wait
  c8.WaitPrimitive();
*/
}
Ejemplo n.º 18
0
void httpserver(const char* jobname = "job1", Long64_t maxcnt = 0)
{
   TString filename = Form("%s.root", jobname);
   TFile *hfile = new TMemFile(filename,"RECREATE","Demo ROOT file with histograms");

   // Create some histograms, a profile histogram and an ntuple
   TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
   hpx->SetFillColor(48);
   TH2F *hpxpy = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
   TProfile *hprof = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
   TNtuple *ntuple = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i");
   hfile->Write();


   // http server with port 8080, use jobname as top-folder name
   THttpServer* serv = new THttpServer(Form("http:8080?top=%s", jobname));

   // fastcgi server with port 9000, use jobname as top-folder name
   // THttpServer* serv = new THttpServer(Form("fastcgi:9000?top=%s_fastcgi", jobname));

   // dabc agent, connects to DABC master_host:1237, works only when DABC configured
   // THttpServer* serv = new THttpServer(Form("dabc:master_host:1237?top=%s_dabc", jobname));

   // when read-only mode disabled one could execute object methods like TTree::Draw()
   serv->SetReadOnly(kFALSE);

   // One could specify location of newer version of JSROOT
   // serv->SetJSROOT("https://root.cern.ch/js/latest/");
   // serv->SetJSROOT("http://jsroot.gsi.de/latest/");

   gBenchmark->Start(jobname);

   // Create a new canvas.
   TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
   c1->SetFillColor(42);
   c1->GetFrame()->SetFillColor(21);
   c1->GetFrame()->SetBorderSize(6);
   c1->GetFrame()->SetBorderMode(-1);


   // Fill histograms randomly
   TRandom3 random;
   Float_t px, py, pz;
   const Int_t kUPDATE = 1000;
   Long64_t i = 0;

   while (true) {
      random.Rannor(px,py);
      pz = px*px + py*py;
      Float_t rnd = random.Rndm(1);
      hpx->Fill(px);
      hpxpy->Fill(px,py);
      hprof->Fill(px,pz);
      // fill only first 25000 events in NTuple
      if (i<25000) ntuple->Fill(px,py,pz,rnd,i);
      if (i && (i%kUPDATE) == 0) {
         if (i == kUPDATE) hpx->Draw();
         c1->Modified();
         c1->Update();
         if (i == kUPDATE) hfile->Write();

         if (gSystem->ProcessEvents()) break;
      }
      i++;
      if ((maxcnt>0) && (i>=maxcnt)) break;
   }

   gBenchmark->Show(jobname);
}
Ejemplo n.º 19
0
Double_t CalibTree::Loop(int loop, TFile *fout, bool useweight, int nMin,
			 bool inverse, double rmin, double rmax, int ietaMax,
			 int applyL1Cut, double l1Cut, bool last, 
			 double fraction, bool writeHisto, bool debug) {

  if (fChain == 0) return 0;
  Long64_t nbytes(0), nb(0), kprint(0);
  Long64_t nentryTot = fChain->GetEntriesFast();
  Long64_t nentries = (fraction > 0.01 && fraction < 0.99) ? 
    (Long64_t)(fraction*nentryTot) : nentryTot;
  if (detIds.size() == 0) {
    for (Long64_t jentry=0; jentry<nentries; jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // Find DetIds contributing to the track
      bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		     ((t_Run < runlo_) || (t_Run > runhi_)));
      if (selRun && (t_nVtx >= nvxlo_) && (t_nVtx <= nvxhi_)) {
	bool isItRBX = (cSelect_ && exclude_ && cSelect_->isItRBX(t_DetIds));
	++kprint;
	if (!isItRBX) {
	  for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	    if (selectPhi((*t_DetIds)[idet])) {
	      unsigned int detid = truncateId((*t_DetIds)[idet],
					      truncateFlag_,debug);
	      if (debug && (kprint<=10)) {
		std::cout << "DetId[" << idet << "] Original " << std::hex 
			  << (*t_DetIds)[idet] << " truncated " << detid 
			  << std::dec;
	      }
	      if (std::find(detIds.begin(),detIds.end(),detid) == detIds.end()){
		detIds.push_back(detid);
		if (debug && (kprint<=10)) std::cout << " new";
	      }
	      if (debug && (kprint<=10)) std::cout << std::endl;
	    }
	  }
	  // Also look at the neighbouring cells if available
	  if (t_DetIds3 != 0) {
	    for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	      if (selectPhi((*t_DetIds3)[idet])) {
		unsigned int detid = truncateId((*t_DetIds3)[idet],
						truncateFlag_,debug);
		if (std::find(detIds.begin(),detIds.end(),detid)==detIds.end()){
		  detIds.push_back(detid);
		}
	      }
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "Total of " << detIds.size() << " detIds and " 
	      << histos.size() << " histos found" << std::endl;
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    for (unsigned int k=0; k<detIds.size(); ++k) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << k << "] " << subdet << ":" << zside*ieta << ":"
		<< depth << ":" << iphi << "  " << std::hex << detIds[k] 
		<< std::dec << std::endl;
    }
  }
  unsigned int k(0);
  for (std::map<unsigned int, TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++k) {
    if (debug) {
      std::cout << "histos[" << k << "] " << std::hex << itr->first 
		<< std::dec << " " << itr->second;
      if (itr->second != 0) std::cout << " " << itr->second->GetTitle();
      std::cout << std::endl;
    }
    if (itr->second != 0) itr->second->Delete();
  }

  for (unsigned int k=0; k<detIds.size(); ++k) {
    char name[20], title[100];
    sprintf (name, "Hist%d_%d", detIds[k], loop);
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
    sprintf (title, "Correction for Subdet %d #eta %d depth %d (Loop %d)", subdet, zside*ieta, depth, loop);
    TH1D* hist = new TH1D(name,title,100, 0.0, 5.0);
    hist->Sumw2();
    if (debug) {
      std::cout << "Book Histo " << k << " " << title << std::endl;
    }
    histos[detIds[k]] = hist;
  }
  std::cout << "Total of " << detIds.size() << " detIds and " << histos.size() 
	    << " found in " << nentries << std::endl;

  nbytes = nb = 0;
  std::map<unsigned int, myEntry > SumW;
  std::map<unsigned int, double  > nTrks;

  int ntkgood(0);
  for (Long64_t jentry=0; jentry<nentries; jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0)                               break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if (std::find(entries.begin(),entries.end(),jentry) !=
	entries.end())                            continue;
    bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		   ((t_Run < runlo_) || (t_Run > runhi_)));
    if (!selRun)                                  continue;
    if ((t_nVtx < nvxlo_) || (t_nVtx > nvxhi_))   continue;
    if (cSelect_ != nullptr) {
      if (exclude_) {
	if (cSelect_->isItRBX(t_DetIds))          continue;
      } else {
	if (!(cSelect_->isItRBX(t_ieta,t_iphi)))  continue;
      }
    }

    if (debug) {
      std::cout << "***Entry (Track) Number : " << ientry << std::endl;
      std::cout << "p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal << "/"
		<< t_eMipDR << "/" << (*t_DetIds).size() << std::endl;
    }
    double pmom = (useGen_ && (t_gentrackP > 0)) ? t_gentrackP : t_p;
    if (goodTrack()) {
      ++ntkgood;
      double Etot(0), Etot2(0);
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	if (selectPhi((*t_DetIds)[idet])) {
	  unsigned int id = (*t_DetIds)[idet];
	  double hitEn(0);
	  unsigned int detid = truncateId(id,truncateFlag_,false);
	  if (Cprev.find(detid) != Cprev.end()) 
	    hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	  else 
	    hitEn = (*t_HitEnergies)[idet];
	  if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	  Etot  += hitEn;
	  Etot2 += ((*t_HitEnergies)[idet]);
	}
      }
      // Now the outer cone 
      double Etot1(0), Etot3(0);
      if (t_DetIds1 != 0 && t_DetIds3 != 0) {
	for (unsigned int idet=0; idet<(*t_DetIds1).size(); idet++) { 
	  if (selectPhi((*t_DetIds1)[idet])) {
	    unsigned int id    = (*t_DetIds1)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies1)[idet];
	    else 
	      hitEn = (*t_HitEnergies1)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot1  += hitEn;
	  }
	}
	for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	  if (selectPhi((*t_DetIds3)[idet])) {
	    unsigned int id    = (*t_DetIds3)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies3)[idet];
	    else 
	      hitEn = (*t_HitEnergies3)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot3  += hitEn;
	  }
	}
      }
      eHcalDelta_ = Etot3-Etot1;
      double evWt = (useweight) ? t_EventWeight : 1.0; 
      // PU correction only for loose isolation cut
      double ehcal = ((puCorr_ == 0) ? Etot : 
		      ((puCorr_ < 0) ? (Etot*puFactor(-puCorr_,t_ieta,pmom,Etot,eHcalDelta_)) :
		       puFactorRho(puCorr_,t_ieta,t_rhoh,Etot)));
      double pufac = (Etot > 0) ? (ehcal/Etot) : 1.0;
      double ratio = ehcal/(pmom-t_eMipDR);
      if (debug) std::cout << " Weights " << evWt << ":" << pufac << " Energy "
			   << Etot2 << ":" << Etot << ":" << pmom << ":" 
			   << t_eMipDR << ":" << t_eHcal << ":" << ehcal 
			   << " ratio " << ratio  << std::endl;
      if (loop==0) {
	h_pbyE->Fill(ratio, evWt);
        h_Ebyp_bfr->Fill(t_ieta, ratio, evWt);
      }
      if (last){
        h_Ebyp_aftr->Fill(t_ieta, ratio, evWt);
      }
      bool l1c(true);
      if (applyL1Cut != 0) l1c = ((t_mindR1 >= l1Cut) || 
				  ((applyL1Cut == 1) && (t_DataType == 1)));
      if ((rmin >=0 && ratio > rmin) && (rmax >= 0 && ratio < rmax) && l1c) {
	for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	  if (selectPhi((*t_DetIds)[idet])) {
	    unsigned int id    = (*t_DetIds)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn=0.0;
	    if (debug) {
	      std::cout << "idet " << idet << " detid/hitenergy : " 
			<< std::hex << (*t_DetIds)[idet] << ":" << detid 
			<< "/" << (*t_HitEnergies)[idet] << std::endl;
	    }
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	    else 
	      hitEn = (*t_HitEnergies)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    double Wi  = evWt * hitEn/Etot;
	    double Fac = (inverse) ? (ehcal/(pmom-t_eMipDR)) : 
	      ((pmom-t_eMipDR)/ehcal);
	    double Fac2= Wi*Fac*Fac;
	    TH1D* hist(0);
	    std::map<unsigned int,TH1D*>::const_iterator itr = histos.find(detid);
	    if (itr != histos.end()) hist = itr->second;
	    if (debug) {
	      std::cout << "Det Id " << std::hex << detid << std::dec 
			<< " " << hist << std::endl;
	    }
	    if (hist != 0) hist->Fill(Fac, Wi);//////histola
	    Fac       *= Wi;
	    if (SumW.find(detid) != SumW.end() ) {
	      Wi  += SumW[detid].fact0;
	      Fac += SumW[detid].fact1;
	      Fac2+= SumW[detid].fact2;
	      int kount = SumW[detid].kount + 1;
	      SumW[detid]   = myEntry(kount,Wi,Fac,Fac2); 
	      nTrks[detid] += evWt;
	    } else {
	      SumW.insert(std::pair<unsigned int,myEntry>(detid,myEntry(1,Wi,Fac,Fac2)));
	      nTrks.insert(std::pair<unsigned int,unsigned int>(detid, evWt));
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "# of Good Tracks " << ntkgood << " out of " << nentries 
	      << std::endl;
  }
  if (loop==0) {
    h_pbyE->Write("h_pbyE");
    h_Ebyp_bfr->Write("h_Ebyp_bfr");
  }
  if (last) {
    h_Ebyp_aftr->Write("h_Ebyp_aftr");
  }

  std::map<unsigned int, std::pair<double,double> > cfactors;
  unsigned int kount(0), kountus(0);
  double       sumfactor(0);
  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr) {
    if (writeHisto) {
      std::pair<double,double> result_write = fitMean(itr->second, 0);
      (itr->second)->Write();
    }
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "DETID :" << subdet << "  IETA :" << ieta 
		<< " HIST ENTRIES :" << (itr->second)->GetEntries()
		<< std::endl;
    }
  }

  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++kount) {
    std::pair<double,double> result = fitMean(itr->second, 0);
    double factor = (inverse) ? (2.-result.first) : result.first;
    if (debug) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << kount << "] " << subdet << ":" << zside*ieta 
		<< ":" << depth << " Factor " << factor << " +- " 
		<< result.second << std::endl;
    }
    if (!useMean_) {
      cfactors[itr->first] = std::pair<double,double>(factor,result.second);
      if (itr->second->GetEntries() > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }
  
  std::map<unsigned int, myEntry>::const_iterator SumWItr = SumW.begin();
  for (; SumWItr != SumW.end(); SumWItr++) {
    unsigned int detid = SumWItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "Detid|kount|SumWi|SumFac|myId : " << subdet << ":" 
		<< zside*ieta << ":" << depth << " | " 
		<< (SumWItr->second).kount << " | " << (SumWItr->second).fact0
		<< "|" << (SumWItr->second).fact1 << "|" 
		<< (SumWItr->second).fact2 << std::endl;
    }
    double factor = (SumWItr->second).fact1/(SumWItr->second).fact0;
    double dfac1  = ((SumWItr->second).fact2/(SumWItr->second).fact0-factor*factor);
    if (dfac1 < 0) dfac1 = 0;
    double dfac   = sqrt(dfac1/(SumWItr->second).kount);
    if (debug) {
      std::cout << "Factor " << factor << " " << dfac1 << " " << dfac
		<< std::endl;
    }
    if (inverse) factor = 2.-factor;
    if (useMean_) {
      cfactors[detid] = std::pair<double,double>(factor,dfac);
      if ((SumWItr->second).kount > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }

  double dets[150], cfacs[150], wfacs[150], myId[150], nTrk[150];
  kount = 0;
  std::map<unsigned int,std::pair<double,double> >::const_iterator itr=cfactors.begin();
  for (; itr !=cfactors.end(); ++itr,++kount) {
    unsigned int detid = itr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    double id  = ieta*zside + 0.25*(depth-1);
    double factor = (itr->second).first;
    double dfac   = (itr->second).second;
    if (ieta > ietaMax) {
      factor = 1;
      dfac   = 0;
    }
    std::pair<double,double> cfac(factor,dfac);
    if (Cprev.find(detid) != Cprev.end()) {
      dfac        /= factor;
      factor      *= Cprev[detid].first;
      dfac        *= factor;
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    } else {
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    }
    wfacs[kount]= factor;
    dets[kount] = detid;
    myId[kount] = id;
    nTrk[kount] = nTrks[detid];
  }
  if (higheta_ > 0) highEtaFactors(ietaMax, debug);

  std::cout << kountus << " detids out of " << kount << " have tracks > "
	    << nMin << std::endl;

  char fname[50];
  fout->cd();
  TGraph *g_fac1 = new TGraph(kount, dets, cfacs); 
  sprintf (fname, "Cfacs%d", loop);
  g_fac1->SetMarkerStyle(7);
  g_fac1->SetMarkerSize(5.0);
  g_fac1->Draw("AP");
  g_fac1->Write(fname);
  TGraph *g_fac2 = new TGraph(kount, dets, wfacs); 
  sprintf (fname, "Wfacs%d", loop);
  g_fac2->SetMarkerStyle(7);
  g_fac2->SetMarkerSize(5.0);
  g_fac2->Draw("AP");
  g_fac2->Write(fname);
  TGraph *g_fac3 = new TGraph(kount, myId, cfacs); 
  sprintf (fname, "CfacsVsMyId%d", loop);
  g_fac3->SetMarkerStyle(7);
  g_fac3->SetMarkerSize(5.0);
  g_fac3->Draw("AP");
  g_fac3->Write(fname);
  TGraph *g_fac4 = new TGraph(kount, myId, wfacs); 
  sprintf (fname, "WfacsVsMyId%d", loop);
  g_fac4->SetMarkerStyle(7);
  g_fac4->SetMarkerSize(5.0);
  g_fac4->Draw("AP");
  g_fac4->Write(fname);
  TGraph *g_nTrk = new TGraph(kount, myId, nTrk); 
  sprintf (fname, "nTrk");
  if(loop==0){
    g_nTrk->SetMarkerStyle(7);
    g_nTrk->SetMarkerSize(5.0);
    g_nTrk->Draw("AP");
    g_nTrk->Write(fname);
  }
  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, std::pair<double,double> >::const_iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (; CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") (nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second.first << " +- "
	      << CprevItr->second.second << std::endl;
  }
  double mean = (kountus > 0) ? (sumfactor/kountus) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << kountus 
	    << " DetIds" << std::endl;
  h_cvg->SetBinContent(loop+1,mean);
  if (last) h_cvg->Write("Cvg0");
  return mean;
}
Ejemplo n.º 20
0
void TOFCheck(string MODE="COMPILE")
{
  if(MODE=="COMPILE") return;

   system("mkdir pictures");

   setTDRStyle();
   gStyle->SetPadTopMargin   (0.06);
   gStyle->SetPadBottomMargin(0.15);
   gStyle->SetPadRightMargin (0.03);
   gStyle->SetPadLeftMargin  (0.07);
   gStyle->SetTitleSize(0.04, "XYZ");
   gStyle->SetTitleXOffset(1.1);
   gStyle->SetTitleYOffset(1.35);
   gStyle->SetPalette(1);
   gStyle->SetNdivisions(505,"X");
   TH1::AddDirectory(kTRUE);

   // get all the samples and clean the list to keep only the one we want to run on... Also initialize the BaseDirectory
   std::vector<stSample> samples;

   InitBaseDirectory();
   GetSampleDefinition(samples, "../../ICHEP_Analysis/Analysis_Samples.txt");
   if(MODE.find("ANALYSE_")==0){
      int sampleIdStart, sampleIdEnd; sscanf(MODE.c_str(),"ANALYSE_%d_to_%d",&sampleIdStart, &sampleIdEnd);
      keepOnlyTheXtoYSamples(samples,sampleIdStart,sampleIdEnd);
      printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n");
      printf("Run on the following samples:\n");
      for(unsigned int s=0;s<samples.size();s++){samples[s].print();}
      printf("----------------------------------------------------------------------------------------------------------------------------------------------------\n\n");
   }else{
      printf("You must select a MODE:\n");
      printf("MODE='ANALYSE_X_to_Y'   : Will run the analysis on the samples with index in the range [X,Y]\n"); 
      return;
   }

   //create histogram file and run the analyis
   system("mkdir pictures/");
   TFile* OutputHisto = new TFile(("pictures/Histos_"+samples[0].Name+"_"+samples[0].FileName+".root").c_str(),"RECREATE");

   TH1D* TOF = new TH1D("TOF", "TOF", 100, 0, 2); TOF->Sumw2();
   TH1D* TOFDT  = new TH1D("TOFDT", "TOFDT", 100, 0, 2); TOFDT->Sumw2();
   TH1D* TOFCSC  = new TH1D("TOFCSC", "TOFCSC", 100, 0, 2); TOFCSC->Sumw2();
   TH1D* Vertex  = new TH1D("Vertex", "Vertex", 100, -10, 10); Vertex->Sumw2();
   TH1D* VertexDT = new TH1D("VertexDT", "VertexDT", 100, -10, 10); VertexDT->Sumw2();
   TH1D* VertexCSC = new TH1D("VertexCSC", "VertexCSC", 100, -10, 10); VertexCSC->Sumw2();
   TProfile* TOFVsEta = new TProfile("TOFVsEta", "TOFVsEta", 50, -2.1, 2.1); TOFVsEta->Sumw2();
   TProfile* TOFVsPhi = new TProfile("TOFVsPhi", "TOFVsPhi", 50, -3.14, 3.14); TOFVsPhi->Sumw2();
   TProfile* TOFVsPt  = new TProfile("TOFVsPt" , "TOFVsPt" , 50, 40, 140); TOFVsPt->Sumw2();
   TProfile* CSCTOFVsEta = new TProfile("CSCTOFVsEta", "CSCTOFVsEta", 50, -2.1, 2.1); CSCTOFVsEta->Sumw2();
   TProfile* CSCTOFVsPhi = new TProfile("CSCTOFVsPhi", "CSCTOFVsPhi", 50, -3.14, 3.14); CSCTOFVsPhi->Sumw2();
   TProfile* CSCTOFVsPt  = new TProfile("CSCTOFVsPt" , "CSCTOFVsPt" , 50, 40, 140); CSCTOFVsPt->Sumw2();
   TProfile* DTTOFVsEta = new TProfile("DTTOFVsEta", "DTTOFVsEta", 50, -2.1, 2.1); DTTOFVsEta->Sumw2();
   TProfile* DTTOFVsPhi = new TProfile("DTTOFVsPhi", "DTTOFVsPhi", 50, -3.14, 3.14); DTTOFVsPhi->Sumw2();
   TProfile* DTTOFVsPt  = new TProfile("DTTOFVsPt" , "DTTOFVsPt" , 50, 40, 140); DTTOFVsPt->Sumw2();

   TProfile* VertexVsEta = new TProfile("VertexVsEta", "VertexVsEta", 50, -2.1, 2.1); VertexVsEta->Sumw2();
   TProfile* VertexVsPhi = new TProfile("VertexVsPhi", "VertexVsPhi", 50, -3.14, 3.14); VertexVsPhi->Sumw2();
   TProfile* VertexVsPt  = new TProfile("VertexVsPt" , "VertexVsPt" , 50, 40, 140); VertexVsPt->Sumw2();
   TProfile* CSCVertexVsEta = new TProfile("CSCVertexVsEta", "CSCVertexVsEta", 50, -2.1, 2.1); CSCVertexVsEta->Sumw2();
   TProfile* CSCVertexVsPhi = new TProfile("CSCVertexVsPhi", "CSCVertexVsPhi", 50, -3.14, 3.14); CSCVertexVsPhi->Sumw2();
   TProfile* CSCVertexVsPt  = new TProfile("CSCVertexVsPt" , "CSCVertexVsPt" , 50, 40, 140); CSCVertexVsPt->Sumw2();
   TProfile* DTVertexVsEta = new TProfile("DTVertexVsEta", "DTVertexVsEta", 50, -2.1, 2.1); DTVertexVsEta->Sumw2();
   TProfile* DTVertexVsPhi = new TProfile("DTVertexVsPhi", "DTVertexVsPhi", 50, -3.14, 3.14); DTVertexVsPhi->Sumw2();
   TProfile* DTVertexVsPt  = new TProfile("DTVertexVsPt" , "DTVertexVsPt" , 50, 40, 140); DTVertexVsPt->Sumw2();

   TypeMode      = 2;


   for(unsigned int s=0;s<samples.size();s++){
     std::vector<string> FileName;
     GetInputFiles(samples[s], BaseDirectory, FileName);
     fwlite::ChainEvent tree(FileName);

     printf("Progressing Bar              :0%%       20%%       40%%       60%%       80%%       100%%\n");
     printf("Looping on Tree              :");
     int TreeStep = tree.size()/50;if(TreeStep==0)TreeStep=1;
     for(Long64_t e=0;e<tree.size();e++){
//      if(e>10)break;
       tree.to(e);
      if(e%TreeStep==0){printf(".");fflush(stdout);}

      if(!PassingTrigger(tree))continue;

      fwlite::Handle<susybsm::HSCParticleCollection> hscpCollHandle;
      hscpCollHandle.getByLabel(tree,"HSCParticleProducer");
      if(!hscpCollHandle.isValid()){printf("HSCP Collection NotFound\n");continue;}
      susybsm::HSCParticleCollection hscpColl = *hscpCollHandle;

      fwlite::Handle<DeDxDataValueMap> dEdxSCollH;
      dEdxSCollH.getByLabel(tree, dEdxS_Label.c_str());
      if(!dEdxSCollH.isValid()){printf("Invalid dEdx Selection collection\n");continue;}

      fwlite::Handle<DeDxDataValueMap> dEdxMCollH;
      dEdxMCollH.getByLabel(tree, dEdxM_Label.c_str());
      if(!dEdxMCollH.isValid()){printf("Invalid dEdx Mass collection\n");continue;}

      fwlite::Handle<MuonTimeExtraMap> TOFCollH;
      TOFCollH.getByLabel(tree, "muontiming",TOF_Label.c_str());
      if(!TOFCollH.isValid()){printf("Invalid TOF collection\n");return;}

      fwlite::Handle<MuonTimeExtraMap> TOFDTCollH;
      TOFDTCollH.getByLabel(tree, "muontiming",TOFdt_Label.c_str());
      if(!TOFDTCollH.isValid()){printf("Invalid DT TOF collection\n");continue;}

      fwlite::Handle<MuonTimeExtraMap> TOFCSCCollH;
      TOFCSCCollH.getByLabel(tree, "muontiming",TOFcsc_Label.c_str());
      if(!TOFCSCCollH.isValid()){printf("Invalid CSCTOF collection\n");continue;}

      double Mass=0;
      int ind1=-1, ind2=-1;

      for(unsigned int c=0;c<hscpColl.size();c++){
         susybsm::HSCParticle hscp  = hscpColl[c];
         reco::TrackRef track = hscp.trackRef();
         if(track.isNull())continue;
	 if(hscp.muonRef().isNull()) continue;

         const DeDxData& dedxSObj  = dEdxSCollH->get(track.key());
         const DeDxData& dedxMObj  = dEdxMCollH->get(track.key());

         const reco::MuonTimeExtra* tof = NULL;
         const reco::MuonTimeExtra* dttof = NULL;
         const reco::MuonTimeExtra* csctof = NULL;
         if(!hscp.muonRef().isNull()){ tof  = &TOFCollH->get(hscp.muonRef().key()); dttof  = &TOFDTCollH->get(hscp.muonRef().key()); csctof  = &TOFCSCCollH->get(hscp.muonRef().key());}
         if(!PassPreselection(hscp, dedxSObj, dedxMObj, tof, dttof, csctof, tree))continue;

	 for(unsigned int d=c+1;d<hscpColl.size();d++){
	   susybsm::HSCParticle hscp2  = hscpColl[d];
	   reco::TrackRef track2 = hscp2.trackRef();
	   if(track2.isNull())continue;
	   if(hscp2.muonRef().isNull()) continue;

	   const DeDxData& dedxSObj2  = dEdxSCollH->get(track.key());
	   const DeDxData& dedxMObj2  = dEdxMCollH->get(track.key());

	   const reco::MuonTimeExtra* tof2 = NULL;
	   const reco::MuonTimeExtra* dttof2 = NULL;
	   const reco::MuonTimeExtra* csctof2 = NULL;
	   if(!hscp2.muonRef().isNull()){ tof2  = &TOFCollH->get(hscp.muonRef().key()); dttof2  = &TOFDTCollH->get(hscp.muonRef().key()); csctof2  = &TOFCSCCollH->get(hscp.muonRef().key());}
	   if(!PassPreselection(hscp2, dedxSObj2, dedxMObj2, tof2, dttof2, csctof2, tree))continue;

	   if(track->charge()==track2->charge()) continue;
	   double E = track->p() + track2->p();
	   double px = track->px() + track2->px();
	   double py = track->py() + track2->py();
	   double pz = track->pz() + track2->pz();
	   double p = px + py +pz;
	   double M = sqrt(E*E - p*p);
	   if(fabs(M-91.1876)>fabs(Mass-91.1876)) continue;
	   Mass=M;
	   ind1=c;
	   ind2=d;
	 }
      }

      for(int c=0;c<(int)hscpColl.size();c++){
	if(c!=ind1 && c!=ind2) continue;
	susybsm::HSCParticle hscp  = hscpColl[c];
	reco::TrackRef track = hscp.trackRef();
	if(track.isNull())continue;
	if(hscp.muonRef().isNull()) continue;

	const reco::MuonTimeExtra* tof = NULL;
	const reco::MuonTimeExtra* dttof = NULL;
	const reco::MuonTimeExtra* csctof = NULL;
	if(!hscp.muonRef().isNull()){ tof  = &TOFCollH->get(hscp.muonRef().key()); dttof  = &TOFDTCollH->get(hscp.muonRef().key()); csctof  = &TOFCSCCollH->get(hscp.muonRef().key());}

	if(tof && tof->nDof()>=GlobalMinNDOF && (dttof->nDof()>=GlobalMinNDOFDT || csctof->nDof()>=GlobalMinNDOFCSC) && tof->inverseBetaErr()<=GlobalMaxTOFErr){
	  TOF->Fill(tof->inverseBeta());
          TOFVsEta->Fill(track->eta(), tof->inverseBeta());
          TOFVsPhi->Fill(track->phi(), tof->inverseBeta());
          TOFVsPt->Fill(track->pt(), tof->inverseBeta());
	  if(dttof->nDof()>=GlobalMinNDOFDT) {
	    TOFDT->Fill(dttof->inverseBeta());
	    DTTOFVsEta->Fill(track->eta(), dttof->inverseBeta());
	    DTTOFVsPhi->Fill(track->phi(), dttof->inverseBeta());
	    DTTOFVsPt->Fill(track->pt(), dttof->inverseBeta());
	  }
	  if(csctof->nDof()>=GlobalMinNDOFCSC) {
	    TOFCSC->Fill(csctof->inverseBeta());
	    CSCTOFVsEta->Fill(track->eta(), csctof->inverseBeta());
	    CSCTOFVsPhi->Fill(track->phi(), csctof->inverseBeta());
	    CSCTOFVsPt->Fill(track->pt(), csctof->inverseBeta());
	  }


	  Vertex->Fill(tof->timeAtIpInOut());
          VertexVsEta->Fill(track->eta(), tof->timeAtIpInOut());
          VertexVsPhi->Fill(track->phi(), tof->timeAtIpInOut());
          VertexVsPt->Fill(track->pt(), tof->timeAtIpInOut());
	  if(dttof->nDof()>=GlobalMinNDOFDT) {
	    VertexDT->Fill(dttof->timeAtIpInOut());
	    DTVertexVsEta->Fill(track->eta(), dttof->timeAtIpInOut());
	    DTVertexVsPhi->Fill(track->phi(), dttof->timeAtIpInOut());
	    DTVertexVsPt->Fill(track->pt(), dttof->timeAtIpInOut());
	  }
	  if(csctof->nDof()>=GlobalMinNDOFCSC) {
	    VertexCSC->Fill(csctof->timeAtIpInOut());
	    CSCVertexVsEta->Fill(track->eta(), csctof->timeAtIpInOut());
	    CSCVertexVsPhi->Fill(track->phi(), csctof->timeAtIpInOut());
	    CSCVertexVsPt->Fill(track->pt(), csctof->timeAtIpInOut());
	  }
	}
      }
     }printf("\n");
   }

   OutputHisto->Write();
   OutputHisto->Close();  
}
TFile *hsimple(Int_t get=0)
{
//  This program creates :
//    - a one dimensional histogram
//    - a two dimensional histogram
//    - a profile histogram
//    - a memory-resident ntuple
//
//  These objects are filled with some random numbers and saved on a file.
//  If get=1 the macro returns a pointer to the TFile of "hsimple.root"
//          if this file exists, otherwise it is created.
//  The file "hsimple.root" is created in $ROOTSYS/tutorials if the caller has
//  write access to this directory, otherwise the file is created in $PWD

   TString filename = "hsimple.root";
   TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   dir.ReplaceAll("hsimple.C","");
   dir.ReplaceAll("/./","/");
   TFile *hfile = 0;
   if (get) {
      // if the argument get =1 return the file "hsimple.root"
      // if the file does not exist, it is created
      TString fullPath = dir+"hsimple.root";
      if (!gSystem->AccessPathName(fullPath,kFileExists)) {
         hfile = TFile::Open(fullPath); //in $ROOTSYS/tutorials
         if (hfile) return hfile;
      }
      //otherwise try $PWD/hsimple.root
      if (!gSystem->AccessPathName("hsimple.root",kFileExists)) {
         hfile = TFile::Open("hsimple.root"); //in current dir
         if (hfile) return hfile;
      }
   }
   //no hsimple.root file found. Must generate it !
   //generate hsimple.root in current directory if we have write access
   if (gSystem->AccessPathName(".",kWritePermission)) {
      printf("you must run the script in a directory with write access\n");
      return 0;
   }
   hfile = (TFile*)gROOT->FindObject(filename); if (hfile) hfile->Close();
   hfile = new TFile(filename,"RECREATE","Demo ROOT file with histograms");

   // Create some histograms, a profile histogram and an ntuple
   TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4);
   hpx->SetFillColor(48);
   TH2F *hpxpy = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
   TProfile *hprof = new TProfile("hprof","Profile of pz versus px",100,-4,4,0,20);
   TNtuple *ntuple = new TNtuple("ntuple","Demo ntuple","px:py:pz:random:i");

   gBenchmark->Start("hsimple");

   // Create a new canvas.
   TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
   c1->SetFillColor(42);
   c1->GetFrame()->SetFillColor(21);
   c1->GetFrame()->SetBorderSize(6);
   c1->GetFrame()->SetBorderMode(-1);


   // Fill histograms randomly
   TRandom3 random;
   Float_t px, py, pz;
   const Int_t kUPDATE = 1000;
   for (Int_t i = 0; i < 25000; i++) {
      random.Rannor(px,py);
      pz = px*px + py*py;
      Float_t rnd = random.Rndm(1);
      hpx->Fill(px);
      hpxpy->Fill(px,py);
      hprof->Fill(px,pz);
      ntuple->Fill(px,py,pz,rnd,i);
      if (i && (i%kUPDATE) == 0) {
         if (i == kUPDATE) hpx->Draw();
         c1->Modified();
         c1->Update();
         if (gSystem->ProcessEvents())
            break;
      }
   }
   gBenchmark->Show("hsimple");

   // Save all objects in this file
   hpx->SetFillColor(0);
   hfile->Write();
   hpx->SetFillColor(48);
   c1->Modified();
   return hfile;

// Note that the file is automatically close when application terminates
// or when the file destructor is called.
}
Ejemplo n.º 22
0
void makePlot(char* canv)
{
	t->SetBranchAddress("LM_PX1", &intree.LM_PX1);
	t->SetBranchAddress("LM_PX2", &intree.LM_PX2);
	t->SetBranchAddress("LM_PY1", &intree.LM_PY1);
	t->SetBranchAddress("LM_PY2", &intree.LM_PY2);
	t->SetBranchAddress("LM_P2_Integral", &intree.LM_P2_Integral);
	t->SetBranchAddress("time", &intree.timeline);
	t->Print();

	if(entries<=0)
		entries = t->GetEntries();

	char title[100]=0;
	sprintf(title,"%s runs 1100-1107",canv);
	TProfile *prof = new TProfile(title,title,24,0,entries);
	TProfile *prof1 = new TProfile(title,title,24,0,entries);
	TProfile *prof2 = new TProfile(title,title,24,0,entries);

	/**************************************
     * read entries
     **************************************
    */
	Double_t *ratio = new Double_t[entries];
	Double_t *parmean = new Double_t[entries];
	Double_t *p1 = new Double_t[entries];
	Double_t *p2 = new Double_t[entries];

	for (int j = 0; j < entries; ++j){
		gSystem->Sleep (sleep);
		t->GetEntry(j);
		ratio[j] = intree.LM_PY1/intree.LM_PY2;
		p1[j] = intree.LM_PY1;
		p2[j] = intree.LM_PY2;
		//cout<<"entry "<<j<<" peak2 "<<intree.LM_PY2<<endl;
	}

	Double_t mean = TMath::Mean(entries,ratio);
	Double_t mean1 = TMath::Mean(entries,p1);
	Double_t mean2 = TMath::Mean(entries,p2);
	for (int j = 0; j < entries; ++j){
		prof->Fill(j,(ratio[j]/mean-1)*100);
		prof1->Fill(j,(p1[j]/mean1-1)*100);
		prof2->Fill(j,(p2[j]/mean2-1)*100);
	}

	TCanvas *c1 = new TCanvas(canv,"frascatirun",900,700);
	c1->cd();

    char axisXname[100];
	sprintf(axisXname,"Time (Entries) (total: %i)",entries);
	prof->SetXTitle(axisXname);
	prof->SetYTitle("Variation (%)");
	prof->SetMaximum(1);
	prof->SetMinimum(-1);
	prof->SetMarkerColor(4);
	prof->SetMarkerSize(1);
	prof->SetMarkerStyle(8);
	prof->SetStats(kFALSE);
	prof->Draw();

	prof1->SetMarkerColor(5);
	prof1->SetMarkerSize(1);
	prof1->SetMarkerStyle(6);
	prof1->Draw("same");

	prof2->SetMarkerColor(1);
	prof2->SetMarkerSize(1);
	prof2->SetMarkerStyle(7);
	prof2->Draw("same");

/*	TLegend leg = new TLegend(0.1,0.7,0.48,0.9);
	leg->SetHeader("The Legend Title");
	leg->AddEntry(h1,"Histogram filled with random numbers","f");
	leg->AddEntry("f1","Function abs(#frac{sin(x)}{x})","l");
	leg->AddEntry("gr","Graph with error bars","lep");
	leg->Draw("same");
*/
}
Ejemplo n.º 23
0
void Dcurvature(const char *chargechoice = "plus", double ptmin=20){

  TString sign=chargechoice;

  gStyle->SetPalette(1);
  gStyle->SetOptStat("e");

//  double ptmin=20;
  double ptmax=200;
  double etamax=2.1; 
  int ptbins=(ptmax-ptmin)/10;
  double ptbinwidth=(ptmax-ptmin)/ptbins;
  int etabins=21;
  int phibins=21;


  TProfile3D *khistptetaphi = new TProfile3D("DeltaCurv(pt,eta,phi)","DeltaCurv(pt,eta,phi) "+sign,ptbins,ptmin,ptmax,etabins,-etamax,etamax,phibins,-3.14,3.14);
  khistptetaphi->GetXaxis()->SetTitle("Pt");
  khistptetaphi->GetYaxis()->SetTitle("Eta");
  khistptetaphi->GetZaxis()->SetTitle("Phi");

  TProfile2D *khistpteta = new TProfile2D("DeltaCurv(pt,eta)","DeltaCurv(pt,eta) "+sign,ptbins,ptmin,ptmax,etabins,-etamax,etamax);
  khistpteta->GetXaxis()->SetTitle("Pt");
  khistpteta->GetYaxis()->SetTitle("Eta");
  TProfile2D *khistptphi = new TProfile2D("DeltaCurv(pt,phi)","DeltaCurv(pt,phi) "+sign,ptbins,ptmin,ptmax,phibins,-3.14,3.14);
  khistptphi->GetXaxis()->SetTitle("Pt");
  khistptphi->GetYaxis()->SetTitle("Phi");

  TProfile *khistpt = new TProfile("DeltaCurv(pt)","DeltaCurv(pt) "+sign,ptbins,ptmin,ptmax);
  khistpt->GetXaxis()->SetTitle("Pt");
  khistpt->SetAxisRange(-0.001,0.001,"Y");
  TProfile *khisteta = new TProfile("DeltaCurv(eta)","DeltaCurv(eta) "+sign,etabins,-etamax,etamax);
  khistpt->GetXaxis()->SetTitle("Eta");
  TProfile *khistphi = new TProfile("DeltaCurv(phi)","DeltaCurv(phi) "+sign,phibins,-3.14,3.14);
  khistpt->GetXaxis()->SetTitle("Phi");

  TObjArray *khistptbins= new TObjArray();
  for (int i=0; i<ptbins; i++) {
    TString name="DeltaCurv(eta,phi), pt bin ";
    name+=int(ptmin+i*(ptmax-ptmin)/ptbins);
    name+=TString(", charge ")+sign;
    TProfile2D *ist = new TProfile2D(name.Data(),name.Data(),phibins,-3.14,3.14,etabins,-etamax,etamax);
    ist->SetAxisRange(-0.002,0.002,"Z");
    khistptbins->Add(ist);
  }

  TFile *f = new TFile("RecoRoutines_Z-selection_ZJets_TuneZ2_7TeV_alpgen_tauola.rew8.corr1.root","read");

  TTree *tree;

  f->GetObject("SingleMuPtScale/"+sign+"muonstree",tree);

  Double_t MCPt;
  Double_t MCEta;
  Double_t MCPhi;
  Double_t RecoPt;
  Double_t RecoEta;
  Double_t RecoPhi;
  Double_t EvWeight;

  tree->SetBranchAddress("RecoPt",&RecoPt);
  tree->SetBranchAddress("RecoEta",&RecoEta);
  tree->SetBranchAddress("RecoPhi",&RecoPhi);
  tree->SetBranchAddress("MCPt",&MCPt);
  tree->SetBranchAddress("MCEta",&MCEta);
  tree->SetBranchAddress("MCPhi",&MCPhi);
  tree->SetBranchAddress("EvWeight",&EvWeight);

  long nentries = tree->GetEntriesFast();

  for (int i=0; i<nentries; i++){
    tree->GetEntry(i);
    if (RecoPt<ptmin || RecoPt>ptmax || RecoEta<-etamax || RecoEta>etamax) continue;
    double quantity=(MCPt-RecoPt)/MCPt/RecoPt;
    khistptetaphi->Fill(RecoPt,RecoEta,RecoPhi,quantity,EvWeight);
    khistpteta->Fill(RecoPt,RecoEta,quantity,EvWeight);
    khistptphi->Fill(RecoPt,RecoPhi,quantity,EvWeight);
    ((TProfile2D*)(khistptbins->At(int((RecoPt-ptmin)/ptbinwidth))))->Fill(RecoPhi,RecoEta,quantity,EvWeight);
    khistpt->Fill(RecoPt,quantity,EvWeight);
    khisteta->Fill(RecoEta,quantity,EvWeight);
    khistphi->Fill(RecoPhi,quantity,EvWeight);
  }



  TCanvas *c1 = new TCanvas();
  khistptetaphi->Draw("BOX");

  TCanvas *c2 = new TCanvas();
  c2->Divide(2,1);
  c2->cd(1);
  khistpteta->Draw("BOX");
  c2->cd(2);
  khistptphi->Draw("BOX");

  TCanvas *c2b = new TCanvas();
  c2b->Divide(3,1);
  c2b->cd(1);
  khistpt->Draw();
  c2b->cd(2);
  khisteta->Draw();
  c2b->cd(3);
  khistphi->Draw();

  TCanvas *c3 = new TCanvas();
  c3->Divide(int(sqrt(ptbins))+1,int(sqrt(ptbins)));
  for (int i=0;i<ptbins;i++) { c3->cd(i+1); ((TProfile2D*)(khistptbins->At(i)))->Draw("SURF1 PSR Z");}




  TProfile *khistcorrpt = new TProfile("DeltaCurv(pt)","DeltaCurv(pt) "+sign,ptbins,ptmin,ptmax);
  khistcorrpt->GetXaxis()->SetTitle("Pt");
  khistcorrpt->SetAxisRange(-0.001,0.001,"Y");
  TProfile *khistcorreta = new TProfile("DeltaCurv(eta)","DeltaCurv(eta) "+sign,etabins,-etamax,etamax);
  khistcorrpt->GetXaxis()->SetTitle("Eta");
  TProfile *khistcorrphi = new TProfile("DeltaCurv(phi)","DeltaCurv(phi) "+sign,phibins,-3.14,3.14);
  khistcorrpt->GetXaxis()->SetTitle("Phi");

  // correction
   for (int i=0; i<nentries; i++){
    tree->GetEntry(i);
    if (RecoPt<ptmin || RecoPt>ptmax || RecoEta<-etamax || RecoEta>etamax) continue;
    double newpt=RecoPt+RecoPt*RecoPt*khistptetaphi->GetBinContent(khistptetaphi->FindBin(RecoPt,RecoEta,RecoPhi));
    double quantity=(MCPt-newpt)/MCPt/newpt;
    khistcorrpt->Fill(RecoPt,quantity,EvWeight);
    khistcorreta->Fill(RecoEta,quantity,EvWeight);
    khistcorrphi->Fill(RecoPhi,quantity,EvWeight);
   }

   TCanvas *corrc2b = new TCanvas();
  corrc2b->Divide(3,1);
  corrc2b->cd(1);
  khistcorrpt->Draw();
  corrc2b->cd(2);
  khistcorreta->Draw();
  corrc2b->cd(3);
  khistcorrphi->Draw();


khistptetaphi->SetName("ist");
khistptetaphi->SaveAs("mcptbinscorrectionfactors.C");

}
Ejemplo n.º 24
0
void AnalysisBase::findBeamRegionAndAlign(int iPass){

  cout << "==================================================================" << endl;
  cout << "findBeamRegionAndAlign(): Determining Fiducial Region, Pass = "******"==================================================================" << endl;

  double dxWindow = dxWin;
  if(iPass == 1) dxWindow = 1000.0;
  if(iPass == 2) dxWindow = 1.0;

  TH1F* hthx = new TH1F("hthx","#theta_{X}",1000,-5.0,5.0);
  TH1F* hthy = new TH1F("hthy","#theta_{Y}",1000,-5.0,5.0);
  TH1F* hx = new TH1F("hx","Y position of matched cluster",800,-40.0,40.0);
  TH1F* hxdut = new TH1F("hxdut","Y position of matched cluster",800,-40.0,40.0);
  TH1F* hs = new TH1F("hs","Strip number of matched cluster",512,0,512.0);
  TH1F* hy = new TH1F("hy","Y position of matched cluster",800,-10.0,10.0);
  TH1F* hw = new TH1F("hw","#DeltaX",20000,-100.0,100.0);
  TH1F* hn = new TH1F("hn","#DeltaX",4000,-2.0,2.0);
  TH1F* hnn = new TH1F("hnn","#DeltaX",400,-0.2,0.2);
  TH2F* hxy = new TH2F("hxy","Y_{trk} vs X_{trk}, with cluster",640,-8,8.0,640,-8,8);
  TProfile *ht = new TProfile("ht","Cluster Charge vs TDC time",12,0,12,100,1000);
  TProfile *hzrot = new TProfile("hzrot","#DeltaX vs Y_{trk} at DUT",1600,-8,8,-1.0,1.0);
  TH2F* hca = new TH2F("hca","Y_{trk} vs X_{trk}, with found cluster",160,-8,8.0,320,-8,8);
  TH2F* hcf = new TH2F("hcf","Y_{trk} vs X_{trk}, with found cluster",160,-8,8.0,320,-8,8);
  
  hca->Sumw2();
  hcf->Sumw2();
  
  int istrip;
  double nomStrip=0, detStrip = 0;
  Long64_t nbytes = 0, nb = 0;
  Int_t nentries = fChain->GetEntriesFast();
  for (Long64_t jentry=0; jentry<max(nentries,200000);jentry++) {
    Long64_t ientry = LoadTree(jentry);
    //if(jentry%1000==0) cout << "At entry = " << jentry << endl;
    
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(n_tp3_tracks > 1) continue;      

    for(int k=0; k<n_tp3_tracks; k++){
      bool goodTime = (clustersTDC >= tdcLo && clustersTDC < tdcHi);
      goodTime = clustersTDC>1.0;
      if(!goodTime) continue;
      double x_trk = vec_trk_tx->at(k)*z_DUT+vec_trk_x->at(k);
      double y_trk = vec_trk_ty->at(k)*z_DUT+vec_trk_y->at(k);

      transformTrackToDUTFrame(k, x_trk, y_trk, nomStrip, detStrip);

      double tx = 1000*vec_trk_tx->at(k);
      double ty = 1000*vec_trk_ty->at(k);

      double x_trk0 = x_trk;

      for(int j=0; j<min(clusterNumberPerEvent,10); j++){
        if(clustersPosition[j] < 0.1) continue;
        if(polarity*clustersCharge[j] < kClusterChargeMin) continue;
        bool goodHit = (clustersPosition[j]>iLo && clustersPosition[j]<iHi);
        istrip = clustersSeedPosition[j];
        if(badStrips[istrip]==0) continue; // exclude bad strips

        double x_dut = getDUTHitPosition(j);

        x_trk = x_trk0;

        double dx = x_dut - x_trk;
        hn->Fill(dx);
        hnn->Fill(dx);

        hca->Fill(x_trk,y_trk);
        if(fabs(dx)<dxWindow || iPass==1) {
          if(goodHit) {
            hx->Fill(x_trk);
            hxdut->Fill(x_dut);
            hs->Fill(clustersPosition[j]);
            hy->Fill(y_trk);
            hthx->Fill(tx);
            hthy->Fill(ty);
            hw->Fill(dx);     
            hxy->Fill(x_trk,y_trk);
            ht->Fill(clustersTDC+0.1,polarity*clustersCharge[j]);
            hzrot->Fill(y_trk,dx);
            hcf->Fill(x_trk,y_trk);
          } 
        }
      }
    }
  }

  //hnn->Draw();

  if(iPass==4) {
    findCutoutRegion(hcf);
  }else {  

    float xmin=0,xmax=0,ymin=0,ymax=0,txmin=0,txmax=0,tymin=0,tymax=0;

    getRange(hthx,txmin,txmax,0.05,2);
    getRange(hthy,tymin,tymax,0.05,2);
    //getRange(hx,xmin,xmax,0.05,2);
    getRange(hy,ymin,ymax,0.2,2);

    // Use strip numbers to get xMin and xMax, since dead strips make holes in xpos plot
    xmin = getEdgePosition(iHi);
    xmax = getEdgePosition(iLo);
    
    xMin = xmin;
    xMax = xmax;
    yMin = ymin;
    yMax = ymax;
    txMin = txmin;
    txMax = txmax;
    tyMin = tymin;
    tyMax = tymax;

    // 
    
    float xlo = 0, xhi=0;
    if(iPass==1) getRange(hw,xlo,xhi,0.1,1);
    if(iPass==2) getRange(hn,xlo,xhi,0.1,1);
    if(iPass==3) getRange(hn,xlo,xhi,0.1,1);
    if(iPass>3) getRange(hnn,xlo,xhi,0.2,1);
    double XOFF = (xhi + xlo)/2.0;
    xOff = xOff - XOFF;
    double x_ave = (xMax + xMin)/2.0;
    double y_ave = (yMax + yMin)/2.0;
    xGloOff = xGloOff - x_ave;
    if(iPass<=4) yGloOff = yGloOff - y_ave;
    
    // Check/correct for z rotation
    if(iPass==3 && correctForZRotation){
      cout << "Checking for z-rotation" << endl;
      TF1* p1 = new TF1("p1","[0]+[1]*x",yMin,yMax);
      p1->SetParameters(0.0,0.0001);
      hzrot->Fit(p1,"0R");
      double rz = p1->GetParameter(1);
      cout << "=======================================================================" << endl;
      cout << "==> Updating z rotation angle from " << Rz << " to " << Rz-rz << " mrad" << endl;    
      Rz = Rz - rz;
      delete p1;
    }
    
    
    float lo = 0, hi = 0;
    getTDCBins(ht,lo,hi);
    tdcLo = lo;
    tdcHi = hi;
    cout << "=================================================================" << endl;
    cout << "====> TDC Range updated to be from " << tdcLo << " -- " << tdcHi << std::endl;
    cout << "=================================================================" << endl;
    cout << "====> Fiducial regions, xLo, xHi (Strip numbers) = " << iLo << " " << iHi << endl;
    cout << "====> Fiducial regions, xLo, xHi (pos in mm) = " << xMin << " " << xMax << " mm " << endl;
    cout << "====> Fiducial regions, yLo, yHi (pos in mm) = " << yMin << " " << yMax << " mm " << endl;
    cout << "====> Fiducial regions, thxLo, thxHi (pos in mrad) = " << txMin << " " << txMax << " mrad" << endl;
    cout << "====> Fiducial regions, thyLo, thxHi (pos in mrad) = " << tyMin << " " << tyMax << " mrad" << endl;
    cout << "=================================================================" << endl;   
    cout << "====> Shifting sensor by dX = " << XOFF << " mm " << ", new xOff = " << xOff << endl;
    cout << "====> Global X, Y shifts: " << x_ave << " " << y_ave << endl;
    cout << "====> New global x,y = " << xGloOff << " " << yGloOff << endl;
    
  }
  
  //if(iPass==1) hw->Draw();  // for debugging   
  //if(iPass==2) hy->Draw();

  //return;
  

  delete hxdut;
  delete hthx;
  delete hthy;
  delete hx;
  delete hy;
  delete hxy;
  delete hw;
  delete hn;
  delete hnn;
  delete hs;
  delete ht;
  delete hzrot;
  delete hcf;
  delete hca;
  
   
  return;
  

}
Ejemplo n.º 25
0
Double_t CalibTree::Loop(int loop) {
  char name[500];
  bool debug=false;
  if (fChain == 0) return 0;
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;
  std::map<unsigned int, std::pair<double,double> >SumW;
  std::map<unsigned int, unsigned int >nTrks;
  unsigned int mask(0xFF80), ntrkMax(0);
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
  //  for (Long64_t jentry=0; jentry<1000;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(debug) std::cout << "***Entry (Track) Number : " << ientry 
			<< " p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal 
			<< "/" << t_eMipDR << "/" << (*t_DetIds).size() 
			<< std::endl;
    if (goodTrack()) {
      if (loop == 0) hprof_ndets->Fill(t_ieta, (*t_DetIds).size());
      double Etot=0.0;
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	double hitEn=0.0;
        unsigned int detid = (*t_DetIds)[idet] & mask;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	Etot += hitEn;
      }
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	unsigned int detid = (*t_DetIds)[idet] & mask;
	double hitEn=0.0;
	if (debug) std::cout << "idet " << idet << " detid/hitenergy : " 
			     << std::hex << (*t_DetIds)[idet] << ":" << detid
			     << "/" << (*t_HitEnergies)[idet] << std::endl;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	double Wi = hitEn/Etot;
	double Fac = (Wi* t_p) / Etot;
	if( SumW.find(detid) != SumW.end() ) {
	  Wi  += SumW[detid].first;
	  Fac += SumW[detid].second;
	  SumW[detid] = std::pair<double,double>(Wi,Fac); 
	  nTrks[detid]++;
	} else {
	  SumW.insert( std::pair<unsigned int, std::pair<double,double> >(detid,std::pair<double,double>(Wi,Fac)));
	  nTrks.insert(std::pair<unsigned int,unsigned int>(detid, 1));
	}
	if (nTrks[detid] > ntrkMax) ntrkMax = nTrks[detid];
      }
    }
  }
  
  std::map<unsigned int, std::pair<double,double> >::iterator SumWItr = SumW.begin();
  unsigned int kount(0), mkount(0);
  double       sumfactor(0);
  double       dets[150], cfacs[150], wfacs[150], nTrk[150];
  unsigned int ntrkCut = ntrkMax/10;
  for (; SumWItr != SumW.end(); SumWItr++) {
    if (debug) 
      std::cout<< "Detid/SumWi/SumFac : " << SumWItr->first << " / "
	       << (SumWItr->second).first << " / " << (SumWItr->second).second
	       << std::endl;
    unsigned int detid = SumWItr->first;
    double factor = (SumWItr->second).second / (SumWItr->second).first;

    if(nTrks[detid]>ntrkCut) {
      if (factor > 1) sumfactor += (1-1/factor);
      else            sumfactor += (1-factor);
      mkount++;
    }
    if (Cprev.find(detid) != Cprev.end()) {
      Cprev[detid] *= factor;
      cfacs[kount] = Cprev[detid];
    } else {
      Cprev.insert( std::pair<unsigned int, double>(detid, factor) );
      cfacs[kount] = factor;
    }
    int ieta = (detid>>7) & 0x3f;
    int zside= (detid&0x2000) ? 1 : -1;
    int depth= (detid>>14)&0x1F;
    wfacs[kount]= factor;
    dets[kount] = zside*(ieta+0.1*(depth-1));
    nTrk[kount] = nTrks[detid];
    kount++;
  }
  TGraph *g_fac, *g_fac2, *g_nTrk;
  g_fac = new TGraph(kount, dets, cfacs); 
  sprintf(name, "Cfacs_detid_it%d", loop);
  fout->WriteTObject(g_fac, name);

  g_fac2 = new TGraph(kount, dets, wfacs); 
  sprintf(name, "Wfacs_detid_it%d", loop);
  fout->WriteTObject(g_fac2, name);

  g_nTrk = new TGraph(kount, dets, nTrk); 
  if (loop==0) fout->WriteTObject(g_nTrk, "nTrk_detid");

  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, double>::iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (CprevItr=Cprev.begin(); CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int ieta = (detid>>7) & 0x3f;
    int zside= (detid&0x2000) ? 1 : -1;
    int depth= (detid>>14)&0x1F;
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") ( nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second << std::endl;
  }
  double mean = (mkount > 0) ? (sumfactor/mkount) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << mkount << ":"
	    << kount << " DetIds" << std::endl;
  return mean;
}
Ejemplo n.º 26
0
void analisi_tree_1hit(){ //faccio gli istogrammi dal Tree T creato nel file CheckESD.C
  gROOT->Reset();
  gStyle->SetOptStat(0012);
  gStyle->SetOptFit(0111);

  Bool_t kCal=kFALSE;

  TFile *fcal = TFile::Open("calibration.root");
  TProfile *hCalX;
  TProfile *hCalZ;
  if(fcal){
    kCal=kTRUE;
    hCalX = (TProfile *) fcal->Get("hCalX");
    hCalZ = (TProfile *) fcal->Get("hCalZ");
  }
  else{
    hCalX= new TProfile("hCalX","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
    hCalZ= new TProfile("hCalZ","z alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  }

  // check alignment
  TProfile *hx = new TProfile("hx","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  TProfile *hz = new TProfile("hz","z alignement per strip;# strip;#DeltaZ (cm)",1700,0,1700);
  
  // definire istogrammi (ricordarsi di fare il write nel file successivamente)
  //TH1F *hdeltat = new TH1F("hdeltat","inside the pad (cl_{1}) - cluster along x;t_{1} - t_{2} (ps)",400,-500,500);
  //TH1F *hdeltax = new TH1F("hdeltax","inside the pad (cl_{1}) - cluster along x;#Deltax_{1} - #Deltax_{2} (cm)",100,-10,10);
  TH1F *hch = new TH1F("hch","inside the pad (cl_{1}) - cluster along x;ch_{1} - ch_{2}",500,0,500);
  //TH2F *pxt = new TH2F("pxt","inside the pad (cl_{1}) - cluster along x ;t_{1} - t_{2} (ps);cl_{1} #Deltax (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //TH2F *pzt = new TH2F("pzt","inside the pad (cl_{1}) - cluster along z ;t_{1} - t_{2} (ps);cl_{1} #Deltaz (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //CFC:Istogramma numero cluster(qua coincidono con le hit)
  //TH1F *hnc = new TH1F("hnc","Number of Hits",12,0.,12.);
  //Istogramma  tempi TOF
  TH1F *ht1 = new TH1F("ht1","TOF's Time ",41,0.,30000.);
  
  //Istogramma 1D per i residui
  TH1F *hresx1 = new TH1F("hresx1","Residui x1",100,-10.,10.);
  TH1F *hresz1 = new TH1F("hresz1","Residui z1",100,-10.,10.);
  TH1F *hresdist1 = new TH1F("hresdist1","Residui sqrt(x1^2+z1^2)",100,-10.,10.);
  
  //Istogramma 2D per i residui
  TH2F *h2resxz1 = new TH2F("h2resxz1" , "Residui dx1 e dz1", 100, -4. , 4. , 100 , -4. , 4.);
  
  //Istogramma tempi meno tempi attesi
  TH1F *ht1_texp = new TH1F("ht1_texp","",100,-2000.,2000.);
  TH1F *ht1_texptot = new TH1F("ht1_texptot","",100,-2000.,2000.);
  
  //TH1F *hexp_time_pi = new TH1F("hexp_time_pi","hexp_time_pi",1000,0.,30000.);
  
  TProfile *hprofx  = new TProfile("hprofx","Profile t1-t_exp_pi vs dx1",26, -2.,2.);
  TProfile *hprofxcorr  = new TProfile("hprofxcorr","Profile t1-t_exp_pi corr vs dx1",26, -2.,2.);
  
  TProfile *hprofz  = new TProfile("hprofz","Profile t1-t_exp_pi vs dz1",26, -3.,3.);
  
  TProfile *hprofd=new TProfile("hprofd","Profile t1-t_exp_pi vs d",26, 0.,4.);
  
  TH1F *htbest = new TH1F("htbest","htbest",100,-2000.,2000.);
  
  TH1F *htcorrtw= new TH1F("htcorrtw","htcorrtw",100,-2000.,2000.);
  
  //TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",30,-10.25.,10.25,50,-10.75.,10.75.);
  //TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",30,-10.25.,10.25,50,-10.75.,10.75.);
  TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",20,-1.25,1.25,10,-1.75,1.75);
  TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",20,-1.25,1.25,10,-1.75,1.75);
  
  //Istogramma 2D distanza eff vs delay time
  TH2F *h2t1_texp_deff= new TH2F("h2t1_texp_deff" , "Delay time 0 vs deff", 50, 0. , 10.,100,-400.,400.);
  TH2F *h2t1_texp_deff_tw= new TH2F("h2t1_texp_deff_tw" , "Delay time 0 corr tw vs deff", 50, 0. , 10.,100,-400.,400.);
  
  TProfile *hprofdeff=new TProfile("hprofdeff","Profile t1-t_exp_pi vs deff",50, -3.,10.);
  
  // Utilizzo TOT.
  TH2F *h2t1_texp_TOT= new TH2F("h2t1_texp_TOT" , "Delay time vs TOT", 50, 0. , 100.,100,-400.,400.);
  TProfile *hproft1_texp_TOT = new TProfile("hproft1_texp_TOT","Profile t1-t_exp_pi vs TOT",50, 0. , 100.);
  TH2F *h2t1_deff_TOT= new TH2F("h2t1_deff_TOT" , "deff vs TOT", 50, 0. , 100.,50, 0. , 10.);
  TH2F *h2t1_TOT_deff= new TH2F("h2t1_TOT_deff" , "TOT vs deff",50, 0. , 10., 50, 0. , 100.);
  
  
  TFile *f = new TFile("AnalysisResults.root");
  TTree *T = (TTree*)f->Get("T"); //in generale . (e non freccia) se Tfile è un oggetto e NON un puntatore(*)
  
  
  //Varibili tree "T"
  //Int_t nevento;
  //Int_t ntracks;
  Int_t ncluster;
  Float_t tempo[100];//con start time sottratto
  Float_t DeltaX[100];
  Float_t DeltaZ[100];

  Int_t ChannelTOF[100];
  Float_t impulso_trasv;
  Float_t exp_time_pi[100];
  Float_t L[100];
  Float_t TOT[100];
  Float_t res[3];
  Int_t charge;
  Float_t phi,eta;
  Float_t secAngle;
  Float_t cval[5];
  Float_t thetay;
  Float_t StartTime,StartTimeRes;
  Float_t z;
  
  //T->Branch("nevento",&nevento,"nevento/I");
  //T->SetBranchAddress("ntracks",&ntracks);
  T->SetBranchAddress("ncluster",&ncluster);
  T->SetBranchAddress("tempo",tempo);
  T->SetBranchAddress("DeltaX",DeltaX);
  T->SetBranchAddress("DeltaZ",DeltaZ);
  T->SetBranchAddress("ChannelTOF",ChannelTOF);
  T->SetBranchAddress("impulso_trasv",&impulso_trasv);
  T->SetBranchAddress("exp_time_pi",exp_time_pi);
  T->SetBranchAddress("L",L);
  T->SetBranchAddress("TOT",TOT);
  T->SetBranchAddress("res",res);
  T->SetBranchAddress("charge",&charge);
  T->SetBranchAddress("phi",&phi);
  T->SetBranchAddress("eta",&eta);
  T->SetBranchAddress("secPhi",&secAngle);
  T->SetBranchAddress("cval",cval);
  T->SetBranchAddress("thetay",&thetay);
  T->SetBranchAddress("StartTime",&StartTime);
  T->SetBranchAddress("StartTimeRes",&StartTimeRes);
  
  
  Int_t nentries = (Int_t)T->GetEntries();
  
  for(Int_t i=0;i<nentries;i++) {
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      
      if(impulso_trasv>1.3){
	hx->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	hz->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);

	if(!kCal){
	  hCalX->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	  hCalZ->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);	  
	}

	h2resxz1->Fill(DeltaX[0],DeltaZ[0]);
	h2resxz1->GetXaxis()->SetTitle("Dx1 (cm)");
	h2resxz1->GetYaxis()->SetTitle("Dz1 (cm)");
	
	hresx1->Fill(DeltaX[0]);
	hresx1->GetXaxis()->SetTitle("Dx1 (cm)");
	
	hresz1->Fill(DeltaZ[0]);
	hresz1->GetXaxis()->SetTitle("Dz1 (cm)");
	
	hresdist1->Fill(sqrt(DeltaX[0]*DeltaX[0]+DeltaZ[0]*DeltaZ[0]));
	hresdist1->GetXaxis()->SetTitle("sqrt(Dx^2+Dz^2) (cm)");
      }

      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	//if( TMath::Abs(DeltaZ[0])<1.75){
	
	
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  if(TMath::Abs(DeltaX[0])<1.5){
	    //if((ChannelTOF[0]/48)%2==0){z=1.75+DeltaZ[0];}
	    //if((ChannelTOF[0]/48)%2 == 1){z=1.75-DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2 == 1){z= -DeltaZ[0];}
	    Float_t w=tempo[0]- exp_time_pi[0];
	    h2dxdzt1_texp->Fill(DeltaX[0],z, w);
	    h2dxdzt1_texp_dummy->Fill(DeltaX[0],z);
	    
	    if( TMath::Abs(DeltaZ[0])<1.75 && TMath::Abs(DeltaX[0])<1.25){ //sto selezionando che il pad matchato sia dove passa la traccia, poichè altrimenti nel grafico con d e delay time vi sarebbero degli effetti di bordo
			  
	      Float_t t1=tempo[0];
	      ht1->Fill(t1);
	      ht1->GetXaxis()->SetTitle("t1(ps)");
	      
	      //cout<<(ChannelTOF[0]/48)%2<<endl;
	      
	      
	      Float_t d;
	      
	      if((ChannelTOF[0]/48)%2 == 0){
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75+DeltaZ[0])*(1.75+DeltaZ[0])); //da quello che ho capito il pad 0 è quello in alto quindi ha punto d raccolta in alto
		/*
		  if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96)) //if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  {
		  cout<<"ciao, io ,pad 0, sono quello sopra"<<endl;
		  }
		*/
	      }
	      if((ChannelTOF[0]/48)%2 == 1) {
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75-DeltaZ[0])*(1.75-DeltaZ[0])); //da quello che ho capito il pad 1 è quello in basso quindi ha punto d raccolta in basso
		/*//if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  
		if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96))
		{
		cout<<"ciao, io ,pad 1, sono quello sopra"<<endl;
		}
		*/
	      }
	      	      
              Float_t res1 = DeltaX[0]*DeltaX[0] + DeltaZ[0]*DeltaZ[0];
	      
              //Float_t posx = (DeltaX[0])*(ChannelTOF[0]-ChannelTOF[1]);
              
	      // hdeltax->Fill(posx);
              //hdeltax->GetXaxis()->SetTitle("posx (cm)");
	      //
	      //              pxt->Fill(tempo[0], DeltaX[0]);
	      //              pxt->GetXaxis()->SetTitle("t (cm)");
	      //              pxt->GetYaxis()->SetTitle("dx (cm)");
	      
              
	      //              pzt->Fill(tempo[0], DeltaZ[0]);
	      //              pzt->GetXaxis()->SetTitle("t(cm)");
	      //              pzt->GetYaxis()->SetTitle("Dz1 (cm)");
	      
              hch->Fill(ChannelTOF[0]);
              hch->GetXaxis()->SetTitle("ch");
	      
              Float_t tw1=tempo[0]- exp_time_pi[0];
	      
              ht1_texp->Fill(tw1);
              ht1_texp->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      //cerco correlazione tra TOT e delay time
              h2t1_texp_TOT->Fill(TOT[0],tw1);
              h2t1_texp_TOT->GetXaxis()->SetTitle("TOT ");
              h2t1_texp_TOT->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
              hproft1_texp_TOT->Fill(TOT[0],tw1 ,1);
              hproft1_texp_TOT->GetXaxis()->SetTitle("TOT");
              hproft1_texp_TOT->GetYaxis()->SetTitle("t_{0}-t_{exp #pi} (ps)");
	      
	      /////////////////////PROFILE  1
	      
              //riempio istogrammma, poi lo fitto fuori dal loop
	      
	      //               hprofx->Fill(DeltaX[0],tw1 ,1);
	      //               hprofx->GetXaxis()->SetTitle("dx (cm)");
	      //               hprofx->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      //        
	      //               hprofz->Fill(DeltaZ[0],tw1 ,1);
	      //               hprofz->GetXaxis()->SetTitle("dz (cm)");
	      //               hprofz->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      hprofd->Fill(d,tw1 ,1);
	      hprofd->GetXaxis()->SetTitle("d (cm)");
	      hprofd->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      
	      //}
	    }
	  }
	}
      }
    }
  }
    
  
  h2dxdzt1_texp->Divide(h2dxdzt1_texp_dummy);
  h2dxdzt1_texp->SetOption("LEGO2");
  h2dxdzt1_texp->GetXaxis()->SetTitle("dx (cm)");
  h2dxdzt1_texp->GetYaxis()->SetTitle("dz (cm)");
  
  //Double_t par[0]=0;
  //Double_t par[1]=0;
  
  TF2 *myfunc=new TF2("myfunc"," [0] * sqrt(x*x+[1]*[1]*(1.75+y)*(1.75+y))+[2]", -1.25,1.25,-1.75,1.75);
  myfunc->SetParameter(1,0.5);
  h2dxdzt1_texp->Fit(myfunc,"R");
  Double_t vel1, alfa;
  vel1= pow(myfunc->GetParameter(0),-1);
  alfa= myfunc->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 3d "<<vel1<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }

    if(ncluster == 1) {
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
	    Float_t tw1tot=tempo[0]- exp_time_pi[0];
	    h2t1_texp_deff->Fill(deff,tw1tot);
	    h2t1_texp_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_texp_deff->GetYaxis()->SetTitle("delay time (ps)");
            
	    hprofdeff ->Fill(deff,tw1tot ,1);
	    hprofdeff->GetXaxis()->SetTitle("deff (cm)");
	    hprofdeff->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
            
	    h2t1_deff_TOT->Fill(TOT[0],deff);
	    h2t1_deff_TOT->GetXaxis()->SetTitle("TOT (ps)");
	    h2t1_deff_TOT->GetYaxis()->SetTitle("deff (cm)");
            
	    h2t1_TOT_deff->Fill(deff, TOT[0]);
	    h2t1_TOT_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_TOT_deff->GetYaxis()->SetTitle("TOT (ps)");
	           
	  }
	}
      }
    }
  }
  
  TF1 *fs = new TF1("fs","gaus",-400.,400.);
  h2t1_texp_deff->FitSlicesY(fs);
  TH1D *h2t1_texp_deff_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_1");
  h2t1_texp_deff_1->Draw("same");
  //h2t1_texp_deff_2->Draw("same");
  
  //   TF1 *f1 = new TF1("f1","pol1",0., 2.15);
  //    h2t1_texp_deff_1->Fit("f1","R");
  //    Double_t vel2;
  //    vel2 = pow(f1->GetParameter(1),-1);
  //    cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  TF1 *f1 = new TF1("f1","[0]*TMath::Min(x,1.75)+[1]",0., 2.8); //Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
  h2t1_texp_deff_1->Fit(f1,"R");
  Double_t p0,vel2, offset_tw;
  p0=f1->GetParameter(0);
  vel2= pow(p0,-1);
  offset_tw=f1->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){                   
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
            
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
            
	    if(deff<2.8){
	      Float_t tw1tot=tempo[0]- exp_time_pi[0];
	      ht1_texptot->Fill(tw1tot);
	      ht1_texptot->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      Float_t tw1corrtw=tw1tot-(offset_tw + p0 *TMath::Min(deff,Float_t(1.75)));//Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
	      htcorrtw->Fill(tw1corrtw);
	      htcorrtw->GetXaxis()->SetTitle("t_corr_tw (ps)");
              
	      h2t1_texp_deff_tw->Fill(deff,tw1corrtw);
	      h2t1_texp_deff_tw->GetXaxis()->SetTitle("deff (cm)");
	      h2t1_texp_deff_tw->GetYaxis()->SetTitle("delay time corr_tw (ps)");
	      
	    }
	  }
	}
      }
    }
  }

    
  TF1 *fstw = new TF1("fstw","gaus",-400.,400.);
  h2t1_texp_deff_tw->FitSlicesY(fstw);
  TH1D *h2t1_texp_deff_tw_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_1");
  TH1D *h2t1_texp_deff_tw_2 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_2");
  
  h2t1_texp_deff_tw_1->Draw("same");
  h2t1_texp_deff_tw_2->Draw("same");
  
  //    TF1 *f1 = new TF1("f1","pol1",-1.25,0.5);
  //    //hprofx->GetYaxis()->SetRangeUser(-40.,100.);
  //    hprofx->Fit("f1","R");
  //    Double_t offset_p1,x1_p1;
  //    offset_p1= f1->GetParameter(0);
  //    x1_p1= f1->GetParameter(1);
  
  
  //    for(Int_t i=0;i<nentries;i++)
  //    {
  //        T->GetEntry(i);
  //    for(Int_t ip=0;ip<ncluster;ip++)
  //      tempo[ip] -= StartTime;
  //        if(ncluster == 1)
  //        {
  //        if(impulso_trasv>0.8 && impulso_trasv<1.2) // serve per gli exp time
  //        {
  //                //if( TMath::Abs(DeltaZ[0])<1.75)
  //                //{
  //        if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigmca che sia un pi*/ )
  //        {
  //
  //            //Float_t posx = (DeltaX[0])* dch;
  //            Float_t tw1=tempo[0]- exp_time_pi[0];
  //            
  //            Float_t tw1corr=tw1-(offset_p1 + x1_p1 *DeltaX[0]);
  //            
  //            hprofxcorr->Fill(DeltaX[0],tw1corr,1);
  //            hprofxcorr->GetXaxis()->SetTitle("Dx1 (cm)");
  //            hprofxcorr->GetYaxis()->SetTitle("t1_corr=t1-t_exp_pi corr(ps)");
  //            
  //            htbest->Fill(tw1corr);
  //            htbest->GetXaxis()->SetTitle("t_best=t1_corr(ps)");
  //        
  //        //}
  //        }
  //        }
  //        }
  //    }
  //    
  //    TF1 *f1c = new TF1("f1c","pol1",-1.25,0.5);
  //    hprofxcorr->Fit("f1c","R");
  
  TFile *fo2 = new TFile("output_ist_tree_1hit.root","RECREATE");
  
  hch->Write();
  ht1->Write();
  h2resxz1->Write();
  hresx1->Write();
  hresz1->Write();
  hresdist1->Write();
  //hdeltax->Write();
  //pxt->Write();
  //pzt->Write();
  //hdeltach->Write();
  ht1_texp->Write();
  ht1_texptot->Write();
  //hprofx->Write();
  //hprofz->Write();
  //hprofxcorr->Write();
  //htbest->Write();
  hprofd->Write();
  h2dxdzt1_texp->Write();
  //h2dxdzt1_texp_dummy->Write();
  h2t1_texp_deff->Write();
  h2t1_texp_deff_1->Write();
  //h2t1_texp_deff_2->Write();
  hprofdeff->Write();
  
  htcorrtw->Write();
  
  h2t1_texp_deff_tw->Write();
  h2t1_texp_deff_tw_1->Write();
  h2t1_texp_deff_tw_2->Write();
  h2t1_texp_TOT->Write();
  hproft1_texp_TOT->Write();
  h2t1_deff_TOT->Write();
  h2t1_TOT_deff->Write();
  hx->Write();
  hz->Write();
  fo2->Close();
  
  if(!kCal){
    printf("write calibration\n");
    fcal = new TFile("calibration.root","RECREATE");
    hCalX->Write();
    hCalZ->Write();
    fcal->Close();
  }

  system("say Ehi you, I have done");
}
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEB fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  // By the definition of these corrections, the timing should be zero for the hits in
  // Module 1 or Low eta EE within the valid A/sigma ranges.
  // Earlier data will have positive time due to the gradual timing shifts in the positive direction.
  timeCorrectionEB_ = new TF1("timeCorrectionEB_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Module 1 of run 144011 EB data; 
  timeCorrectionEB_->SetParameters(0.0399144,-1.32993,2.00013,-1.51769,0.407406);
  //coefficients obtained in the interval (-0.5, 2.0)
  //timeCorrectionEB_->SetParameters(0.0544539,-1.51924,2.57379,-2.11848,0.606632);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEB, minHitTimeEB;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEB = 15; // ns
  minHitTimeEB = -15; // ns
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-ebhittimemax") && argc>i+1) maxHitTimeEB = atof(argv[i+1]);
    if (argv[i] == std::string("-ebhittimemin") && argc>i+1) minHitTimeEB = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxSwissCrossNoise (EB): " << maxSwissCrossNoise
    << " maxHitTimeEB: " << maxHitTimeEB << " minHitTimeEB: " << minHitTimeEB                                                                   
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEB";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEB = new TH1F("timingCalibsEB","timingCalibs EB [ns]",2000,-100,100);
  TH1F* calibErrorHistEB = new TH1F("calibErrorEB","timingCalibError EB [ns]",500,0,5);
  calibHistEB->Sumw2();
  calibErrorHistEB->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  TH1F* expectedStatPresHistEB = new TH1F("expectedStatPresEB","Avg. expected statistical precision EB [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEB = new TH2F("expectedStatPresVsObsEB","Expected stat. pres. vs. obs. error on mean each event EB [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEB = new TH1F("expectedStatPresSingleEventEB","Expected stat. pres. each event EB [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();

  TH1F* hitsPerCryHistEB = new TH1F("hitsPerCryEB","Hits used in each crystal;hashedIndex",61200,0,61200);
  TH2F* hitsPerCryMapEB = new TH2F("hitsPerCryMapEB","Hits used in each crystal;i#phi;i#eta",360,1.,361.,172,-86,86);

  TProfile2D* ampProfileMapEB = new TProfile2D("ampProfileMapEB","amp profile map [ADC];i#phi;i#eta",360,1.,361.,172,-86,86);
  TProfile* ampProfileEB = new TProfile("ampProfileEB","Average amplitude in cry [ADC];hashedIndex",61200,0,61200);

  TH1F* sigmaHistEB = new TH1F("sigmaCalibsEB"," Sigma of calib distributions EB [ns]",100,0,1);

  //=============Special Bins for TT and Modules borders=============================
  double ttEtaBins[36] = {-85, -80, -75, -70, -65, -60, -55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86 };
  // double modEtaBins[10]={-85, -65, -45, -25, 0, 1, 26, 46, 66, 86};
  double ttPhiBins[73];
  double modPhiBins[19];
  double timingBins[79];
  double highEBins[11];
  for (int i = 0; i < 79; ++i)
  {
    timingBins[i]=-7.+double(i)*14./78.;
    if (i<73)
    {
      ttPhiBins[i]=1+5*i;
      if ( i < 19) 
      {
        modPhiBins[i]=1+20*i;
        if (i < 11)
        {
          highEBins[i]=10.+double(i)*20.;
        }
      }
    }

  } 
  TH2F* calibMapEB = new TH2F("calibMapEB","time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  calibMapEB->Sumw2();
  TH2F* sigmaMapEB = new TH2F("sigmaMapEB","Sigma of time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  TH2F* calibErrorMapEB = new TH2F("calibErrorMapEB","Error of time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  TProfile2D* calibTTMapEB = new TProfile2D("calibTTMapEB","time calib map EB (TT) [ns];i#phi;i#eta",360/5,ttPhiBins,35, ttEtaBins);

  TDirectory* cryDirEB = gDirectory->mkdir("crystalTimingHistsEB");
  cryDirEB->cd();
  TH1C* cryTimingHistsEB[61200];
  EBDetId det;
  for(int hi=0; hi < 61200; ++hi)
  {
    det = EBDetId::unhashIndex(hi);
    if(det==EBDetId())
      continue;
    string histname = "EB_cryTiming_ieta";
    histname+=intToString(det.ieta());
    histname+="_iphi";
    histname+=intToString(det.iphi());
    cryTimingHistsEB[hi] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
    cryTimingHistsEB[hi]->Sumw2();
  }
  outfile->cd();
  
  cout << "Making calibs...";

  CrystalCalibration* ebCryCalibs[61200];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 61200; ++i)
    ebCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //ebCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEB = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] == -999999) continue; // skip EE clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEB++;
      }
    }
    //debug
    //cout << "Number of EB crys in event: " << numEBcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEB > avgTimeMax || sumTime/numCrysEB < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEB  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EB crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] == -999999) continue; // skip EE clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
        //float cryEt = treeVars_.cryETEB_[cryIndex]; // not in the tree
        //SIC FEB 14,16 2011 - removed E/E9
        //                - spike cleaning done higher up
        float crySwissCrossNoise = treeVars_.xtalInBCSwissCross[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEB;
	float AoLog = log10(Ao/25);

        EBDetId det = EBDetId::unhashIndex(hashedIndex);
        if(det==EBDetId()) // make sure DetId is valid
          continue;

        int ieta = det.ieta();
        int iphi = det.iphi();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEB
          && crySwissCrossNoise < maxSwissCrossNoise
          && cryTime > minHitTimeEB
          && cryTime < maxHitTimeEB
          && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

        // Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEB_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        ebCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);
        //SIC Use when we don't have time_error available
        //ebCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        ampProfileEB->Fill(hashedIndex,cryAmp);
        ampProfileMapEB->Fill(iphi,ieta,cryAmp);
        //if(cryTime > 33 || cryTime < -33)
        //  cout << "Crystal: " << det << " event time is over/underflow: " << cryTime << endl;
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 61200; ++hashedIndex)
  {
    EBDetId det = EBDetId::unhashIndex(hashedIndex);
    if(det==EBDetId())
      continue;
    CrystalCalibration cryCalib = *(ebCryCalibs[hashedIndex]);
    int ieta = det.ieta();
    int iphi = det.iphi();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
      cryTimingHistsEB[hashedIndex]->Fill(timeItr->time,weight);
    }
    cryDirEB->cd();
    cryTimingHistsEB[hashedIndex]->Write();
    outfile->cd();
    hitsPerCryHistEB->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
    hitsPerCryMapEB->Fill(iphi,ieta,cryCalib.timingEvents.size());
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << ieta <<", " << iphi << ", hash: "
                                                                        << hashedIndex
                                                                        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EB\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      calibHistEB->Fill(p1);
      //calibMapEEMFlip->Fill(y-85,x+1,p1);
      calibMapEB->Fill(iphi,ieta,p1);
      calibTTMapEB->Fill(iphi,ieta,p1);
      //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
      //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EBDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << ieta <<", " << iphi << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << ieta <<", " << iphi << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
    }
    //calibsVsErrorsEB->Fill(p1err, p1 > 0 ? p1 : -1*p1);
    calibErrorHistEB->Fill(p1err);
    calibErrorMapEB->Fill(iphi,ieta,p1err);
    sigmaHistEB->Fill(cryCalib.stdDev);
    sigmaMapEB->Fill(iphi,ieta,cryCalib.stdDev);
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EBDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEB.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEB.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EEDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEB->SetXTitle("timingCalib [ns]");
  calibHistEB->Write();
  sigmaHistEB->Write();
  calibErrorHistEB->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEB->Write();
  //eventsEBHist->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //cout << "Writing calibErrorHists" << endl;
  //calibErrorHistEB->Write();

  //cout << "Writing calib maps" << endl;
  sigmaMapEB->Write();
  calibMapEB->Write();
  calibErrorMapEB->Write();
  calibTTMapEB->Write();
  //calibMapEBFlip->SetXTitle("ieta");
  //calibMapEBFlip->SetYTitle("iphi");
  //calibMapEBFlip->Write();
  //calibMapEBPhase->SetXTitle("iphi");
  //calibMapEBPhase->SetYTitle("ieta");
  //calibMapEBPhase->Write();
  
  //Move empty bins out of the way
  //int nxbins = calibMapEEM->GetNbinsX();
  //int nybins = calibMapEEM->GetNbinsY();
  //for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  //{
  //  double binentsM = calibMapEEM->GetBinContent(i);
  //  if(binentsM==0)
  //  {
  //    calibMapEEM->SetBinContent(i,-1000);
  //  }
  //  double binentsP = calibMapEEP->GetBinContent(i);
  //  if(binentsP==0)
  //  {
  //    calibMapEEP->SetBinContent(i,-1000);
  //  }
  //}
  //calibMapEEM->SetXTitle("ix");
  //calibMapEEM->SetYTitle("iy");
  //calibMapEEM->Write();
  //calibMapEEP->SetXTitle("ix");
  //calibMapEEP->SetYTitle("iy");
  //calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEB->Write();
  expectedStatPresVsObservedMeanErrHistEB->Write();
  expectedStatPresEachEventHistEB->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();

  //calibMapEtaAvgEB->SetXTitle("i#phi");
  //calibMapEtaAvgEB->SetYTitle("i#eta");
  //calibMapEtaAvgEB->Write();
  //calibHistEtaAvgEB->Write();
  
  hitsPerCryHistEB->Write();
  hitsPerCryMapEB->Write();
  ampProfileMapEB->Write();
  ampProfileEB->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
Ejemplo n.º 28
0
void ecaltree::Loop(const char* outputfilename)
{
//   In a ROOT session, you can do:
//      Root > .L ecaltree.C
//      Root > ecaltree t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   std::cout << "Output file is " << outputfilename << std::endl;

#if ANALYSIS == 1

   TFile *fileo = TFile::Open(outputfilename,"recreate");

   // correlation plots
  TH2D *timesCorr_EB = new TH2D("timesCorr_EB","",1000,-10,10,1000,-10,10);
  TH2D *timesCorr_EE = new TH2D("timesCorr_EE","",1000,-25,25,1000,-25,25);

  TH2D *time1EnergyCorr_EB = new TH2D("time1EnergyCorr_EB","",1000,-10,10,1000,0,200);
  TH2D *time1EnergyCorr_EE = new TH2D("time1EnergyCorr_EE","",1000,-50,50,1000,0,200);
  TH2D *time2EnergyCorr_EB = new TH2D("time2EnergyCorr_EB","",1000,-10,10,1000,0,200);
  TH2D *time2EnergyCorr_EE = new TH2D("time2EnergyCorr_EE","",1000,-50,50,1000,0,200);

  // time ratio vs eta, ET, chi2
  TProfile *timeRatioVsEta = new TProfile("timeRatioVsEta","",100,0,3.0); 
  TProfile *timeRatioVsE_EB = new TProfile("timeRatioVsE_EB","",20,0.0,200.); 
  TProfile *timeRatioVsE_EE = (TProfile*)timeRatioVsE_EB->Clone("timeRatioVsE_EE");
  TProfile *timeRatioVsChi2_EB = new TProfile("timeRatioVsChi2_EB","",50,0.0,30.); 
  TProfile *timeRatioVsChi2_EE = (TProfile*)timeRatioVsChi2_EB->Clone("timeRatioVsChi2_EE");

  // time with weights for different slices of times with ratio
  double t_window=5.0; // ns
  TH1F *time_0_EB = new TH1F("time_0_EB","",1000,-75,75);
  TH1F *time_p1_EB = new TH1F("time_p1_EB","",1000,-50,100);
  TH1F *time_p2_EB = new TH1F("time_p2_EB","",1000,-25,125);
  TH1F *time_m1_EB = new TH1F("time_m1_EB","",1000,-100,50);
  TH1F *time_m2_EB = new TH1F("time_m2_EB","",1000,-125,25);
  TH1F *time_0_EE = new TH1F("time_0_EE","",1000,-75,75);
  TH1F *time_p1_EE = new TH1F("time_p1_EE","",1000,-50,100);
  TH1F *time_p2_EE = new TH1F("time_p2_EE","",1000,-25,125);
  TH1F *time_m1_EE = new TH1F("time_m1_EE","",1000,-100,50);
  TH1F *time_m2_EE = new TH1F("time_m2_EE","",1000,-125,25);

  std::vector<TH1F*> time1Dplots;
  time1Dplots.push_back(time_0_EB);
  time1Dplots.push_back(time_p1_EB);
  time1Dplots.push_back(time_p2_EB);
  time1Dplots.push_back(time_m1_EB);
  time1Dplots.push_back(time_m2_EB);
  time1Dplots.push_back(time_0_EE);
  time1Dplots.push_back(time_p1_EE);
  time1Dplots.push_back(time_p2_EE);
  time1Dplots.push_back(time_m1_EE);
  time1Dplots.push_back(time_m2_EE);

   Long64_t nentries = fChain->GetEntries();

   std::cout << "Total entries = " << nentries << std::endl;
   
   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      if(jentry % 1000 == 0) std::cout << "Processing entry " << jentry << std::endl;

      // barrel
      for(int h=0;h<std::min(nEBRecHits,10000);++h) {
        double r=timeEBRecHits2[h]-timeEBRecHits[h];
          if(energyEBRecHits[h]>10) {
            timesCorr_EB->Fill(timeEBRecHits[h],timeEBRecHits2[h]);
            timeRatioVsEta->Fill(etaEBRecHits[h],r);
            timeRatioVsChi2_EB->Fill(chi2EBRecHits[h],r);
            if(abs(timeEBRecHits[h])<t_window) time_0_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]-25.)<t_window) time_p1_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]-50.)<t_window) time_p2_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]+25.)<t_window) time_m1_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]+50.)<t_window) time_m2_EB->Fill(timeEBRecHits2[h]);
          }
          time1EnergyCorr_EB->Fill(timeEBRecHits[h],energyEBRecHits[h]);
          time2EnergyCorr_EB->Fill(timeEBRecHits2[h],energyEBRecHits[h]);
          timeRatioVsE_EB->Fill(energyEBRecHits[h],r);
      }
      // endcap
      for(int h=0;h<std::min(nEERecHits,10000);++h) {
        double r=timeEERecHits2[h]-timeEERecHits[h];
        if(energyEERecHits[h]>10) {
          timesCorr_EE->Fill(timeEERecHits[h],timeEERecHits2[h]);
          timeRatioVsEta->Fill(etaEERecHits[h],r);
          timeRatioVsChi2_EE->Fill(chi2EERecHits[h],r);
          if(abs(timeEERecHits[h])<t_window) time_0_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]-25.)<t_window) time_p1_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]-50.)<t_window) time_p2_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]+25.)<t_window) time_m1_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]+50.)<t_window) time_m2_EE->Fill(timeEERecHits2[h]);
        }
        time1EnergyCorr_EE->Fill(timeEERecHits[h],energyEERecHits[h]);
        time2EnergyCorr_EE->Fill(timeEERecHits2[h],energyEERecHits[h]);
        timeRatioVsE_EE->Fill(energyEERecHits[h],r);
      }

   } // event loop

   timeRatioVsEta->Write();

   timesCorr_EB->Write();
   time1EnergyCorr_EB->Write();
   time2EnergyCorr_EB->Write();
   timeRatioVsChi2_EB->Write();
   timeRatioVsE_EB->Write();

   timesCorr_EE->Write();
   time1EnergyCorr_EE->Write();
   time2EnergyCorr_EE->Write();
   timeRatioVsChi2_EE->Write();
   timeRatioVsE_EE->Write();
   
   for(int i=0; i<(int) time1Dplots.size(); ++i)  time1Dplots[i]->Write();

   fileo->Close();

#endif

#if ANALYSIS == 2

   ofstream txtfile;
   txtfile.open(outputfilename,std::ios::trunc);

   Long64_t nentries = fChain->GetEntries();

   std::cout << "Total entries = " << nentries << std::endl;

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     if(jentry%1000==0) std::cout << "Processing entry " << jentry << "..." << std::endl;
     for(int h=0; h<std::min(nEERecHits,10000); ++h) {
       if(energyEERecHits[h]>5.0)
         txtfile << eventNumber << "\t"
                 << ixEERecHits[h] << "\t"
                 << iyEERecHits[h] << "\t"
                 << nTruePU[12] << "\t" // the bx = 0
                 << energyEERecHits[h] << "\t"
                 << timeEERecHits[h] << "\t"
                 << chi2EERecHits[h] << "\t"
                 << ootenergyEERecHits[h] << std::endl;
     }
     // if (Cut(ientry) < 0) continue;
   }
   txtfile.close();

#endif


}
Ejemplo n.º 29
0
void striptree(TString fileName="", Int_t nAPVs=4)
{
  //===========================================================================
  // Change the inputs
  //===========================================================================

  //TString fileName = "Raw_Data_July1_Ped_300V";
  //TString fileName = "Raw_Data_July1_Source_300V";
  //TString fileName = "Raw_Data_July1_Ped_200V";
  //TString fileName = "Raw_Data_Pedestal_300V";
  // TString fileName = "Raw_Data_Source_300V";

  // TString fileName = "Raw_Data_Sept_3_1";
  // TString fileName = "Raw_Data_test_3_7";
  // TString fileName = "Raw_Data_Albox_2011_03_31_1";
  //-- TString fileName = "Raw_Data_04_01_AL_center_1";
  // TString fileName = "Raw_Data_04_01_AL_7820_1";
  //-- TString fileName = "Raw_Data_7817_04_01_1";
  // TString fileName = "Raw_Data_7817_04_01_bkg_1";

  //int nAPVs = 4;

  //TString fileName = "Raw_Data_July1_Source_200V";
  //int nAPVs = 1;

  int nEvents = -1; // -1 means all

  TString dat = fileName;
  TString eps = fileName + "-events.eps";
  TString root = fileName + "-events.root";

  TFile* file = new TFile(root, "RECREATE");

  //===========================================================================
  // Read the data and make a 2D scatter plot
  //===========================================================================

  ifstream in(dat);
  if (!in) {
     cout<< "File " << dat << " not found" <<endl;
     return;
  }

  TString comments = "vertical --> APV0, APV1, ... of event 1, ...";
  TString s;
  while (1) {
    s.ReadLine(in);
    if (s.BeginsWith(comments))
      break;
  }
  gStyle->SetOptStat(10);
  TString title = fileName+"   ADC Counts vs Channel";
  TString title32 = fileName+"   ADC Counts vs Channel for 32 ch";
  TH2D *h2d = new TH2D("h2d", title.Data(), nAPVs*128, 0, nAPVs*128, 200, 0, 200);
  TH2D *h2d32 = new TH2D("h2d32", title.Data(), 16, 0, 16, 200, 0, 200);
  TProfile *profile = new TProfile("profile", title32.Data(), nAPVs*128, 0, nAPVs*128);

  int event, apv, channel, adc;
  // TTree* tree = new TTree("tree", "tree");
  // tree->Branch("event",   &event,   "event/I");
  // tree->Branch("apv",     &apv,     "apv/I");
  // tree->Branch("channel", &channel, "channel/I");
  // tree->Branch("adc",     &adc,     "adc/I");

  Int_t raw[512];
  TTree* etree = new TTree("etree", "etree");
  etree->Branch("raw",   &raw,   "raw[512]/I");    // etree->Draw("raw:Iteration$","Entry$==0")
  etree->SetMarkerStyle(6);
  etree->SetMarkerColor(2);

  int n = 0;
  while (1) {
    in >> s;
    if (!in.good())
      break;
    if (s.BeginsWith("]DATA]")) // last line
      break;
    n++;
    if ((nEvents != -1) && (n > nEvents))
      break;
    event = atoi(s.Data());
    if (event%100 == 0)
      cout << "Processing event " << event << endl;
    for (int i=0; i<2; i++)
      in >> s; // time

    Int_t ichannel = 0;
    for (apv=1; apv<=nAPVs; apv++) {
      in >> s; // header + analog APV data + one tick mark
      int sequenceNumber = 0;
      TString subString = "";
      int length = s.Length();
      for (int j=0; j<length; j++) {
        char c = s[j];
        if (c != ',') {
          subString += c;
        } else {
          if (sequenceNumber >= 12) {
            channel = sequenceNumber - 12;
            adc = atoi(subString.Data());
            h2d->Fill((apv - 1) * 128 + channel + 0.5, adc);
            h2d32->Fill(((apv - 1) * 128 + channel)/32 + 0.5, adc);
            profile->Fill((apv - 1) * 128 + channel + 0.5, adc);
            //tree->Fill();
            raw[ichannel] = adc;
            ++ichannel;
          }
          subString = "";
          sequenceNumber++;
        }
      }
    }
    etree->Fill();
  }
  in.close();

  TCanvas *canvas = new TCanvas;
  canvas->Divide(1,2);
  canvas->cd();
  canvas->cd(1); h2d->Draw();
  canvas->cd(2); profile->Draw();
  canvas->SaveAs(eps);
  // //-- TFile file(root, "RECREATE");
  // h2d->Write();
  // profile->Write();
  // tree->Write();
  // //file.Close();
  cout<< "\nWrite " << etree->GetEntries() << " of tree " << etree->GetName() << " into file " << file->GetName() <<endl;
  cout<< "To plot strip content use e.g. etree->Draw(\"raw:Iteration$\",\"Entry$==0\")" <<endl;
  file->Write();
}
Ejemplo n.º 30
0
Archivo: Analyze.C Proyecto: XuQiao/HI
void
Analyze(const TString mode="CLOSED",
        UShort_t       maxH=6,
        Bool_t         /*doLoops*/=false,
        Int_t ifile=0   )
{
#ifdef __CINT__
  gROOT->LoadMacro("correlations/Types.hh++");
  gROOT->LoadMacro("correlations/Result.hh++");
  gROOT->LoadMacro("correlations/QVector.hh++");
  gROOT->LoadMacro("correlations/recursive/FromQVector.hh++");
  gROOT->LoadMacro("correlations/recurrence/FromQVector.hh++");
  gROOT->LoadMacro("correlations/closed/FromQVector.hh++");
  gROOT->LoadMacro("correlations/test/ReadData.hh++");
#endif
  // --- Setup of harmonics, etc -------------------------------------
  gRandom->SetSeed(54321);
  UShort_t emode = 0;
  if      (mode.EqualTo("closed",     TString::kIgnoreCase)) emode = 0;
  else if (mode.EqualTo("recurrence", TString::kIgnoreCase)) emode = 1;
  else if (mode.EqualTo("recursive",  TString::kIgnoreCase)) emode = 2;
  else
    Warning("Analyze", "Mode %s unknown, assuming CLOSED", mode.Data());

  correlations::QVector        q[nbin];
  correlations::FromQVector*   c[nbin];
  correlations::HarmonicVector h(maxH);
  for (UShort_t i = 0; i < maxH; i++) {
    // Generate random harmonicx
   // h[i] = -6 + gRandom->Integer(12);
   h[0] = 2;
   h[1] = -2;
   h[2] = 2;
   h[3] = -2;
   h[4] = 2;
   h[5] = -2;
   h[6] = -2;
   h[7] = 2;
   // Printf("h_%d:\t%d", i, h[i]);
  }

  // Resize the Q-vector to fit the harmonics
    for(int ibin=0;ibin<nbin;ibin++){
    q[ibin] = correlations::QVector(0,0,false);
    q[ibin].resize(h);
  switch (emode) {
  case 0: c[ibin] = new correlations::closed::FromQVector(q[ibin]); break;
  case 1: c[ibin] = new correlations::recurrence::FromQVector(q[ibin]); break;
  case 2: c[ibin] = new correlations::recursive::FromQVector(q[ibin]); break;
    }
  }
  //Printf("Correlator: %s", c->name());


  // --- Some histograms ---------------------------------------------
  TH1* sumreals[nbin];
  TH1* sumimags[nbin];
  TH1* weights[nbin];
  TVectorD tottrk;
  TVectorD Nevent;
  tottrk.ResizeTo(nbin);
  tottrk.Zero();
  Nevent.ResizeTo(nbin);
  Nevent.Zero();

  //TH1*      reals  = new TH1D("reals", "Re(C{n})", maxH-2+1, 2+.5, maxH+1+.5);
  //TH1*      imags  = static_cast<TH1*>(reals->Clone("imags"));
    for(int ibin=0;ibin<nbin;ibin++){
  sumreals[ibin]  = new TH1D(Form("sumreals_%d",ibin), "Re(C{n})", maxH-2+1, 2+.5, maxH+1+.5);
  sumimags[ibin]  = static_cast<TH1*>(sumreals[ibin]->Clone(Form("sumimags_%d",ibin)));
  weights[ibin]  = static_cast<TH1*>(sumreals[ibin]->Clone(Form("weights_%d",ibin)));
    }
  TProfile* timing = new TProfile("timing", "Timing", maxH-2+1, 2+.5,maxH+1+.5);
  TH1*      hs     = new TH1I("harmonics", "Harmonics", maxH, 1.5, maxH+1.5);
  /*reals->SetFillColor(kGreen+1);
  reals->SetFillStyle(3001);
  reals->SetStats(0);
  imags->SetTitle("Im(C{n})");
  imags->SetFillColor(kBlue+1);
  imags->SetFillStyle(3001);
  imags->SetStats(0);
  timing->SetFillColor(kRed+1);
  timing->SetFillStyle(3001);
  timing->SetStats(0);
  hs->SetFillColor(kMagenta+1);
  hs->SetFillStyle(3001);
  hs->SetStats(0);*/
  for (UShort_t i = 0; i < maxH-1; i++) {
    TString label = TString::Format("C{%d}", i+2);
//    reals->GetXaxis()->SetBinLabel(i+1, label);
//    imags->GetXaxis()->SetBinLabel(i+1, label);
    timing->GetXaxis()->SetBinLabel(i+1, label);
    hs->GetXaxis()->SetBinLabel(i+1,Form("h_{%d}", i+1));
    hs->SetBinContent(i+1, h[i]);
  }
  hs->GetXaxis()->SetBinLabel(maxH,Form("h_{%d}", maxH));
  hs->SetBinContent(maxH, h[maxH-1]);

  TStopwatch timer;
 
  // --- Setup input ------------------------------------------------
  TFile*   file = TFile::Open(Form("%s/vndata_50k_%d.root",dir.Data(),ifile), "READ");
  TTree*   tree = static_cast<TTree*>(file->Get("tree"));
//  TArrayD  phis(0);
  Int_t M;
  Float_t phi[10000],pt[10000],eta[10000];
//  TArrayD  weights(0);
//  Double_t phiR = 0;
//  TArrayD* pPhis = &phis;
//  TArrayD* pWeights = &weights;
  tree->SetBranchAddress("phig", phi);
  tree->SetBranchAddress("ptg",pt);
  tree->SetBranchAddress("etag",eta);
  tree->SetBranchAddress("n", &M);
//  tree->SetBranchAddress("weight", &pWeights);
//  tree->SetBranchAddress("event", &phiR);


  // --- The results -------------------------------------------------
  const UShort_t             nQ = maxH - 1;
  correlations::ResultVector qs[nbin];
    for(int ibin=0;ibin<nbin;ibin++)
        qs[ibin] = correlations::ResultVector(nQ);

  // --- Event loop --------------------------------------------------
  Int_t nEvents = tree->GetEntries();
  for (Int_t event = 0; event < nEvents; event++) {
    tree->GetEntry(event);
    int ntrk = M; int xbin=-1;
    for(int j=0;j<nbin;j++)
        if(ntrk<trkbin[j]&&ntrk>=trkbin[j+1])
            xbin=j;
        if(xbin<0 || xbin==nbin) continue;
    tottrk[xbin]+=ntrk;
    q[xbin].reset();
 //   printf("Event # %4u  %4d particles ", event++, phis.GetSize());
    for (UShort_t pa = 0; pa < M; pa++){
	if(fabs(eta[pa])>etamax) continue;
        if(pt[pa]<ptmin||pt[pa]>ptmax) continue; //event selection
  //  phis.Set(n,pPhis);
      q[xbin].fill(phi[pa], 1.);
    }
    for (UShort_t i = 0; i < nQ; i++) {
      UShort_t n = i + 2;
   //   printf("%s%d", i == 0 ? "" : "..", n);
      timer.Reset();
      timer.Start();
      qs[xbin][i] += c[xbin]->calculate(n, h);
      timer.Stop();
      timing->Fill(n+.5, timer.RealTime());
    }

  //  printf(" done\n");
  Nevent[xbin]++;
  }
  file->Close();

    for(int ibin=0;ibin<nbin;ibin++){
  for (UShort_t i = 0; i < nQ; i++) {
 //   UShort_t iq = i+2;
 //   Double_t              t  = timing->GetBinContent(i+1);
 //   correlations::Complex rc = qs[i].eval();
   // Printf("QC{%2d}: %12g + %12gi  <t>: %10gs",
//	   iq, rc.real(), rc.imag(), t);
   // if(i==0)Printf("v2{%2d}: %3g\n",2,sqrt(qs[0].eval().real()));
   // if(i==2)Printf("v2{%2d}: %3g\n",4,TMath::Power(fabs(qs[2].eval().real()),1./4));
   // if(i==4)Printf("v2{%2d}: %3g\n",6,TMath::Power(fabs(qs[4].eval().real()),1./6));
    sumreals[ibin]->SetBinContent(i+1,qs[ibin][i]._sum.real());
    sumimags[ibin]->SetBinContent(i+1,qs[ibin][i]._sum.imag());
    weights[ibin]->SetBinContent(i+1,qs[ibin][i]._weights);
    //reals->SetBinContent(i+1, rc.real());
    //imags->SetBinContent(i+1, rc.imag());
  }
    }

/*
  TCanvas* can = new TCanvas("C", "C");
  can->SetTopMargin(0.15);
  can->SetBottomMargin(0.15);
  can->SetRightMargin(0.03);
  can->Divide(1,3, 0, 0);

  DrawInPad(can, 3, timing, true);
  DrawInPad(can, 1, reals);
  DrawInPad(can, 2, imags);

  can->cd(0);
  TLatex* ltx = new TLatex(0.5,0.995,c->name());
  ltx->SetNDC(true);
  ltx->SetTextAlign(23);
  ltx->SetTextSize(0.04);
  ltx->Draw();

  can->Modified();
  can->Update();
  can->cd();
*/
  TString out(mode);
  out.ToLower();
  file = TFile::Open(Form("%s/%s_%d.root",outdir.Data(),out.Data(),ifile), "RECREATE");
    for(int ibin=0;ibin<nbin;ibin++){
  sumimags[ibin]->Write();
  sumreals[ibin]->Write();
  weights[ibin]->Write();
    }
  Nevent.Write("Nevent");
  tottrk.Write("tottrk");
  timing->Write();
  hs->Write();
  file->Write();
  file->Close();
    for(int ibin=0;ibin<nbin;ibin++){
  delete sumimags[ibin];
  delete sumreals[ibin];
  delete weights[ibin];
    }
  delete timing;
  delete hs;
}