void ECALEndcapCorrectionFactorCalculator()
{
    std::string detectorModel("90");
    std::string recoVar("71");

    TString rootFilesToCompare("/r04/lc/sg568/HCAL_Optimisation_Studies/Calibration/Detector_Model_" + detectorModel + "/Reco_Stage_" + recoVar + "/MuonCalibration/RootFiles/*Photon*.root");
    std::string resultsFileName("ECALEndcapCorrectionFactorCalculator_DetectorModel" + detectorModel + "_RecoStage" + recoVar + ".txt");

    std::ofstream resultsFile;
    resultsFile.open (resultsFileName.c_str());

    float ecalTotalCaloHitEnergy(-1.f);
    std::vector<float> *pPfoTargetCosTheta(NULL);

    TChain *pTChain = new TChain("PfoAnalysisTree");
    pTChain->Add(rootFilesToCompare);
    pTChain->SetBranchAddress("ECalTotalCaloHitEnergy",&ecalTotalCaloHitEnergy);
    pTChain->SetBranchAddress("pfoTargetCosTheta",&pPfoTargetCosTheta);

    TCanvas *pTCanvas = new TCanvas("PhotonDistPic", "PhotonDistPic");
    TH2F *pPhotonDist = new TH2F("PhotonDist","PhotonDist",100,0,1,150,0,15);
    pPhotonDist->GetXaxis()->SetTitle("abs( cos (#theta_{#gamma}) )");
    pPhotonDist->GetYaxis()->SetTitle("ECal Calo Hit Energy [GeV]");

    for (int entry = 0; entry < pTChain->GetEntries(); entry++)
    {
//        std::cout << "Reading entry " << entry << std::endl;
        pTChain->GetEvent(entry);

        if (!pPfoTargetCosTheta->empty())
        {
//            std::cout << "Target cos theta : " << pPfoTargetCosTheta.at(0) << std::endl;
            pPhotonDist->Fill(TMath::Abs(pPfoTargetCosTheta->at(0)),ecalTotalCaloHitEnergy);
        }
    }

    TF1 *barrelFit = new TF1("BarrelFit","[0]",0.1,0.7);
    barrelFit->SetLineColor(kGray);
    barrelFit->SetLineWidth(4);

    TF1 *endcapFit = new TF1("EndcapFit","[0]",0.85,0.95);
    endcapFit->SetLineColor(kGray);
    endcapFit->SetLineWidth(4);

    pTCanvas->cd();
    pPhotonDist->Draw("COLZ");

    pPhotonDist->Fit(barrelFit,"QR+");
    pPhotonDist->Fit(endcapFit,"QR+");

    resultsFile << "For the barrel the best fit is : " << barrelFit->GetParameter(0) << std::endl;
    resultsFile << "For the endcap the best fit is : " << endcapFit->GetParameter(0) << std::endl;
    resultsFile << "ECALEndcapCorrectionFactorCalculator -> " << (barrelFit->GetParameter(0))/(endcapFit->GetParameter(0)) << std::endl;
    resultsFile.close();

    TString picName = "ECALEndcapCorrectionFactorCalculator_DetectorModel" + detectorModel + "_RecoStage" + recoVar + ".pdf";
    pTCanvas->SaveAs(picName);   
}
示例#2
0
void makeLowMETTree(){

  TFile fout("/cu2/kreis/reducedTrees/lowMETTree.V00_02_05_v2_highStat.root","RECREATE");

  TChain* myChain = new TChain("reducedTree");
  myChain->Add("/cu2/ra2b/reducedTrees/V00-02-05_v2/reducedTree.SSVHPT.ht_*.root");

  bool cutHT, cutPV, cut3Jets, cutEleVeto, cutMuVeto, pass_utilityHLT_HT300;
  float HT, MET, minDeltaPhiN, deltaPhiN1, deltaPhiN2, deltaPhiN3;
  int nbjetsSSVHPT;
  double weight;

  myChain->SetBranchAddress("cutHT",&cutHT);
  myChain->SetBranchAddress("cutPV",&cutPV);
  myChain->SetBranchAddress("cut3Jets",&cut3Jets);
  myChain->SetBranchAddress("cutEleVeto",&cutEleVeto);
  myChain->SetBranchAddress("cutMuVeto",&cutMuVeto);
  myChain->SetBranchAddress("pass_utilityHLT_HT300",&pass_utilityHLT_HT300);
  myChain->SetBranchAddress("HT",&HT);
  myChain->SetBranchAddress("MET",&MET);
  myChain->SetBranchAddress("minDeltaPhiN",&minDeltaPhiN);
  myChain->SetBranchAddress("deltaPhiN1",&deltaPhiN1);
  myChain->SetBranchAddress("deltaPhiN2",&deltaPhiN2);
  myChain->SetBranchAddress("deltaPhiN3",&deltaPhiN3);
  myChain->SetBranchAddress("nbjetsSSVHPT",&nbjetsSSVHPT);
  myChain->SetBranchAddress("weight",&weight);


  TTree lowMETTree("lowMETTree","low MET data from prescaled triggers");
  lowMETTree.Branch("HT",&HT,"HT/F");
  lowMETTree.Branch("MET",&MET,"MET/F");
  lowMETTree.Branch("minDeltaPhiN",&minDeltaPhiN,"minDeltaPhiN/F");
  lowMETTree.Branch("deltaPhiN1",&deltaPhiN1,"deltaPhiN1/F");
  lowMETTree.Branch("deltaPhiN2",&deltaPhiN2,"deltaPhiN2/F");
  lowMETTree.Branch("deltaPhiN3",&deltaPhiN3,"deltaPhiN3/F");
  lowMETTree.Branch("nbjetsSSVHPT",&nbjetsSSVHPT,"nbjetsSSVHPT/I"); 
  lowMETTree.Branch("weight",&weight,"weight/D");


  const int numE = myChain->GetEntries();
  cout << "numEntries: " << numE << endl;
  for(int i=0; i<numE; i++){
    if(i%100000==0) cout << "  entry: " << i << ", percent done=" << (int)(i/(double)numE*100.) << endl;

    myChain->GetEvent(i);
    if(! (cutHT==1 && cutPV==1 && cut3Jets==1 && cutEleVeto==1 && cutMuVeto==1 && pass_utilityHLT_HT300==1 ) ) continue;
    lowMETTree.Fill();
  }
  
  fout.Write();
  fout.Close();
}
void applyCutSignal(){
  TFile* file ;
  TChain* tree = new TChain("angles");
  tree->Add("../datafiles/JHUGenFiles/SMHiggs_125_JHU.root");
  double mZZ, m2, m1, costhetastar, costheta1, costheta2, phi, phi1,sepLD;
  tree->SetBranchAddress("zzmass",&mZZ);
  tree->SetBranchAddress("z2mass",&m2);
  tree->SetBranchAddress("z1mass",&m1);
  tree->SetBranchAddress("costhetastar",&costhetastar);
  tree->SetBranchAddress("phi",&phi);
  tree->SetBranchAddress("costheta1",&costheta1);
  tree->SetBranchAddress("costheta2",&costheta2);
  tree->SetBranchAddress("phi1",&phi1);

  TFile* fileOut; 
  double mZZout, m2out, m1out, costhetastarout, costheta1out, costheta2out, phiout, phi1out, Psig, Pbkg, D;
  fileOut = new TFile("../datafiles/JHUGenFiles/SMHiggs_125_JHU_withCuts.root","RECREATE");

  TTree* treeOut = new TTree("angles","angles, mzz, D");
  treeOut->Branch("zzmass",&mZZout,"zzmass/D");
  treeOut->Branch("z2mass",&m2out,"z2mass/D");
  treeOut->Branch("z1mass",&m1out,"z1mass/D");
  treeOut->Branch("costhetastar",&costhetastarout,"costhetastar/D");
  treeOut->Branch("phi",&phiout,"phi/D");
  treeOut->Branch("costheta1",&costheta1out,"costheta1/D");
  treeOut->Branch("costheta2",&costheta2out,"costheta2/D");
  treeOut->Branch("phi1",&phi1out,"phi1/D");

  for (Int_t i=0; i<tree->GetEntries();i++) {
    tree->GetEvent(i); 
    if(mZZ>180 || mZZ<110)
      continue;
    //if(m1+m2>125)
    //continue;
    if((i%10000)==0)
      cout<<"event "<<i<<endl;

    mZZout=mZZ;
    m1out= m1;
    m2out=m2;
    costhetastarout=costhetastar;
    costheta1out=costheta1;
    costheta2out=costheta2;
    phiout=phi;
    phi1out=phi1;
    if(m1>20 && m2>20)
      treeOut->Fill();
 }

  fileOut->cd();
  treeOut->Write();
}
示例#4
0
void process()
{
   Int_t raw[512];   // buffer for input signal and bkg trees
   // buffers for output trees
   Int_t sig[512];
   Int_t cmsig[512];
   Int_t cm[16];

   // pedestal
   const char* fbkg_name = "Raw_Data_FZ320P_05_MSSD_2_250V_K237_Pedestal.dat-events.root";
   TFile* fbkg = TFile::Open(fbkg_name);
   if (!fbkg) cout<< "File not found: " << fbkg <<endl<<exitl;

   TTree* tree = (TTree*) fbkg->Get("etree");
   tree->SetBranchAddress("raw", &raw);

   TH2* h2d = (TH2*) fbkg->Get("h2d");
   new TCanvas;
   h2d->Draw();

   TProfile* profile = (TProfile*) fbkg->Get("profile"); 
   //new TCanvas;
   //profile->Draw();

   Int_t pedestal[512];
   for (int i=0; i<512; i++) {
      // pedestal[i] = profile->GetBinContent(i+1) - 0.5;
      // pedestal[i] = profile->GetBinContent(i+1) + 0.5;
      pedestal[i] = profile->GetBinContent(i+1);
   }

   // cout << "\nPedestals for every channel\n" << endl;
   // for (int i=0; i<512; i++) {
   //    cout << pedestal[i] << " ";
   //    if (i>0 && (i+1)%128==0)
   //       cout << endl;
   // }

   cout<< "processing bkg" <<endl;

   // output file with tree
   const char* obfname = "FZ320P_05_MSSD_2-bkg.root";
   TFile* obfile = TFile::Open(obfname, "recreate");

   TTree* btree = new TTree("btree", "btree");
   btree->Branch("sig", &sig, "sig[512]/I");
   btree->Branch("cmsig", &cmsig, "cmsig[512]/I");
   btree->Branch("cm", &cm, "cm[16]/I");
   btree->SetMarkerStyle(6);
   btree->SetMarkerColor(2);

   for (int jentry=0; jentry<tree->GetEntries(); ++jentry)
   {
      tree->GetEvent(jentry);
      // sig
      for (int i=0; i<512; ++i) {
         sig[i] = raw[i] - pedestal[i];
      }
      // calc common mode
      Int_t group32[32];
      Int_t index32[32];
      for (int igroup=0; igroup<16; ++igroup) {
         for (int istrip=0; istrip<32; ++istrip)   // istrip is number inside group of 32
         {
            group32[istrip] = sig[igroup*32 + istrip];
         }
         // sort array group32 in ascending order
         TMath::Sort(32, group32, index32, kFALSE);
         Int_t median = group32[index32[14]];
         cm[igroup] = median;
      }
      // subtract common mode
      for (int istrip=0; istrip<512; ++istrip) {
         Int_t igroup = istrip/32;
         cmsig[istrip] = sig[istrip] - cm[igroup];
      }
      // Fill sig, cmsig, cm
      btree->Fill();
   }
   obfile->Write();

   /////////////////////////////////////////////////
   //
   // signal tree
   //
   /////////////////////////////////////////////////

   cout<< "processing signal" <<endl;
   
   TChain* chain = new TChain("etree");
   chain->Add("Raw_Data_FZ320P_05_MSSD_250V_K237_Position_1.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_250V_K237_Position_2.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_2_250V_K237_Position_3.dat-events.root");
   chain->Add("Raw_Data_FZ320P_05_MSSD_2_250V_K237_Position_4.dat-events.root");
   chain->SetBranchAddress("raw", &raw);

   // output file with tree
   const char* osfname = "FZ320P_05_MSSD_2-signal.root";
   TFile* osfile = TFile::Open(osfname, "recreate");

   TTree* stree = new TTree("stree", "stree");
   stree->Branch("sig", &sig, "sig[512]/I");
   stree->Branch("cmsig", &cmsig, "cmsig[512]/I");
   stree->Branch("cm", &cm, "cm[16]/I");
   stree->SetMarkerStyle(6);
   stree->SetMarkerColor(2);

   for (int jentry=0; jentry<chain->GetEntries(); ++jentry)
   {
      chain->GetEvent(jentry);
      // sig
      for (int i=0; i<512; ++i) {
         sig[i] = raw[i] - pedestal[i];
      }
      // calc common mode
      Int_t group32[32];
      Int_t index32[32];
      for (int igroup=0; igroup<16; ++igroup) {
         for (int istrip=0; istrip<32; ++istrip)   // istrip is number inside group of 32
         {
            group32[istrip] = sig[igroup*32 + istrip];
         }
         // sort array group32 in ascending order
         TMath::Sort(32, group32, index32, kFALSE);
         Int_t median = group32[index32[14]];
         cm[igroup] = median;
      }
      // subtract common mode
      for (int istrip=0; istrip<512; ++istrip) {
         Int_t igroup = istrip/32;
         cmsig[istrip] = sig[istrip] - cm[igroup];
      }
      // Fill sig, cmsig, cm
      stree->Fill();
   }
   osfile->Write();

   ////////////////////////////////////////////////////////
   //
   // process trees
   //
   ///////////////////////////////////////////////////////

   cout<< "results" <<endl;

   Double_t a, mean, sigma;

   TH1F* h_sigma_bkg = new TH1F("h_sigma_bkg","CM subtr. noise for groups", 16,0,16);
   TH1F* h_mean_sig = new TH1F("h_mean_sig","CM subtr. signal for groups", 16,0,16);
   TH1F* h_SN = new TH1F("h_SN","Signal to Noise Ratio for groups", 16,0,16);

   new TCanvas;
   btree->Draw("cmsig","Iteration$>=0&&Iteration$<32");
   fitgr(0,0, "Q", "goff", btree->GetHistogram());
   pargaus(a,mean,sigma,"htemp");
   //cout<< "mean = " << mean << " sigma = " << sigma <<endl;
   //-- png("FZ320P_05_MSSD_2-bkg-ex");

   new TCanvas;
   // for (int igroup=0; igroup<16; ++igroup) {
   for (int igroup=0; igroup<15; ++igroup) {
      Int_t ch1 = igroup*32;
      Int_t ch2 = (igroup+1)*32;
      btree->Draw("cmsig",Form("Iteration$>=%d&&Iteration$<%d",ch1,ch2),"");
      fitgr(0,0, "", "", btree->GetHistogram());
      pargaus(a,mean,sigma,"htemp");
      // h_sigma_bkg->Fill(igroup, sigma);
      h_sigma_bkg->SetBinContent(igroup+1, sigma);
   }
   new TCanvas;
   h_sigma_bkg->Draw();
   //-- png("FZ320P_05_MSSD_2-bkg-allgroups");

   // signal
   new TCanvas;
   stree->Draw("cmsig","cmsig>8 &&Iteration$>=0&&Iteration$<32");
   //-- png("FZ320P_05_MSSD_2-sig-ex");

   new TCanvas;
   // for (int igroup=0; igroup<16; ++igroup) {
   for (int igroup=0; igroup<15; ++igroup) {
      Int_t ch1 = igroup*32;
      Int_t ch2 = (igroup+1)*32;
      stree->Draw("cmsig",Form("cmsig>8 &&Iteration$>=%d&&Iteration$<%d",ch1,ch2),"");
      gPad->Update();
      gPad->Modified();
      mean = stree->GetHistogram()->GetMean();
      h_mean_sig->SetBinContent(igroup+1, mean);
   }
   new TCanvas;
   h_mean_sig->Draw();
   //-- png("FZ320P_05_MSSD_2-signal-allgroups");

   for (int igroup=0; igroup<16; ++igroup) {
      Double_t signal32 =  h_mean_sig->GetBinContent(igroup+1);
      Double_t noise32 = h_sigma_bkg->GetBinContent(igroup+1);
      Double_t snr = 0;
      if (noise32 > 0) snr = signal32 / noise32;
      h_SN->SetBinContent(igroup+1, snr);
   }
   new TCanvas;
   h_SN->Draw();
   //-- png("FZ320P_05_MSSD_2-SN-allgroups");
}
示例#5
0
int main(int argc, char* argv[])
{
  TFile* file = new TFile("neutrons.root", "recreate");

  TChain* chain = createChain(argc, argv);
  // Assign addresses
  double target_charge, veto_charge, target_cb, veto_cb;
  unsigned long long time;
  chain->SetBranchAddress("target_total", &target_charge);
  chain->SetBranchAddress("veto_total", &veto_charge);
  chain->SetBranchAddress("target_cb", &target_cb);
  chain->SetBranchAddress("veto_cb", &veto_cb);
  chain->SetBranchAddress("time", &time);

  const int chainEntries = chain->GetEntries();
  const double adc2us = 4/1000.0;
  const int maxCharge = 30000;
  TH1F* histogram = new TH1F("timing", "timing", 2000, 0, 2000);
  TH1F* neutrons = new TH1F("nspec", "neutron spectrum", 200, 0, maxCharge);
  TH1F* hydrogen = new TH1F("nhspec", "capture on hydrogen", 200, 0, maxCharge);
  TH1F* externals = new TH1F("externspec", "externals", 200, 0, maxCharge);
  TH1F* tsa_neutrons = new TH1F("tsa_spec", "neutron spectrum from tsa plot", 200, 0, maxCharge);
  TH1I* multiplicity = new TH1I("mult", "Event multiplicity", 20, 0, 20);

  unsigned long long t1=0;
  unsigned long long t2=0;
  unsigned long long t3=0;

  // cuts
  const double max_target_cb = 0.5;
  const double max_veto_charge = 500;
  const double min_target_charge = 0;
  const double tale_min = 800;
  const double tale_max = 2000;
  const double neutrons_min = 0;
  const double neutrons_time = 50;
  const double hydro_min = 100;
  const double hydro_max = 150;

  double previous_charge = 0;

  // TSA Plots
  const int nbins = 100;
  double logmin = -0.3;
  double logmax = 4.5;
  double binwidth = (logmax-logmin)/double(nbins);
  double bin_array[nbins+1];
  bin_array[0]=std::pow(10, logmin);
  for(int i=1; i<=nbins; i++)
    bin_array[i]=bin_array[0]+std::pow(10,logmin + i*binwidth);
  TH2F* tsa = new TH2F("tsa", "time series analysis", nbins, bin_array, nbins, bin_array);

  // Keep track of timing in order to get multiplicity
  std::vector<unsigned long long> time_vec;
  time_vec.resize(1, 0);

  for(int evt=0; evt<chainEntries; ++evt)
  {
    // Print out progress
    if(!(evt%1000))
      std::cout << std::floor(double(evt)/chainEntries*100) << "%\r";
    previous_charge = target_charge;
    chain->GetEvent(evt);    

    if(veto_charge<max_veto_charge &&
       target_charge>min_target_charge &&
       target_cb < max_target_cb )
    {
      
      t3=t2;
      t2=t1;
      t1=time;
      double d12 = (t1-t2)*adc2us;
      double d23 = (t2-t3)*adc2us;
      tsa->Fill(d23, d12);
      if((time-time_vec[0])*adc2us < 50)
	time_vec.push_back(time);
      else
      {
	multiplicity->Fill(time_vec.size());
	time_vec.clear();
	time_vec.push_back(time);
      }

      histogram->Fill(d12);
      if(d12 < neutrons_time && d12 > neutrons_min)
	neutrons->Fill(target_charge);
      if(d12 < tale_max && d12 > tale_min)
	externals->Fill(target_charge);
      if(d12 < hydro_max && d12 > hydro_min)
	hydrogen->Fill(target_charge);
      if(d12 < neutrons_time && d23 < neutrons_time)
	tsa_neutrons->Fill(previous_charge);
    }
  }
  std::cout << std::endl;
  // Events in tale:
  TF1* fitter_extern = new TF1("fitter_extern", "[0]*TMath::Exp([1]*x)",
			       0, 2000);
  fitter_extern->SetParameters(1000, -4e-4);
  histogram->Fit(fitter_extern, "QO", "", tale_min, tale_max);
  TF1* fitter_h = new TF1("fitter_h", "[0]*TMath::Exp([1]*x)",
			  0, 2000);
  fitter_h->SetParameters(1000, -4e-3);
  histogram->Fit(fitter_h, "QO+", "", hydro_min, hydro_max);

  

  int tale_events = fitter_extern->Integral(tale_min, tale_max);
  int bkg_events = fitter_extern->Integral(neutrons_min, neutrons_time);

  int h_long_events = fitter_h->Integral(hydro_min, hydro_max);
  int h_short_events = fitter_h->Integral(neutrons_min, neutrons_time);

  double talebkgratio = bkg_events / double(tale_events);
  externals->Scale(talebkgratio);
  double h_ratio = h_short_events / h_long_events;
  hydrogen->Scale(h_ratio);

  TH1F* pureNeutrons = new TH1F("pureNeutrons", "pureNeutrons", 200, 0, maxCharge);
  for(int i=0; i<neutrons->GetNbinsX(); i++)
    pureNeutrons->SetBinContent(i, neutrons->GetBinContent(i) - externals->GetBinContent(i) 
				- hydrogen->GetBinContent(i));

  file->Write();
  std::cout << "Wrote histograms to neutrons.root" << std::endl;

  // TRint* app = new TRint("EVIL", &argc, argv);
  // TCanvas* c1 = new TCanvas();
  //c1->Divide(1,2);
  //c1->cd(1);
  //histogram->Draw();
  //fitter_h->Draw("same");
  //fitter_extern->Draw("same");
  //c1->cd(2);
  // externals->SetLineColor(kBlack);
  // neutrons->SetLineColor(kGreen);
  // pureNeutrons->SetLineColor(kRed);
  // hydrogen->SetLineColor(kBlue);
  // neutrons->Draw();
  // externals->Draw("same");
  // hydrogen->Draw("same");
  // pureNeutrons->Draw("same");
  //app->Run();

  delete histogram;
  delete externals;
  delete neutrons;
  delete pureNeutrons;
  //delete c1;
  delete chain;
  delete file;
  return 0;
}
示例#6
0
int main (int argc, char** argv)
{
  gROOT->ProcessLine("#include <vector>"); //needed by ROOT to deal with standard vectors

  //HACK to use the dictionary easily
  std::string fullFileName = "";
  // Code taken from: http://www.gamedev.net/community/forums/topic.asp?topic_id=459511
  std::string path = "";
  pid_t pid = getpid();
  char buf[20] = {0};
  sprintf(buf,"%d",pid);
  std::string _link = "/proc/";
  _link.append( buf );
  _link.append( "/exe");
  char proc[512];
  int ch = readlink(_link.c_str(),proc,512);
  if (ch != -1) {
    proc[ch] = 0;
    path = proc;
    std::string::size_type t = path.find_last_of("/");
    path = path.substr(0,t);
  }
  fullFileName = path + std::string("/");
  //now even worse, assuming the executable is in build and the .C macro in code
  // std::string command = ".L " + fullFileName.substr(0,fullFileName.size()-7) + "/code/structDictionary.C+";
  std::string command = ".L " + fullFileName + "structDictionary.C+";
  // std::cout << fullFileName << std::endl;
  // std::cout << "command " << command << std::endl;
  gROOT->ProcessLine(command.c_str());


  //-------------------
  // Input Files
  //-------------------
  TChain *tree =  new TChain("tree"); // read input files
  for (int i = 1 ; i < argc ; i++)
  {
    std::cout << "Adding file " << argv[i] << std::endl;
    tree->Add(argv[i]);
  }
  // find the number of channels directly from the tchain file
  // before creating the variables
  // first, get the list of leaves
  TObjArray *leavescopy = tree->GetListOfLeaves();
  int nLeaves = leavescopy->GetEntries();
  std::vector<std::string> leavesName;
  // fill a vector with the leaves names
  for(int i = 0 ; i < nLeaves ; i++)
  {
    leavesName.push_back(leavescopy->At(i)->GetName());
  }
  // count the entries that start with "ch"
  int numOfCh = 0;
  // int numOfCry = 0;
  std::string det_prefix("detector");
  // std::string cry_prefix("cry");
  for(int i = 0 ; i < nLeaves ; i++)
  {
    //     leavesName.push_back(leavescopy->At(i)->GetName());
    if (!leavesName[i].compare(0, det_prefix.size(), det_prefix))
    numOfCh++;
    // if (!leavesName[i].compare(0, cry_prefix.size(), cry_prefix))
    // numOfCry++;
  }
  //the string "cry" appears 4 times per crystal..
  // numOfCry = numOfCry / 4;
  std::cout << "Detector Channels \t= " << numOfCh << std::endl;
  // std::cout << "Number of Crystals \t= "<< numOfCry << std::endl;


  //------------------
  // Input TTree
  //------------------

  //create the branches in the input ttree and connect to the variables

  // global variables
  // these are 1 number per TTree entry - so 1 number per gamma shot
  Long64_t Seed;                      // seed of the simulation (read every time, but always the same)
  int Run;                            // run id (usually just 1)(read every time, but always the same)
  int Event;                          // event id
  float totalEnergyDeposited;         // total energy deposited in this event, in all the matrix
  int NumOptPhotons;                  // number of optical photons generated in this event, in the entire matrix
  int NumCherenkovPhotons;            // number of Cherenkov photons generated in this event, in the entire matrix

  // energy deposition, each gamma 511 event has a std::vector of struct (type enDep) with all the data of each energy deposition
  std::vector<enDep> *energyDeposition = 0;

  // Total number of photons detected in this event
  // for each TTree entry, a simple number saying how many optical photons entered that
  // specific detector, passed the PDE check and where "detected" (i.e. saved)
  Short_t  *detector;
  detector = new Short_t [numOfCh];

  // optical photons. for each gamma 511 event, every optical photon detected is a struct of type optPhot. a std::vector<optPhot> is saved for each gamma 511
  std::vector<optPhot> *photons = 0;

  //------------------------
  // Set Branch Addresses
  //------------------------
  tree->SetBranchAddress("Seed",&Seed);
  tree->SetBranchAddress("Run",&Run);
  tree->SetBranchAddress("Event",&Event);
  tree->SetBranchAddress("totalEnergyDeposited",&totalEnergyDeposited);
  tree->SetBranchAddress("NumOptPhotons",&NumOptPhotons);
  tree->SetBranchAddress("NumCherenkovPhotons",&NumCherenkovPhotons);

  tree->SetBranchAddress("optical",&photons);
  tree->SetBranchAddress("energyDeposition",&energyDeposition);

  for (int i = 0 ; i < numOfCh ; i++)
  {
    std::stringstream snames;
    snames << "detector" << i;
    tree->SetBranchAddress(snames.str().c_str(),&detector[i]);
  }

  //output ttree
  // long long int DeltaTimeTag,ExtendedTimeTag;
  // Short_t charge[32]; //adc type is always 32 channels
  // Float_t RealX,RealY,RealZ;
  // Short_t CrystalsHit;
  // Short_t NumbOfInteractions;
  //
  // TTree* t1 = new TTree("adc","adc");
  //
  // t1->Branch("ExtendedTimeTag",&ExtendedTimeTag,"ExtendedTimeTag/l"); 	//absolute time tag of the event
  // t1->Branch("DeltaTimeTag",&DeltaTimeTag,"DeltaTimeTag/l"); 			//delta time from previous event
  // //branches of the 32 channels data
  // for (int i = 0 ; i < 32 ; i++)
  // {
  //   //empty the stringstreams
  //   std::stringstream snames,stypes;
  //   charge[i] = 0;
  //   snames << "ch" << i;
  //   stypes << "ch" << i << "/S";
  //   t1->Branch(snames.str().c_str(),&charge[i],stypes.str().c_str());
  // }
  // t1->Branch("RealX",&RealX,"RealX/F");
  // t1->Branch("RealY",&RealY,"RealY/F");
  // t1->Branch("RealZ",&RealZ,"RealZ/F");
  // t1->Branch("CrystalsHit",&CrystalsHit,"CrystalsHit/S");
  // t1->Branch("NumbOfInteractions",&NumbOfInteractions,"NumbOfInteractions/S");
  long long int DeltaTimeTag,ExtendedTimeTag;
  Short_t charge[16];

  // correct geometry for 4x4 mppc
  // Double_t xmppc[16]={-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8};
  // Double_t ymppc[16]={-4.8,-4.8,-4.8,-4.8,-1.6,-1.6,-1.6,-1.6,1.6,1.6,1.6,1.6,4.8,4.8,4.8,4.8};

  Double_t xmppc[16]={-4.8,-4.8,-4.8,-4.8,-1.6,-1.6,-1.6,-1.6,1.6,1.6,1.6,1.6,4.8,4.8,4.8,4.8};
  Double_t ymppc[16]={-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8,-4.8,-1.6,1.6,4.8};

  TH2F *flood = new TH2F("FloodHisto","FloodHisto",1000,-7,7,1000,-7,7);
  flood->GetXaxis()->SetTitle("X [mm]");
  flood->GetYaxis()->SetTitle("Y [mm]");
  flood->GetZaxis()->SetTitle("N");
  //   recClean->SetTitle("Reconstruction of entire dataset");
  //   varStream << "FloodY_" << k << ":FloodX_" << k << ">>" << histoString ;

  // TH2F *positions = new TH2F("Positions","Positions",1000,-7,7,1000,-7,7);
  // positions->GetXaxis()->SetTitle("X [mm]");
  // positions->GetYaxis()->SetTitle("Y [mm]");
  // positions->GetZaxis()->SetTitle("N");


  // TH2F *HitPositions = new TH2F("HitPositions","HitPositions",1000,-7,7,1000,-7,7);
  // HitPositions->GetXaxis()->SetTitle("X [mm]");
  // HitPositions->GetYaxis()->SetTitle("Y [mm]");
  // HitPositions->GetZaxis()->SetTitle("N");
  double columsum = 0;
  double rowsum = 0;
  double total = 0;
  double floodx = 0;
  double floody = 0;
  double floodz = 0;


  // TBranch *b_floodx = tree->Branch("FloodX",&floodx,"floodx/F");
  // TBranch *b_floody = tree->Branch("FloodY",&floody,"floody/F");
  // TBranch *b_floodz = tree->Branch("FloodZ",&floodz,"floodz/F");

  //----------------------------------------//
  //             LOOP ON EVENTS             //
  //----------------------------------------//
  long int counter = 0;
  int nEntries = tree->GetEntries();
  std::cout << "nEntries = " << nEntries << std::endl;


  TH1F *histoSigmaX = new TH1F("histoSigmaX","Sigma x distribution",1000,0,1);
  histoSigmaX->GetXaxis()->SetTitle("Sigma x [mm]");

  TH1F *histoSigmaY = new TH1F("histoSigmaY","Sigma y distribution",1000,0,1);
  histoSigmaY->GetXaxis()->SetTitle("Sigma y [mm]");

  TH1F *histoSigmaZ = new TH1F("histoSigmaZ","Sigma z distribution",1000,0,1);
  histoSigmaZ->GetXaxis()->SetTitle("Sigma z [mm]");

  TH1F *DeltaR = new TH1F("DeltaR","Delta r distribution",1000,-30,30);
  DeltaR->GetXaxis()->SetTitle("Delta r [mm]");

  TH1F *DeltaR_xy = new TH1F("DeltaR_xy","Delta r_xy distribution",1000,-30,30);
  DeltaR_xy->GetXaxis()->SetTitle("Delta r_xy [mm]");

  TH1F *DeltaZ = new TH1F("DeltaZ","Delta z distribution",1000,-15,15);
  DeltaZ->GetXaxis()->SetTitle("Delta z [mm]");

  TH1F *DeltaE = new TH1F("DeltaE","Delta E distribution",1000,-0.511,0.511);
  DeltaE->GetXaxis()->SetTitle("Delta E [MeV]");

  TH2F *DeltaEvsDeltaZ = new TH2F("DeltaZvsDeltaE","DeltaE vs DeltaZ",1000,-15,15,1000,-0.511,0.511);
  DeltaEvsDeltaZ->GetXaxis()->SetTitle("Delta z [mm]");
  DeltaEvsDeltaZ->GetYaxis()->SetTitle("Delta E [MeV]");


  TH2F *averageZvsRatio = new TH2F("AverageZ vs Ratio","AverageZ vs Ratio",100,0,1,100,-8,8);
  averageZvsRatio->GetXaxis()->SetTitle("Ratio (Fi/(Fi+Bi))");
  averageZvsRatio->GetYaxis()->SetTitle("AverageZ [mm]");

  TH2F *normalizedZvsRatio = new TH2F("NormalizedZ vs Ratio","NormalizedZ vs Ratio",100,0,1,100,0,1);
  normalizedZvsRatio->GetXaxis()->SetTitle("Ratio (Fi/(Fi+Bi))");
  normalizedZvsRatio->GetYaxis()->SetTitle("NormalizedZ [fraction of crystal z]");

  TH2F *wivsRatio = new TH2F("wi vs Ratio","wi vs Ratio",100,0,1,100,0,1);
  wivsRatio->GetXaxis()->SetTitle("Ratio (Fi/(Fi+Bi))");
  wivsRatio->GetYaxis()->SetTitle("Wi");

  TH2F *wMeasuredvsRatioW = new TH2F("wMeasuredvsRatioW","Measured w vs. Weighted average w_0 w_1",100,0,1,100,0,1);
  wMeasuredvsRatioW->GetXaxis()->SetTitle("RatioW = Sum_i(Wi*Ei/Etot)");
  wMeasuredvsRatioW->GetYaxis()->SetTitle("Measured W");

  TH2F *uMeasuredVsRatioU = new TH2F("uMeasuredVsRatioU","Measured u vs. Weighted average u_0 u_1",100,-1.3,-1,100,-1.3,-1);
  uMeasuredVsRatioU->GetXaxis()->SetTitle("RatioU = Sum_i(Ui*Ei/Etot)");
  uMeasuredVsRatioU->GetYaxis()->SetTitle("Measured U");

  TH2F *vMeasuredVsRatioV = new TH2F("vMeasuredVsRatioV","Measured v vs. Weighted average v_0 v_1",100,1,2,100,1,2);
  vMeasuredVsRatioV->GetXaxis()->SetTitle("RatioV = Sum_i(Vi*Ei/Etot)");
  vMeasuredVsRatioV->GetYaxis()->SetTitle("Measured V");

  TH2F *averageZvsWi = new TH2F("AverageZ vs Wi","AverageZ vs Wi",100,0,1,100,-8,8);
  averageZvsWi->GetXaxis()->SetTitle("Wi");
  averageZvsWi->GetYaxis()->SetTitle("AverageZ [mm]");

  TH2F *kMeasuredvsRatioF = new TH2F("kMeasuredveRatioF","kMeasuredveRatioF",100,0,1,100,0,1);
  kMeasuredvsRatioF->GetXaxis()->SetTitle("RatioF");
  kMeasuredvsRatioF->GetYaxis()->SetTitle("Measured K");

  TH2F *pmaxiVsRatioF = new TH2F("pmaxiVsRatioF","Pmax_i vs. F_i",100,0,2000,100,0,2000);
  pmaxiVsRatioF->GetXaxis()->SetTitle("F");
  pmaxiVsRatioF->GetYaxis()->SetTitle("Pmax_i");

  TH2F *kMeasuredvsPmaxi = new TH2F("kMeasuredvsPmaxi","k vs. Ratio(Pmax_i)",100,0,1,100,0,1);
  kMeasuredvsPmaxi->GetXaxis()->SetTitle("Ratio(Pmax_i)");
  kMeasuredvsPmaxi->GetYaxis()->SetTitle("Measured K");



  // for(int i =0 ; i < 2; i++)
  // {
  //   std::stringstream name;
  //   name << "AverageZ vs. (Fi/(Fi+Bi)) - Crystal " << i
  //   averageZvsRatio[i] = new TH2F()
  // }
  long int foundCandidate = 0;
  long int singleCounter = 0;
  long int doubleCounter = 0;
  long int tripleCounter = 0;
  long int multipleCounter = 0;
  // int firstCrystal[64];
  // int secondCrystal[64];
  //
  // for (int i = 0 ; i < 64 ; i++)
  // {
  //   firstCrystal[i] = 0;
  //   secondCrystal[i] = 0;
  // }


  long int globalReturned = 0;
  for(int iEvent = 0; iEvent < nEntries ; iEvent++)
  // for(int iEvent = 5; iEvent < 6 ; iEvent++)
  {
    tree->GetEvent(iEvent);
    // std::cout << "iEvent "<<iEvent << std::endl;
    columsum = 0;
    rowsum = 0;
    total = 0;
    floodx = 0;
    floody = 0;
    floodz = 0;



    //first clean the array
    // for(int i = 0; i < 16 ; i++)
    // {
    //   charge[i] = 0;
    // }

    //then fill it with the detector data
    // for(int i = 0; i < numOfCh ; i++)
    // {
    //   charge[i] = detector[i];
    // }

    //calculate weighted energy and fill 2d histo
    for(int i = 0; i < 16 ; i++)
    {
      columsum += detector[i]*ymppc[i];
      rowsum += detector[i]*xmppc[i];
      total += detector[i];
    }
    floodx = rowsum/total;
    floody = columsum/total;
    // b_floodx->Fill();

    flood->Fill(floodx,floody);




    std::vector<int> crystals;
    // std::vector<enDep> EventDepositions;



    // stackingaction is last-in-first-out so we need to sort energyDeposition before we check what crystal was hit first
    // check crystal sequence, check for returning gammas, calculate an average xyz per crystal
    std::sort(energyDeposition->begin(), energyDeposition->end(), compareByTime);
    std::vector<std::vector < enDep > > separatedEnDep;
    // float EnDepPerCrystal = 0.0;
    int CurrentID = -1;
    // bool newcrystal = false;
    float RealX = 0.0;
    float RealY = 0.0;
    float RealZ = 0.0;
    std::vector < enDep > CrystalEnDepCollection;

    for(int eEvent = 0; eEvent < energyDeposition->size(); eEvent++) //run on energy depositions and find in how many crystals energy was deposited
    {
      //read the crystal where energy was deposited
      int cry = energyDeposition->at(eEvent).CrystalID;
      //create temp enDep variable and copy this eEvent into it

      //DEBUG
      // std::cout << eEvent <<" ";
      // std::cout << energyDeposition->at(eEvent).CrystalID << " ";
      // std::cout << energyDeposition->at(eEvent).EnergyDeposited<< " ";
      // std::cout << energyDeposition->at(eEvent).DepositionTime<< " ";
      // std::cout << energyDeposition->at(eEvent).DepositionX<< " ";
      // std::cout << energyDeposition->at(eEvent).DepositionY<< " ";
      // std::cout << energyDeposition->at(eEvent).DepositionZ<< std::endl;
      //---DEBUG

      enDep tempCrystalEnDep;
      tempCrystalEnDep = energyDeposition->at(eEvent);

      // std::cout << eEvent <<" ";
      // std::cout << tempCrystalEnDep.CrystalID << " ";
      // std::cout << tempCrystalEnDep.EnergyDeposited<< " ";
      // std::cout << tempCrystalEnDep.DepositionTime<< " ";
      // std::cout << tempCrystalEnDep.DepositionX<< " ";
      // std::cout << tempCrystalEnDep.DepositionY<< " ";
      // std::cout << tempCrystalEnDep.DepositionZ<< std::endl;

      //if the crystal is changing
      if(eEvent == 0) CurrentID = cry;
      if(cry != CurrentID) // changes everytime the gamma enters a new crystal
      {
        separatedEnDep.push_back(CrystalEnDepCollection); // save the collection of this crystal into the std::vector of collections
        CrystalEnDepCollection.clear(); //clear this collection
        CurrentID = cry; //change the current id
      }

      CrystalEnDepCollection.push_back(tempCrystalEnDep); // save this enDep event into the collection if this crystal

      if(eEvent == energyDeposition->size() -1)
      {
        separatedEnDep.push_back(CrystalEnDepCollection);
      }
      //loop in the crystals found
      //look for the same id
      bool sameID = false;
      for(int j = 0 ; j < crystals.size(); j++)
      {
        if(crystals[j] == cry) sameID = true;
      }
      if(!sameID) crystals.push_back(cry);
    }
    // std::cout << separatedEnDep.size() << std::endl;

    //DEBUG
    // for(int iColl = 0 ; iColl < separatedEnDep.size(); iColl++)
    // {
    //   std::cout << separatedEnDep.at(iColl).size()<< std::endl;
    //   for(int iEndep = 0; iEndep < separatedEnDep.at(iColl).size(); iEndep++)
    //   {
    //     std::cout << iColl << " " << iEndep << " " ;
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).CrystalID << " ";
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).EnergyDeposited<< " ";
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).DepositionTime<< " ";
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).DepositionX<< " ";
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).DepositionY<< " ";
    //     std::cout << separatedEnDep.at(iColl).at(iEndep).DepositionZ<< std::endl;
    //   }
    // }
    //---DEBUG


    std::vector<avgCryEnergyDep> averageDepEvents;
    // now the en dep events are collected by crystal
    // run on each collection and find average
    for(int iColl = 0 ; iColl < separatedEnDep.size(); iColl++)
    {
      avgCryEnergyDep tempAvgEnDep;

      tempAvgEnDep.id = separatedEnDep.at(iColl).at(0).CrystalID;
      tempAvgEnDep.x = 0;
      tempAvgEnDep.y = 0;
      tempAvgEnDep.z = 0;
      tempAvgEnDep.time = 0;
      tempAvgEnDep.energy = 0;
      tempAvgEnDep.sx = 0;
      tempAvgEnDep.sy = 0;
      tempAvgEnDep.sz = 0;
      for(int iEndep = 0; iEndep < separatedEnDep.at(iColl).size(); iEndep++)
      {
        tempAvgEnDep.energy += separatedEnDep.at(iColl).at(iEndep).EnergyDeposited;
        // std::cout << separatedEnDep.at(iColl).at(iEndep).EnergyDeposited << std::endl;
        tempAvgEnDep.x += separatedEnDep.at(iColl).at(iEndep).DepositionX * separatedEnDep.at(iColl).at(iEndep).EnergyDeposited;
        tempAvgEnDep.y += separatedEnDep.at(iColl).at(iEndep).DepositionY * separatedEnDep.at(iColl).at(iEndep).EnergyDeposited;
        tempAvgEnDep.z += separatedEnDep.at(iColl).at(iEndep).DepositionZ * separatedEnDep.at(iColl).at(iEndep).EnergyDeposited;
        tempAvgEnDep.time += separatedEnDep.at(iColl).at(iEndep).DepositionTime * separatedEnDep.at(iColl).at(iEndep).EnergyDeposited;
      }
      tempAvgEnDep.x = tempAvgEnDep.x / tempAvgEnDep.energy;
      tempAvgEnDep.y = tempAvgEnDep.y / tempAvgEnDep.energy;
      tempAvgEnDep.z = tempAvgEnDep.z / tempAvgEnDep.energy;
      tempAvgEnDep.time = tempAvgEnDep.time / tempAvgEnDep.energy;
      float varx = 0.0;
      float vary = 0.0;
      float varz = 0.0;
      for(int iEndep = 0; iEndep < separatedEnDep.at(iColl).size(); iEndep++)
      {
        varx += (separatedEnDep.at(iColl).at(iEndep).EnergyDeposited * pow(separatedEnDep.at(iColl).at(iEndep).DepositionX  - tempAvgEnDep.x,2)) / tempAvgEnDep.energy;
        vary += (separatedEnDep.at(iColl).at(iEndep).EnergyDeposited * pow(separatedEnDep.at(iColl).at(iEndep).DepositionY  - tempAvgEnDep.y,2)) / tempAvgEnDep.energy;
        varz += (separatedEnDep.at(iColl).at(iEndep).EnergyDeposited * pow(separatedEnDep.at(iColl).at(iEndep).DepositionZ  - tempAvgEnDep.z,2)) / tempAvgEnDep.energy;
      }
      tempAvgEnDep.sx = sqrt(varx);
      tempAvgEnDep.sy = sqrt(vary);
      tempAvgEnDep.sz = sqrt(varz);

      averageDepEvents.push_back(tempAvgEnDep);

    }
    //DEBUG
    // for (int iAvg = 0 ; iAvg < averageDepEvents.size() ; iAvg++)
    // {
    //   std::cout << "----------------------" << std::endl;
    //   std::cout << averageDepEvents.at(iAvg).id << " " << averageDepEvents.at(iAvg).energy << " " << averageDepEvents.at(iAvg).time << std::endl;
    //   std::cout << "(" << averageDepEvents.at(iAvg).x << "," << averageDepEvents.at(iAvg).y << "," << averageDepEvents.at(iAvg).z <<  ") " << std::endl;
    //   std::cout << "(" << averageDepEvents.at(iAvg).sx << "," << averageDepEvents.at(iAvg).sy << "," << averageDepEvents.at(iAvg).sx <<  ") " << std::endl;
    //
    // }
    //---DEBUG

    //fill a global histogram of energy deposition sigmas in the crystals
    for (int iAvg = 0 ; iAvg < averageDepEvents.size() ; iAvg++)
    {
      // std::cout << "----------------------" << std::endl;
      // std::cout << averageDepEvents.at(iAvg).id << " " << averageDepEvents.at(iAvg).energy << " " << averageDepEvents.at(iAvg).time << std::endl;
      // std::cout << "(" << averageDepEvents.at(iAvg).x << "," << averageDepEvents.at(iAvg).y << "," << averageDepEvents.at(iAvg).z <<  ") " << std::endl;
      // std::cout << "(" << averageDepEvents.at(iAvg).sx << "," << averageDepEvents.at(iAvg).sy << "," << averageDepEvents.at(iAvg).sx <<  ") " << std::endl;
      histoSigmaX->Fill(averageDepEvents.at(iAvg).sx);
      histoSigmaY->Fill(averageDepEvents.at(iAvg).sy);
      histoSigmaZ->Fill(averageDepEvents.at(iAvg).sz);
    }


    //two crystals or more hit, but a crystal is hit more than once (like, 28 -> 36 -> 28)
    std::vector <int> checkReturning; // this std::vector has same size of averageDepEvents if there is no returning, smaller if there is
    int returned = 0;
    for (int iAvg = 0 ; iAvg < averageDepEvents.size() ; iAvg++)
    {
      int cry = averageDepEvents.at(iAvg).id;
      bool sameID = false;
      for(int i = 0 ; i < checkReturning.size(); i++)
      {
        if(cry == checkReturning[i])
        {
          sameID = true;
          returned++;
        }
      }
      if(!sameID) checkReturning.push_back(cry);
    }
    globalReturned += returned;

    if(totalEnergyDeposited > 0.400)
    {
      if(averageDepEvents.size() == 2)
      {
        DeltaZ->Fill(averageDepEvents[0].z - averageDepEvents[1].z);
        DeltaE->Fill(averageDepEvents[0].energy - averageDepEvents[1].energy);
        DeltaEvsDeltaZ->Fill(averageDepEvents[0].z - averageDepEvents[1].z,averageDepEvents[0].energy - averageDepEvents[1].energy);
        DeltaR->Fill(sqrt(pow(averageDepEvents[0].x - averageDepEvents[1].x,2)+pow(averageDepEvents[0].y - averageDepEvents[1].y,2)+pow(averageDepEvents[0].z - averageDepEvents[1].z,2)));
        DeltaR_xy->Fill(sqrt(pow(averageDepEvents[0].x - averageDepEvents[1].x,2)+pow(averageDepEvents[0].y - averageDepEvents[1].y,2)));
      }
    }


    //now take only events where energy was deposited in 2 crystals and total energy deposited is around 511KeV
    //very not general, but this is only for testing: choose crystals 28 and 29 (2 crystals on the same mppc)
    //and run only on the 9 relevant mppcs to compute w_near
    // if((crystals[0] == 27 && crystals[1] == 28) | (crystals[0] == 28 && crystals[1] == 27))

    // if(true)
    // std::cout << counter << " " << crystals[0] << " " << crystals[1] << std::endl;
    // if(totalEnergyDeposited > 0.510)
    // {
      // if(crystals.size() == 2)
      // {
      //   firstCrystal[crystals[0]]++;
      //   secondCrystal[crystals[1]]++;
      // }
    // }

    if((crystals[0] == 28 && crystals[1] == 29) /*| (crystals[0] == 29 && crystals[1] == 28)*/)
    {

      if(totalEnergyDeposited > 0.510)
      {
        if(crystals.size() == 2 )
        {

          //consider only non-lateral crystals - not needed if it's restricted to 28 and 29...
          bool isCandidate = true;
          for(int eEvent = 0; eEvent < energyDeposition->size(); eEvent++) //run on energy depositions and check is not on borders
          {
            bool check_b = energyDeposition->at(eEvent).CrystalI < 2 | energyDeposition->at(eEvent).CrystalI > 5 | energyDeposition->at(eEvent).CrystalJ < 2 | energyDeposition->at(eEvent).CrystalJ > 5;
            if(check_b)
            {
              isCandidate = false;
            }
          }
          if(isCandidate)
          {
            //calculate average Z of production in the 2 crystals
            // foundCandidate++;

            //calculate the measured W
            int Measured_pmaxID = 0;
            int Measured_pmax = 0;
            int Measured_pSecond = 0;
            int Measured_totalDetCounts = 0;
            std::vector<int> vToSort;
            for(int i = 0; i < numOfCh ; i++)
            {
              if(i == 1 | i == 2 | i == 3 | i == 5 | i == 6 | i == 7 | i == 9 | i == 10 | i == 11) //just channel 6 (where 28 and 29 are) and surrounding
              {
                Measured_totalDetCounts+=detector[i];
              }
              vToSort.push_back(detector[i]);
            }
            std::sort (vToSort.begin(),vToSort.end());
            Measured_pmax = vToSort[vToSort.size()-1];
            Measured_pSecond = vToSort[vToSort.size()-2];

            // {
            //   Measured_totalDetCounts += detector[i];
            //   if(detector[i] > Measured_pmax1)
            //   {
            //     Measured_pmax1 = detector[i];
            //     Measured_pmaxID = i;
            //   }
            // }



            double Measured_w = ((double) Measured_pmax) / ((double)Measured_totalDetCounts);
            // double Measured_w = ((double) Measured_pmax + (double)Measured_pSecond) / (2.0*(double)Measured_totalDetCounts);
            // double Measured_w = ((double) Measured_pmax + (double)Measured_pSecond) / ((double)Measured_totalDetCounts);
            double RatioW = 0.0;
            double RatioF = 0.0;

            //compute k

            // we have u v coordinates for this event (floodx and floody)
            // we roughly measured the center of the two spots,
            // P28 = (-1.087,1.17) - P29 = (-1.087,1.97)
            // now we should calculate the line connecting the two spots in u,v, then the normal, then intersection and bla bla.
            // but we took same x for the two points, so the only coordinate that matters is y
            double SpotsDistance = 1.97 - 1.17;
            // std::cout << floodx << " "<<  floody << std::endl;
            double kDistance = fabs(floody - 1.97);// 28 is 0, 29 is 1 - but maybe i've inverted. whatever
            double Measured_k = kDistance/SpotsDistance;


            std::vector<double> totalEnergyPerCrystal;
            std::vector<double> averageZ;
            std::vector<double> normalizedZ;
            std::vector<double> wi;
            std::vector<double> ratio;
            std::vector<long int> Fi;
            std::vector<long int> Bi;
            std::vector<double> pmax_i;
            std::vector<double> ui;
            std::vector<double> vi;

            for(int j = 0 ; j < crystals.size() ; j++) // we are in a specific crystal
            {
              double temp_totalEnergyPerCrystal = 0.0;
              for(int eEvent = 0; eEvent < energyDeposition->size(); eEvent++)
              {

                if(energyDeposition->at(eEvent).CrystalID == crystals[j])
                temp_totalEnergyPerCrystal += energyDeposition->at(eEvent).EnergyDeposited;
              }

              double temp_averageZ = 0.0;
              for(int eEvent = 0; eEvent < energyDeposition->size(); eEvent++)
              {
                if(energyDeposition->at(eEvent).CrystalID == crystals[j])
                temp_averageZ += (energyDeposition->at(eEvent).DepositionZ *  energyDeposition->at(eEvent).EnergyDeposited)/temp_totalEnergyPerCrystal;
              }

              // now on opticals
              // 1.is averageZ correlated to Fi/(Fi+Bi)?
              // count Fi and Bi for this crystal

              // 2. next, is wi correlated with ratio (actually are they the same?)?
              // so calculate wi
              // divide opticals on the basis of origin crystal
              // count the photons detected by each detector for both origins
              // compute the two wi
              long int temp_Fi = 0;
              long int temp_Bi = 0;
              short detectorSorted[numOfCh];
              for(int iDet = 0; iDet < numOfCh ;iDet++)
              {
                detectorSorted[iDet] = 0;
              }

              for(int oEvent = 0; oEvent < photons->size(); oEvent++)
              {
                // calc origin crystal ID
                int OriginCrystalID = photons->at(oEvent).OriginCrystalI * 8 +  photons->at(oEvent).OriginCrystalJ;
                if(OriginCrystalID == crystals[j])
                {
                  if(photons->at(oEvent).ExitFace == 1)
                    temp_Fi++;
                  if(photons->at(oEvent).ExitFace == 2)
                    temp_Bi++;
                  //the array of detectors
                  // std::cout << photons->at(oEvent).PositionX << " "<< (int) ((photons->at(oEvent).PositionX + 6.3) /  3.2) << std::endl;
                  int iDetector = (int) ((photons->at(oEvent).PositionX + 6.3) /  3.2);
                  int jDetector = (int) ((photons->at(oEvent).PositionY + 6.3) /  3.2);
                  int detectorID = iDetector * 4 +  jDetector;
                  detectorSorted[detectorID]++;
                }
              }

              int pmaxID = 0;
              int pmax = 0;
              int totalDetCounts = 0;
              int allDetCounts = 0;
              double temp_floodx = 0;
              double temp_floody = 0;

              for(int i = 0; i < numOfCh ; i++)
              {
                if(i == 1 | i == 2 | i == 3 | i == 5 | i == 6 | i == 7 | i == 9 | i == 10 | i == 11) //just channel 6 (where 28 and 29 are) and surrounding
                {
                  totalDetCounts += detectorSorted[i];

                }

                allDetCounts += detectorSorted[i];
                temp_floodx += xmppc[i]*detectorSorted[i];
                temp_floody += ymppc[i]*detectorSorted[i];

                if(detectorSorted[i] > pmax)
                {
                  pmax = detectorSorted[i];
                  pmaxID = i;
                }
              }
              temp_floodx = temp_floodx/( (double) allDetCounts);
              temp_floody = temp_floody/( (double) allDetCounts);
              pmax_i.push_back(pmax);
              ui.push_back(temp_floodx);
              vi.push_back(temp_floody);
              double temp_wi = ((double) pmax) / ((double)totalDetCounts);
              double temp_ratio = ((double) temp_Fi)/((double) temp_Fi+ (double) temp_Bi);
              Fi.push_back(temp_Fi);
              Bi.push_back(temp_Bi);
              wi.push_back(temp_wi);
              totalEnergyPerCrystal.push_back(temp_totalEnergyPerCrystal);
              ratio.push_back(temp_ratio);
              averageZ.push_back(temp_averageZ);
              normalizedZ.push_back((temp_averageZ + 7.5) / 15.0);
              // RatioW += (wi * totalEnergyPerCrystal) / totalEnergyDeposited;

            }

            bool doubleAccepted = true;
            for(int countCry = 0; countCry < wi.size() ;countCry++ )
            {
              if(totalEnergyPerCrystal[countCry] < 0.05) doubleAccepted = false;
            }
            if(doubleAccepted)
            {
              foundCandidate++;
              RatioF = ((double) Fi[0])/(( (double) Fi[0])+( (double) Fi[1]));
              double RatioP = ((double) pmax_i[0])/(((double) pmax_i[0])+( (double) pmax_i[1]));
              double RatioU = (totalEnergyPerCrystal[0] * ui[0] + totalEnergyPerCrystal[1] * ui[1] )/ totalEnergyDeposited;
              double RatioV = (totalEnergyPerCrystal[0] * vi[0] + totalEnergyPerCrystal[1] * vi[1] )/ totalEnergyDeposited;
              for(int countCry = 0; countCry < wi.size() ;countCry++ )
              {
                averageZvsRatio->Fill(ratio[countCry],averageZ[countCry]);
                normalizedZvsRatio->Fill(ratio[countCry],normalizedZ[countCry]);
                wivsRatio->Fill(ratio[countCry],wi[countCry]);
                averageZvsWi->Fill(wi[countCry],averageZ[countCry]);
                RatioW += (wi[countCry] * totalEnergyPerCrystal[countCry]) / totalEnergyDeposited;
                // std::cout << pmax_i[countCry] << " " << Fi[countCry] << std::endl;
                pmaxiVsRatioF->Fill(Fi[countCry],pmax_i[countCry]);
              }
              wMeasuredvsRatioW->Fill(RatioW,Measured_w);
              kMeasuredvsRatioF->Fill(RatioF,Measured_k);
              kMeasuredvsPmaxi->Fill(RatioP,Measured_k);
              uMeasuredVsRatioU->Fill(RatioU,floodx);
              vMeasuredVsRatioV->Fill(RatioV,floody);
            }

          }
        }
      }
    }

    if(totalEnergyDeposited > 0.510)
    {
      if(crystals.size() == 1) singleCounter++;
      if(crystals.size() == 2) doubleCounter++;
      if(crystals.size() == 3) tripleCounter++;
      if(crystals.size() > 3)  multipleCounter++;
    }
    // std::cout << "Event " << iEvent << " - Dep in crystals = " << crystals.size() << std::endl;




    //calculate the average x and y deposition position
    // double averageX = 0;
    // double averageY = 0;
    // double energyColumnSum = 0;
    // double energyRowSum = 0;
    //
    // for(int i = 0; i < nCrystals ; i++)
    // {
    //   for (int j = 0 ; j < pEdep[i]->size() ; j++)
    //   {
    //     energyRowSum    += px[i]->at(j) * pEdep[i]->at(j);
    //     energyColumnSum += py[i]->at(j) * pEdep[i]->at(j);
    //   }
    // }
    // averageX = energyRowSum / totalEnergyDeposited;
    // averageY = energyColumnSum / totalEnergyDeposited ;
    //
    // positions->Fill(averageX,averageY);
    //t1->Fill();


    // ExtendedTimeTag = 1e-9;
    // DeltaTimeTag = 1e-9;
    //
    // NumbOfInteractions = 0;
    // CrystalsHit = 0;
    //
    //
    // for(int i = 0; i < numOfCh ; i++)
    // {
    //   //convert to ADC channels, as if it was data from a digitizer
    //   //mppc gain = 1.25e6
    //   //adc channel binning 156e-15 C
    //   double adcCh = detector[i]*1.25e6*1.6e-19/156e-15;
    //   charge[i*2] = (Short_t) adcCh;
    // }
    //
    // RealX = RealY = RealZ = 0;
    //
    // // calculate a weigthed energy deposition in x,y,z
    // for(int i = 0; i < numOfCry ; i++) //first total energy deposited
    // {
    //   NumbOfInteractions += px[i]->size();
    //   if(px[i]->size()) CrystalsHit++;
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealX += (px[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealY += (py[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealZ += (pz[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    // }
    //
    // if(NumbOfInteractions > 0) // discard events with no energy deposition (they would never trigger the detectors anyway..)
    // {
    //   t1->Fill();
    // }

    counter++;
    // std::cout << std::endl;
    // std::cout << "============================================"<< std::endl;
    // std::cout << std::endl;


    int perc = ((100*counter)/nEntries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }


  }

  std::cout << std::endl;
  // int sumFirst = 0;
  // int sumSecond = 0;
  // for (int i = 0 ; i < 64; i++)
  // {
  //   std::cout << "First["<< i <<  "] = " << firstCrystal[i] << std::endl;
  //   std::cout << "Second["<< i <<  "] = " << secondCrystal[i] << std::endl;
  //   sumFirst += firstCrystal[i];
  //   sumSecond += secondCrystal[i];
  // }
  // std::cout << "sumFirst = " << sumFirst << " sumSecond = " << sumSecond << std::endl;
  std::cout << "1 cry [511 KeV deposition] events = "    << singleCounter << std::endl;
  std::cout << "2 cry [511 KeV deposition] events = "    << doubleCounter << std::endl;
  std::cout << "3 cry [511 KeV deposition] events = "    << tripleCounter << std::endl;
  std::cout << "Multi cry [511 KeV deposition] events = "<< multipleCounter << std::endl;
  std::cout << "Returned = " << globalReturned << std::endl;
  std::cout << "Candidates = "<< foundCandidate << std::endl;

  TF1 *line = new TF1("line","x",-7,7);
  line->SetLineColor(kRed);
  TF1 *line2 = new TF1("line2","x",0,2000);
  line2->SetLineColor(kRed);



  std::string outFile = "FileOut.root";
  TFile* fOut = new TFile(outFile.c_str(),"recreate");


  histoSigmaX->Write();
  histoSigmaY->Write();
  histoSigmaZ->Write();
  DeltaZ->Write();
  DeltaE->Write();
  DeltaR->Write();
  DeltaR_xy->Write();
  DeltaEvsDeltaZ->Write();
  TCanvas *C_flood = new TCanvas("C_flood","C_flood",800,800);
  flood->Draw("COLZ");
  C_flood->Write();
  TCanvas *C_averageZvsRatio = new TCanvas("C_averageZvsRatio","C_averageZvsRatio",800,800);
  C_averageZvsRatio->cd();
  averageZvsRatio->Draw();
  C_averageZvsRatio->Write();

  TCanvas *C_normalizedZvsRatio = new TCanvas("C_normalizedZvsRatio","C_normalizedZvsRatio",800,800);
  C_normalizedZvsRatio->cd();
  normalizedZvsRatio->Draw();
  C_normalizedZvsRatio->Write();

  TCanvas *C_averageZvsWi = new TCanvas("C_averageZvsWi","C_averageZvsWi",800,800);
  C_averageZvsWi->cd();
  averageZvsWi->Draw();
  C_averageZvsWi->Write();

  TCanvas *C_wivsRatio = new TCanvas("C_wivsRatio","C_wivsRatio",800,800);
  C_wivsRatio->cd();
  wivsRatio->Draw();
  line->Draw("same");
  C_wivsRatio->Write();

  TCanvas *C_wMeasuredvsRatioW = new TCanvas("C_wMeasuredvsRatioW","C_wMeasuredvsRatioW",800,800);
  C_wMeasuredvsRatioW->cd();
  wMeasuredvsRatioW->Draw();
  line->Draw("same");
  C_wMeasuredvsRatioW->Write();

  TCanvas *C_uMeasuredVsRatioU = new TCanvas("C_uMeasuredVsRatioU","C_uMeasuredVsRatioU",800,800);
  C_uMeasuredVsRatioU->cd();
  uMeasuredVsRatioU->Draw();
  line->Draw("same");
  C_uMeasuredVsRatioU->Write();

  TCanvas *C_vMeasuredVsRatioV = new TCanvas("C_vMeasuredVsRatioV","C_vMeasuredVsRatioV",800,800);
  C_vMeasuredVsRatioV->cd();
  vMeasuredVsRatioV->Draw();
  line->Draw("same");
  C_vMeasuredVsRatioV->Write();




  TCanvas *C_kMeasuredvsRatioF = new TCanvas("C_kMeasuredvsRatioF","C_kMeasuredvsRatioF",800,800);
  C_kMeasuredvsRatioF->cd();
  kMeasuredvsRatioF->Draw();
  line->Draw("same");
  C_kMeasuredvsRatioF->Write();

  TCanvas *C_kMeasuredvsPmaxi = new TCanvas("C_kMeasuredvsPmaxi","C_kMeasuredvsPmaxi",800,800);
  C_kMeasuredvsPmaxi->cd();
  kMeasuredvsPmaxi->Draw();
  line->Draw("same");
  C_kMeasuredvsPmaxi->Write();

  TCanvas *C_pmaxiVsRatioF = new TCanvas("C_pmaxiVsRatioF","C_pmaxiVsRatioF",800,800);
  C_pmaxiVsRatioF->cd();
  pmaxiVsRatioF->Draw();
  line2->Draw("same");
  C_pmaxiVsRatioF->Write();


  // t1->Write();

  //   f1->Close();

  // std::string outFile = "analysis_OUT.root";
  // TFile* fOut = new TFile(outFile.c_str(),"recreate");

  // flood->Write();
  // positions->Write();
  //   f1->Close();

  fOut->Close();



  return 0;
}
示例#7
0
void RunUEAnalysis(int nentries = 1E3,
		   const char* jetfile  = "/gpfs01/star/i_bnl/gdwebb/Run9/500GeVJets/Data/10103041/st_physics_10103041_raw_*.jets.root",
		   const char* skimfile = "/gpfs01/star/i_bnl/gdwebb/Run9/500GeVJets/Data/10103041/st_physics_10103041_raw_*.skim.root",
		   const char* uefile = "/gpfs01/star/i_bnl/gdwebb/Run9/500GeVJets/Data/10103041/st_physics_10103041_raw_*.ue.root",
		   const char* outfile = "test_jetQAData500Gev_10103041.root",
		   const Int_t  mEmbed = 0)
{
  cout << "jetfile  = " << jetfile  << endl;
  cout << "skimfile = " << skimfile << endl;
  cout << "uefile   = " << uefile << endl;
  cout << "outfile  = " << outfile << endl;
  const float area  =  4*TMath::Pi()/3;
  const float area2 =  2*TMath::Pi()/3;

  cout << "area: " << area << endl;

  // Open jet & skim files
  TChain* jetChain  = new TChain("jet");
  TChain* skimChain = new TChain("jetSkimTree");
  TChain* ueChain   = new TChain("ue");

  jetChain->Add(jetfile);
  skimChain->Add(skimfile);
  ueChain->Add(uefile);
  nentries = jetChain->GetEntriesFast();
  cout << "nentries = " << nentries << endl;
  
  // Set jet buffer
  StJetEvent* jetEvent = 0;
  jetChain->SetBranchAddress("AntiKtR060NHits12",&jetEvent);

  // Set skim buffer
  StJetSkimEvent* skimEvent = 0;
  skimChain->SetBranchAddress("skimEventBranch",&skimEvent); 

  StUeEvent* ueEvent_transP = 0;
  ueChain->SetBranchAddress("transP_AntiKtR060NHits12",&ueEvent_transP);

  StUeEvent* ueEvent_transM = 0;
  ueChain->SetBranchAddress("transM_AntiKtR060NHits12",&ueEvent_transM);

  StUeEvent* ueEvent_away = 0;
  ueChain->SetBranchAddress("away_AntiKtR060NHits12",&ueEvent_away);

  StUeEvent* ueEvent_toward = 0;
  ueChain->SetBranchAddress("toward_AntiKtR060NHits12",&ueEvent_toward);

  // Open output file for writing
  TFile* ofile = TFile::Open(outfile,"recreate");
  assert(ofile);

  //Book histograms
  TH1F* hleadingjetpTJP2 = new TH1F("hleadingjetpTJP2",";Leading jet p_{T} [GeV]",40,0,80);

  //Event Histograms
  TH2F* htransP_numTracksVsMaxJetpTJP2 = new TH2F("htransP_numTracksVsMaxJetpTJP2","transP; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransP_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransP_sumTrackpTVsMaxJetpTJP2","transP;  jet p_{T} [GeV]; <#Sigmap_{T,ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransP_numTowersVsMaxJetpTJP2 = new TH2F("htransP_numTowersVsMaxJetpTJP2","transP; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransP_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransP_sumTowerEtVsMaxJetpTJP2","transP;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransP_sumpTVsMaxJetpTJP2 = new TH2F("htransP_sumpTVsMaxJetpTJP2","transP; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransM_numTracksVsMaxJetpTJP2 = new TH2F("htransM_numTracksVsMaxJetpTJP2","transM; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransM_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransM_sumTrackpTVsMaxJetpTJP2","transM;  jet p_{T} [GeV]; #Sigmatrack p_{T}",40,0,80,320,0.,20.);

  TH2F* htransM_numTowersVsMaxJetpTJP2 = new TH2F("htransM_numTowersVsMaxJetpTJP2","transM; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransM_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransM_sumTowerEtVsMaxJetpTJP2","transM;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransM_sumpTVsMaxJetpTJP2 = new TH2F("htransM_sumpTVsMaxJetpTJP2","transM; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransverse_numTracksVsMaxJetpTJP2 = new TH2F("htransverse_numTracksVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransverse_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransverse_sumTrackpTVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; #Sigmatrack p_{T}",40,0,80,320,0.,20.);

  TH2F* htransverse_numTowersVsMaxJetpTJP2 = new TH2F("htransverse_numTowersVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransverse_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransverse_sumTowerEtVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransverse_sumpTVsMaxJetpTJP2 = new TH2F("htransverse_sumpTVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransverse_dPtVsMaxJetpTJP2 = new TH2F("htransverse_dPtVsMaxJetpTJP2","transverse; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)] * (jet area)",40,0,80,320,0.,20.);

  TH2F* htransDiff_numTracksVsMaxJetpTJP2 = new TH2F("htransDiff_numTracksVsMaxJetpTJP2","transDiff; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransDiff_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransDiff_sumTrackpTVsMaxJetpTJP2","transDiff; jet p_{T} [GeV]; #Sigmatrack p_{T}",40,0,80,320,0.,20.);
  TH2F* htransDiff_numTowersVsMaxJetpTJP2 = new TH2F("htransDiff_numTowersVsMaxJetpTJP2","transDiff; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransDiff_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransDiff_sumTowerEtVsMaxJetpTJP2","transDiff; jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransDiff_sumpTVsMaxJetpTJP2 = new TH2F("htransDiff_sumpTVsMaxJetpTJP2","transDiff; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransMax_numTracksVsMaxJetpTJP2 = new TH2F("htransMax_numTracksVsMaxJetpTJP2","transMax; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransMax_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransMax_sumTrackpTVsMaxJetpTJP2","transMax;  jet p_{T} [GeV]; <#Sigmap_{T,ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransMax_numTowersVsMaxJetpTJP2 = new TH2F("htransMax_numTowersVsMaxJetpTJP2","transMax; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransMax_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransMax_sumTowerEtVsMaxJetpTJP2","transMax;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransMin_numTracksVsMaxJetpTJP2 = new TH2F("htransMin_numTracksVsMaxJetpTJP2","transMin; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransMin_sumTrackpTVsMaxJetpTJP2 = new TH2F("htransMin_sumTrackpTVsMaxJetpTJP2","transMin;  jet p_{T} [GeV]; <#Sigmap_{T,ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransMin_numTowersVsMaxJetpTJP2 = new TH2F("htransMin_numTowersVsMaxJetpTJP2","transMin; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransMin_sumTowerEtVsMaxJetpTJP2 = new TH2F("htransMin_sumTowerEtVsMaxJetpTJP2","transMin;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htransMax_sumpTVsMaxJetpTJP2 = new TH2F("htransMax_sumpTVsMaxJetpTJP2", "transMax; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htransMin_sumpTVsMaxJetpTJP2 = new TH2F("htransMin_sumpTVsMaxJetpTJP2", "transMin; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* haway_numTracksVsMaxJetpTJP2 = new TH2F("haway_numTracksVsMaxJetpTJP2","away; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* haway_sumTrackpTVsMaxJetpTJP2 = new TH2F("haway_sumTrackpTVsMaxJetpTJP2","away;  jet p_{T} [GeV]; <#Sigmap_{T,ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* haway_numTowersVsMaxJetpTJP2 = new TH2F("haway_numTowersVsMaxJetpTJP2","away; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* haway_sumTowerEtVsMaxJetpTJP2 = new TH2F("haway_sumTowerEtVsMaxJetpTJP2","away;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* haway_sumpTVsMaxJetpTJP2 = new TH2F("haway_sumpTVsMaxJetpTJP2","away; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htoward_numTracksVsMaxJetpTJP2 = new TH2F("htoward_numTracksVsMaxJetpTJP2","toward; jet p_{T} [GeV]; <N_{ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htoward_sumTrackpTVsMaxJetpTJP2 = new TH2F("htoward_sumTrackpTVsMaxJetpTJP2","toward;  jet p_{T} [GeV]; <#Sigmap_{T,ch}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  TH2F* htoward_numTowersVsMaxJetpTJP2 = new TH2F("htoward_numTowersVsMaxJetpTJP2","toward; jet p_{T} [GeV]; <N_{0}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htoward_sumTowerEtVsMaxJetpTJP2 = new TH2F("htoward_sumTowerEtVsMaxJetpTJP2","toward;  jet p_{T} [GeV]; <#SigmaE_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);
  TH2F* htoward_sumpTVsMaxJetpTJP2 = new TH2F("htoward_sumpTVsMaxJetpTJP2","toward; jet p_{T} [GeV]; <#Sigmap_{T}>/[#Delta#eta#Delta(#Delta#phi)]",40,0,80,320,0.,20.);

  Float_t sumtrackpT_transP, sumtowerEt_transP, sumpT_transP, sumtrackpT_transM, sumtowerEt_transM, sumpT_transM;
  Float_t numtracks_transP, numtowers_transP, numtracks_transM, numtowers_transM;
  Float_t sumtrackpT_transMax, sumtowerEt_transMax,sumpT_transMax, sumtrackpT_transMin, sumtowerEt_transMin, sumpT_transMin;
  Float_t numtracks_transMax, numtowers_transMax, numtracks_transMin, numtowers_transMin;
  Float_t sumtowerEt_away, sumtrackpT_away, sumpT_away, sumtrackpT_toward, sumtowerEt_toward, sumpT_toward;
  Float_t numtowers_away, numtracks_away, numtracks_toward, numtowers_toward;
  Float_t leadingJetpT;

  for (int iEntry = 0; iEntry < nentries; ++iEntry) {
    if (jetChain->GetEvent(iEntry) <= 0 || skimChain->GetEvent(iEntry) <= 0 || ueChain->GetEvent(iEntry) <= 0) break;
    // Should not be null
    assert(jetEvent && skimEvent && ueEvent_transP);
    
    // Enforce event synchronization
    assert(jetEvent->runId() == skimEvent->runId() && jetEvent->eventId() == skimEvent->eventId());
    assert(jetEvent->runId() == ueEvent_transP->runId() && jetEvent->eventId() == ueEvent_transP->eventId());
    
    if (iEntry % 1000 == 0) cout << iEntry << endl;
    //   hrunnumber->Fill(jetEvent->runId());
  
    //JP2 trigger
    StJetSkimTrig* trigJP2 = skimEvent->trigger(370621);
    if (!trigJP2) trigJP2 = skimEvent->trigger(230411);
    bool flagtrigJP2 = trigPass(trigJP2, mEmbed); // hardware and software triggers
    map<int,int> barrelJetPatches = skimEvent->barrelJetPatchesAboveTh(2);
    
    StJetVertex* vertex = jetEvent->vertex();
    StJetVertex* ue_vertex = ueEvent_transP->vertex();
    bool vertexBool = vertexPass(vertex, ue_vertex);
    if(!vertexBool) continue;
    
    StJetCandidate *leadingjet = findLeadingJet(vertex); // Leading jet from jet 
    if(leadingjet->pt() != ueEvent_transP->leadingJetpt()) continue;
    if(TMath::Abs(leadingjet->detEta()) > 0.5) { continue;}
    if(leadingjet->rt() > 0.9){continue;} 
    bool trackpT_high = hightrackpT(leadingjet);
    if(trackpT_high) continue;
    
    Bool_t geoFlagJP2  = matchedToJetPatch(leadingjet,barrelJetPatches); // Geo Flag

    leadingJetpT = leadingjet->pt(); //Define the leading jet pT 
    if( flagtrigJP2 && geoFlagJP2){//did, should, and geo trigs fired 

      hleadingjetpTJP2->Fill(leadingJetpT); 
      
      //-----------------Transverse Plus ------------------------
      sumtrackpT_transP = ueEvent_transP->sumTrackPt();
      sumtowerEt_transP = ueEvent_transP->sumTowerPt();
      sumpT_transP      = ueEvent_transP->sumPt();

      numtracks_transP = ueEvent_transP->numberOfTracks();
      numtowers_transP = ueEvent_transP->numberOfTowers();

      //track transP
      htransP_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_transP/area2);
      htransP_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_transP/area2);

      //tower transP
      htransP_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_transP/area2);
      htransP_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_transP/area2);

      htransP_sumpTVsMaxJetpTJP2->Fill(leadingJetpT, sumpT_transP/area2);
      // ------------------- End Of Trans Plus --------------------------

      //-----------------Transverse Minus ------------------------
      sumtrackpT_transM = ueEvent_transM->sumTrackPt();
      sumtowerEt_transM = ueEvent_transM->sumTowerPt(); 
      sumpT_transM      = ueEvent_transM->sumPt();

      numtracks_transM = ueEvent_transM->numberOfTracks();
      numtowers_transM = ueEvent_transM->numberOfTowers();
      
      //track transM
      htransM_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_transM/area2);
      htransM_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_transM/area2);
      
      //tower transM
      htransM_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_transM/area2);
      htransM_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_transM/area2);

      htransM_sumpTVsMaxJetpTJP2->Fill(leadingJetpT, sumpT_transM/area2);
      // ------------------- End Of Trans Minus --------------------------
      
      //----------------Transverse Region------------------------

      //track transverse
      htransverse_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,(numtracks_transP + numtracks_transM)/area);
      htransverse_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,(sumtrackpT_transP + sumtrackpT_transM)/area);
      
      //tower transverse
      htransverse_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,(numtowers_transP + numtowers_transM)/area);
      htransverse_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,(sumtowerEt_transP + sumtowerEt_transM)/area);

      htransverse_sumpTVsMaxJetpTJP2->Fill(leadingJetpT, (sumpT_transP + sumpT_transM)/area);

      double jet_area = leadingjet->area();
      htransverse_dPtVsMaxJetpTJP2->Fill(leadingJetpT, (sumpT_transP + sumpT_transM) / area * jet_area);

      //--------------End of Transverse-------------------------      

      htransDiff_numTracksVsMaxJetpTJP2->Fill(leadingJetpT, fabs(numtracks_transP - numtracks_transM)/area);
      htransDiff_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT, fabs(sumtrackpT_transP - sumtrackpT_transM)/area);

      htransDiff_numTowersVsMaxJetpTJP2->Fill(leadingJetpT, fabs(numtowers_transP - numtowers_transM)/area);
      htransDiff_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT, fabs(sumtowerEt_transP - sumtowerEt_transM)/area);

      htransDiff_sumpTVsMaxJetpTJP2->Fill(leadingJetpT, fabs(sumpT_transP - sumpT_transM)/area);

      //----------------- Away Region ------------------------
      sumtrackpT_away = sumtowerEt_away = 0; 
      numtracks_away = numtowers_away = 0; 
      sumpT_away = 0;

      sumtrackpT_away = ueEvent_away->sumTrackPt();
      sumtowerEt_away = ueEvent_away->sumTowerPt(); 
      sumpT_away      = ueEvent_away->sumPt();
     
      numtracks_away = ueEvent_away->numberOfTracks();
      numtowers_away = ueEvent_away->numberOfTowers();
      
      //track away
      haway_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_away/area);
      haway_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_away/area);
      
      //tower away
      haway_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_away/area);
      haway_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_away/area);

      haway_sumpTVsMaxJetpTJP2->Fill(leadingJetpT,sumpT_away/area);
      // ------------------- End Of Away --------------------------

      //----------------- Toward Region ---------------------------
      sumtrackpT_toward = sumtowerEt_toward = 0;      
      numtracks_toward  = numtowers_toward  = 0;      
      sumpT_toward = 0;

      sumtrackpT_toward = ueEvent_toward->sumTrackPt();
      sumtowerEt_toward = ueEvent_toward->sumTowerPt(); 
      sumpT_toward      = ueEvent_toward->sumPt();

      numtracks_toward = ueEvent_toward->numberOfTracks();
      numtowers_toward = ueEvent_toward->numberOfTowers(); 

      //track toward
      htoward_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_toward/area);
      htoward_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_toward/area);
      
      //tower toward
      htoward_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_toward/area);
      htoward_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_toward/area);

      htoward_sumpTVsMaxJetpTJP2->Fill(leadingJetpT, sumpT_toward/area);
      // ------------------- End Of Toward --------------------------
      
    
      //--------- Sum Track pT Trans Max and Trans Min -------------
      if (sumtrackpT_transP == sumtrackpT_transM) {
         cout << "sumtrackpT_transP = " << sumtrackpT_transP << "\t"
              << "sumtrackpT_transM = " << sumtrackpT_transM << endl;
      }
      sumtrackpT_transMax =  std::max(sumtrackpT_transP, sumtrackpT_transM);
      sumtrackpT_transMin =  std::min(sumtrackpT_transP, sumtrackpT_transM);

      htransMax_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_transMax/area2);
      htransMin_sumTrackpTVsMaxJetpTJP2->Fill(leadingJetpT,sumtrackpT_transMin/area2);     
      //---------------------------------------------------      
      

      //--------- Num Tracks Trans Max and Trans Min -------------
      if (numtracks_transP == numtracks_transM) {
         cout << "numtracks_transP = " << numtracks_transP << "\t"
              << "numtracks_transM = " << numtracks_transM << endl;
      }
      numtracks_transMax = std::max(numtracks_transP, numtracks_transM);
      numtracks_transMin = std::min(numtracks_transP, numtracks_transM);
      
      htransMax_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_transMax/area2);
      htransMin_numTracksVsMaxJetpTJP2->Fill(leadingJetpT,numtracks_transMin/area2);
      // -----------------------------------------------------------
    
      //--------- Sum Tower Et Trans Max and Trans Min -------------
      if (sumtowerEt_transP == sumtowerEt_transM) {
         cout << "sumtowerEt_transP = " << sumtowerEt_transP << "\t"
              << "sumtowerEt_transM = " << sumtowerEt_transM << endl;
      }
      sumtowerEt_transMax = std::max(sumtowerEt_transP, sumtowerEt_transM);
      sumtowerEt_transMin = std::min(sumtowerEt_transP, sumtowerEt_transM);

      htransMax_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_transMax/area2);
      htransMin_sumTowerEtVsMaxJetpTJP2->Fill(leadingJetpT,sumtowerEt_transMin/area2);
      //----------------------------------------------------------

      //--------- Num Towers Trans Max and Trans Min -------------
      if (numtowers_transP == numtowers_transM) {
         cout << "numtowers_transP = " << numtowers_transP << "\t"
              << "numtowers_transM = " << numtowers_transM << endl;
      }
      numtowers_transMax = std::max(numtowers_transP, numtowers_transM);
      numtowers_transMin = std::min(numtowers_transP, numtowers_transM);

      htransMax_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_transMax/area2);
      htransMin_numTowersVsMaxJetpTJP2->Fill(leadingJetpT,numtowers_transMin/area2);
      // -------------------------------------------------------


      //--------- Sum pT Trans Max and Trans Min -------------
      if (sumpT_transP == sumpT_transM) {
         cout << "sumpT_transP = " << sumpT_transP << "\t"
              << "sumpT_transM = " << sumpT_transM << endl;
      }
      sumpT_transMax = std::max(sumpT_transP, sumpT_transM);
      sumpT_transMin = std::min(sumpT_transP, sumpT_transM);

      htransMax_sumpTVsMaxJetpTJP2->Fill(leadingJetpT,sumpT_transMax/area2);
      htransMin_sumpTVsMaxJetpTJP2->Fill(leadingJetpT,sumpT_transMin/area2);     
      //---------------------------------------------------      
      
    }// End of JP2 if statement 
  }//End of Event Loop
  ofile->Write();
  ofile->Close();
}
示例#8
0
void revCalSimulation (Int_t runNumber, string b, string A) 
{

  int numFiles = 180;//(b==std::string("inf")?200:(A==std::string("-1")?200:20));

  bool allEvtsTrigg = false; //This just removes the use of the trigger function for an initial calibration. 
                            // Once a calibration is established (or if running on Betas), you can keep this false

  bool simProperStatistics = false; // If True, this uses the actual data run to determine the number of Type 0s to simulate

  
  cout << "Running reverse calibration for run " << runNumber << endl;  

  UInt_t BetaEvents = 0; //Holds the number of electron like Type 0 events to process

  Char_t temp[500],tempE[500],tempW[500];
  
  //First get the number of total electron events around the source position from the data file and also the length of the run
  
  //sprintf(temp,"%s/replay_pass4_%i.root",getenv("REPLAY_PASS4"),runNumber);
  sprintf(temp,"%s/replay_pass3_%i.root",getenv("REPLAY_PASS3"),runNumber);
  TFile *dataFile = new TFile(temp,"READ");
  TTree *data = (TTree*)(dataFile->Get("pass3"));
  
  sprintf(tempE,"Type<4 && Type>=0 && PID==1 && Side==0 && (xE.center*xE.center+yE.center*yE.center)<2500. && (xW.center*xW.center+yW.center*yW.center)<2500.");
  sprintf(tempW,"Type<4 && Type>=0 && PID==1 && Side==1 && (xW.center*xW.center+yW.center*yW.center)<2500. && (xE.center*xE.center+yE.center*yE.center)<2500.");
 
  BetaEvents = data->GetEntries(tempE) + data->GetEntries(tempW);
  cout << "Electron Events in Data file: " << BetaEvents << endl;
  cout << "East: " << data->GetEntries(tempE) << "\tWest: " << data->GetEntries(tempW) << endl;
  delete data;
  dataFile->Close(); 
  
  
  //If we have a Beta run and we don't want exact statistics, simulate 16 times the number of events
  if ( !simProperStatistics  ) {
    BetaEvents = 100*BetaEvents;
  } 

  std::cout << "Processing " << BetaEvents << " events...\n";



  ///////////////////////// SETTING GAIN OF FIRST and second DYNYODE
  Double_t g_d = 16.;
  Double_t g_rest = 12500.;

  /////// Loading other run dependent quantities
  vector <Int_t> pmtQuality = getEreconPMTQuality(runNumber); // Get the quality of the PMTs for that run
  UInt_t calibrationPeriod = getSrcRunPeriod(runNumber); // retrieve the calibration period for this run
  UInt_t XePeriod = getXeRunPeriod(runNumber); // Get the proper Xe run period for the Trigger functions
  //GetPositionMap(XePeriod);
  PositionMap posmap(5.0,50.); //Load position map with 5 mm bins
  posmap.readPositionMap(XePeriod,"endpoint");
  vector <Double_t> alpha = GetAlphaValues(calibrationPeriod); // fill vector with the alpha (nPE/keV) values for this run period


  /////////////// Load trigger functions //////////////////
  TriggerFunctions trigger(runNumber);

  std::vector < std::vector <Double_t> > pedestals = loadPMTpedestals(runNumber);
  std::vector < Double_t > PMTgain = loadGainFactors(runNumber);

  //Load the simulated relationship between EQ and Etrue
  EreconParameterization eRecon(runNumber);
  // Int_t pol = source=="Beta" ? getPolarization(runNumber) : 1;

  LinearityCurve linCurve(calibrationPeriod,false);
  std::cout << "Loaded Linearity Curves\n";

  //Decide which simulation to use...
  TChain *chain = new TChain("anaTree"); 

  std::string geom;
  if (runNumber<20000) geom = "2011-2012_geom";
  else if (runNumber>=21087 && runNumber<21679) geom = "2012-2013_isobutane_geom";
  else geom = "2012-2013_geom";
  
  TString fileLocation = TString::Format("/extern/mabrow05/ucna/xuan_stuff/AbFit_Fierz_2011-2013/%s/A_%s_b_%s/",
					 geom.c_str(),A.c_str(),b.c_str());
 
  std::cout << "Using simulation from " << fileLocation << "...\n";

  //Read in simulated data and put in a TChain
  TRandom3 *randFile = new TRandom3(runNumber*2);
  
  int fileNum = (int)(randFile->Rndm()*numFiles);
  delete randFile;
  for (int i=0; i<numFiles; i++) {
    if (fileNum==numFiles) fileNum=0;
    chain->AddFile(TString::Format("%s/xuan_analyzed_%i.root",fileLocation.Data(),fileNum));
    fileNum++;
  }

  // Set the addresses of the information read in from the simulation file
  /*chain->SetBranchAddress("MWPCEnergy",&mwpcE);       x
  chain->SetBranchAddress("time",&Time);                x
  chain->SetBranchAddress("Edep",&edep);                x
  chain->SetBranchAddress("EdepQ",&edepQ);              x
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);         x 
  chain->SetBranchAddress("ScintPos",&scint_pos);       x
  chain->SetBranchAddress("primKE",&primKE);            x
  chain->SetBranchAddress("primTheta",&primTheta);
  chain->SetBranchAddress("Cath_EX",Cath_EX);
  chain->SetBranchAddress("Cath_EY",Cath_EY);
  chain->SetBranchAddress("Cath_WX",Cath_WX);
  chain->SetBranchAddress("Cath_WY",Cath_WY);
  chain->SetBranchAddress("hitCountSD",hitCountSD);*/
  
  //These are for feeding in Xuan's simulations... this needs to be updated so that I can pass a flag and change these on the fly
  chain->SetBranchAddress("primaryParticleSpecies",&primaryID);
  chain->SetBranchAddress("mwpcEnergy",&mwpcE);
  chain->SetBranchAddress("scintTimeToHit",&Time);
  chain->SetBranchAddress("scintillatorEdep",&edep);
  chain->SetBranchAddress("scintillatorEdepQuenched",&edepQ);
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);
  chain->SetBranchAddress("ScintPos",&scint_pos);
  chain->SetBranchAddress("primaryKE",&primKE);
  chain->SetBranchAddress("primaryMomentum",primMom);


  //Set random number generator

  TRandom3 *seed = new TRandom3( 3*runNumber ); // seed generator
  TRandom3 *rand0 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );

  //Initialize random numbers for 8 pmt trigger probabilities
  TRandom3 *randPMTE1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );

  std::vector <Double_t> triggRandVec(4,0.);

  // Wirechamber information
  bool EastScintTrigger, WestScintTrigger, EMWPCTrigger, WMWPCTrigger; //Trigger booleans
  Double_t MWPCAnodeThreshold=0.; // keV dep in the wirechamber.. 


  //Get total number of events in TChain
  UInt_t nevents = chain->GetEntries();
  cout << "events = " << nevents << endl;
 
  //Start from random position in evt sequence if we aren't simulating veryHighStatistics
  UInt_t evtStart = seed->Rndm()*nevents;
    
  
  UInt_t evtTally = 0; //To keep track of the number of events 
  UInt_t evt = evtStart; //current event number


  vector < vector <Int_t> > gridPoint;

  
  //Create simulation output file
  
  TFile *outfile = new TFile(TString::Format("%s/revCalSim_%i.root",fileLocation.Data(),runNumber), "RECREATE");

  //Setup the output tree
  TTree *tree = new TTree("revCalSim", "revCalSim");
  SetUpTree(tree); //Setup the output tree and branches

  //Histograms of event types for quick checks
  vector <TH1D*> finalEn (6,NULL);
  finalEn[0] = new TH1D("finalE0", "Simulated Weighted Sum East Type 0", 400, 0., 1200.);
  finalEn[1] = new TH1D("finalW0", "Simulated Weighted Sum West Type 0", 400, 0., 1200.);
  finalEn[2] = new TH1D("finalE1", "Simulated Weighted Sum East Type 1", 400, 0., 1200.);
  finalEn[3] = new TH1D("finalW1", "Simulated Weighted Sum West Type 1", 400, 0., 1200.);
  finalEn[4] = new TH1D("finalE23", "Simulated Weighted Sum East Type 2/3", 400, 0., 1200.);
  finalEn[5] = new TH1D("finalW23", "Simulated Weighted Sum West Type 2/3", 400, 0., 1200.);


  //Read in events and determine evt type based on triggers
  while (evtTally<=BetaEvents) {
    if (evt>=nevents) evt=0; //Wrapping the events back to the beginning
    EastScintTrigger = WestScintTrigger = EMWPCTrigger = WMWPCTrigger = false; //Resetting triggers each event

    chain->GetEvent(evt);

    //Checking that the event occurs within the fiducial volume in the simulation to minimize
    // contamination from edge effects and interactions with detector walls
    // This is also the fiducial cut used in extracting asymmetries and doing calibrations
    Double_t fidCut = 50.;


    /////////////// Do position and Wirechamber stuff ///////////////////
    
    // Following negative sign is to turn x-coordinate into global coordinate on East
    scint_pos_adj.ScintPosAdjE[0] = scint_pos.ScintPosE[0]*sqrt(0.6)*1000.;
    scint_pos_adj.ScintPosAdjE[1] = scint_pos.ScintPosE[1]*sqrt(0.6)*1000.;
    scint_pos_adj.ScintPosAdjW[0] = scint_pos.ScintPosW[0]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[0]+displacementX;
    scint_pos_adj.ScintPosAdjW[1] = scint_pos.ScintPosW[1]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[1]+displacementY;
    scint_pos_adj.ScintPosAdjE[2] = scint_pos.ScintPosE[2]*1000.;
    scint_pos_adj.ScintPosAdjW[2] = scint_pos.ScintPosW[2]*1000.;

    
    Double_t mwpcAdjE[3] = {0.,0.,0.};
    Double_t mwpcAdjW[3] = {0.,0.,0.};
   
    mwpcAdjE[0] = mwpc_pos.MWPCPosE[0] * sqrt(0.6) * 1000.; 
    mwpcAdjE[1] = mwpc_pos.MWPCPosE[1] * sqrt(0.6) * 1000.; 
    mwpcAdjW[0] = mwpc_pos.MWPCPosW[0] * sqrt(0.6) * 1000. ;
    mwpcAdjW[1] = mwpc_pos.MWPCPosW[1] * sqrt(0.6) * 1000. ;
    mwpcAdjE[2] = mwpc_pos.MWPCPosE[2] * 1000. ;
    mwpcAdjW[2] = mwpc_pos.MWPCPosW[2] * 1000. ;
    

    
    //std::cout << mwpcAdjE[0] << "\t" << mwpcAdjW[0] << std::endl;
    //if (evtTally==5) exit(0);


    /////////////////////////////////////////////////////////////////////
    // Creating all extra structs to hold the alternate position reconstruction
    // crap before writing it all out
    /////////////////////////////////////////////////////////////////////
    

    std::vector <Double_t> eta; 
    std::vector <Double_t> trueEta; // This is the position map value of the actual event position, not the position as determined
                                    // by cathode reconstruction
    

    trueEta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0],
					scint_pos_adj.ScintPosAdjE[1],
					scint_pos_adj.ScintPosAdjW[0],
					scint_pos_adj.ScintPosAdjW[1]);
   
    eta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0],
				    scint_pos_adj.ScintPosAdjE[1],
				    scint_pos_adj.ScintPosAdjW[0],
				    scint_pos_adj.ScintPosAdjW[1]);

      
      
    //MWPC triggers
    if (mwpcE.MWPCEnergyE>MWPCAnodeThreshold) EMWPCTrigger=true;
    if (mwpcE.MWPCEnergyW>MWPCAnodeThreshold) WMWPCTrigger=true;
    
    std::vector<Double_t> ADCvecE(4,0.);
    std::vector<Double_t> ADCvecW(4,0.);

    //East Side smeared PMT energies
    
    
    for (UInt_t p=0; p<4; p++) {
      if ( edep.EdepE>0. ) { //Check to make sure that there is light to see in the scintillator
	
	if (eta[p]>0.) {

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQE))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecE[p] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p]/eta[p];

	}

	else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut
	  
	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQE))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecE[p] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p];

	}


	
	pmt.nPE[p] = alpha[p]*pmt.etaEvis[p] ;

      }

    // If eQ is 0...
      else {
	pmt.etaEvis[p] = 0.;
	pmt.Evis[p] = 0.;
	pmt.nPE[p] = 0.;
	
      }
    }
  
    Double_t numer=0., denom=0.;
    
    for (UInt_t p=0;p<4;p++) {
      numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.;
      denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.;
      //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.;
      //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.;
    }

    
    Double_t totalEnE = denom>0. ? numer/denom : 0.;
    evis.EvisE = totalEnE;

    //Now we apply the trigger probability
    triggRandVec[0] = randPMTE1->Rndm();
    triggRandVec[1] = randPMTE2->Rndm();
    triggRandVec[2] = randPMTE3->Rndm();
    triggRandVec[3] = randPMTE4->Rndm();
    
    if ( (allEvtsTrigg && totalEnE>0.) || ( trigger.decideEastTrigger(ADCvecE,triggRandVec) ) ) EastScintTrigger = true; 
      
    //West Side
    for (UInt_t p=4; p<8; p++) {
      if ( !(p==5 && runNumber>16983 && runNumber<17249) &&  edep.EdepW>0. ) { //Check to make sure that there is light to see in the scintillator and that run isn't one where PMTW2 was dead
	
	if (eta[p]>0.) {

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQW))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecW[p-4] = ADC;
	  //cout << ADCvecW[p-4] << endl;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);	  
	  pmt.Evis[p] = pmt.etaEvis[p]/eta[p];

	}

	else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQW))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecW[p-4] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p];
	  
	}

	pmt.nPE[p] = alpha[p]*pmt.etaEvis[p];
	
      }
      // If PMT is dead and EQ=0...
      else {
	pmt.etaEvis[p] = 0.;
	pmt.Evis[p] = 0.;
	pmt.nPE[p] = 0.;
      }
    }

     //Calculate the total weighted energy
    numer=denom=0.;
    for (UInt_t p=4;p<8;p++) {
      numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.;
      denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.;
      //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.;
      //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.;
    }
    //Now we apply the trigger probability
    Double_t totalEnW = denom>0. ? numer/denom : 0.;
    evis.EvisW = totalEnW;

    triggRandVec[0] = randPMTW1->Rndm();
    triggRandVec[1] = randPMTW2->Rndm();
    triggRandVec[2] = randPMTW3->Rndm();
    triggRandVec[3] = randPMTW4->Rndm();
    
    if ( (allEvtsTrigg && totalEnW>0.) || ( trigger.decideWestTrigger(ADCvecW,triggRandVec) ) ) WestScintTrigger = true;

    //if (totalEnW<25.) std::cout << totalEnW << " " << WestScintTrigger << "\n";

            
    //Fill proper total event histogram based on event type
    PID=6; //This is an unidentified particle
    type=4; //this is a lost event
    side=2; //This means there are no scintillator triggers

    //Type 0 East
    if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && !WMWPCTrigger) {
      PID=1;
      type=0;
      side=0;
      //finalEn[0]->Fill(evis.EvisE);
      //cout << "Type 0 East E = " << totalEnE << endl;
    }
    //Type 0 West
    else if (WestScintTrigger && WMWPCTrigger && !EastScintTrigger && !EMWPCTrigger) {
      PID=1;
      type=0;
      side=1;
      //finalEn[1]->Fill(totalEnW);
    }
    //Type 1 
    else if (EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=1;
      //East
      if (Time.timeE<Time.timeW) {
	//finalEn[2]->Fill(totalEnE);
	side=0;
      }
      //West
      else if (Time.timeE>Time.timeW) {
	//finalEn[3]->Fill(totalEnW);
	side=1;
      }
    }
    //Type 2/3 East
    else if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=2;
      side=0;
      //finalEn[4]->Fill(totalEnE);
      //cout << "Type 2/3 East E = " << totalEnE << endl;
    }
    //Type 2/3 West
    else if (!EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=2;
      side=1;
      //finalEn[5]->Fill(totalEnW);
      //cout << "Type 2/3 East W = " << totalEnW << endl;
    }   
    //Gamma events and missed events (Type 4)
    else {
      if (!WMWPCTrigger && !EMWPCTrigger) {
	if (EastScintTrigger && !WestScintTrigger) {
	  PID=0;
	  type=0;
	  side=0;
	}
	else if (!EastScintTrigger && WestScintTrigger) {
	  PID=0;
	  type=0;
	  side=1;
	}
	else if (EastScintTrigger && WestScintTrigger) {
	  PID=0;
	  type=1;
	  if (Time.timeE<Time.timeW) {
	    side=0;
	  }
	  else {
	    side=1;
	  }
	}
	else {
	  PID=6;
	  type=4;
	  side=2;
	}
      }
      else {
	PID=1;
	type=4;
	side = (WMWPCTrigger && EMWPCTrigger) ? 2 : (WMWPCTrigger ? 1 : 0); //Side==2 means the event triggered both wirechambers, but neither scint
      }
    }
    
    //Calculate Erecon
    Erecon = -1.;
    Int_t typeIndex = (type==0 || type==4) ? 0:(type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue
    if (side==0) {
      Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisE;
      if (evis.EvisE>0. && totalEvis>0.) {
	Erecon = eRecon.getErecon(0,typeIndex,totalEvis);
	if (type==0) finalEn[0]->Fill(Erecon); 
	else if (type==1) finalEn[2]->Fill(Erecon); 
	else if(type==2 ||type==3) finalEn[4]->Fill(Erecon);
      }
      else Erecon=-1.;
      
    }
    if (side==1) {
      Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisW;
      if (evis.EvisW>0. && totalEvis>0.) {
	Erecon = eRecon.getErecon(1,typeIndex,totalEvis);	
	if (type==0) finalEn[1]->Fill(Erecon); 
	else if (type==1) finalEn[3]->Fill(Erecon); 
	else if(type==2 ||type==3) finalEn[5]->Fill(Erecon);
      }
      else Erecon=-1.;
    }    
  
    if ( PID==1 && Erecon>0. &&  sqrt( scint_pos_adj.ScintPosAdjE[0]*scint_pos_adj.ScintPosAdjE[0]
				       + scint_pos_adj.ScintPosAdjE[1]*scint_pos_adj.ScintPosAdjE[1] )<fidCut &&
	 sqrt( scint_pos_adj.ScintPosAdjW[0]*scint_pos_adj.ScintPosAdjW[0]
				       + scint_pos_adj.ScintPosAdjW[1]*scint_pos_adj.ScintPosAdjW[1] )<fidCut ) evtTally++;
    
    evt++;
    
    tree->Fill();
    if (evtTally%10000==0) {std::cout << evtTally  << "    PID=" << PID << "    Erecon=" << Erecon << std::endl;}//cout << "filled event " << evt << endl;
  }
  cout << endl;

  delete chain; delete seed; delete rand0; delete rand1; delete rand2; delete rand3;
  delete randPMTE1; delete randPMTE2; delete randPMTE3; delete randPMTE4; delete randPMTW1; delete randPMTW2; delete randPMTW3; delete randPMTW4;

  outfile->Write();
  outfile->Close();
  

}
示例#9
0
void filter(const int type){
  int M_MODE = 0;
  TChain* tree = new TChain("TEvent");
  string fname;
  switch(type){
  case 0://Data
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_data.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_data.root");
    break;
  case 11://Signal MC pi0
    M_MODE = 1;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcPI0_s7.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcPi0_s7.root");
    break;
  case 12://Signal MC eta
    M_MODE = 2;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcETA_s2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcEta_s2.root");
    break;
  case 13://Signal MC omega
    M_MODE = 3;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcOMEGA_s5.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcOmega_s5.root");
    break;
  case 14://Signal MC rho
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcRHO_s1.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcRho_s1.root");
    break;
  case 15://Signal MC eta'
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcETAP_s1.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcETAP_s1.root");
    break;
  case 21://charged
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_2.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_12.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charged_2_12.root");
    break;
  case 22://mixed
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_2.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_12.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_mixed_2_12.root");
    break;
  case 23://charm
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charm_12.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charm_2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charm_2_12.root");
    break;
  case 24://uds
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_uds_12.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_uds_2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_uds_2_12.root");
    break;
  case 2://Generic MC
//    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_gen.root");
//    stringstream out;
//    string path("/home/vitaly/B0toDh0/Tuples/");
    vector<string> types;
    types.push_back(string("charged"));
    types.push_back(string("mixed"));
    types.push_back(string("uds"));
    types.push_back(string("charm"));
    for(int i=0; i<types.size(); i++){
      for(int j=0; j<1; j++){
        out.str("");
        out << path << "b2dh_" << types[i] << "_" << j << ".root";
        tree->Add(out.str().c_str());
      }
    }
    fname = string("fil_b2dh_gen_0_2.root");
    break;
  case 3://Continuum
//    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_cont.root");
    stringstream out;
    string path("/home/vitaly/B0toDh0/Tuples/");
    vector<string> types;
    types.push_back(string("uds"));
    types.push_back(string("charm"));
    for(int i=0; i<types.size(); i++){
      for(int j=0; j<6; j++){
        out.str("");
	    out << path << "b2dh_" << types[i] << "_" << j << ".root";
	    tree->Add(out.str().c_str());
	  }
    }
    fname = string("fil_b2dh_cont.root");
    break;
  case 4://Custom
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_0.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_0.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_11.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_1.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_11.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_1.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charm_0_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/fil_b2dh_uds_0_10.root");
    fname = string("fil_b2dh_gen.root");
    break;
  default:
    return;
  }
  Double_t p_d0,p_h0,p_ks,p_pi0_h0,p_pip_h0,p_pim_h0,pi0_chi2,egamma,cos_thr,cos_hel,thr_sig,thr_oth;
  Int_t ndf_tag_vtx,phsp,bin,exp,run,evtn;
  Int_t b0f,d0f;
  Double_t k0mm2,k0et,k0hso00,k0hso02,k0hso04,k0hso10,k0hso12,k0hso14,k0hso20,k0hso22,k0hso24,k0hoo0,k0hoo1,k0hoo2,k0hoo3,k0hoo4;
  Double_t k1mm2,k1et,k1hso00,k1hso01,k1hso02,k1hso03,k1hso04,k1hso10,k1hso12,k1hso14,k1hso20,k1hso22,k1hso24,k1hoo0,k1hoo1,k1hoo2,k1hoo3,k1hoo4;

  Double_t mbc,de,mp,mm,dz,atckpi_max,mpi0,mh0,mk;
  Double_t ks_dr,ks_dz,ks_dphi,ks_fl,tag_LH,tag_LH_err;
  Double_t mp_mc,mm_mc,d0_t_mc,dt_mc,dz_mc,bin_mc,flv_mc,d0_flv_mc;
//  Double_t z_sig_d0;
//  Double_t sz_sig_d0;
//  Double_t dz_mc_sig_d0;
  Double_t chi2_vtx_d0, chi2_mass_d0;
  Int_t good_icpv;//,good_icpv_d0;

  Int_t mode,h0mode,h0f,pi0f;
  Double_t z_sig,z_asc;
  Double_t sz_sig,sz_asc;
  Int_t ntrk_sig,ntrk_asc,ndf_z_sig,ndf_z_asc;
  Double_t chisq_z_sig,chisq_z_asc,h0_chi2;
  Double_t cl_z_sig,cl_z_asc;
  Double_t costhB,costhBcms,Ecms;
  Double_t t_sig_mc,z_sig_mc,t_asc_mc,z_asc_mc;
  Double_t dz_mc_sig, dz_mc_asc;
  Double_t z_upsilon;
//  Double_t dz_pull_sig,dz_pull_sig_d0,dz_pull_asc;
  Int_t nptag;

  tree->Print();

  TFile *ofile = new TFile(fname.c_str(),"RECREATE");
  TTree* TEvent = new TTree("TEvent","TEvent");

  tree->SetBranchAddress("exp",&exp);
  tree->SetBranchAddress("run",&run);
  tree->SetBranchAddress("evtn",&evtn);

  tree->SetBranchAddress("p_d0",&p_d0);
  tree->SetBranchAddress("p_h0",&p_h0);
  tree->SetBranchAddress("p_ks",&p_ks);
  tree->SetBranchAddress("p_pi0_h0",&p_pi0_h0);
  tree->SetBranchAddress("p_pip_h0",&p_pip_h0);
  tree->SetBranchAddress("p_pim_h0",&p_pim_h0);
  tree->SetBranchAddress("egamma",&egamma);
  tree->SetBranchAddress("cos_thr",&cos_thr);
  tree->SetBranchAddress("cos_hel",&cos_hel);
  tree->SetBranchAddress("thr_sig",&thr_sig);
  tree->SetBranchAddress("thr_oth",&thr_oth);
  tree->SetBranchAddress("ndf_tag_vtx",&ndf_tag_vtx);
  tree->SetBranchAddress("thr_oth",&thr_oth);
  tree->SetBranchAddress("phsp",&phsp);
  tree->SetBranchAddress("bin",&bin);

  Double_t px_pim,py_pim,pz_pim;
  Double_t px_pip,py_pip,pz_pip;
  Double_t px_ks,py_ks,pz_ks;

  tree->SetBranchAddress("px_pim",&px_pim);
  tree->SetBranchAddress("py_pim",&py_pim);
  tree->SetBranchAddress("pz_pim",&pz_pim);
  tree->SetBranchAddress("px_pip",&px_pip);
  tree->SetBranchAddress("py_pip",&py_pip);
  tree->SetBranchAddress("pz_pip",&pz_pip);
  tree->SetBranchAddress("px_ks",&px_ks);
  tree->SetBranchAddress("py_ks",&py_ks);
  tree->SetBranchAddress("pz_ks",&pz_ks);

  TEvent->Branch("px_pim",&px_pim,"px_pim/D");
  TEvent->Branch("py_pim",&py_pim,"py_pim/D");
  TEvent->Branch("pz_pim",&pz_pim,"pz_pim/D");
  TEvent->Branch("px_pip",&px_pip,"px_pip/D");
  TEvent->Branch("py_pip",&py_pip,"py_pip/D");
  TEvent->Branch("pz_pip",&pz_pip,"pz_pip/D");
  TEvent->Branch("px_ks",&px_ks,"px_ks/D");
  TEvent->Branch("py_ks",&py_ks,"py_ks/D");
  TEvent->Branch("pz_ks",&pz_ks,"pz_ks/D");

  Int_t b0id,d0id,h0id,dst0id,dst0f,etapid,etapf;

  tree->SetBranchAddress("chi2_vtx_d0",&chi2_vtx_d0);
  tree->SetBranchAddress("chi2_mass_d0",&chi2_mass_d0);

  TEvent->Branch("chi2_vtx_d0",&chi2_vtx_d0,"chi2_vtx_d0/D");
  TEvent->Branch("chi2_mass_d0",&chi2_mass_d0,"chi2_mass_d0/D");
  TEvent->Branch("good_icpv",&good_icpv,"good_icpv/I");

  if(type){
    tree->SetBranchAddress("b0id",&b0id);
    tree->SetBranchAddress("b0f",&b0f);
    tree->SetBranchAddress("d0id",&d0id);
    tree->SetBranchAddress("d0f",&d0f);
    tree->SetBranchAddress("h0id",&h0id);
    tree->SetBranchAddress("h0f",&h0f);
    tree->SetBranchAddress("pi0f",&pi0f);
    tree->SetBranchAddress("dst0id",&dst0id);
    tree->SetBranchAddress("dst0f",&dst0f);
    tree->SetBranchAddress("etapid",&etapid);
    tree->SetBranchAddress("etapf",&etapf);

    TEvent->Branch("b0id",&b0id,"b0id/I");
    TEvent->Branch("b0f",&b0f,"b0f/I");
    TEvent->Branch("d0id",&d0id,"d0id/I");
    TEvent->Branch("d0f",&d0f,"d0f/I");
    TEvent->Branch("h0id",&h0id,"h0id/I");
    TEvent->Branch("h0f",&h0f,"h0f/I");
    TEvent->Branch("pi0f",&pi0f,"pi0f/I");
    TEvent->Branch("dst0id",&dst0id,"dst0id/I");
    TEvent->Branch("dst0f",&dst0f,"dst0f/I");
    TEvent->Branch("etapid",&etapid,"etapid/I");
    TEvent->Branch("etapf",&etapf,"etapf/I");

    Double_t mp_raw, mm_raw;
    if(type>10 && type<20 || type == 111){
      tree->SetBranchAddress("mp_mc",&mp_mc);
      tree->SetBranchAddress("mm_mc",&mm_mc);
      tree->SetBranchAddress("mp_raw",&mp_raw);
      tree->SetBranchAddress("mm_raw",&mm_raw);
      tree->SetBranchAddress("d0_t_mc",&d0_t_mc);
      tree->SetBranchAddress("z_upsilon",&z_upsilon);
      tree->SetBranchAddress("bin_mc",&bin_mc);
      tree->SetBranchAddress("flv_mc",&flv_mc);
      tree->SetBranchAddress("d0_flv_mc",&d0_flv_mc);

      tree->SetBranchAddress("t_sig_mc",&t_sig_mc);
      tree->SetBranchAddress("z_sig_mc",&z_sig_mc);
      tree->SetBranchAddress("t_asc_mc",&t_asc_mc);
      tree->SetBranchAddress("z_asc_mc",&z_asc_mc);

      TEvent->Branch("mp_mc",&mp_mc,"mp_mc/D");
      TEvent->Branch("mm_mc",&mm_mc,"mm_mc/D");
      TEvent->Branch("mp_raw",&mp_raw,"mp_raw/D");
      TEvent->Branch("mm_raw",&mm_raw,"mm_raw/D");
      TEvent->Branch("d0_t_mc",&d0_t_mc,"d0_t_mc/D");
      TEvent->Branch("dt_mc",&dt_mc,"dt_mc/D");
      TEvent->Branch("dz_mc",&dz_mc,"dz_mc/D");
      TEvent->Branch("dz_mc_sig",&dz_mc_sig,"dz_mc_sig/D");
      TEvent->Branch("dz_mc_asc",&dz_mc_asc,"dz_mc_asc/D");
//      TEvent->Branch("dz_pull_sig",&dz_pull_sig,"dz_pull_sig/D");
//      if(type == 12 || type == 13 || type == 14){
//        tree->SetBranchAddress("z_sig_d0",&z_sig_d0);
//        tree->SetBranchAddress("sz_sig_d0",&sz_sig_d0);

//        TEvent->Branch("good_icpv_d0",&good_icpv_d0,"good_icpv_d0/I");
//        TEvent->Branch("dz_mc_sig_d0",&dz_mc_sig_d0,"dz_mc_sig_d0/D");
//        TEvent->Branch("dz_pull_sig_d0",&dz_pull_sig_d0,"dz_pull_sig_d0/D");
//        TEvent->Branch("z_sig_d0",&z_sig_d0,"z_sig_d0/D");
//        TEvent->Branch("sz_sig_d0",&sz_sig_d0,"sz_sig_d0/D");
//      }
//      TEvent->Branch("dz_pull_asc",&dz_pull_asc,"dz_pull_asc/D");
      TEvent->Branch("bin_mc",&bin_mc,"bin_mc/I");
      TEvent->Branch("flv_mc",&flv_mc,"flv_mc/I");
      TEvent->Branch("d0_flv_mc",&d0_flv_mc,"d0_flv_mc/I");

      TEvent->Branch("t_sig_mc",&t_sig_mc,"t_sig_mc/D");
      TEvent->Branch("z_sig_mc",&z_sig_mc,"z_sig_mc/D");
      TEvent->Branch("t_asc_mc",&t_asc_mc,"t_asc_mc/D");
      TEvent->Branch("z_asc_mc",&z_asc_mc,"z_asc_mc/D");

    }
  }

  tree->SetBranchAddress("nptag",&nptag);
  tree->SetBranchAddress("mbc",&mbc);
  tree->SetBranchAddress("de",&de);
  tree->SetBranchAddress("mp",&mp);
  tree->SetBranchAddress("mm",&mm);
  tree->SetBranchAddress("atckpi_max",&atckpi_max);
  tree->SetBranchAddress("mh0_raw",&mh0);
  tree->SetBranchAddress("mpi0_raw",&mpi0);
  tree->SetBranchAddress("mks_raw",&mk);

  Double_t md, md_raw, md_fit, mdpip, mdpim;
  tree->SetBranchAddress("md0_raw",&md_raw);
  tree->SetBranchAddress("md0_fit",&md_fit);
  tree->SetBranchAddress("md0",&md);
  tree->SetBranchAddress("md0pip",&mdpip);
  tree->SetBranchAddress("md0pim",&mdpim);

  TEvent->Branch("md",&md,"md/D");
  TEvent->Branch("md_raw",&md_raw,"md_raw/D");
  TEvent->Branch("md_fit",&md_fit,"md_fit/D");
  TEvent->Branch("mdpip",&mdpip,"mdpip/D");
  TEvent->Branch("mdpim",&mdpim,"mdpim/D");

  Double_t mdst0, metap, dmdst0, dmetap;
  tree->SetBranchAddress("mdst0",&mdst0);
  tree->SetBranchAddress("dmdst0",&dmdst0);
  tree->SetBranchAddress("metap",&metap);
  tree->SetBranchAddress("dmetap",&dmetap);

  TEvent->Branch("mdst0",&mdst0,"mdst0/D");
  TEvent->Branch("dmdst0",&dmdst0,"dmdst0/D");
  TEvent->Branch("metap",&metap,"metap/D");
  TEvent->Branch("dmetap",&dmetap,"dmetap/D");

  tree->SetBranchAddress("mode",&mode);
  tree->SetBranchAddress("h0mode",&h0mode);

  tree->SetBranchAddress("z_sig",&z_sig);
  tree->SetBranchAddress("z_asc",&z_asc);

  tree->SetBranchAddress("sz_sig",&sz_sig);
  tree->SetBranchAddress("sz_asc",&sz_asc);

  tree->SetBranchAddress("ntrk_sig",&ntrk_sig);
  tree->SetBranchAddress("ntrk_asc",&ntrk_asc);
  tree->SetBranchAddress("ndf_z_sig",&ndf_z_sig);
  tree->SetBranchAddress("ndf_z_asc",&ndf_z_asc);

  tree->SetBranchAddress("chisq_z_sig",&chisq_z_sig);
  tree->SetBranchAddress("chisq_z_asc",&chisq_z_asc);
  tree->SetBranchAddress("cl_z_sig",&cl_z_sig);
  tree->SetBranchAddress("cl_z_asc",&cl_z_asc);

  tree->SetBranchAddress("pi0_chi2",&pi0_chi2);
  tree->SetBranchAddress("h0_chi2",&h0_chi2);

  TEvent->Branch("h0_chi2",&h0_chi2,"h0_chi2/D");
  TEvent->Branch("pi0_chi2",&pi0_chi2,"pi0_chi2/D");

  tree->SetBranchAddress("costhB",&costhB);
  tree->SetBranchAddress("costhBcms",&costhBcms);
  tree->SetBranchAddress("Ecms",&Ecms);

  tree->SetBranchAddress("tag_LH",&tag_LH);
  tree->SetBranchAddress("tag_LH_err",&tag_LH_err);

  tree->SetBranchAddress("k0mm2",&k0mm2);
  tree->SetBranchAddress("k0et",&k0et);
  tree->SetBranchAddress("k0hso00",&k0hso00);
  tree->SetBranchAddress("k0hso02",&k0hso02);
  tree->SetBranchAddress("k0hso04",&k0hso04);
  tree->SetBranchAddress("k0hso10",&k0hso10);
  tree->SetBranchAddress("k0hso12",&k0hso12);
  tree->SetBranchAddress("k0hso14",&k0hso14);
  tree->SetBranchAddress("k0hso20",&k0hso20);
  tree->SetBranchAddress("k0hso22",&k0hso22);
  tree->SetBranchAddress("k0hso24",&k0hso24);
  tree->SetBranchAddress("k0hoo0",&k0hoo0);
  tree->SetBranchAddress("k0hoo1",&k0hoo1);
  tree->SetBranchAddress("k0hoo2",&k0hoo2);
  tree->SetBranchAddress("k0hoo3",&k0hoo3);
  tree->SetBranchAddress("k0hoo4",&k0hoo4);

  tree->SetBranchAddress("k1mm2",&k1mm2);
  tree->SetBranchAddress("k1et",&k1et);
  tree->SetBranchAddress("k1hso00",&k1hso00);
  tree->SetBranchAddress("k1hso01",&k1hso01);
  tree->SetBranchAddress("k1hso02",&k1hso02);
  tree->SetBranchAddress("k1hso03",&k1hso03);
  tree->SetBranchAddress("k1hso04",&k1hso04);
  tree->SetBranchAddress("k1hso10",&k1hso10);
  tree->SetBranchAddress("k1hso12",&k1hso12);
  tree->SetBranchAddress("k1hso14",&k1hso14);
  tree->SetBranchAddress("k1hso20",&k1hso20);
  tree->SetBranchAddress("k1hso22",&k1hso22);
  tree->SetBranchAddress("k1hso24",&k1hso24);
  tree->SetBranchAddress("k1hoo0",&k1hoo0);
  tree->SetBranchAddress("k1hoo1",&k1hoo1);
  tree->SetBranchAddress("k1hoo2",&k1hoo2);
  tree->SetBranchAddress("k1hoo3",&k1hoo3);
  tree->SetBranchAddress("k1hoo4",&k1hoo4);

  TEvent->Branch("exp",&exp,"exp/I");
  TEvent->Branch("run",&run,"run/I");
  TEvent->Branch("evtn",&evtn,"evtn/I");

  TEvent->Branch("p_d0",&p_d0,"p_d0/D");
  TEvent->Branch("p_h0",&p_h0,"p_h0/D");
  TEvent->Branch("p_ks",&p_ks,"p_ks/D");
  TEvent->Branch("p_pi0_h0",&p_pi0_h0,"p_pi0_h0/D");
  TEvent->Branch("p_pip_h0",&p_pip_h0,"p_pip_h0/D");
  TEvent->Branch("p_pim_h0",&p_pim_h0,"p_pim_h0/D");
  TEvent->Branch("egamma",&egamma,"egamma/D");
  TEvent->Branch("cos_thr",&cos_thr,"cos_thr/D");
  TEvent->Branch("cos_hel",&cos_hel,"cos_hel/D");
  TEvent->Branch("thr_sig",&thr_sig,"thr_sig/D");
  TEvent->Branch("thr_oth",&thr_oth,"thr_oth/D");
  TEvent->Branch("ndf_tag_vtx",&ndf_tag_vtx,"ndf_tag_vtx/I");
  TEvent->Branch("thr_oth",&thr_oth,"thr_oth/D");
  TEvent->Branch("phsp",&phsp,"phsp/I");
  TEvent->Branch("bin",&bin,"bin/I");

  TEvent->Branch("nptag",&nptag,"nptag/I");
  TEvent->Branch("mbc",&mbc,"mbc/D");
  TEvent->Branch("de",&de,"de/D");
  TEvent->Branch("mp",&mp,"mp/D");
  TEvent->Branch("mm",&mm,"mm/D");
  TEvent->Branch("dz",&dz,"dz/D");

  TEvent->Branch("atckpi_max",&atckpi_max,"atckpi_max/D");
  TEvent->Branch("mh0",&mh0);
  TEvent->Branch("mpi0",&mpi0,"mpi0/D");
  TEvent->Branch("mk",&mk,"mk/D");

  TEvent->Branch("mode",&mode,"mode/I");
  TEvent->Branch("h0mode",&h0mode,"h0mode/I");

  TEvent->Branch("z_sig",&z_sig,"z_sig/D");
  TEvent->Branch("z_asc",&z_asc,"z_asc/D");
  TEvent->Branch("sz_sig",&sz_sig,"sz_sig/D");
  TEvent->Branch("sz_asc",&sz_asc,"sz_asc/D");

  TEvent->Branch("ntrk_sig",&ntrk_sig,"ntrk_sig/I");
  TEvent->Branch("ntrk_asc",&ntrk_asc,"ntrk_asc/I");
  TEvent->Branch("ndf_z_sig",&ndf_z_sig,"ndf_z_sig/I");
  TEvent->Branch("ndf_z_asc",&ndf_z_asc,"ndf_z_asc/I");

  TEvent->Branch("chisq_z_sig",&chisq_z_sig,"chisq_z_sig/D");
  TEvent->Branch("chisq_z_asc",&chisq_z_asc,"chisq_z_asc/D");
  TEvent->Branch("cl_z_sig",&cl_z_sig,"cl_z_sig/D");
  TEvent->Branch("cl_z_asc",&cl_z_asc,"cl_z_asc/D");

  TEvent->Branch("costhB",&costhB,"costhB/D");
  TEvent->Branch("costhBcms",&costhBcms,"costhBcms/D");
  TEvent->Branch("Ecms",&Ecms,"Ecm/D");

  TEvent->Branch("ks_dr",&ks_dr,"ks_dr/D");
  TEvent->Branch("ks_dz",&ks_dz,"ks_dz/D");
  TEvent->Branch("ks_dphi",&ks_dphi,"ks_dphi/D");
  TEvent->Branch("ks_fl",&ks_fl,"ks_fl/D");
  TEvent->Branch("tag_LH",&tag_LH,"tag_LH/D");
  TEvent->Branch("tag_LH_err",&tag_LH_err,"tag_LH_err/D");

  TEvent->Branch("k0mm2",&k0mm2,"k0mm2/D");
  TEvent->Branch("k0et",&k0et,"k0et/D");
  TEvent->Branch("k0hso00",&k0hso00,"k0hso00/D");
  TEvent->Branch("k0hso02",&k0hso02,"k0hso02/D");
  TEvent->Branch("k0hso04",&k0hso04,"k0hso04/D");
  TEvent->Branch("k0hso10",&k0hso10,"k0hso10/D");
  TEvent->Branch("k0hso12",&k0hso12,"k0hso12/D");
  TEvent->Branch("k0hso14",&k0hso14,"k0hso14/D");
  TEvent->Branch("k0hso20",&k0hso20,"k0hso20/D");
  TEvent->Branch("k0hso22",&k0hso22,"k0hso22/D");
  TEvent->Branch("k0hso24",&k0hso24,"k0hso24/D");
  TEvent->Branch("k0hoo0",&k0hoo0,"k0hoo0/D");
  TEvent->Branch("k0hoo1",&k0hoo1,"k0hoo1/D");
  TEvent->Branch("k0hoo2",&k0hoo2,"k0hoo2/D");
  TEvent->Branch("k0hoo3",&k0hoo3,"k0hoo3/D");
  TEvent->Branch("k0hoo4",&k0hoo4,"k0hoo4/D");

  TEvent->Branch("k1mm2",&k1mm2,"k1mm2/D");
  TEvent->Branch("k1et",&k1et,"k1et/D");
  TEvent->Branch("k1hso00",&k1hso00,"k1hso00/D");
  TEvent->Branch("k1hso01",&k1hso01,"k1hso01/D");
  TEvent->Branch("k1hso02",&k1hso02,"k1hso02/D");
  TEvent->Branch("k1hso03",&k1hso03,"k1hso03/D");
  TEvent->Branch("k1hso04",&k1hso04,"k1hso04/D");
  TEvent->Branch("k1hso10",&k1hso10,"k1hso10/D");
  TEvent->Branch("k1hso12",&k1hso12,"k1hso12/D");
  TEvent->Branch("k1hso14",&k1hso14,"k1hso14/D");
  TEvent->Branch("k1hso20",&k1hso20,"k1hso20/D");
  TEvent->Branch("k1hso22",&k1hso22,"k1hso22/D");
  TEvent->Branch("k1hso24",&k1hso24,"k1hso24/D");
  TEvent->Branch("k1hoo0",&k1hoo0,"k1hoo0/D");
  TEvent->Branch("k1hoo1",&k1hoo1,"k1hoo1/D");
  TEvent->Branch("k1hoo2",&k1hoo2,"k1hoo2/D");
  TEvent->Branch("k1hoo3",&k1hoo3,"k1hoo3/D");
  TEvent->Branch("k1hoo4",&k1hoo4,"k1hoo4/D");

  const int NTot = tree->GetEntries();
  for(int i=1; i<NTot; i++){
    if(!(i%10000)){ cout << i << " events" << endl;}
    tree->GetEvent(i);
    if((b0f == 0 || b0f<-1) && type) continue;
    if(M_MODE){
      if(M_MODE != mode) continue;
    }
//    if(type == 11){
//      if((b0f != 1) && (b0f != 5) && (b0f != 10)) continue;
//    }
//    if(type == 11 || type == 12 || type == 13 || type == 14){
//      if(b0f < 1) continue;
//    }
//    if(type == 3){
//      if(!(b0f != 1 && b0f != 10 && !(d0f == 1 && (b0f == 5 || b0f == 4)))) continue;
//    }
//    if(type == 2){

//    }
//    if(md_raw<(DMass-md_cut) || md_raw>(DMass+md_cut)) continue;
//    if(!(mode == 2 && h0mode == 10) && mode != 14){
//      if(mpi0<(Pi0Mass-mpi0_cut) || mpi0>(Pi0Mass+mpi0_cut)) continue;
//    }
    if(mk<(KMass-mk_cut) || mk>(KMass+mk_cut)) continue;
//    if(chi2_vtx_d0>1000) continue;

    z_sig *= 10; z_asc *=10;// z_sig_d0 *= 10;
//    dz_mc_sig_d0   = z_sig_d0-z_sig_mc;
    dz_mc_sig      = z_sig-z_sig_mc;
    dz_mc_asc      = z_asc-z_asc_mc;
    dz = z_sig - z_asc;
    dt_mc = t_sig_mc - t_asc_mc;
    dz_mc = z_sig_mc - z_asc_mc;
    sz_sig      = 10.*TMath::Sqrt(sz_sig);
//    sz_sig_d0   = 10.*TMath::Sqrt(sz_sig_d0);
    sz_asc      = 10.*TMath::Sqrt(sz_asc);
//    dz_pull_sig      = dz_mc_sig/sz_sig;
//    dz_pull_sig_d0   = dz_mc_sig_d0/sz_sig_d0;
//    dz_pull_asc      = dz_mc_asc/sz_asc;

    // * Standatd ICPV cuts * //
    good_icpv    = IsGoodICPV(ndf_z_sig,sz_sig,chisq_z_sig,ndf_z_asc,sz_asc,chisq_z_asc);
//    good_icpv_d0 = IsGoodICPV(0,sz_sig_d0,1,ndf_z_asc,sz_asc,chisq_z_asc);
    // * ////////////////// * //

    TEvent->Fill();
  }
  TEvent->Print();
  TEvent->Write();
  ofile->Close();
  return;
}
void srcPositionStudy(Int_t binWidth, TString source, TString geometry) {

  int numFiles = 200; 

  TString simLocation;
  TChain *chain = new TChain("anaTree");

  if (geometry==TString("2011-2012")) simLocation = TString(getenv("SIM_2011_2012"));
  else if (geometry==TString("2012-2013")) simLocation = TString(getenv("SIM_2012_2013"));
  else if (geometry==TString("2012-2013_ISOBUTANE")) simLocation = TString(getenv("SIM_2012_2013_ISOBUTANE"));
  else { std::cout << "BAD GEOMETRY\n"; exit(0); }

  for (int i=0; i<numFiles; i++) {
    chain->AddFile(TString::Format("%s/%s/analyzed_%i.root",simLocation.Data(),source.Data(),i));
  }
  

  Double_t maxEn = 1500.;
  Double_t minEn = 0.;
  Double_t fidMax = 55.;
  Int_t nHists = (int)(fidMax/binWidth);
  
  
  
  std::vector <TH1D*> histsE(nHists, 0);
  std::vector <TH1D*> histsW(nHists, 0);
  std::vector <Double_t> rmin(nHists,0);
  std::vector <Double_t> rmax(nHists,0);
  std::vector <Double_t> rmid(nHists,0);

  //final means and errors
  std::vector < Double_t > EastMeans(nHists,0.);
  std::vector < Double_t > WestMeans(nHists,0.);
  
  std::vector < Double_t > EastMeanErrors(nHists,0.);
  std::vector < Double_t > WestMeanErrors(nHists,0.);

  for (Int_t i=0; i<nHists; i++) {

    rmin[i] = i*binWidth;
    rmax[i] = (i+1)*binWidth;
    rmid[i] = (double)rmin[i] + (double)binWidth/2.;

    histsE[i] = new TH1D(TString::Format("his%iE",i), 
			 TString::Format("%s %i mm radius bins East", source.Data(),binWidth),
			550, 0., 1100.);
    histsW[i] = new TH1D(TString::Format("his%iW",i), 
			 TString::Format("%s %i mm radius bins West", source.Data(),binWidth),
			550, 0., 1100.);

    histsE[i]->SetLineColor(i+1);
    histsW[i]->SetLineColor(i+1);
  }

  Double_t primPos[4];

  // Set the addresses of the information read in from the simulation file
  chain->SetBranchAddress("MWPCEnergy",&mwpcE);
  chain->SetBranchAddress("time",&Time);
  chain->SetBranchAddress("Edep",&edep);
  chain->SetBranchAddress("EdepQ",&edepQ);
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);
  chain->SetBranchAddress("ScintPos",&scint_pos);
  chain->SetBranchAddress("primKE",&primKE);
  chain->SetBranchAddress("primTheta",&primTheta);
  chain->SetBranchAddress("primPos",&primPos);


  //Get total number of events in TChain
  UInt_t nevents = chain->GetEntries();
  cout << "events = " << nevents << endl;

  for (Int_t i=0; i<nevents; i++) {
    
    chain->GetEvent(i);

    Int_t nBin = primPos[3]*1000./binWidth;

    if (edepQ.EdepQE>0. && primKE<maxEn && primKE>minEn && mwpcE.MWPCEnergyE>0.1 && primTheta>TMath::Pi()/2.) histsE[nBin]->Fill(edepQ.EdepQE);
    if (edepQ.EdepQW>0. && primKE<maxEn && primKE>minEn && mwpcE.MWPCEnergyW>0.1 && primTheta<TMath::Pi()/2.) histsW[nBin]->Fill(edepQ.EdepQW);

    if (i%100000==0) std::cout << "*";
  }
  
  std::cout << std::endl;

  TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
  c1->Divide(2,2);
  //TCanvas *c2 = new TCanvas("c2");
  
  //histsE[1]->Draw("SAME");
  
  Double_t refMeanE = 0., refMeanW = 0.; //This will hold the mean of the center pixel

  std::cout << nHists << endl;  
  for (Int_t i=0; i<nHists; i++) {
    c1->cd(1);
    histsE[i]->Draw("SAME");
    
    EastMeans[i] = histsE[i]->GetMean();
    EastMeanErrors[i] = EastMeans[i]>0. ? EastMeans[i]/sqrt(histsE[i]->GetEntries()) : 0.;
    //cout << EastMeans[i][0] << " " << EastMeans[i][1] << endl;

    c1->cd(2);
    histsW[i]->Draw("SAME");
    
    WestMeans[i] = histsW[i]->GetMean();
    WestMeanErrors[i] = WestMeans[i]>0. ? WestMeans[i]/sqrt(histsW[i]->GetEntries()) : 0.;

    if (i==0) { refMeanE = EastMeans[i], refMeanW = WestMeans[i]; }
  }

  

  //TCanvas *c3 = new TCanvas("c3");
  c1->cd(3);

  std::vector <Double_t> xerr(nHists,0.);
  
  TGraphErrors *gEast = new TGraphErrors(11, &rmax[0],&EastMeans[0],&xerr[0],&EastMeanErrors[0]);
  gEast->SetMarkerStyle(21);
  gEast->SetTitle(TString::Format("East %s Mean EQ vs. position",source.Data()));
  gEast->GetXaxis()->SetTitle("Position Bin Edge (mm)");
  gEast->GetYaxis()->SetTitle("Energy (keV)");
  gEast->Draw("AP");

  TLine *eastLine = new TLine(gEast->GetXaxis()->GetXmin(),refMeanE,gEast->GetXaxis()->GetXmax(),refMeanE);
  eastLine->SetLineStyle(2);
  eastLine->Draw();
 

  //TCanvas *c4 = new TCanvas("c4");
  c1->cd(4);

  TGraphErrors *gWest = new TGraphErrors(11, &rmax[0],&WestMeans[0],&xerr[0],&WestMeanErrors[0]);
  gWest->SetMarkerStyle(21);
  gWest->SetTitle(TString::Format("West %s Mean EQ vs. position",source.Data()));
  gWest->GetXaxis()->SetTitle("Position Bin Edge (mm)");
  gWest->GetYaxis()->SetTitle("Energy (keV)");
  gWest->Draw("AP");

  TLine *westLine = new TLine(gWest->GetXaxis()->GetXmin(),refMeanW,gWest->GetXaxis()->GetXmax(),refMeanW);
  westLine->SetLineStyle(2);
  westLine->Draw();

  
    


}
示例#11
0
int main (int argc, char** argv)
{
  
  int nCrystals = 1;
  int nDetectors = 16;
  gROOT->ProcessLine("#include <vector>");
  
  //TFile* f1 = new TFile(argv[1]);
  TChain *tree =  new TChain("tree");
  for (int i = 1 ; i < argc ; i++)
  {
    std::cout << "Adding file " << argv[i] << std::endl;
    tree->Add(argv[i]);
  }
  
  
  
  
  long int Seed;
  int Run;
  int Event;
  float totalEnergyDeposited;
  int NumOptPhotons;
  int NumCherenkovPhotons;
  
  std::vector<float> CryEnergyDeposited[nCrystals]; 
  std::vector<float> *pCryEnergyDeposited[nCrystals];
  std::vector<float> PosXEnDep[nCrystals]; 
  std::vector<float> *pPosXEnDep[nCrystals];
  std::vector<float> PosYEnDep[nCrystals]; 
  std::vector<float> *pPosYEnDep[nCrystals];
  std::vector<float> PosZEnDep[nCrystals]; 
  std::vector<float> *pPosZEnDep[nCrystals];
  short RunDetectorHit[nDetectors];
  
  
  std::vector<float> *pEdep[nCrystals];
  std::vector<float> *px[nCrystals];
  std::vector<float> *py[nCrystals];
  std::vector<float> *pz[nCrystals];
  
  for (int i = 0 ; i < nCrystals ; i++)
  {
    pEdep[i] = 0; 
    px[i] = 0;
    py[i] = 0;
    pz[i] = 0;
  }
  Short_t  detector[nDetectors];
  
  tree->SetBranchAddress("Seed",&Seed);
  tree->SetBranchAddress("Run",&Run);
  tree->SetBranchAddress("Event",&Event);
  tree->SetBranchAddress("totalEnergyDeposited",&totalEnergyDeposited);
  tree->SetBranchAddress("NumOptPhotons",&NumOptPhotons);
  tree->SetBranchAddress("NumCherenkovPhotons",&NumCherenkovPhotons);
  
  for (int i = 0 ; i < nCrystals ; i++)
  {
    std::stringstream snames;
    snames << "cry" << i;
    tree->SetBranchAddress(snames.str().c_str(),&pEdep[i]);
    snames.str("");
    snames<< "cry" << i << "PosXEnDep";    
    tree->SetBranchAddress(snames.str().c_str(),&px[i]);
    snames.str("");
    snames<< "cry" << i << "PosYEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&py[i]);
    snames.str("");
    snames<< "cry" << i << "PosZEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&pz[i]);
  }
  for (int i = 0 ; i < nDetectors ; i++)
  {
    std::stringstream snames;
    snames << "detector" << i;
    tree->SetBranchAddress(snames.str().c_str(),&detector[i]);
  }
  
  
  
  
  
  //output ttree
  
  long long int DeltaTimeTag,ExtendedTimeTag;
  Short_t charge[32];
  
//   TTree* t1 = new TTree("adc","adc");
//   
//   t1->Branch("ExtendedTimeTag",&ExtendedTimeTag,"ExtendedTimeTag/l"); 	//absolute time tag of the event
//   t1->Branch("DeltaTimeTag",&DeltaTimeTag,"DeltaTimeTag/l"); 			//delta time from previous event
//   //branches of the 32 channels data
//   for (int i = 0 ; i < 32 ; i++)
//   {
//     //empty the stringstreams
//     std::stringstream snames,stypes;
//     charge[i] = 0;
//     snames << "ch" << i;
//     stypes << "ch" << i << "/S";  
//     t1->Branch(snames.str().c_str(),&charge[i],stypes.str().c_str());
//   }
  
  // correct one
  Double_t xmppc[32]={-4.8,0,-1.6,0,1.6,0,4.8,0,-4.8,0,-1.6,0,1.6,0,4.8,0,-4.8,0,-1.6,0,1.6,0,4.8,0,-4.8,0,-1.6,0,1.6,0,4.8,0};
  Double_t ymppc[32]={-4.8,0,-4.8,0,-4.8,0,-4.8,0,-1.6,0,-1.6,0,-1.6,0,-1.6,0,1.6,0,1.6,0,1.6,0,1.6,0,4.8,0,4.8,0,4.8,0,4.8,0};
  
  // wrong geometry
//   Double_t xmppc[32]={-4.65,0,-1.55,0,1.55,0,4.65,0,-4.65,0,-1.55,0,1.55,0,4.65,0,-4.65,0,-1.55,0,1.55,0,4.65,0,-4.65,0,-1.55,0,1.55,0,4.65,0};
//   Double_t ymppc[32]={-4.65,0,-4.65,0,-4.65,0,-4.65,0,-1.55,0,-1.55,0,-1.55,0,-1.55,0,1.55,0,1.55,0,1.55,0,1.55,0,4.65,0,4.65,0,4.65,0,4.65,0};
  
  
  TH2F *flood = new TH2F("FloodHisto","FloodHisto",1000,-7,7,1000,-7,7);
  flood->GetXaxis()->SetTitle("X [mm]");
  flood->GetYaxis()->SetTitle("Y [mm]");
  flood->GetZaxis()->SetTitle("N");
//   recClean->SetTitle("Reconstruction of entire dataset");
//   varStream << "FloodY_" << k << ":FloodX_" << k << ">>" << histoString ;
  
  TH2F *positions = new TH2F("Positions","Positions",1000,-7,7,1000,-7,7);
  positions->GetXaxis()->SetTitle("X [mm]");
  positions->GetYaxis()->SetTitle("Y [mm]");
  positions->GetZaxis()->SetTitle("N");
  
  
  TH2F *HitPositions = new TH2F("HitPositions","HitPositions",1000,-7,7,1000,-7,7);
  HitPositions->GetXaxis()->SetTitle("X [mm]");
  HitPositions->GetYaxis()->SetTitle("Y [mm]");
  HitPositions->GetZaxis()->SetTitle("N");
//
  
  long int counter = 0;
  int nEntries = tree->GetEntries();
  std::cout << "nEntries = " << nEntries << std::endl;
  for(int iEntry = 0; iEntry < nEntries ; iEntry++)
  {  
    tree->GetEvent(iEntry);
    double columsum = 0; 
    double rowsum = 0;
    double total = 0;
    double floodx = 0;
    double floody = 0;
    
    //first clean the array
    for(int i = 0; i < 32 ; i++)
    {
      charge[i] = 0;
    }
    
    //then fill it with the detector data
    for(int i = 0; i < nDetectors ; i++)
    {
      charge[i*2] = detector[i];
    }
    
    //calculate weighted energy and fill 2d histo
    for(int i = 0; i < 32 ; i++)
    {
      columsum += charge[i]*ymppc[i];
      rowsum += charge[i]*xmppc[i];
      total += charge[i];
    }
    floodx = rowsum/total;
    floody = columsum/total;
    flood->Fill(floodx,floody);
    
    
    //calculate the average x and y deposition position 
    double averageX = 0;
    double averageY = 0;
    double energyColumnSum = 0;
    double energyRowSum = 0;
    
    for(int i = 0; i < nCrystals ; i++)
    {
      for (int j = 0 ; j < pEdep[i]->size() ; j++)
      {
        energyRowSum    += px[i]->at(j) * pEdep[i]->at(j);
        energyColumnSum += py[i]->at(j) * pEdep[i]->at(j);
      }
    }
    averageX = energyRowSum / totalEnergyDeposited;
    averageY = energyColumnSum / totalEnergyDeposited ;
    
    positions->Fill(averageX,averageY);
    //t1->Fill();
    
    counter++;
    
    int perc = ((100*counter)/nEntries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }
    
    
  }
  
  std::string outFile = "analysis_OUT.root";
  TFile* fOut = new TFile(outFile.c_str(),"recreate");
  
  flood->Write();
  positions->Write();
//   f1->Close();
  
  fOut->Close();
  
  
  
  return 0;
}
示例#12
0
int main (int argc, char** argv)
{
  gROOT->ProcessLine("#include <vector>"); //needed by ROOT to deal with standard vectors

  //HACK to use the dictionary easily
  std::string fullFileName = "";
  // Code taken from: http://www.gamedev.net/community/forums/topic.asp?topic_id=459511
  std::string path = "";
  pid_t pid = getpid();
  char buf[20] = {0};
  sprintf(buf,"%d",pid);
  std::string _link = "/proc/";
  _link.append( buf );
  _link.append( "/exe");
  char proc[512];
  int ch = readlink(_link.c_str(),proc,512);
  if (ch != -1) {
    proc[ch] = 0;
    path = proc;
    std::string::size_type t = path.find_last_of("/");
    path = path.substr(0,t);
  }
  fullFileName = path + std::string("/");
  //now even worse, assuming the executable is in build and the .C macro in code
  // std::string command = ".L " + fullFileName.substr(0,fullFileName.size()-7) + "/code/structDictionary.C+";
  std::string command = ".L " + fullFileName + "structDictionary.C+";
  // std::cout << fullFileName << std::endl;
  // std::cout << "command " << command << std::endl;
  gROOT->ProcessLine(command.c_str());


  //-------------------
  // Input Files
  //-------------------
  TChain *tree =  new TChain("tree"); // read input files
  for (int i = 1 ; i < argc ; i++)
  {
    std::cout << "Adding file " << argv[i] << std::endl;
    tree->Add(argv[i]);
  }
  // find the number of channels directly from the tchain file
  // before creating the variables
  // first, get the list of leaves
  TObjArray *leavescopy = tree->GetListOfLeaves();
  int nLeaves = leavescopy->GetEntries();
  std::vector<std::string> leavesName;
  // fill a vector with the leaves names
  for(int i = 0 ; i < nLeaves ; i++)
  {
    leavesName.push_back(leavescopy->At(i)->GetName());
  }
  // count the entries that start with "ch"
  int numOfCh = 0;
  // int numOfCry = 0;
  std::string det_prefix("detector");
  // std::string cry_prefix("cry");
  for(int i = 0 ; i < nLeaves ; i++)
  {
    //     leavesName.push_back(leavescopy->At(i)->GetName());
    if (!leavesName[i].compare(0, det_prefix.size(), det_prefix))
    numOfCh++;
    // if (!leavesName[i].compare(0, cry_prefix.size(), cry_prefix))
    // numOfCry++;
  }
  //the string "cry" appears 4 times per crystal..
  // numOfCry = numOfCry / 4;
  std::cout << "Detector Channels \t= " << numOfCh << std::endl;
  // std::cout << "Number of Crystals \t= "<< numOfCry << std::endl;


  //------------------
  // Input TTree
  //------------------

  //create the branches in the input ttree and connect to the variables

  // global variables
  // these are 1 number per TTree entry - so 1 number per gamma shot
  Long64_t Seed;                      // seed of the simulation (read every time, but always the same)
  int Run;                            // run id (usually just 1)(read every time, but always the same)
  int Event;                          // event id
  float totalEnergyDeposited;         // total energy deposited in this event, in all the matrix
  int NumOptPhotons;                  // number of optical photons generated in this event, in the entire matrix
  int NumCherenkovPhotons;            // number of Cherenkov photons generated in this event, in the entire matrix

  // energy deposition, each gamma 511 event has a std::vector of struct (type enDep) with all the data of each energy deposition
  std::vector<enDep> *energyDeposition = 0;

  // Total number of photons detected in this event
  // for each TTree entry, a simple number saying how many optical photons entered that
  // specific detector, passed the PDE check and where "detected" (i.e. saved)
  Short_t  *detector;
  detector = new Short_t [numOfCh];

  // optical photons. for each gamma 511 event, every optical photon detected is a struct of type optPhot. a std::vector<optPhot> is saved for each gamma 511
  std::vector<optPhot> *photons = 0;

  //------------------------
  // Set Branch Addresses
  //------------------------
  tree->SetBranchAddress("Seed",&Seed);
  tree->SetBranchAddress("Run",&Run);
  tree->SetBranchAddress("Event",&Event);
  tree->SetBranchAddress("totalEnergyDeposited",&totalEnergyDeposited);
  tree->SetBranchAddress("NumOptPhotons",&NumOptPhotons);
  tree->SetBranchAddress("NumCherenkovPhotons",&NumCherenkovPhotons);

  tree->SetBranchAddress("optical",&photons);
  tree->SetBranchAddress("energyDeposition",&energyDeposition);

  for (int i = 0 ; i < numOfCh ; i++)
  {
    std::stringstream snames;
    snames << "detector" << i;
    tree->SetBranchAddress(snames.str().c_str(),&detector[i]);
  }

  //output ttree

  std::string outFileName = "treeout.root"; //+ std::string(argv[1]);
  //output ttree
  long long int DeltaTimeTag,ExtendedTimeTag;

  Short_t *charge; //adc type
  charge = new Short_t[numOfCh];
  Float_t RealX,RealY,RealZ;
  Short_t CrystalsHit;
  Short_t NumbOfInteractions;

  TTree* t1 = new TTree("adc","adc");

  t1->Branch("ExtendedTimeTag",&ExtendedTimeTag,"ExtendedTimeTag/l"); 	//absolute time tag of the event
  t1->Branch("DeltaTimeTag",&DeltaTimeTag,"DeltaTimeTag/l"); 			//delta time from previous event
  //branches of the channels data
  for (int i = 0 ; i < numOfCh ; i++)
  {
    //empty the stringstreams
    std::stringstream snames,stypes;
    charge[i] = 0;
    snames << "ch" << i;
    stypes << "ch" << i << "/S";
    t1->Branch(snames.str().c_str(),&charge[i],stypes.str().c_str());
  }
  t1->Branch("RealX",&RealX,"RealX/F");
  t1->Branch("RealY",&RealY,"RealY/F");
  t1->Branch("RealZ",&RealZ,"RealZ/F");
  t1->Branch("CrystalsHit",&CrystalsHit,"CrystalsHit/S");
  t1->Branch("NumbOfInteractions",&NumbOfInteractions,"NumbOfInteractions/S");



  //----------------------------------------//
  //             LOOP ON EVENTS             //
  //----------------------------------------//
  long int counter = 0;
  int nEntries = tree->GetEntries();
  std::cout << "nEntries = " << nEntries << std::endl;

  for(int iEvent = 0; iEvent < nEntries ; iEvent++)
  {
    tree->GetEvent(iEvent);

    ExtendedTimeTag = 1e-9;
    DeltaTimeTag = 1e-9;

    NumbOfInteractions = 0;
    CrystalsHit = 0;


    for(int i = 0; i < numOfCh ; i++)
    {
      //convert to ADC channels, as if it was data from a digitizer
      //mppc gain = 1.25e6
      //adc channel binning 156e-15 C
      double adcCh = detector[i]*1.25e6*1.6e-19/156e-15;
      charge[i] = (Short_t) adcCh; //potentially truncation error?
    }

    RealX = RealY = RealZ = 0;

    NumbOfInteractions = energyDeposition->size();

    std::vector<int> crystals;
    for(int eEvent = 0; eEvent < energyDeposition->size(); eEvent++)// run on energy depositions for this gamma event
    {
      // -- counting the crystals where energy was deposited in this event
      //read the crystal where energy was deposited
      int cry = energyDeposition->at(eEvent).CrystalID;
      //loop in the crystals found
      //look for the same id
      bool sameID = false;
      for(int j = 0 ; j < crystals.size(); j++)
      {
        if(crystals[j] == cry) sameID = true;
      }
      if(!sameID) crystals.push_back(cry);  // add the crystal if it was not already counted as hit

      // -- calculate the average coordinate of energy deposition

	      // RealX += (px[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      RealX += (energyDeposition->at(eEvent).DepositionX * energyDeposition->at(eEvent).EnergyDeposited)/totalEnergyDeposited;
      RealY += (energyDeposition->at(eEvent).DepositionY * energyDeposition->at(eEvent).EnergyDeposited)/totalEnergyDeposited;
      RealZ += (energyDeposition->at(eEvent).DepositionZ * energyDeposition->at(eEvent).EnergyDeposited)/totalEnergyDeposited;
    }

    CrystalsHit = crystals.size();


    // calculate a weigthed energy deposition in x,y,z
    // for(int i = 0; i < numOfCry ; i++) //first total energy deposited
    // {
    //   NumbOfInteractions += px[i]->size();
    //   if(px[i]->size()) CrystalsHit++;
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealX += (px[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealY += (py[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    //   for(int j = 0; j < px[i]->size(); j++)
    //   {
    //     RealZ += (pz[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
    //   }
    // }

    if(NumbOfInteractions > 0) // discard events with no energy deposition (they would never trigger the detectors anyway..)
    {
      t1->Fill();
    }

    counter++;

    int perc = ((100*counter)/nEntries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }


  }

  // std::cout << std::endl;
  // std::cout << "1 cry [511 KeV deposition] events = "    << singleCounter << std::endl;
  // std::cout << "2 cry [511 KeV deposition] events = "    << doubleCounter << std::endl;
  // std::cout << "3 cry [511 KeV deposition] events = "    << tripleCounter << std::endl;
  // std::cout << "Multi cry [511 KeV deposition] events = "<< multipleCounter << std::endl;
  // std::cout << "Candidates = "<< foundCandidate << std::endl;
  //
  // TF1 *line = new TF1("line","x",-7,7);
  // line->SetLineColor(kRed);
  // TF1 *line2 = new TF1("line2","x",0,2000);
  // line2->SetLineColor(kRed);
  //
  //
  //
  // std::string outFile = "FileOut.root";
  // TFile* fOut = new TFile(outFile.c_str(),"recreate");
  //
  // TCanvas *C_flood = new TCanvas("C_flood","C_flood",800,800);
  // flood->Draw("COLZ");
  // C_flood->Write();
  // TCanvas *C_averageZvsRatio = new TCanvas("C_averageZvsRatio","C_averageZvsRatio",800,800);
  // C_averageZvsRatio->cd();
  // averageZvsRatio->Draw();
  // C_averageZvsRatio->Write();
  //
  // TCanvas *C_normalizedZvsRatio = new TCanvas("C_normalizedZvsRatio","C_normalizedZvsRatio",800,800);
  // C_normalizedZvsRatio->cd();
  // normalizedZvsRatio->Draw();
  // C_normalizedZvsRatio->Write();
  //
  // TCanvas *C_averageZvsWi = new TCanvas("C_averageZvsWi","C_averageZvsWi",800,800);
  // C_averageZvsWi->cd();
  // averageZvsWi->Draw();
  // C_averageZvsWi->Write();
  //
  // TCanvas *C_wivsRatio = new TCanvas("C_wivsRatio","C_wivsRatio",800,800);
  // C_wivsRatio->cd();
  // wivsRatio->Draw();
  // line->Draw("same");
  // C_wivsRatio->Write();
  //
  // TCanvas *C_wMeasuredvsRatioW = new TCanvas("C_wMeasuredvsRatioW","C_wMeasuredvsRatioW",800,800);
  // C_wMeasuredvsRatioW->cd();
  // wMeasuredvsRatioW->Draw();
  // line->Draw("same");
  // C_wMeasuredvsRatioW->Write();
  //
  // TCanvas *C_uMeasuredVsRatioU = new TCanvas("C_uMeasuredVsRatioU","C_uMeasuredVsRatioU",800,800);
  // C_uMeasuredVsRatioU->cd();
  // uMeasuredVsRatioU->Draw();
  // line->Draw("same");
  // C_uMeasuredVsRatioU->Write();
  //
  // TCanvas *C_vMeasuredVsRatioV = new TCanvas("C_vMeasuredVsRatioV","C_vMeasuredVsRatioV",800,800);
  // C_vMeasuredVsRatioV->cd();
  // vMeasuredVsRatioV->Draw();
  // line->Draw("same");
  // C_vMeasuredVsRatioV->Write();
  //
  //
  //
  //
  // TCanvas *C_kMeasuredvsRatioF = new TCanvas("C_kMeasuredvsRatioF","C_kMeasuredvsRatioF",800,800);
  // C_kMeasuredvsRatioF->cd();
  // kMeasuredvsRatioF->Draw();
  // line->Draw("same");
  // C_kMeasuredvsRatioF->Write();
  //
  // TCanvas *C_kMeasuredvsPmaxi = new TCanvas("C_kMeasuredvsPmaxi","C_kMeasuredvsPmaxi",800,800);
  // C_kMeasuredvsPmaxi->cd();
  // kMeasuredvsPmaxi->Draw();
  // line->Draw("same");
  // C_kMeasuredvsPmaxi->Write();
  //
  // TCanvas *C_pmaxiVsRatioF = new TCanvas("C_pmaxiVsRatioF","C_pmaxiVsRatioF",800,800);
  // C_pmaxiVsRatioF->cd();
  // pmaxiVsRatioF->Draw();
  // line2->Draw("same");
  // C_pmaxiVsRatioF->Write();


  // t1->Write();

  //   f1->Close();

  // std::string outFile = "analysis_OUT.root";
  // TFile* fOut = new TFile(outFile.c_str(),"recreate");

  // flood->Write();
  // positions->Write();
  //   f1->Close();
  std::cout << std::endl;
  std::cout << "Writing output to file "<< outFileName << std::endl;

  TFile* fOut = new TFile(outFileName.c_str(),"recreate");
  t1->Write();

  fOut->Close();



  return 0;
}
示例#13
0
int main (int argc, char** argv)
{
  
  //----------------------------------------------------------//
  //  Check input args                                        //
  //----------------------------------------------------------//
  if(argc == 0)
  {
    std::cout << "ERROR: YOU NEED TO PROVIDE AT LEAST AN INPUT FILE!" << std::endl;
  }
  else//if there is at least one file, go!
  {
    //play with strings for the output files...
    std::string firstFileName = argv[1];
    std::size_t found = firstFileName.find_first_of("_",firstFileName.find_first_of("_")+1);
    std::string fileRoot;
    fileRoot = firstFileName.substr(found+1,(firstFileName.length()-(found+1)) -5 );
    //std::cout << "fileRoot " << fileRoot << std::endl;
    //     if (Params.deepAnalysis)
    //       fileRoot += "_deep_";
    //     //std::string fileRoot;
    //     if (correctingForSaturation)
    //       fileRoot += "_saturation_corrected.root";
    //     else
    //       fileRoot += ".root";
    
    //a function for fitting...
    TF1 *gauss = new TF1("gauss",  "[0]*exp(-0.5*((x-[1])/[2])**2)",0,20000); //quite incredibly, this means that [2] can be negative... so the fix will be to take always the module of [2]...
    
    
    //----------------------//
    //  TChain              //
    //----------------------//
    //tchain to merge the input root ttrees
    TChain *chain =  new TChain("adc");
    for (int i = 1 ; i < argc ; i++)
    {
      std::cout << "Adding file " << argv[i] << std::endl;
      chain->Add(argv[i]);
    }
    
    
    
    
    
    
    
    
    std::stringstream snames[32],stypes[32];
    std::string names[32],types[32];
    //variables
    long long int t1_ExtendedTimeTag;
    long long int t1_DeltaTimeTag;
    int TriggerChannel[2];
    //Float_t t1_charge[32];
    int t1_charge[32];
    long long int counter = 0;
    float floodx[2],floody[2],firstonsecond[2];
    
    //branches
    TBranch *b_ExtendedTimeTag;
    TBranch *b_DeltaTimeTag;
    TBranch *b_charge[32];
    TBranch *b_TriggerChannel;
    TBranch *b_floodx;
    TBranch *b_floody;
    TBranch *b_firstonsecond;
    
    chain->SetBranchAddress("ExtendedTimeTag", &t1_ExtendedTimeTag, &b_ExtendedTimeTag);
    chain->SetBranchAddress("DeltaTimeTag", &t1_DeltaTimeTag, &b_DeltaTimeTag);  
    
    for(int i=0; i<32; i++)
    {
      snames[i].str(std::string());
      stypes[i].str(std::string());
      snames[i] << "ch" << i;
      names[i] = snames[i].str();
      chain->SetBranchAddress(names[i].c_str(), &t1_charge[i], &b_charge[i]);
    }
    chain->SetBranchAddress("TriggerChannel_0", &TriggerChannel[0], &b_TriggerChannel);
    chain->SetBranchAddress("FloodX_0", &floodx[0], &b_floodx);  
    chain->SetBranchAddress("FloodY_0", &floody[0], &b_floody);  
    chain->SetBranchAddress("FirstOnSecond_0", &firstonsecond[0], &b_firstonsecond);
    
//     Int_t nevent = chain->GetEntries();
    Int_t nevent = 100;
    
    for (Int_t i=0;i<nevent;i++) //loop on all the entries of tchain
    {
      chain->GetEvent(i);
      for(int i=0; i<32; i++)
      {
	if(!(i%2))
	  std::cout << t1_charge[i] << "\t";
      }
      std::cout << TriggerChannel[0] << "\t";
      std::cout << floodx[0] << "\t";
      std::cout << floody[0] << std::endl;
    }
    
    
  }
  
}
示例#14
0
int main(int argc, char* argv[])
{
  vector<vector<double> >* voltages = new vector<vector<double> >;
  vector<vector<double> >* currents = new vector<vector<double> >;
  voltages->resize(52);
  currents->resize(52);
  TChain* chain = loadChain(argc, argv);
  int entries = chain->GetEntries();

  cout << entries/2 << " files\n";

  for(int i=0; i<entries; i++)
  {
    chain->GetEvent(i);
    for(int slot=0; slot<16; slot++)
    {
      TLeaf* vleaf = chain->GetLeaf(("VHS_"+target_card[slot]+".VM."+target_channel[slot]).c_str());
      voltages->at(slot).push_back(vleaf->GetValue(0));
      TLeaf* ileaf = chain->GetLeaf(("VHS_"+target_card[slot]+".IM."+target_channel[slot]).c_str());
      currents->at(slot).push_back(ileaf->GetValue(0));      
    }
    for(int slot=0; slot<36; slot++)
    {
      if(veto_card[slot]=="4_3")
      {
	voltages->at(slot+16).push_back(-1);
	currents->at(slot+16).push_back(-1);
      }
      else
      {
	TLeaf* vleaf = chain->GetLeaf(("VHS_"+veto_card[slot]+".VM."+veto_channel[slot]).c_str());
	voltages->at(slot+16).push_back(vleaf->GetValue(0));
	TLeaf* ileaf = chain->GetLeaf(("VHS_"+veto_card[slot]+".IM."+veto_channel[slot]).c_str());
	currents->at(slot+16).push_back(ileaf->GetValue(0));
      }
    }
  }
  
  const double allowed_dv = 100;
  const double allowed_di = 50e-06;

  vector<bool> pmt_flags_v;
  vector<bool> pmt_flags_i;
  pmt_flags_v.resize(52,0);
  pmt_flags_i.resize(52,0);


  for( auto pmt = voltages->begin();
       pmt!=voltages->end(); ++pmt )
  {
    double meanvalue = mean(*pmt);
    double deviation = std_dev(*pmt);
    //cout << "Mean: " << meanvalue << " Dev: " << deviation << endl;
    for(auto it2 = (*pmt).begin();
	it2!=(*pmt).end(); ++it2)
    {
      //cout << distance((*it).begin(), it2) << " ";
      if( abs(*it2-meanvalue) > allowed_dv )
	pmt_flags_v.at( distance(voltages->begin(), pmt) ) = true;
    }
  }

  for( auto pmt = currents->begin();
       pmt!=currents->end(); ++pmt )
  {
    double meanvalue = mean(*pmt);
    double deviation = std_dev(*pmt);
    for(auto it2 = (*pmt).begin();
	it2!=(*pmt).end(); ++it2)
      if( abs(*it2-meanvalue) > allowed_di )
	pmt_flags_i.at( distance(currents->begin(), pmt) ) = true;
  }

  bool error = false;
  // Now if we managed to pick up some flags lets say so
  for(auto it = pmt_flags_v.begin();
      it!=pmt_flags_v.end(); ++it)
    if(*it==true)
    {
      cout << "PMT: " << distance(pmt_flags_v.begin(), it) << " varied VOLTAGE more than "
	   << allowed_dv << " from its mean value" << endl;
      error = true;
    }

  for(auto it = pmt_flags_i.begin();
      it!=pmt_flags_i.end(); ++it)
    if(*it==true)
    {
      cout << "PMT: " << distance(pmt_flags_i.begin(), it) << " varied CURRENT more than "
	   << allowed_di << " from its mean value" << endl;
      error = true;
    }

  if(error == true)
  {
    cout << ">>> See error.txt for full report <<<" << endl;
    writeReport(voltages, pmt_flags_v, currents, pmt_flags_i);
  }

  delete currents;
  delete voltages;
  return 0;
}
示例#15
0
int main (int argc, char** argv)
{
  gROOT->ProcessLine("#include <vector>");
  
  //TFile* f1 = new TFile(argv[1]);
  TChain *tree =  new TChain("tree");
  for (int i = 1 ; i < argc ; i++)
  {
    std::cout << "Adding file " << argv[i] << std::endl;
    tree->Add(argv[i]);
  }
  
  //play with input names
//   std::string inputFileName = 
  
  // find the number of channels directly from the tchain file
  // before creating the variables
  // first, get the list of leaves
  TObjArray *leavescopy = tree->GetListOfLeaves();
  int nLeaves = leavescopy->GetEntries();
  std::vector<std::string> leavesName;
  // fill a vector with the leaves names
//   std::cout << nLeaves << std::endl;
  for(int i = 0 ; i < nLeaves ; i++)
  {
//     std::cout << i << std::endl;
    leavesName.push_back(leavescopy->At(i)->GetName());
  }
  // count the entries that start with "ch"
  int numOfCh = 0;
  int numOfCry = 0;
  std::string det_prefix("detector");
  std::string cry_prefix("cry");
  for(int i = 0 ; i < nLeaves ; i++)
  {
//     leavesName.push_back(leavescopy->At(i)->GetName());
    if (!leavesName[i].compare(0, det_prefix.size(), det_prefix))
      numOfCh++;
    if (!leavesName[i].compare(0, cry_prefix.size(), cry_prefix))
      numOfCry++;
    
  }
  
  //the string "cry" appears 4 times per crystal..
  numOfCry = numOfCry / 4;
  
  std::cout << numOfCh << std::endl;
  std::cout << numOfCry << std::endl;
  
  
  Long64_t Seed;
  int Run;
  int Event;
  float totalEnergyDeposited;
  int NumOptPhotons;
  int NumCherenkovPhotons;
  
  std::vector<float> *CryEnergyDeposited;
  std::vector<float> **pCryEnergyDeposited;
  std::vector<float> *PosXEnDep; 
  std::vector<float> **pPosXEnDep;
  std::vector<float> *PosYEnDep; 
  std::vector<float> **pPosYEnDep;
  std::vector<float> *PosZEnDep; 
  std::vector<float> **pPosZEnDep;
  
//   DetectorHit         = new Short_t             [numOfCh];
  CryEnergyDeposited  = new std::vector<float>  [numOfCry];
  pCryEnergyDeposited = new std::vector<float>* [numOfCry];
  PosXEnDep           = new std::vector<float>  [numOfCry];
  pPosXEnDep          = new std::vector<float>* [numOfCry];
  PosYEnDep           = new std::vector<float>  [numOfCry];
  pPosYEnDep          = new std::vector<float>* [numOfCry];
  PosZEnDep           = new std::vector<float>  [numOfCry];
  pPosZEnDep          = new std::vector<float>* [numOfCry];
  
//   short RunDetectorHit[16];
  
  
  std::vector<float> **pEdep;
  std::vector<float> **px;
  std::vector<float> **py;
  std::vector<float> **pz;
  
  pEdep = new std::vector<float>* [numOfCry];
  px    = new std::vector<float>* [numOfCry];
  py    = new std::vector<float>* [numOfCry];
  pz    = new std::vector<float>* [numOfCry];
  
  for (int i = 0 ; i < numOfCry ; i++)
  {
    pEdep[i] = 0; 
    px[i] = 0;
    py[i] = 0;
    pz[i] = 0;
  }

  Short_t  *detector;
  detector = new Short_t [numOfCh];
  
  tree->SetBranchAddress("Seed",&Seed);
  tree->SetBranchAddress("Run",&Run);
  tree->SetBranchAddress("Event",&Event);
  tree->SetBranchAddress("totalEnergyDeposited",&totalEnergyDeposited);
  tree->SetBranchAddress("NumOptPhotons",&NumOptPhotons);
  tree->SetBranchAddress("NumCherenkovPhotons",&NumCherenkovPhotons);
  
  for (int i = 0 ; i < numOfCry ; i++)
  {
    std::stringstream snames;
    snames << "cry" << i;
    tree->SetBranchAddress(snames.str().c_str(),&pEdep[i]);
    snames.str("");
    snames<< "cry" << i << "PosXEnDep";    
    tree->SetBranchAddress(snames.str().c_str(),&px[i]);
    snames.str("");
    snames<< "cry" << i << "PosYEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&py[i]);
    snames.str("");
    snames<< "cry" << i << "PosZEnDep";
    tree->SetBranchAddress(snames.str().c_str(),&pz[i]);


  }
  for (int i = 0 ; i < numOfCh ; i++)
  {
    std::stringstream snames;
    snames << "detector" << i;
    tree->SetBranchAddress(snames.str().c_str(),&detector[i]);
  }
  
  
  
  //output ttree
  long long int DeltaTimeTag,ExtendedTimeTag;
  Short_t charge[32]; //adc type is always 32 channels
  Float_t RealX,RealY,RealZ;
  Short_t CrystalsHit;
  Short_t NumbOfInteractions;
  std::vector <float> TotalCryEnergy;	
  std::vector <float>* pTotalCryEnergy; 
  pTotalCryEnergy = &TotalCryEnergy;
  
  TTree* t1 = new TTree("adc","adc");
  
  t1->Branch("ExtendedTimeTag",&ExtendedTimeTag,"ExtendedTimeTag/l"); 	//absolute time tag of the event
  t1->Branch("DeltaTimeTag",&DeltaTimeTag,"DeltaTimeTag/l"); 			//delta time from previous event
  t1->Branch("TotalCryEnergy","std::vector<float>",&pTotalCryEnergy);	
  //branches of the 32 channels data
  for (int i = 0 ; i < 32 ; i++)
  {
    //empty the stringstreams
    std::stringstream snames,stypes;
    charge[i] = 0;
    snames << "ch" << i;
    stypes << "ch" << i << "/S";  
    t1->Branch(snames.str().c_str(),&charge[i],stypes.str().c_str());
  }
  t1->Branch("RealX",&RealX,"RealX/F"); 
  t1->Branch("RealY",&RealY,"RealY/F"); 
  t1->Branch("RealZ",&RealZ,"RealZ/F"); 
  t1->Branch("CrystalsHit",&CrystalsHit,"CrystalsHit/S"); 
  t1->Branch("NumbOfInteractions",&NumbOfInteractions,"NumbOfInteractions/S"); 

  
  long int counter = 0;
  int nEntries = tree->GetEntries();
  std::cout << "nEntries = " << nEntries << std::endl;
  for(int i = 0; i < nEntries ; i++)
  {  
    
    tree->GetEvent(i);
    
    ExtendedTimeTag = 1e-9;
    DeltaTimeTag = 1e-9;
    
    NumbOfInteractions = 0;
    CrystalsHit = 0;

    
    
    for(int i = 0; i < numOfCh ; i++)
    {
      //convert to ADC channels, as if it was data from a digitizer
      //mppc gain = 1.25e6
      //adc channel binning 156e-15 C
      double adcCh = detector[i]*1.25e6*1.6e-19/156e-15;
      charge[i*2] = (Short_t) adcCh; 
    }
    
    RealX = RealY = RealZ = 0;
    
    // calculate a weigthed energy deposition in x,y,z
    for(int i = 0; i < numOfCry ; i++) //first total energy deposited
    {
      Float_t SumEnergy = 0;
      NumbOfInteractions += px[i]->size();
      if(px[i]->size()) CrystalsHit++;
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealX += (px[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealY += (py[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		RealZ += (pz[i]->at(j) * pEdep[i]->at(j))/totalEnergyDeposited;
      }
      for(int j = 0; j < px[i]->size(); j++)
      {
		SumEnergy += pEdep[i]->at(j);	
      }
      TotalCryEnergy.push_back(SumEnergy);
    }
/*
    //find crystal with max energy deposition
    Float_t MaxEnergyCry = 0;
    Short_t MaxEnergyCryNum = -1;
    MaxEnergyCry = *std::max_element(TotalCryEnergy.begin(), TotalCryEnergy.end());
    MaxEnergyCryNum = std::distance(TotalCryEnergy.begin(), (std::max_element(TotalCryEnergy.begin(), TotalCryEnergy.end())));
*/
    
    if(NumbOfInteractions > 0) // discard events with no energy deposition (they would never trigger the detectors anyway..)
    {
      t1->Fill();
    }
    
    counter++;
    
    int perc = ((100*counter)/nEntries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }
    
  TotalCryEnergy.clear();
  
  }
  std::cout << std::endl;
  std::string outFile = "Tree_OUT.root";
  TFile* fOut = new TFile(outFile.c_str(),"recreate");
  
  t1->Write();
  
//   f1->Close();
  
  fOut->Close();
  
  
  
  return 0;
}
示例#16
0
void analyzer (TString inputFileName,TString outputFileName, TString runPeriod, bool isData, bool isSignal, unsigned maxEvents)
{
  using namespace std;

  ///////////////////
  // Configuration

  float minMmm = 110;
  float maxMmm = 160;

  //gErrorIgnoreLevel = kError;
  const unsigned ISMEAR = 2;

  ///////////////////////////
  // Output Histograms

  setStyle();

  TH1F* dimuonMassHist = new TH1F("dimuonMass","",50,110,160);
  setHistTitles(dimuonMassHist,"M(#mu#mu) [GeV/c^{2}]","Events");
  dimuonMassHist->Sumw2();
  TH1F* nJetsHist = new TH1F("nJets","",10,0,10);
  setHistTitles(nJetsHist,"N_{Jets}","Events");
  nJetsHist->Sumw2();

  ///////////////////////////
  Double_t MASS_MUON = 0.105658367;    //GeV/c2

  //////////////////////////
  // Tree Branches
  cout << "Analyzing filename: "<< inputFileName.Data() << endl;
  if (isData)
    cout << "isData\n";
  if (isSignal)
    cout << "isSignal\n";

  TChain * tree = new TChain("tree");
  tree->Add(inputFileName);


  // These are the names of the muons (See src/DataFormats.h for definitions!)
  _MuonInfo reco1, reco2;

  tree->SetBranchAddress("reco1", &reco1);
  tree->SetBranchAddress("reco2", &reco2);

  // These are the dimuon mass, pt, rapidity, and phi
  float recoCandMass, recoCandPt, recoCandY, recoCandPhi;
  float recoCandMassRes, recoCandMassResCov;

  tree->SetBranchAddress("recoCandMass",       &recoCandMass);
  tree->SetBranchAddress("recoCandPt",         &recoCandPt);
  tree->SetBranchAddress("recoCandY",          &recoCandY);
  tree->SetBranchAddress("recoCandPhi",        &recoCandPhi);
  tree->SetBranchAddress("recoCandMassRes",    &recoCandMassRes);
  tree->SetBranchAddress("recoCandMassResCov", &recoCandMassResCov);

  // MC truth info
  float trueMass=-99999.0;
  if(!isData && tree->GetBranchStatus("trueMass"))
    tree->SetBranchAddress("trueMass", &trueMass);

  /// Higgs Boson MC truth info (after FSR)
  _genPartInfo genHpostFSR;
  if(!isData && tree->GetBranchStatus("genHpostFSR"))
    tree->SetBranchAddress("genHpostFSR", &genHpostFSR);

  _TrackInfo reco1GenPostFSR;
  if(!isData && tree->GetBranchStatus("genM1HpostFSR"))
    tree->SetBranchAddress("genM1HpostFSR", &reco1GenPostFSR);

  _TrackInfo reco2GenPostFSR;
  if(!isData && tree->GetBranchStatus("genM2HpostFSR"))
    tree->SetBranchAddress("genM2HpostFSR", &reco2GenPostFSR);

  /// the jet collection
  // these 'rawJets' already have Loose Jet ID applied, and JES corrections
  // and are cross-cleaned of tight muons
  // later, jets will have JER corrections, PUID, and basic cuts applied
  _PFJetInfo rawJets;
  tree->SetBranchAddress("pfJets",&rawJets);

  float puJetFullDisc[10];
  float puJetSimpleDisc[10];
  float puJetCutDisc[10];

  tree->SetBranchAddress("puJetFullDisc",&puJetFullDisc);
  tree->SetBranchAddress("puJetSimpleDisc",&puJetSimpleDisc);
  tree->SetBranchAddress("puJetCutDisc",&puJetCutDisc);

  float puJetFullId[10];
  float puJetSimpleId[10];
  float puJetCutId[10];

  tree->SetBranchAddress("puJetFullId",&puJetFullId);
  tree->SetBranchAddress("puJetSimpleId",&puJetSimpleId);
  tree->SetBranchAddress("puJetCutId",&puJetCutId);

  int nPU=0;
  if (!isData)
    {
      tree->SetBranchAddress("nPU",&nPU);
    }
  _VertexInfo vertexInfo;
  tree->SetBranchAddress("vertexInfo",&vertexInfo);
  _EventInfo eventInfo;
  tree->SetBranchAddress("eventInfo",&eventInfo);

  // Be careful, the met has not been well validated
  _MetInfo met;
  tree->SetBranchAddress("met",&met);

  //////////////////////////
  //for PU reweighting

  reweight::LumiReWeighting lumiWeights("pileupDists/PileUpHistMC2012Summer50nsPoissonOOTPU.root","pileupDists/PileUpHist2012ABCD.root","pileup","pileup");
  if (runPeriod == "7TeV")
  {
    cout << "Using 2011AB PU reweighting\n";
    lumiWeights = reweight::LumiReWeighting("pileupDists/PileUpHistMCFall11.root","pileupDists/PileUpHist2011AB.root","pileup","pileup");
  }
  else
  {
    cout << "Using 2012ABCD PU reweighting\n";
  }

  ///////////////////////////////
  // Which Muon Selection to Use

  bool (*muonIdFuncPtr)(_MuonInfo&);
  if (runPeriod == "7TeV")
    {
      cout << "Using 2011 Tight Muon Selection\n";
      muonIdFuncPtr = &isKinTight_2011_noIso;
    }
  else
    {
      cout << "Using 2012 Tight Muon Selection\n";
      muonIdFuncPtr = &isKinTight_2012_noIso;
    }

  /////////////////////////
  // Smearing
  SmearingTool *smearPT = new SmearingTool();
  SmearingTool2011 *smearPT2011 = new SmearingTool2011();

  /////////////////////////////
  /////////////////////////////

  unsigned nEvents = tree->GetEntries();
  unsigned reportEach=1000;
  if (nEvents/1000>reportEach)
    reportEach = nEvents/1000;

  ///////////////////////////////
  ///////////////////////////////
  ///////////////////////////////
  // Event Loop

  for(unsigned i=0; i<nEvents;i++)
  {
    if(i >= maxEvents)
      break;

    tree->GetEvent(i);
    if (i % reportEach == 0) cout << "Event: " << i << endl;

    // Reject events with invalid muons
    if (reco1.pt < 0. || reco2.pt < 0.)
        continue;

    /////////////////////////////////////////////////
    // Muon Resolution Smearing to match MuScleFit

    if(isSignal) // smear only signal because it has muons from higgs 
    {
      if(reco1GenPostFSR.pt<0.)
        cout << "Muon 1 Post FSR not valid!\n";
      if(reco2GenPostFSR.pt<0.)
        cout << "Muon 2 Post FSR not valid!\n";
      float ptReco1 = -1.;
      float ptReco2 = -1.;
      if(runPeriod == "7TeV")
      {
        ptReco1 = smearPT2011 -> PTsmear(reco1GenPostFSR.pt, reco1GenPostFSR.eta, reco1GenPostFSR.charge, reco1.pt, ISMEAR);
        ptReco2 = smearPT2011 -> PTsmear(reco2GenPostFSR.pt, reco2GenPostFSR.eta, reco2GenPostFSR.charge, reco2.pt, ISMEAR);
      }
      else
      {
        ptReco1 = smearPT -> PTsmear(reco1GenPostFSR.pt, reco1GenPostFSR.eta, reco1GenPostFSR.charge, reco1.pt, ISMEAR);
        ptReco2 = smearPT -> PTsmear(reco2GenPostFSR.pt, reco2GenPostFSR.eta, reco2GenPostFSR.charge, reco2.pt, ISMEAR);
      }
      TLorentzVector reco1Vec;
      TLorentzVector reco2Vec;
      reco1Vec.SetPtEtaPhiM(ptReco1,reco1.eta,reco1.phi,MASS_MUON);
      reco2Vec.SetPtEtaPhiM(ptReco2,reco2.eta,reco2.phi,MASS_MUON);
      TLorentzVector diMuonVec = reco1Vec + reco2Vec;

      reco1.pt = ptReco1;
      reco2.pt = ptReco2;
      recoCandMass = diMuonVec.M();
      recoCandPt = diMuonVec.Pt();
      recoCandY = diMuonVec.Rapidity();
      recoCandPhi = diMuonVec.Phi();
    
      reco1Vec.SetPtEtaPhiM(ptReco1,reco1.eta,reco1.phi,MASS_MUON);
      reco2Vec.SetPtEtaPhiM(ptReco2,reco2.eta,reco2.phi,MASS_MUON);
      diMuonVec = reco1Vec + reco2Vec;
    }

    //////////////////////////////////////////
    // Muon-related cuts

    if (recoCandMass > maxMmm || recoCandMass < minMmm)
        continue;

    bool muon1PassId = (*muonIdFuncPtr)(reco1);
    bool muon2PassId = (*muonIdFuncPtr)(reco2);
    if ( !(muon1PassId && muon2PassId))
        continue;

    bool muon1PassIso = (getPFRelIso(reco1) <= 0.12);
    bool muon2PassIso = (getPFRelIso(reco2) <= 0.12);
    if ( !(muon1PassIso && muon2PassIso))
        continue;

    // Order muons by pt
    if (reco1.pt < reco2.pt)
    {
      _MuonInfo tmpMuon = reco1;
      reco1 = reco2;
      reco1 = tmpMuon;
    }

    // PU reweight
    float weight = 1.;
    if (!isData)
    {
      weight *= lumiWeights.weight(nPU);
    }

    // Jet Part
    // Do basic selection on jets and JER corrections
    std::vector<TLorentzVector> jets;
    std::vector<TLorentzVector> genJets;
    const float jetPtCut = 30.;
    const float jetAbsEtaCut = 4.7;
    const int jetPUIDCut = 4; // >=    tight = 7, medium = 6, loose = 4. Only loose is useful!!
    for(unsigned iJet=0; (iJet < unsigned(rawJets.nJets) && iJet < 10);iJet++)
    {
      // apply jet energy resolution corrections
      if (rawJets.genPt[iJet]>0.0 && rawJets.pt[iJet]>15.)
        rawJets.pt[iJet] = jerCorr(rawJets.pt[iJet],rawJets.genPt[iJet],rawJets.eta[iJet]); 
      bool goodPt = rawJets.pt[iJet]>jetPtCut;
      bool goodEta = fabs(rawJets.eta[iJet])<jetAbsEtaCut;
      bool goodPUID = puJetFullId[iJet] >= jetPUIDCut;
      if (goodPt && goodEta && goodPUID)
      {
        TLorentzVector tmpJetVec;
        tmpJetVec.SetPtEtaPhiM(rawJets.pt[iJet],rawJets.eta[iJet],rawJets.phi[iJet],rawJets.mass[iJet]);
        jets.push_back(tmpJetVec);
        TLorentzVector tmpGenJetVec;
        tmpGenJetVec.SetPtEtaPhiM(rawJets.genPt[iJet],rawJets.genEta[iJet],rawJets.genPhi[iJet],rawJets.genMass[iJet]);
        genJets.push_back(tmpGenJetVec);
      }
    }

//    /////////////////////////////////////////////
//
//    cout << "Event: "<< eventInfo.run << ":" << eventInfo.event << endl;
//
//    // print muon-related info
//    cout << "recoCandMass: " << recoCandMass << endl;
//    cout << "muon Pt1: " << reco1.pt << endl;
//    cout << "muon Pt2: " << reco2.pt << endl;
//    cout << "muon eta1: " << reco1.eta << endl;
//    cout << "muon eta2: " << reco2.eta << endl;
//    cout << "muon iso1: " << getPFRelIso(reco1) << endl;
//    cout << "muon iso2: " << getPFRelIso(reco2) << endl;
//    cout << "PU weight: " << weight << endl;
//    cout << endl;
//
//    // print jet-related info
//    cout << "nJets: " << jets.size() << endl;
//    for (unsigned iJet=0; iJet < jets.size(); iJet++)
//    {
//      cout << "Jet "<<(iJet+1)<<": pt="<< jets[iJet].Pt() << " eta="<<jets[iJet].Eta()<<endl;
//    }
//    cout << endl;
//
//    /////////////////////////////////////////////
      // Fill Histograms

      dimuonMassHist->Fill(recoCandMass,weight);
      nJetsHist->Fill(jets.size(),weight);

  }

  TFile* outFile = new TFile(outputFileName,"RECREATE");
  outFile->cd();
  dimuonMassHist->Write();
  nJetsHist->Write();

}
示例#17
0
void RunMipHistogramMaker(Int_t nEntries = 1e8,
			 const Char_t* listname="test.list",
			 const Char_t* outfile="testMipFile.root")

{
  gROOT->Macro("LoadLogger.C");
  gROOT->Macro("loadMuDst.C");
  gSystem->Load("StTpcDb");
  gSystem->Load("StDaqLib");
  gSystem->Load("StDetectorDbMaker");
  gSystem->Load("St_db_Maker");
  gSystem->Load("StDbUtilities");
  gSystem->Load("StEmcRawMaker");
  gSystem->Load("StMcEvent");
  gSystem->Load("StMcEventMaker");//***
  gSystem->Load("StEmcSimulatorMaker");//***
  gSystem->Load("StEmcADCtoEMaker");
  gSystem->Load("StEpcMaker");
  gSystem->Load("StDbBroker");
  gSystem->Load("StEEmcUtil");
  gSystem->Load("StAssociationMaker");
  gSystem->Load("StTriggerUtilities");
  gSystem->Load("StEmcOfflineCalibrationMaker");

  //Instantiate StChain
  StChain *chain = new StChain;

  TChain *MipChain = new TChain("calibTree");
  Char_t file[300];
  ifstream filelist(listname,ifstream::in);
  while(1){
    filelist >> file;
    if (!filelist.good()) break;
    cout << file << endl;
    MipChain->Add(file);
  }
  
  StEmcOfflineCalibrationMipAnalysis *mipAnalysis = new StEmcOfflineCalibrationMipAnalysis("StEmcOfflineCalibrationMipAnalysis",outfile,MipChain);
  
  //Initialize chain
  chain->Init();
  cout << "Successful Init" << endl;

  //Loop over all Make() in Chain
  for (Int_t iEntry = 0; iEntry < MipChain->GetEntries(); ++iEntry){
    if (MipChain->GetEvent(iEntry) <= 0)
      break;
    
    if (iEntry%10000 == 0)
      cout << "Working on event: " << iEntry << endl;
    
    chain->Clear();
    Int_t iret = chain->Make(iEntry);
    if(iret){
      cout << "Bad return code" << endl;
      break;
    }
  }
  
  chain->Finish();
}