void MyFunctions::BuildGradeNormMap() {
	// This function build the gradeNormMap if it isn't already filled
	if (gradeNormMap.size() > 0) return;  // Already filled
	
	// This is build from the Students root file.  Maybe this should be from a course file instead?
	TFile* f = new TFile("Students.root");
	TTree* studentTree = (TTree*)f->Get("Students");
	Student* student = 0;
	studentTree->SetBranchAddress("student", &student);
	
	Long64_t nentries = studentTree->GetEntriesFast();
	for (Long64_t jentry = 0; jentry < nentries; jentry++) {
		studentTree->GetEntry(jentry);
		//Loop over all terms for this student and accumulate grade distribution info
		for (auto const& grade : student->Grades()) {
			// Only look at Fall and Spring Terms
			int term = grade.term;
			if (!regularSemester(term)) continue;
			if (!ValidGrade(grade.grade)) continue;
			auto thisKey = std::make_pair(grade.course, 0);
			auto thisKeyAll = std::make_pair("AllCourses", 0);
			MyFunctions::gradeNormMap[thisKey].AddGrade(grade.grade);  // Will automatically create entry in map if it doesn't exist
			MyFunctions::gradeNormMap[thisKeyAll].AddGrade(grade.grade);
			auto termKey = std::make_pair(grade.course, term);
			auto termKeyAll = std::make_pair("AllCourses", term);
			MyFunctions::gradeNormMap[termKey].AddGrade(grade.grade);
			MyFunctions::gradeNormMap[termKeyAll].AddGrade(grade.grade);
		}			
	}
	
	f->Close();
}
Example #2
0
void CalibSort::Loop() {
  //   In a ROOT session, you can do:
  //      Root > .L CalibSort.C
  //      Root > CalibSort t
  //      Root > t.GetEntry(12); // Fill t data members with entry number 12
  //      Root > t.Show();       // Show values of entry 12
  //      Root > t.Show(16);     // Read and show values of entry 16
  //      Root > t.Loop();       // Loop on all entries
  //

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

  std::ofstream fileout;
  if ((flag_%10)==1) {
    fileout.open("events.txt", std::ofstream::out);
    std::cout << "Opens events.txt in output mode\n";
  } else {
    fileout.open("events.txt", std::ofstream::app);
    std::cout << "Opens events.txt in append mode\n";
  }
  fileout << "Input file: " << fname_ << " Directory: " << dirnm_ 
	  << " Prefix: " << prefix_ << "\n";
  Long64_t nbytes(0), nb(0), good(0);
  Long64_t nentries = fChain->GetEntriesFast();
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    double cut = (t_p > 20) ? 10.0 : 0.0;
    if ((flag_/10)%10 > 0) 
      std::cout << "Entry " << jentry << " p " << t_p << " Cuts " << t_qltyFlag
		<< "|" << t_selectTk << "|" << (t_hmaxNearP < cut) << "|" 
		<< (t_eMipDR < mipCut_) << std::endl;
    if (t_qltyFlag && t_selectTk && (t_hmaxNearP<cut) && (t_eMipDR<mipCut_)) {
      good++;
      fileout << good << " " << jentry << " " << t_Run  << " " << t_Event 
	      << " " << t_ieta << " " << t_p << std::endl;
    }
  }
  fileout.close();
  std::cout << "Writes " << good << " events in the file events.txt from "
	    << nentries << " entries" << std::endl;
}
Example #3
0
void spectraMaker(std::string file)
{
  Double_t fidCut = 50.;
  
  std::string filePath = "analyzed_files/"+file;

  TFile *fout = new TFile("outputHistsTest.root","RECREATE");
  TH1D *hEreconALL = new TH1D("hEreconALL","Reconstructed Energy Spectra for All events",120,0., 1200.);
  TH1D *hErecon0 = new TH1D("hErecon0","Reconstructed Energy Spectra for All events",120,0., 1200.);
  TH1D *hErecon1 = new TH1D("hErecon1","Reconstructed Energy Spectra for All events",120,0., 1200.);
  TH1D *hErecon23 = new TH1D("hErecon23","Reconstructed Energy Spectra for All events",120,0., 1200.);

  hEreconALL->GetXaxis()->SetTitle("E_{recon} (keV)");
  hErecon0->GetXaxis()->SetTitle("E_{recon} (keV)");
  hErecon1->GetXaxis()->SetTitle("E_{recon} (keV)");
  hErecon23->GetXaxis()->SetTitle("E_{recon} (keV)");
  
  TFile *fin = new TFile(filePath.c_str(),"READ");
  TTree *tin = (TTree*)(fin->Get("SimAnalyzed"));

  //variables to be read in
  Int_t PID, side, type;
  Double_t Erecon;
  Double_t mwpcPosW[3], mwpcPosE[3];
  
  tin->SetBranchAddress("PID",&PID);
  tin->SetBranchAddress("side",&side);
  tin->SetBranchAddress("type",&type);
  tin->SetBranchAddress("Erecon",&Erecon);
  tin->GetBranch("MWPCPosAdjusted")->GetLeaf("MWPCPosAdjE")->SetAddress(mwpcPosE);
  tin->GetBranch("MWPCPosAdjusted")->GetLeaf("MWPCPosAdjW")->SetAddress(mwpcPosW);

  UInt_t nevents = tin->GetEntriesFast();

  for (UInt_t evt=0; evt<nevents; evt++) {
    tin->GetEvent(evt);

    if (PID!=1) continue;
    if ((mwpcPosW[0]*mwpcPosW[0]+mwpcPosW[1]*mwpcPosW[1]>fidCut*fidCut) || (mwpcPosE[0]*mwpcPosE[0]+mwpcPosE[1]*mwpcPosE[1]>fidCut*fidCut)) continue;

    //Fill appropriate histograms if cuts are passed.
    if (type<4) hEreconALL->Fill(Erecon);
    if (type==0) hErecon0->Fill(Erecon);
    else if (type==1) hErecon1->Fill(Erecon);
    else if (type==2 || type==3) hErecon23->Fill(Erecon);  
  }

  fin->Close();

  fout->Write();
  fout->Close();
}
void PileUpMaker() {
  // Access data file
  TFile *file = TFile::Open("ZmumuGammaNtuple_Full2012_MuCorr.root");
  TTree *Datatree = (TTree*)file->Get("ZmumuGammaEvent");

  // Set up histogram for data pile up
  TH1F *pileupraw = new TH1F("pileup","",40,0,80);
 
  // Fill pile up distribution
  Int_t nentries = Datatree->GetEntriesFast();
  Int_t nbytes = 0; 
  for (Int_t i=0; i<nentries;i++) {
    nbytes += Datatree->GetEvent(i);
    UInt_t NVertices;
    Datatree->SetBranchAddress("NVertices",&NVertices);
    pileupraw->Fill(float(NVertices)/0.7);
  }

  // Normalize the distribution
  TH1F* PU = (TH1F*)pileupraw->Clone("pileup");
  PU->Scale(1./PU->Integral());

  // Plot both the normalized and unnormalized pile up
  TCanvas *cv = 0;
  cv= new TCanvas("cv","cv",800, 600);
  pileupraw->Draw("");
  cv->SaveAs("DataPU.pdf");

  cv= new TCanvas("cv","cv",800,600);
  PU->Draw("");
  cv->SaveAs("DataPU_normalized.pdf");

  // Save the normalized distribution to a root file for weighting MC
  TFile *file = TFile::Open("2012_PhosphorData_PileUp.root","UPDATE");
  file->cd();
  file->WriteTObject(PU,PU->GetName(),"WriteDelete");
  file->Close();
  delete file;
}
Example #5
0
void beamSpot() {

	gSystem->Load("libCintex.so");
	//gSystem->Load("libFWCoreFWLite.so");
	gSystem->Load("libRecoParticleFlowPFAnalyses");
	gSystem->Load("libDataFormatsParticleFlowReco");
	Cintex::Enable();


	TFile* f = TFile::Open("PFlowTB_Tree_9GeV_2k.root");
	TTree* tree = (TTree*) gDirectory->FindObjectAny("Extraction");

	//gPad->Divide(2);
	TH2F beamSpotHcal("beamSpotHcal", "beamSpotHcal;eta;phi", 100, 0, 3, 100, -1, 1);
	TH2F beamSpotEcal("beamSpotEcal", "beamSpotEcal;eta;phi", 100, 0, 3, 100, -1, 1);

	using namespace pftools;
	using namespace std;
	Calibratable* calib = new Calibratable();
	tree->SetBranchAddress("Calibratable", &calib);

	for (unsigned j(0); j < tree->GetEntriesFast(); ++j) {
			tree->GetEntry(j);
			for(unsigned k(0); k < calib->tb_numEcal_; ++k) {
				beamSpotEcal.Fill(calib->tb_ecal_[k].eta_,calib->tb_ecal_[k].phi_, calib->tb_ecal_[k].energy_);
			}
			for(unsigned k(0); k < calib->tb_numHcal_; ++k) {
				beamSpotHcal.Fill(calib->tb_hcal_[k].eta_,calib->tb_hcal_[k].phi_, calib->tb_hcal_[k].energy_);
			}
	}
	//gPad->cd(1);
	beamSpotEcal.Draw("colz");
	//gPad->cd(2);
	//beamSpotHcal.Draw("colz");

}
void number_of_events_table_xi1690(TString inFile=""){

	//*** In file

	TFile * input = new TFile(inFile, "READ");

	TTree * ntpMC = (TTree*) input->Get("ntpMC");
	TTree * ntpPiMinus = (TTree*) input->Get("ntpPiMinus");
	TTree * ntpPiPlus = (TTree*) input->Get("ntpPiPlus");
	TTree * ntpKaonMinus = (TTree*) input->Get("ntpKaonMinus");
	TTree * ntpProton = (TTree*) input->Get("ntpProton");
	TTree * ntpAntiProton = (TTree*) input->Get("ntpAntiProton");
	TTree * ntpLambda0 = (TTree*) input->Get("ntpLambda0");
	TTree * ntpAntiLambda0 = (TTree*) input->Get("ntpAntiLambda0");
	TTree * ntpXiPlus = (TTree*) input->Get("ntpXiPlus");
	TTree * ntpXiMinus1690 = (TTree*) input->Get("ntpXiMinus1690");
	TTree * ntpXiSys = (TTree*) input->Get("ntpXiSys");


	double nevents_mc = ntpMC->GetEntriesFast();
	TString cuts = " McTruthMatch && VtxFit_HowGood==1 && MassFit_prob>0.01";
	TString VtxCut = " McTruthMatch && VtxFit_HowGood==1 & HitTag==1";
	TString cut4c = "McTruthMatch && 4CFit_prob>0.01";


	cout << "particle|   #evts (uncut)|    #evts (ratio in %)|   MC ratio in %|   dp/p in %" << endl;


	//**** PiMinus
	TH1D * h_piminus_tht_uncut = new TH1D("h_piminus_tht_uncut", "h_piminus_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus_tht_uncut", "piminus_tht", "McTruthMatch && Mother==3122");
	double piminus_uncut =  h_piminus_tht_uncut->GetEntries();

	TH1D * h_piminus_tht = new TH1D("h_piminus_tht", "h_piminus_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus_tht", "piminus_tht", "McTruthMatch && piminus_HitTag && Mother==3122");
	int piminus =  h_piminus_tht->GetEntries();

	TH1D * h_piminus_dp = new TH1D("h_piminus_dp", "h_piminus_dp", 250, -0.1,0.1);
	ntpPiMinus->Project("h_piminus_dp", "(piminus_p-piminus_MC_p)/piminus_MC_p", "McTruthMatch && piminus_HitTag && Mother==3122");

//	Double_t param[6] = jenny::GetFitParameterDoubleFit(h_piminus_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piminus_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_piminus_cut = piminus/piminus_uncut;
	double ratio_piminus_mc = piminus/nevents_mc;

	cout << "PiMinus|   " <<  piminus_uncut << "|   " <<  piminus << "(" << ratio_piminus_cut*100 << ")|   " << ratio_piminus_mc*100 << endl; //param[2]*100 << endl;


	//**** PiPlus (AntiLambda0)
	TH1D * h_piplus_tht_uncut = new TH1D("h_piplus_tht_uncut", "h_piplus_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus_tht_uncut", "piplus_tht", "McTruthMatch && Mother==-3122");
	double piplus_uncut =  h_piplus_tht_uncut->GetEntries();

	TH1D * h_piplus_tht = new TH1D("h_piplus_tht", "h_piplus_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus_tht", "piplus_tht", "McTruthMatch && piplus_HitTag && Mother==-3122");
	int piplus =  h_piplus_tht->GetEntries();

	double ratio_piplus_cut = piplus/piplus_uncut;
	double ratio_piplus_mc = piplus/nevents_mc;

	TH1D * h_piplus_dp = new TH1D("h_piplus_dp", "h_piplus_dp", 250, -0.1,0.1);
	ntpPiPlus->Project("h_piplus_dp", "(piplus_p-piplus_MC_p)/piplus_MC_p", "McTruthMatch && piplus_HitTag && Mother==-3122");

//	Double_t parampip[6] = jenny::GetFitParameterDoubleFit(h_piplus_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piplus_dp, "","", false, false, false, 0.02,0.1, true);

	cout << "PiPlus(AL0)|   " <<  piplus_uncut << "|   " <<  piplus << "(" << ratio_piplus_cut*100 << ")|   " << ratio_piplus_mc*100 << endl; //pip[2]*100 << endl;



	//**** piplus (Xi+)
	TH1D * h_piplus2_tht_uncut = new TH1D("h_piplus2_tht_uncut", "h_piplus2_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus2_tht_uncut", "piplus_tht", "McTruthMatch && Mother==-3312");
	double piplus2_uncut =  h_piplus2_tht_uncut->GetEntries();

	TH1D * h_piplus2_tht = new TH1D("h_piplus2_tht", "h_piplus2_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus2_tht", "piplus_tht", "McTruthMatch && piplus_HitTag && Mother==-3312");
	int piplus2 =  h_piplus2_tht->GetEntries();

	TH1D * h_piplus2_dp = new TH1D("h_piplus2_dp", "h_piplus_dp", 250, -0.1,0.1);
	ntpPiPlus->Project("h_piplus2_dp", "(piplus_p-piplus_MC_p)/piplus_MC_p", "McTruthMatch && piplus_HitTag && Mother==-3312");

//	Double_t parampip2[6] = jenny::GetFitParameterDoubleFit(h_piplus2_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piplus2_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_piplus2_cut = piplus2/piplus2_uncut;
	double ratio_piplus2_mc = piplus2/nevents_mc;

	cout << "PiPlus(Xi+)|" <<  piplus2_uncut << "|" <<  piplus2 << "(" << ratio_piplus2_cut*100 << ")|" << ratio_piplus2_mc*100 << endl; //pip2[2]*100 << endl;


	//**** kaonMinus
	TH1D * h_kaonMinus_tht_uncut = new TH1D("h_kaonMinus_tht_uncut", "h_kaonMinus_tht", 100, 0,10);
	ntpKaonMinus->Project("h_kaonMinus_tht_uncut", "kaonminus_tht", "McTruthMatch && Mother==13314");
	double kaonMinus_uncut =  h_kaonMinus_tht_uncut->GetEntries();

	TH1D * h_kaonMinus_tht = new TH1D("h_kaonMinus_tht", "h_kaonMinus_tht", 100, 0,10);
	ntpKaonMinus->Project("h_kaonMinus_tht", "kaonminus_tht", "McTruthMatch && kaonminus_HitTag && Mother==13314");
	int kaonMinus =  h_kaonMinus_tht->GetEntries();

	TH1D * h_kaonminus_dp = new TH1D("h_kaonminus_dp", "h_kaonminus_dp", 250, -0.1,0.1);
	ntpKaonMinus->Project("h_kaonminus_dp", "(kaonminus_p-kaonminus_MC_p)/kaonminus_MC_p", "McTruthMatch && kaonminus_HitTag && Mother==13314");

//	Double_t paramk[6] = jenny::GetFitParameterDoubleFit(h_kaonminus_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_kaonminus_dp, "","", false, false, false, 0.02,0.1, true);


	double ratio_kaonMinus_cut = kaonMinus/kaonMinus_uncut;
	double ratio_kaonMinus_mc = kaonMinus/nevents_mc;

	cout << "kaonMinus|   " <<  kaonMinus_uncut << "|   " <<  kaonMinus << "(" << ratio_kaonMinus_cut*100 << ")|   " << ratio_kaonMinus_mc*100 << endl; //k[2]*100 << endl;


	//**** Proton
	TH1D * h_proton_tht_uncut = new TH1D("h_proton_tht_uncut", "h_proton_tht", 100, 0,10);
	ntpProton->Project("h_proton_tht_uncut", "proton_tht", "McTruthMatch && Mother==3122");
	double proton_uncut =  h_proton_tht_uncut->GetEntries();

	TH1D * h_proton_tht = new TH1D("h_proton_tht", "h_proton_tht", 100, 0,10);
	ntpProton->Project("h_proton_tht", "proton_tht", "McTruthMatch && proton_HitTag && Mother==3122");
	int proton =  h_proton_tht->GetEntries();

	TH1D * h_proton_dp = new TH1D("h_proton_dp", "h_proton_dp", 250, -0.1,0.1);
	ntpProton->Project("h_proton_dp", "(proton_p-proton_MC_p)/proton_MC_p", "McTruthMatch && proton_HitTag && Mother==3122");

//	Double_t paramProt[6] = jenny::GetFitParameterDoubleFit(h_proton_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_proton_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_proton_cut = proton/proton_uncut;
	double ratio_proton_mc = proton/nevents_mc;

	cout << "proton|   " <<  proton_uncut << "|   " <<  proton << "(" << ratio_proton_cut*100 << ")|   " << ratio_proton_mc*100 <<  endl; //Prot[2]*100 << endl;



	//**** AntiProton
	TH1D * h_AntiProton_tht_uncut = new TH1D("h_AntiProton_tht_uncut", "h_AntiProton_tht", 100, 0,10);
	ntpAntiProton->Project("h_AntiProton_tht_uncut", "AntiProton_tht", "McTruthMatch");
	double AntiProton_uncut =  h_AntiProton_tht_uncut->GetEntries();

	TH1D * h_AntiProton_tht = new TH1D("h_AntiProton_tht", "h_AntiProton_tht", 100, 0,10);
	ntpAntiProton->Project("h_AntiProton_tht", "AntiProton_tht", "McTruthMatch && AntiProton_HitTag");
	int AntiProton =  h_AntiProton_tht->GetEntries();

	TH1D * h_proton_dp = new TH1D("h_AntiProton_dp", "h_AntiProton_dp", 250, -0.1,0.1);
	ntpAntiProton->Project("h_AntiProton_dp", "(AntiProton_p-AntiProton_MC_p)/AntiProton_MC_p", "McTruthMatch && AntiProton_HitTag");

//	Double_t paramAProt[6] = jenny::GetFitParameterDoubleFit(h_AntiProton_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_AntiProton_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_AntiProton_cut = AntiProton/AntiProton_uncut;
	double ratio_AntiProton_mc = AntiProton/nevents_mc;



	cout << "AntiProton|   " <<  AntiProton_uncut << "|   " <<  AntiProton << "(" << ratio_AntiProton_cut*100 << ")|   " << ratio_AntiProton_mc*100 << endl; //AProt[2]*100 << endl;



	//**** lambda0
	TH1D * h_Lambda0_tht_uncut = new TH1D("h_Lambda0_tht_uncut", "h_Lambda0_tht", 100, 0,10);
	ntpLambda0->Project("h_Lambda0_tht_uncut", "Lambda0_tht", "McTruthMatch & HitTag");
	h_Lambda0_tht_uncut->Draw();
	double Lambda0_uncut =  h_Lambda0_tht_uncut->GetEntries();

	TH1D * h_Lambda0_tht = new TH1D("h_Lambda0_tht", "h_Lambda0_tht", 100, 0,10);
	ntpLambda0->Project("h_Lambda0_tht", "Lambda0_tht", "HitTag && "+cuts);
	int lambda0 =  h_Lambda0_tht->GetEntries();
	TH1D * h_Lambda0_dp = new TH1D("h_Lambda0_dp", "h_Lambda0_dp", 250, -0.1,0.1);
	ntpLambda0->Project("h_Lambda0_dp", "(Lambda0_p-McTruth_p)/McTruth_p", "HitTag && "+cuts );

//	Double_t paraml0[6] = jenny::GetFitParameterDoubleFit(h_Lambda0_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_Lambda0_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_Lambda0_cut = lambda0/Lambda0_uncut;
	double ratio_Lambda0_mc = lambda0/nevents_mc;

	cout << "lambda0|   " <<  Lambda0_uncut << "|   " <<  lambda0 << "(" << ratio_Lambda0_cut*100 << ")|   " << ratio_Lambda0_mc*100 << endl; //l0[2]*100 << endl;


	//**** AntiLambda0
	TH1D * h_antiLambda0_tht_uncut = new TH1D("h_antiLambda0_tht_uncut", "h_antiLambda0_tht", 100, 0,10);
	ntpAntiLambda0->Project("h_antiLambda0_tht_uncut", "antiLambda0_tht", "McTruthMatch & HitTag");
	double antiLambda0_uncut =  h_antiLambda0_tht_uncut->GetEntries();

	TH1D * h_antiLambda0_tht = new TH1D("h_antiLambda0_tht", "h_antiLambda0_tht", 100, 0,10);
	ntpAntiLambda0->Project("h_antiLambda0_tht", "antiLambda0_tht", "HitTag && "+cuts);
	int AntiLambda0 =  h_antiLambda0_tht->GetEntries();

	TH1D * h_antiLambda0_dp = new TH1D("h_antiLambda0_dp", "h_antiLambda0_dp", 250, -0.1,0.1);
	ntpAntiLambda0->Project("h_antiLambda0_dp", "(antiLambda0_p-McTruth_p)/McTruth_p", "HitTag && "+cuts);

//	Double_t paramAL0[6] = jenny::GetFitParameterDoubleFit(h_antiLambda0_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_antiLambda0_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_antiLambda0_cut = AntiLambda0/antiLambda0_uncut;
	double ratio_antiLambda0_mc = AntiLambda0/nevents_mc;

	cout << "AntiLambda0|   " <<  antiLambda0_uncut << "|   " <<  AntiLambda0 << "(" << ratio_antiLambda0_cut*100 << ")|   " << ratio_antiLambda0_mc*100 << endl; //AL0[2]*100 << endl;



	//**** XiPlus
	TH1D * h_xiplus_tht_uncut = new TH1D("h_xiplus_tht_uncut", "h_xiplus_tht", 100, 0,10);
	ntpXiPlus->Project("h_xiplus_tht_uncut", "xiplus_tht", "McTruthMatch & HitTag");
	double xiplus_uncut =  h_xiplus_tht_uncut->GetEntries();

	TH1D * h_xiplus_tht = new TH1D("h_xiplus_tht", "h_xiplus_tht", 100, 0,10);
	ntpXiPlus->Project("h_xiplus_tht", "xiplus_tht", cuts+"& HitTag");
	int XiPlus =  h_xiplus_tht->GetEntries();

	TH1D * h_xiplus_dp = new TH1D("h_xiplus_dp", "h_xiplus_dp", 250, -0.1,0.1);
	ntpXiPlus->Project("h_xiplus_dp", "(xiplus_p-MCTruth_p)/MCTruth_p", cuts+"& HitTag");

//	Double_t paramxip[6] = jenny::GetFitParameterDoubleFit(h_xiplus_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_xiplus_dp, "","", false, false, false, 0.02,0.1, true);


	double ratio_xiplus_cut = XiPlus/xiplus_uncut;
	double ratio_XiPlus_McTruth = XiPlus/nevents_mc;

	cout << "XiPlus|   " <<  xiplus_uncut << "|   " <<  XiPlus << "(" << ratio_xiplus_cut*100 << ")|   " << ratio_XiPlus_McTruth*100 << endl; //xip[2]*100 << endl;

	//**** XiMinus1820
	TH1D * h_XiMinus_tht_uncut = new TH1D("h_XiMinus_tht_uncut", "h_XiMinus_tht", 100, 0,10);
	ntpXiMinus1690->Project("h_XiMinus_tht_uncut", "XiMinus_tht", "McTruthMatch & HitTag");
	double XiMinus_uncut =  h_XiMinus_tht_uncut->GetEntries();

	TH1D * h_XiMinus_tht = new TH1D("h_XiMinus_tht", "h_XiMinus_tht", 100, 0,10);
	ntpXiMinus1690->Project("h_XiMinus_tht", "XiMinus_tht", VtxCut);
	int XiMinus1820 =  h_XiMinus_tht->GetEntries();

	TH1D * h_xiMinus_dp = new TH1D("h_xiMinus_dp", "h_xiMinus_dp", 250, -0.1,0.1);
	ntpXiMinus1690->Project("h_xiMinus_dp", "VtxFit_p-MCTruth_p", VtxCut);

	//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_xiMinus_dp, " ", " ", false, false, false, 0.02 , 0.1, true);
//	Double_t paramxim[6] = jenny::GetFitParameterDoubleFit(h_xiMinus_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_xiMinus_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_XiMinus_cut = XiMinus1820/XiMinus_uncut;
	double ratio_XiMinus_mc = XiMinus1820/nevents_mc;

	cout << "XiMinus1690|   " <<  XiMinus_uncut << "|   " <<  XiMinus1820 << "(" << ratio_XiMinus_cut*100 << ")|   " << ratio_XiMinus_mc*100 <<  endl; //xim[2]*100 << endl;


	//**** XiSys
	TH1D * h_XiSys_tht_uncut = new TH1D("h_XiSys_tht_uncut", "h_XiSys_tht", 100, 0,10);
	ntpXiSys->Project("h_XiSys_tht_uncut", "XiSys_tht", "McTruthMatch");
	double XiSys_uncut =  h_XiSys_tht_uncut->GetEntries();

	TH1D * h_XiSys_tht = new TH1D("h_XiSys_tht", "h_XiSys_tht", 100, 0,10);
	ntpXiSys->Project("h_XiSys_tht", "XiSys_tht", cut4c);
	int XiSys =  h_XiSys_tht->GetEntries();

	TH1D * h_XiSys_dp = new TH1D("h_XiSys_dp", "h_XiSys_dp", 250, -0.1,0.1);
	ntpXiSys->Project("h_XiSys_dp", "(XiSys_p-McTruth_p)/McTruth_p", cut4c);

//	Double_t paramxisys[6] = jenny::GetFitParameterDoubleFit(h_XiSys_dp, false, 0.02,0.1, true);
//	jenny::CreateDrawAndSaveHistogramDoulbeFit(h_XiSys_dp, "","", false, false, false, 0.02,0.1, true);


	double ratio_XiSys_cut = XiSys/XiSys_uncut;
	double ratio_XiSys_mc = XiSys/nevents_mc;

	cout << "XiSys|   " <<  XiSys_uncut << "|   " <<  XiSys << "(" << ratio_XiSys_cut*100 << ")|   " << ratio_XiSys_mc*100 << endl; //xisys[2]*100 << endl;


	setPandaStyle();

	TCanvas *c = new TCanvas("c","c", 0,0, 800,500);

	TH1D * reco = new TH1D("reco", "fraction of reconstructed final state particles; particle type; reco efficiency in %", 5,0,5);
	reco->Fill("#pi^{-}", ratio_piminus_mc*100);
	reco->Fill("#pi^{+}", (ratio_piplus_mc+ratio_piplus2_mc)/2*100);
	reco->Fill("K^{-}", ratio_kaonMinus_mc*100);
	reco->Fill("p", ratio_proton_mc*100);
	reco->Fill("#bar{p}", ratio_AntiProton_mc*100);


	reco->GetYaxis()->SetRangeUser(0,100);
	reco->Draw();
	PandaSmartLabel("Lprel");


}
void readNtuplesNoFilter_forAN_isMC(TString inputfilename="results.root", int flavor=Sig::Prompt,  std::string effmeasured="IterL3_NOHP_NOL1"){

  bool doingL1 = effmeasured.find("L1OverOffline") != std::string::npos; 
  
  TFile* outfile = TFile::Open(Form("%s_efficiency.root", effmeasured.c_str()),"RECREATE");
  std::cout << "output file: " << outfile -> GetName() << std::endl;

  //Create histograms  
  TH1F* dimuon_mass             = new TH1F("h_dimuon_mass"          ,"dimuon_mass"      , 1500,  0,  150 );
  TH1F* tagiso                  = new TH1F("h_tagiso"               ,"tagiso"           ,  100,  0,  1   );
  TH1F* tagMuonPt               = new TH1F("h_tagMuonPt"            ,"tagMuonPt"        ,  150,  0,  150 );
  TH1F* nvtx_event              = new TH1F("h_nvtx_event"           ,"nvtx_event"       ,   60,  0,   60 );
  
  // L1 over GEN:
  TEfficiency* L1muonPt         = new TEfficiency("L1muonPt"        ,"L1muonPt"         ,   16,  pt_bins ); 
  TEfficiency* L1muonEta        = new TEfficiency("L1muonEta"       ,"L1muonEta"        ,   15, eta_bins );
  TEfficiency* L1muonPhi        = new TEfficiency("L1muonPhi"       ,"L1muonPhi"        ,   20, -3.2, 3.2);
  TEfficiency* L1muonEff        = new TEfficiency("L1muonEff"       ,"L1muonEff"        ,    1,   0., 1.0);
  								    
  // L2 over L1: 						    
  TEfficiency* L2muonPt         = new TEfficiency("L2muonPt"        ,"L2muonPt"         ,   16,  pt_bins ); 
  TEfficiency* L2muonEta        = new TEfficiency("L2muonEta"       ,"L2muonEta"        ,   15, eta_bins );
  TEfficiency* L2muonPhi        = new TEfficiency("L2muonPhi"       ,"L2muonPhi"        ,   20, -3.2, 3.2);
  TEfficiency* L2muonEff        = new TEfficiency("L2muonEff"       ,"L2muonEff"        ,    1,   0., 1.0);

  // L3 over L1:
  TEfficiency* muonPt           = new TEfficiency("muonPt"          ,"muonPt"           ,   16,  pt_bins ); 
  TEfficiency* muonPtTurnOn     = new TEfficiency("muonPtTurnOn"    ,"muonPtTurnOn"     ,   16,  pt_bins ); 
  TEfficiency* muonEta          = new TEfficiency("muonEta"         ,"muonEta"          ,   15, eta_bins );
  TEfficiency* muonPhi          = new TEfficiency("muonPhi"         ,"muonPhi"          ,   20, -3.2, 3.2);
  TEfficiency* muonEff          = new TEfficiency("muonEff"         ,"muonEff"          ,    1,   0., 1.0);
  TEfficiency* muonDeltaR       = new TEfficiency("muonDeltaR"      ,"muonDeltaR"       ,   30,   0., 3.0);
  TEfficiency* muonDeltaPhi     = new TEfficiency("muonDeltaPhi"    ,"muonDeltaPhi"     ,   30,   0., 3.2); 

  TEfficiency* failingMuonPt    = new TEfficiency("failingMuonPt"   ,"failingMuonPt"    ,   16,  pt_bins ); 
  TEfficiency* failingMuonEta   = new TEfficiency("failingMuonEta"  ,"failingMuonEta"   ,   15, eta_bins );
  TEfficiency* failingMuonPhi   = new TEfficiency("failingMuonPhi"  ,"failingMuonPhi"   ,   20, -3.2, 3.2);
  TEfficiency* failingMuonEff   = new TEfficiency("failingMuonEff"  ,"failingMuonEff"   ,   1 ,   0., 1.0);

  TEfficiency* fakeMuonPt    = new TEfficiency("fakeMuonPt"   ,"fakeMuonPt"    ,   16,  pt_bins ); 
  TEfficiency* fakeMuonEta   = new TEfficiency("fakeMuonEta"  ,"fakeMuonEta"   ,   15, eta_bins );
  TEfficiency* fakeMuonPhi   = new TEfficiency("fakeMuonPhi"  ,"fakeMuonPhi"   ,   20, -3.2, 3.2);
  TEfficiency* fakeMuonEff   = new TEfficiency("fakeMuonEff"  ,"fakeMuonEff"   ,   1 ,   0., 1.0);

  TH1F* PassingProbePt          = new TH1F("h_PassingProbePt"       ,"PassingMuonPt"    ,  16,  pt_bins );
  TH1F* PassingProbeEta         = new TH1F("h_PassingProbeEta"      ,"PassingMuonEta"   ,  15, eta_bins );
  TH1F* PassingProbePhi         = new TH1F("h_PassingProbePhi"      ,"PassingMuonPhi"   ,  20, -3.2, 3.2);
  TH1F* PassingProbeMll         = new TH1F("h_PassingProbeMll"      ,"PassingMuonMll"   ,  40, 60., 120.); 
  TH1F* PassingProbeDeltaR      = new TH1F("h_PassingProbeDeltaR"   ,"PassingMuonDeltaR",  30,  0.,  3.0); 

  TH1F* FailingProbePt          = new TH1F("h_FailingProbePt"       ,"FailingMuonPt"    ,  16,  pt_bins );
  TH1F* FailingProbeEta         = new TH1F("h_FailingProbeEta"      ,"FailingMuonEta"   ,  15, eta_bins );
  TH1F* FailingProbePhi         = new TH1F("h_FailingProbePhi"      ,"FailingMuonPhi"   ,  20, -3.2, 3.2);
  TH1F* FailingProbeMll         = new TH1F("h_FailingProbeMll"      ,"FailingMuonMll"   ,  40,  60., 120.);
  TH1F* FailingProbeDeltaR      = new TH1F("h_FailingProbeDeltaR"   ,"FailingMuonDeltaR",  30,  0.,  3.0); 

  // Di-muon efficiencies 
  TEfficiency* diMuonPt         = new TEfficiency("diMuonPt"      ,"diMuonPt"       ,   16,  pt_bins  , 16,  pt_bins ); 
  TEfficiency* diMuonEta        = new TEfficiency("diMuonEta"     ,"diMuonEta"      ,   15, eta_bins  , 15, eta_bins );
  TEfficiency* diMuonPhi        = new TEfficiency("diMuonPhi"     ,"diMuonPhi"      ,   20, -3.2, 3.2 , 20, -3.2, 3.2);
  TEfficiency* diMuonEff        = new TEfficiency("diMuonEff"     ,"diMuonEff"      ,    1,   0., 1.0);
  TEfficiency* diMuonDeltaR     = new TEfficiency("diMuonDeltaR"  ,"diMuonDeltaR"   ,   30,   0., 3.0);
  TEfficiency* diMuonLeadPt     = new TEfficiency("diMuonLeadPt"  ,"diMuonLeadPt"   ,   16,  pt_bins ); 
  TEfficiency* diMuonLeadEta    = new TEfficiency("diMuonLeadEta" ,"diMuonLeadEta"  ,   15,  eta_bins );
  TEfficiency* diMuonLeadPhi    = new TEfficiency("diMuonLeadPhi" ,"diMuonLeadPhi"  ,   20, -3.2, 3.2);
  TEfficiency* diMuonTrailPt    = new TEfficiency("diMuonTrailPt" ,"diMuonTrailPt"  ,   16,  pt_bins ); 
  TEfficiency* diMuonTrailEta   = new TEfficiency("diMuonTrailEta","diMuonTrailEta" ,   15, eta_bins );
  TEfficiency* diMuonTrailPhi   = new TEfficiency("diMuonTrailPhi","diMuonTrailPhi" ,   20, -3.2, 3.2);
  
  TEfficiency* nvtx             = new TEfficiency("nvtx"             ,"nvtx"             ,   60,    0,  60);
  TEfficiency* nvtx_barrel      = new TEfficiency("nvtx_barrel"      ,"nvtx_barrel"      ,   60,    0,  60);
  TEfficiency* nvtx_endcap      = new TEfficiency("nvtx_endcap"      ,"nvtx_endcap"      ,   60,    0,  60);   
 
  TFile* inputfile = TFile::Open(inputfilename, "READ");
  std::cout << "input file: " << inputfile -> GetName() << std::endl;

  TTree *tree = (TTree*) inputfile -> Get("muonNtuples/muonTree"); 
  
  if (!tree) {
    std::cout << " *** tree not found *** " << std::endl;
    return;
  }
    
  MuonEvent* ev      = new MuonEvent(); 
  TBranch*  evBranch = tree->GetBranch("event"); 
  evBranch -> SetAddress(&ev);

  int nentries = tree->GetEntriesFast();
  std::cout << "Number of entries = " << nentries << std::endl;

  bool flagfile = false;
  offlinePtCut = getLeadingPtCut(flavor);
  float ptcut1 = getLeadingPtCut(flavor);
  float ptcut2 = getTrailingPtCut(flavor);
      
  for (Int_t eventNo=0; eventNo < nentries; eventNo++)     {
    Int_t IgetEvent   = tree   -> GetEvent(eventNo);
    if (!debug) printProgBar((int)(eventNo*100./nentries));
    if (debug && eventNo==100) break;

    nvtx_event-> Fill( ev -> nVtx   ); 
    unsigned int nmuons = ev->genParticles.size();
    for (int imu = 0; imu < nmuons; imu++){ 
      if (! selectTagMuon(ev->genParticles.at(imu), tagiso)) continue; 
      if (! matchMuon(ev->genParticles.at(imu), ev-> hltTag.objects, isofilterTag)) continue;
      
      tagMuonPt -> Fill ( ev->genParticles.at(imu).pt) ; 
      
      for (int jmu = 0; jmu < nmuons; jmu++){
	bool passL1 = false;
	bool passL2 = false;
	bool passL3 = false;
	
	// Select the probe muon  & match to the probe:  
	if (!selectProbeMuon(ev->genParticles.at(jmu), ev->genParticles.at(imu), dimuon_mass)) continue;
	
	// Check L1 passing: 
	if (matchMuonWithL1(ev->genParticles.at(jmu),ev->L1muons))   passL1=true;
//
//	// Check L2 passing: 
	if (matchMuonWithHLT(ev->genParticles.at(jmu),ev->L2muons))  passL2=true;
//
//	// Check L3 passing: 
	if (matchMuonWithHLT(ev->genParticles.at(jmu),ev->hltmuons)) passL3=true;
	
	L1muonPt     -> Fill( passL1          , ev->genParticles.at(jmu).pt ); 
	L2muonPt     -> Fill( passL2 && passL1, ev->genParticles.at(jmu).pt ); 
	muonPtTurnOn -> Fill( passL3 && passL1, ev->genParticles.at(jmu).pt ); 
	
	if (ev->genParticles.at(jmu).pt < ptcut1) continue;
	L1muonEta    -> Fill( passL1, ev->genParticles.at(jmu).eta);
	L1muonPhi    -> Fill( passL1, ev->genParticles.at(jmu).phi);
	L1muonEff    -> Fill( passL1, 0.5                    );
	
	if (!passL1) continue;  // exit the loop if there is no L1
	
	// Fill L2:
	L2muonEta    -> Fill( passL2, ev->genParticles.at(jmu).eta);
	L2muonPhi    -> Fill( passL2, ev->genParticles.at(jmu).phi);
	L2muonEff    -> Fill( passL2, 0.5                    );

	// Fill L3:
	TLorentzVector mu1, mu2;
	mu1.SetPtEtaPhiM (ev->genParticles.at(imu).pt,ev->genParticles.at(imu).eta,ev->genParticles.at(imu).phi, muonmass); 
	mu2.SetPtEtaPhiM (ev->genParticles.at(jmu).pt,ev->genParticles.at(jmu).eta,ev->genParticles.at(jmu).phi, muonmass);
	double mumumass = (mu1 + mu2).M();
	double DeltaR   = mu1.DeltaR(mu2);
	double DeltaPhi = mu1.DeltaPhi(mu2);

	if (passL3) { 
	  PassingProbePt    -> Fill( ev->genParticles.at(jmu).pt  );
	  PassingProbeEta   -> Fill( ev->genParticles.at(jmu).eta );
	  PassingProbePhi   -> Fill( ev->genParticles.at(jmu).phi );
	  PassingProbeMll   -> Fill( mumumass                );
	  PassingProbeDeltaR-> Fill( DeltaR );
	}	      
	else {       
	  FailingProbePt    -> Fill( ev->genParticles.at(jmu).pt  );
	  FailingProbeEta   -> Fill( ev->genParticles.at(jmu).eta );
	  FailingProbePhi   -> Fill( ev->genParticles.at(jmu).phi );
	  FailingProbeMll   -> Fill( mumumass                );
	  FailingProbeDeltaR-> Fill( DeltaR );
	}
	
	muonPt       -> Fill( passL3, ev->genParticles.at(jmu).pt );
	muonEta      -> Fill( passL3, ev->genParticles.at(jmu).eta);
	muonPhi      -> Fill( passL3, ev->genParticles.at(jmu).phi);
	muonEff      -> Fill( passL3, 0.5                    );
	muonDeltaR   -> Fill( passL3, DeltaR);
	muonDeltaPhi -> Fill( passL3, DeltaPhi);
	
	failingMuonPt  -> Fill( !passL3, ev->genParticles.at(jmu).pt );
	failingMuonEta -> Fill( !passL3, ev->genParticles.at(jmu).eta);
	failingMuonPhi -> Fill( !passL3, ev->genParticles.at(jmu).phi);
	failingMuonEff -> Fill( !passL3, 0.5                    );
      } // nmuons
    }
    
    /// Now FOR DIMUONS (Using HLT info):
    // both should pass the L1 filter! 
    continue;
    if (debug) cout << "fired L1?" << endl;
    if (ev->L1muons.size()>1) { 
      if (debug) cout << "YES!" << endl;      
      for (int imu=0; imu<ev->hltmuons.size(); imu++){ 
	bool fake = false;
	if (!matchHLTMuonWithGen(ev->hltmuons.at(imu), ev->genParticles)) fake = true;
	fakeMuonPt  -> Fill( fake, ev->hltmuons.at(imu).pt );
	if (ev->hltmuons.at(imu).pt > ptcut1) { 
	  fakeMuonEta -> Fill( fake, ev->hltmuons.at(imu).eta);
	  fakeMuonPhi -> Fill( fake, ev->hltmuons.at(imu).phi);
	  fakeMuonEff -> Fill( fake, 0.5                     );
	}
	for (int jmu=imu+1; jmu<ev->hltmuons.size(); jmu++){ 
	  bool pass = false;
	  if (matchHLTMuonWithGen(ev->hltmuons.at(imu),ev->genParticles) && 
	      matchHLTMuonWithGen(ev->hltmuons.at(jmu),ev->genParticles)) pass = true;
	  
	  double DeltaR = deltaR(ev->hltmuons.at(imu).eta,ev->hltmuons.at(imu).phi,ev->hltmuons.at(jmu).eta,ev->hltmuons.at(jmu).phi);
	  diMuonPt       -> Fill( pass, ev->hltmuons.at(imu).pt , ev->hltmuons.at(jmu).pt  ); 
	  diMuonLeadPt   -> Fill( pass, ev->hltmuons.at(imu).pt ); 
	  diMuonTrailPt  -> Fill( pass, ev->hltmuons.at(jmu).pt ); 
	  
	  if (ev->hltmuons.at(imu).pt < ptcut1) continue;
	  if (ev->hltmuons.at(jmu).pt < ptcut2) continue;
	  diMuonEta      -> Fill( pass, ev->hltmuons.at(imu).eta, ev->hltmuons.at(jmu).eta );
	  diMuonPhi      -> Fill( pass, ev->hltmuons.at(imu).phi, ev->hltmuons.at(jmu).phi );
	  diMuonDeltaR   -> Fill( pass, DeltaR);
	  diMuonEff      -> Fill( pass, 0.5);
	  
	  diMuonLeadEta  -> Fill( pass, ev->hltmuons.at(imu).eta ); 
	  diMuonTrailEta -> Fill( pass, ev->hltmuons.at(jmu).eta ); 
	  diMuonLeadPhi  -> Fill( pass, ev->hltmuons.at(imu).phi ); 
	  diMuonTrailPhi -> Fill( pass, ev->hltmuons.at(jmu).phi ); 
	}
      }
      /*
	for (int imu = 0; imu < nmuons; imu++){
	if (!selectMuon(ev->genParticles.at(imu))) continue; 
	for (int jmu = imu+1; jmu < nmuons; jmu++){
	if (!selectMuon(ev->genParticles.at(jmu))) continue; 
	bool pass = false;
	if (matchMuonWithL3(ev->genParticles.at(jmu),ev->hltmuons) && 
	matchMuonWithL3(ev->genParticles.at(imu),ev->hltmuons)) pass = true;
	
	if (ev->genParticles.at(imu).pt  == ev->genParticles.at(jmu).pt)  continue;
	if (ev->genParticles.at(imu).eta == ev->genParticles.at(jmu).eta) continue;
	if (ev->genParticles.at(imu).phi == ev->genParticles.at(jmu).phi) continue;
	
	double DeltaR   = deltaR(ev->genParticles.at(imu).eta,ev->genParticles.at(imu).phi,ev->genParticles.at(jmu).eta,ev->genParticles.at(jmu).phi);
	h_diMuonDeltaR -> Fill( DeltaR );
	
	diMuonPt       -> Fill( pass, ev->genParticles.at(imu).pt ); 
	diMuonEta      -> Fill( pass, ev->genParticles.at(imu).eta);
	diMuonPhi      -> Fill( pass, ev->genParticles.at(imu).phi);
	diMuonPt       -> Fill( pass, ev->genParticles.at(jmu).pt );
	diMuonEta      -> Fill( pass, ev->genParticles.at(jmu).eta);
	diMuonPhi      -> Fill( pass, ev->genParticles.at(jmu).phi);
	diMuonDeltaR   -> Fill( pass, DeltaR);
	diMuonDeltaR   -> Fill( pass, DeltaR);
	diMuonEff      -> Fill( pass, 0.5);
	diMuonEff      -> Fill( pass, 0.5);
	}
	}
      */
    }
  }  
  
  //Writing the histograms in a file.
  outfile           -> cd();
  tagMuonPt         -> Write();

  L1muonPt            -> Write();
  L1muonEta           -> Write();
  L1muonPhi           -> Write();
  L1muonEff           -> Write();
  
  L2muonPt            -> Write();
  L2muonEta           -> Write();
  L2muonPhi           -> Write();
  L2muonEff           -> Write();
  
  muonPtTurnOn      -> Write();
  muonPt            -> Write();
  muonEta           -> Write();
  muonPhi           -> Write();
  muonEff           -> Write();
  muonDeltaR        -> Write();
  muonDeltaPhi      -> Write();

  failingMuonPt   -> Write();
  failingMuonEta  -> Write();
  failingMuonPhi  -> Write();
  failingMuonEff  -> Write();

  fakeMuonPt   -> Write();
  fakeMuonEta  -> Write();
  fakeMuonPhi  -> Write();
  fakeMuonEff  -> Write();

  PassingProbePt  -> Write();
  PassingProbeEta -> Write();
  PassingProbePhi -> Write();
  PassingProbeMll -> Write();
  PassingProbeDeltaR -> Write();
  
  FailingProbePt  -> Write();
  FailingProbeEta -> Write();
  FailingProbePhi -> Write();
  FailingProbeMll -> Write();
  FailingProbeDeltaR -> Write();

  /// Per-event (di-muon) efficiency.
  diMuonPt         -> Write();
  diMuonEta        -> Write();
  diMuonPhi        -> Write();
  diMuonEff        -> Write();
  diMuonDeltaR     -> Write();
  diMuonLeadPt     -> Write(); 
  diMuonLeadEta    -> Write();
  diMuonLeadPhi    -> Write();
  diMuonTrailPt    -> Write(); 
  diMuonTrailEta   -> Write();
  diMuonTrailPhi   -> Write();

  nvtx_event       -> Write();
  nvtx             -> Write();
  
  dimuon_mass      -> Write();
  tagiso           -> Write();
  
  outfile          -> Close();  
  
  return;
}
Example #8
0
int main(int argc, char* argv[]){
  using namespace muon_pog;


  if (argc < 3) 
    {
      std::cout << "Usage : "
		<< argv[0] << " PATH_TO_INPUT_FILE PAT_TO_CONFIG_FILE(s)\n";
      exit(100);
    }

  // Input root file
  TString fileName = argv[1];

  std::cout << "[" << argv[0] << "] Processing file " << fileName.Data() << std::endl;
  
  std::vector<Plotter> plotters;
  for (int iConfig = 2; iConfig < argc; ++iConfig)
    {
        std::cout << "[" << argv[0] << "] Using config file " << argv[iConfig] << std::endl;
	plotters.push_back(std::string(argv[iConfig]));
    }
  
  // Set it to kTRUE if you do not run interactively
  gROOT->SetBatch(kTRUE); 

  // Initialize Root application
  TRint* app = new TRint("CMS Root Application", &argc, argv);

  //setTDRStyle(); what to do here?
   
  // Initialize pointers to summary and full event structure
 
  muon_pog::Event* ev = new muon_pog::Event();
  TTree* tree;
  TBranch* evBranch;

  // Open file, get tree, set branches

  TFile* inputFile = TFile::Open(fileName,"READONLY");
  tree = (TTree*)inputFile->Get("MUONPOGTREE");
  if (!tree) inputFile->GetObject("MuonPogTree/MUONPOGTREE",tree);

  evBranch = tree->GetBranch("event");
  evBranch->SetAddress(&ev);

  system("mkdir -p results");
  
  TFile* outputFile = TFile::Open("results/results.root","RECREATE"); // CB find a better name for output file  

  for (auto & plotter : plotters)
    plotter.book(outputFile);
      
  // Watch number of entries
  int nEntries = tree->GetEntriesFast();
  std::cout << "[" << argv[0] << "] Number of entries = " << nEntries << std::endl;

  int nFilteredEvents = 0;
  
  for (Long64_t iEvent=0; iEvent<nEntries; ++iEvent) 
    {
      if (tree->LoadTree(iEvent)<0) break;

      evBranch->GetEntry(iEvent);

      for (auto & plotter : plotters)
	plotter.fill(ev->muons, ev->hlt);

    }

  outputFile->Write();
  
  if (!gROOT->IsBatch()) app->Run();

  return 0;
}
Example #9
0
int looperCR2lep( analysis* myAnalysis, sample* mySample, int nEvents = -1, bool fast = true) {

	// Benchmark
	TBenchmark *bmark = new TBenchmark();
	bmark->Start("benchmark");

	// Setup
	TChain *chain = mySample->GetChain();
	TString sampleName = mySample->GetLabel();
	const int nSigRegs = myAnalysis->GetSigRegionsAll().size();
	const int nVariations = mySample->IsData() ? 0 : myAnalysis->GetSystematics(false).size();
	bool isFastsim = mySample->IsSignal();
	cout << "\nSample: " << sampleName.Data() << " (CR2L";
	if(      myContext.GetJesDir() == contextVars::kUp )   cout << ", JES up";
	else if( myContext.GetJesDir() == contextVars::kDown ) cout << ", JES down";
	cout << ")" << endl;

	myContext.SetUseRl( true );

	/////////////////////////////////////////////////////////
	// Histograms
	TDirectory *rootdir = gDirectory->GetDirectory("Rint:");  // Use TDirectories to assist in memory management
	TDirectory *histdir = new TDirectory( "histdir", "histdir", "", rootdir );
	TDirectory *systdir = new TDirectory( "systdir", "systdir", "", rootdir );
	TDirectory *zerodir = new TDirectory( "zerodir", "zerodir", "", rootdir );

	TH1::SetDefaultSumw2();

	TH1D* h_bkgtype_sum[nSigRegs][nVariations+1];
	TH1D* h_evttype_sum[nSigRegs][nVariations+1];
	TH2D* h_sigyields[nSigRegs][nVariations+1];

	TH1D* h_bkgtype[nSigRegs][nVariations+1]; // per-file versions for zeroing
	TH1D* h_evttype[nSigRegs][nVariations+1];

	TH1D *h_mt[nSigRegs];
	TH1D *h_met[nSigRegs];
	TH1D *h_mt2w[nSigRegs];
	TH1D *h_chi2[nSigRegs];
	TH1D *h_htratio[nSigRegs];
	TH1D *h_mindphi[nSigRegs];
	TH1D *h_ptb1[nSigRegs];
	TH1D *h_drlb1[nSigRegs];
	TH1D *h_ptlep[nSigRegs];
	TH1D *h_metht[nSigRegs];
	TH1D *h_dphilw[nSigRegs];
	TH1D *h_njets[nSigRegs];
	TH1D *h_nbtags[nSigRegs];
	TH1D *h_ptj1[nSigRegs];
	TH1D *h_j1btag[nSigRegs];
	TH1D *h_modtop[nSigRegs];
	TH1D *h_dphilmet[nSigRegs];
	TH1D *h_mlb[nSigRegs];

	vector<TString> regNames = myAnalysis->GetSigRegionLabelsAll();
	vector<sigRegion*> sigRegions = myAnalysis->GetSigRegionsAll();
	vector<systematic*> variations = myAnalysis->GetSystematics(false);

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

		TString plotLabel = sampleName + "_" + regNames.at(i);
		systdir->cd();

		for( int j=1; j<=nVariations; j++ ) {
			TString varName = variations.at(j-1)->GetNameLong();
			h_bkgtype_sum[i][j] = new TH1D( "bkgtype_" + plotLabel + "_" + varName, "Yield by background type",  5, 0.5, 5.5);
			h_evttype_sum[i][j] = new TH1D( "evttype_" + regNames.at(i) + "_" + varName, "Yield by event type",  6, 0.5, 6.5);
			h_sigyields[i][j] = new TH2D( "sigyields_" + regNames.at(i) + "_" + varName, "Signal yields by mass point", 37,99,1024, 19,-1,474 );
		}

		histdir->cd();

		h_bkgtype_sum[i][0] = new TH1D( "bkgtype_" + plotLabel, "Yield by background type",  5, 0.5, 5.5);
		h_evttype_sum[i][0] = new TH1D( "evttype_" + regNames.at(i), "Yield by event type",  6, 0.5, 6.5);
		h_sigyields[i][0] = new TH2D( "sigyields_" + regNames.at(i), "Signal yields by mass point", 37,99,1024, 19,-1,474 );

		h_mt[i]       = new TH1D(  "mt_"      + plotLabel, "Transverse mass",          80, 0, 800);
		h_met[i]      = new TH1D(  "met_"     + plotLabel, "MET",                      40, 0, 1000);
		h_mt2w[i]     = new TH1D(  "mt2w_"    + plotLabel, "MT2W",                     50, 0, 500);
		h_chi2[i]     = new TH1D(  "chi2_"    + plotLabel, "Hadronic #chi^{2}",        50, 0, 15);
		h_htratio[i]  = new TH1D(  "htratio_" + plotLabel, "H_{T} ratio",              50, 0, 1);
		h_mindphi[i]  = new TH1D(  "mindphi_" + plotLabel, "min #Delta#phi(j12,MET)",  63, 0, 3.15);
		h_ptb1[i]     = new TH1D(  "ptb1_"    + plotLabel, "p_{T} (b1)",               50, 0, 500);
		h_drlb1[i]    = new TH1D(  "drlb1_"   + plotLabel, "#DeltaR (lep, b1)",        50, 0, 5);
		h_ptlep[i]    = new TH1D(  "ptlep_"   + plotLabel, "p_{T} (lep)",              50, 0, 500);
		h_metht[i]    = new TH1D(  "metht_"   + plotLabel, "MET/sqrt(HT)",             50, 0, 100);
		h_dphilw[i]   = new TH1D(  "dphilw_"  + plotLabel, "#Delta#phi (lep,W)",       63, 0, 3.15);
		h_njets[i]    = new TH1D(  "njets_"   + plotLabel, "Number of jets",           16, -0.5, 15.5);
		h_nbtags[i]   = new TH1D(  "nbtags_"  + plotLabel, "Number of b-tags",          7, -0.5, 6.5);
		h_ptj1[i]     = new TH1D(  "ptj1_"    + plotLabel, "Leading jet p_{T}",        40, 0, 1000);
		h_j1btag[i]   = new TH1D(  "j1btag_"  + plotLabel, "Is leading jet b-tagged?",  2, -0.5, 1.5);
		h_modtop[i]   = new TH1D(  "modtop_"  + plotLabel, "Modified topness",         30, -15., 15.);
		h_dphilmet[i] = new TH1D(  "dphilmet_"+ plotLabel, "#Delta#phi (lep1, MET)",   63, 0., 3.15);
		h_mlb[i]      = new TH1D(  "mlb_"     + plotLabel, "M_{lb}",                   50, 0., 500.);


		for( int j=0; j<=nVariations; j++ ) {

			TAxis* axis = h_bkgtype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "2+lep" );
			axis->SetBinLabel( 2, "1lepW" );
			axis->SetBinLabel( 3, "1lepTop" );
			axis->SetBinLabel( 4, "ZtoNuNu" );
			axis->SetBinLabel( 5, "Other" );

			axis = h_evttype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "Data" );
			axis->SetBinLabel( 2, "Signals" );
			axis->SetBinLabel( 3, "2+lep" );
			axis->SetBinLabel( 4, "1lepW" );
			axis->SetBinLabel( 5, "1lepTop" );
			axis->SetBinLabel( 6, "ZtoNuNu" );
		}

	}

	TH1D *h_yields_sum = new TH1D( Form("srYields_%s", sampleName.Data()), "Yield by signal region", nSigRegs, 0.5, float(nSigRegs)+0.5);
	for( int i=0; i<nSigRegs; i++ ) h_yields_sum->GetXaxis()->SetBinLabel( i+1, regNames.at(i) );

	// Set up copies of histograms, in order to zero out negative yields
	zerodir->cd();
	TH1D* h_yields = (TH1D*)h_yields_sum->Clone( "tmp_" + TString(h_yields_sum->GetName()) );

	for( int i=0; i<nSigRegs; i++ ) {
		for( int j=0; j<=nVariations; j++ ) {
			h_bkgtype[i][j] = (TH1D*)h_bkgtype_sum[i][j]->Clone( "tmp_" + TString(h_bkgtype_sum[i][j]->GetName()) );
			h_evttype[i][j] = (TH1D*)h_evttype_sum[i][j]->Clone( "tmp_" + TString(h_evttype_sum[i][j]->GetName()) );
		}
	}

	// Set up cutflow variables
	double yield_total = 0;
	double yield_unique = 0;
	double yield_filter = 0;
	double yield_vtx = 0;
	double yield_1goodlep = 0;
	double yield_lepSel = 0;
	double yield_2lepveto = 0;
	double yield_trkVeto = 0;
	double yield_2lepCR = 0;
	double yield_tauVeto = 0;
	double yield_njets = 0;
	double yield_1bjet = 0;
	double yield_METcut = 0;
	double yield_MTcut = 0;
	double yield_dPhi = 0;
	double yield_chi2 = 0;

	int yGen_total = 0;
	int yGen_unique = 0;
	int yGen_filter = 0;
	int yGen_vtx = 0;
	int yGen_1goodlep = 0;
	int yGen_lepSel = 0;
	int yGen_2lepveto = 0;
	int yGen_trkVeto = 0;
	int yGen_tauVeto = 0;
	int yGen_2lepCR = 0;
	int yGen_njets = 0;
	int yGen_1bjet = 0;
	int yGen_METcut = 0;
	int yGen_MTcut = 0;
	int yGen_dPhi = 0;
	int yGen_chi2 = 0;

	////////////////////////////////////////////////////////////////////
	// Set up data-specific filters

	if( mySample->IsData() ) {
		set_goodrun_file_json( "reference-files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt" );
		duplicate_removal::clear_list();
	}


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

	// Loop over events to Analyze
	unsigned int nEventsTotal = 0;
	unsigned int nEventsChain = chain->GetEntries();
	if( nEvents >= 0 ) nEventsChain = nEvents;
	TObjArray *listOfFiles = chain->GetListOfFiles();
	TIter fileIter(listOfFiles);
	TFile *currentFile = 0;

	// File Loop
	while ( (currentFile = (TFile*)fileIter.Next()) ) {

		// Get File Content
		TFile file( currentFile->GetTitle() );
		TString filename = file.GetName();
		TTree *tree = (TTree*)file.Get("t");
		if(fast) TTreeCache::SetLearnEntries(10);
		if(fast) tree->SetCacheSize(128*1024*1024);
		cms3.Init(tree);

		// Load event weight histograms
		TH2F* hNEvts = (TH2F*)file.Get("histNEvts");
		TH3D* hCounterSMS = (TH3D*)file.Get("h_counterSMS");
		TH1D* hCounter = (TH1D*)file.Get("h_counter");
		myHelper.Setup( isFastsim, hCounter, hNEvts, hCounterSMS );

		// Reset zeroing histograms
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				h_bkgtype[i][j]->Reset();
				h_evttype[i][j]->Reset();
			}
		}
		h_yields->Reset();

		// Loop over Events in current file
		if( nEventsTotal >= nEventsChain ) continue;
		unsigned int nEventsTree = tree->GetEntriesFast();
		for( unsigned int event = 0; event < nEventsTree; ++event) {

			// Get Event Content
			if( nEventsTotal >= nEventsChain ) continue;
			if(fast) tree->LoadTree(event);
			cms3.GetEntry(event);
			++nEventsTotal;

			// Progress
			CMS3::progress( nEventsTotal, nEventsChain );

			////////////////////////////////////////////////////////////////////////////////////////////////////////
			// Analysis Code
			// ---------------------------------------------------------------------------------------------------//


			///////////////////////////////////////////////////////////////
			// Special filters to more finely categorize background events
			if(      sampleName == "tt2l"  && gen_nfromtleps_() != 2 ) continue;  //Require 2 leps from top in "tt2l" events
			else if( sampleName == "tt1l"  && gen_nfromtleps_() != 1 ) continue;  //Require 1 lep from top in "tt1l" events

			// Stitch W+NJets samples together by removing the MET<200 events from the non-nupT samples
			if( sampleName.Contains("wjets") && filename.Contains("JetsToLNu_madgraph") && nupt()>=200. ) continue;

			//FastSim anomalous event filter
			if( isFastsim && !context::filt_fastsimjets() ) continue;

			if( !mySample->PassSelections() ) continue;


			/////////////////////////////////
			// Set event weight

			double evtWeight = 1.;

			// Data should have a weight of 1.0
			if( is_data() || mySample->IsData() ) evtWeight = 1.;
			else {

				// Weight background MC using scale1fb
				evtWeight = myAnalysis->GetLumi() * scale1fb();

				// Weight signal MC using xsec and nEvents
				if( mySample->IsSignal() ) {
					myHelper.PrepSignal();
					double nEvtsSample = hNEvts->GetBinContent( hNEvts->FindBin( mass_stop(), mass_lsp() ) );
					evtWeight = myAnalysis->GetLumi() * 1000. * xsec() / nEvtsSample;
				}

				// Apply scale factors to correct the shape of the MC
				evtWeight *= myHelper.TrigEff2l();
				evtWeight *= myHelper.LepSF();
				evtWeight *= myHelper.BtagSF();
				if(  isFastsim ) evtWeight *= myHelper.LepSFfastsim();
				if( !isFastsim ) evtWeight *= myHelper.PileupSF();
				if( mySample->GetLabel() == "tt2l" || filename.Contains("W_5f_powheg_pythia8") ) {
					evtWeight *= myHelper.MetResSF();
					// evtWeight *= myHelper.TopSystPtSF();
				}
				else if( mySample->GetLabel() == "tt1l" || mySample->GetLabel() == "wjets" ) evtWeight *= myHelper.MetResSF();
				if( mySample->GetLabel() == "tt2l" || mySample->GetLabel() == "tt1l" || mySample->IsSignal() ) evtWeight *= myHelper.ISRnJetsSF();

				// Correct event weight when samples are merged together
				if(      filename.Contains("ttbar_diLept_madgraph_pythia8_ext1_25ns") ) evtWeight *= 23198554./(23198554.+5689986.);
				else if( filename.Contains("ttbar_diLept_madgraph_pythia8_25ns") ) evtWeight *= 5689986./(23198554.+5689986.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 4473156./(4473156.+3145334.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3145334./(4473156.+3145334.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 5029568./(5029568.+3146940.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3146940./(5029568.+3146940.);
			}

			// Count the number of events processed
			yield_total += evtWeight;
			yGen_total++;

			// Remove duplicate events in data
			if( is_data() ) {
				duplicate_removal::DorkyEventIdentifier id( run(), evt(), ls() );
				if( is_duplicate(id) ) continue;
				yield_unique += evtWeight;
				yGen_unique++;
			}

			// MET filters, bad event filters, and triggers for data
			if( is_data() ) {
				if( !goodrun( run(), ls() ) ) continue;
				if( !filt_met() ) continue;
				if( !filt_badChargedCandidateFilter() ) continue;
				if( !filt_badMuonFilter() ) continue;
				if( !context::filt_jetWithBadMuon() ) continue;
				if( !filt_pfovercalomet() ) continue;
				if( !HLT_MET() && !HLT_MET110_MHT110() && !HLT_MET120_MHT120() ) {
					if( !(HLT_SingleEl() && (abs(lep1_pdgid())==11 || abs(lep2_pdgid())==11) ) &&
					    !(HLT_SingleMu() && (abs(lep1_pdgid())==13 || abs(lep2_pdgid())==13) ) ) continue;
				}
				yield_filter += evtWeight;
				yGen_filter++;
			}

			// First vertex must be good
			if( nvtxs() < 1 ) continue;
			yield_vtx += evtWeight;
			yGen_vtx++;

			// Must have at least 1 good lepton
			if( ngoodleps() < 1 ) continue;
			yield_1goodlep += evtWeight;
			yGen_1goodlep++;

			// Lep 1 must pass lepton selections
			// if( abs(lep1_pdgid())==11 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 1.4442 ) continue;
			// 	if( !lep1_passMediumID() ) continue;
			// }
			// else if( abs(lep1_pdgid())==13 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 2.4 ) continue;
			// 	if( !lep1_passTightID() ) continue;
			// }
			yield_lepSel += evtWeight;
			yGen_lepSel++;


			///////////////////
			// Make 2-lepton CR

			int countGoodLeps = 0;

			// Count the number of veto leptons
			if( nvetoleps() >= 2 && lep2_p4().pt() > 10. ) countGoodLeps += nvetoleps();

			if( countGoodLeps > 1 ) {
				yield_2lepveto += evtWeight;
				yGen_2lepveto++;
			}

			// If we fail the track veto, count another good lepton
			// if( !PassTrackVeto() ) {
			// 	countGoodLeps++;
			// 	yield_trkVeto += evtWeight;
			// 	yGen_trkVeto++;
			// }

			// If we fail the tau veto, count another good lepton
			// if( !PassTauVeto() ) {
			// 	countGoodLeps++;
			// 	yield_tauVeto += evtWeight;
			// 	yGen_tauVeto++;
			// }

			if( countGoodLeps < 2 ) continue;
			yield_2lepCR += evtWeight;
			yGen_2lepCR++;


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

			// N-jet requirement
			if( context::ngoodjets() < 2 ) continue;
			yield_njets += evtWeight;
			yGen_njets++;

			j1pt = context::ak4pfjets_p4().at(0).pt();

			// B-tag requirement
			if( context::ngoodbtags() < 1 ) continue;
			yield_1bjet += evtWeight;
			yGen_1bjet++;

			j1_isBtag = context::ak4pfjets_passMEDbtag().at(0);

			// Baseline MET cut (with 2nd lepton pT added to MET)
			if( context::Met() < 250. ) continue;
			yield_METcut += evtWeight;
			yGen_METcut++;

			// MT cut (with 2nd lepton pT added to MET)
			if( context::MT_met_lep() < 150. ) continue;
			yield_MTcut += evtWeight;
			yGen_MTcut++;

			// Min delta-phi between MET and j1/j2 (with 2nd lepton pT added to MET)
			if( context::Mindphi_met_j1_j2() < 0.5 ) continue;
			yield_dPhi += evtWeight;
			yGen_dPhi++;

			// Chi^2 cut
			// if( hadronic_top_chi2() >= 10. ) continue;
			yield_chi2 += evtWeight;
			yGen_chi2++;


			//////////////////////////////////////////////////////////
			// Classify event based on number of leptons / neutrinos
			// Order of evaluation matters, because some events fall into multiple categories

			int bkgType = -99;
			if( filename.Contains("ZZTo2L2Nu") && isZtoNuNu() ) bkgType = 1; // Force ZZto2L2Nu to be 2lep
			else if( isZtoNuNu() )     bkgType = 4;   // Z to nu nu
			else if( is2lep() )        bkgType = 1;   // 2 or more leptons
			else if( is1lepFromTop() ) bkgType = 3;   // 1 lepton from top quark
			else if( is1lepFromW() )   bkgType = 2;   // 1 lepton from a W not from top
			else                       bkgType = 5;   // Other

			int evtType = -99;
			if(      mySample->IsData()   ) evtType = 1;
			else if( mySample->IsSignal() ) evtType = 2;
			else                            evtType = 2+bkgType;

			// Quickly calculate some variables
			double metSqHT = context::Met() / sqrt( context::ak4_HT() );

			const TVector3 lepVec( lep1_p4().x(), lep1_p4().y(), lep1_p4().z() );
			const TVector3 metVec( context::Met()*cos(context::MetPhi()), context::Met()*sin(context::MetPhi()), 0 );
			const TVector3 wVec = lepVec + metVec;
			double dPhiLepW = fabs( lepVec.DeltaPhi(wVec) );

			double drLepLeadb = ROOT::Math::VectorUtil::DeltaR( lep1_p4(), context::ak4pfjets_leadMEDbjet_p4() );

			lep1pt = lep1_p4().Pt();

			myMlb = context::Mlb_closestb();

			///////////////////////////////////////////
			// Signal region cuts and histo filling

			// If the event passes the SR cuts, store which background type this event is, and fill histograms
			for( int i=0; i<nSigRegs; i++ ) {

				if( !sigRegions.at(i)->PassAllCuts() ) continue;

				// Make some corrections that depend on the signal region
				double fillWeight = evtWeight;
				bool is_corridor = sigRegions.at(i)->GetLabel().Contains("corr");
				myHelper.SetCorridor( is_corridor );
				if(      !is_data() &&  is_corridor ) fillWeight *= sfhelp::MetResCorrectionCorridor();
				else if( !is_data() && !is_corridor ) fillWeight *= sfhelp::BtagCorrectionTight();

				h_bkgtype[i][0]->Fill( bkgType,                            fillWeight );
				h_evttype[i][0]->Fill( evtType,                            fillWeight );
				if( mySample->IsSignal() ) h_sigyields[i][0]->Fill( mass_stop(), mass_lsp(), fillWeight );

				h_mt[i]->Fill(      context::MT_met_lep(),                 fillWeight );
				h_met[i]->Fill(     context::Met(),                        fillWeight );
				h_mt2w[i]->Fill(    context::MT2W(),                       fillWeight );
				h_chi2[i]->Fill(    hadronic_top_chi2(),                   fillWeight );
				h_htratio[i]->Fill( context::ak4_htratiom(),               fillWeight );
				h_mindphi[i]->Fill( context::Mindphi_met_j1_j2(),          fillWeight );
				h_ptb1[i]->Fill( context::ak4pfjets_leadMEDbjet_p4().pt(), fillWeight );
				h_drlb1[i]->Fill(   drLepLeadb,                            fillWeight );
				h_ptlep[i]->Fill(   lep1_p4().pt(),                        fillWeight );
				h_metht[i]->Fill(   metSqHT,                               fillWeight );
				h_dphilw[i]->Fill(  dPhiLepW,                              fillWeight );
				h_njets[i]->Fill(   context::ngoodjets(),                  fillWeight );
				h_nbtags[i]->Fill(  context::ngoodbtags(),                 fillWeight );
				h_ptj1[i]->Fill(    j1pt,                                  fillWeight );
				h_j1btag[i]->Fill(  j1_isBtag,                             fillWeight );
				h_modtop[i]->Fill(  context::TopnessMod(),                 fillWeight );
				h_dphilmet[i]->Fill( context::lep1_dphiMET(),              fillWeight );
				h_mlb[i]->Fill(     myMlb,                                 fillWeight );

				h_yields->Fill(     double(i+1),                           fillWeight );

				// Special systematic variation histograms
				for( int j=1; j<=nVariations; j++ ) {
					h_bkgtype[i][j]->Fill( bkgType,  fillWeight * variations.at(j-1)->GetWeight() );
					h_evttype[i][j]->Fill( evtType,  fillWeight * variations.at(j-1)->GetWeight() );
					if( mySample->IsSignal() ) h_sigyields[i][j]->Fill( mass_stop(), mass_lsp(), fillWeight * variations.at(j-1)->GetWeight() );
				}

			}

			// ---------------------------------------------------------------------------------------------------//
			////////////////////////////////////////////////////////////////////////////////////////////////////////
		} //End of loop over events in file

		// Clean Up
		delete tree;
		file.Close();

		// Zero negative values in each signal region
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				bool negsFound = false;

				// First zero any decay modes with negative yields
				for( int k=1; k<= h_bkgtype[i][j]->GetNbinsX(); k++ ) {
					if( h_bkgtype[i][j]->GetBinContent(k) < 0.0 ) {
						h_bkgtype[i][j]->SetBinContent(k, 0.);
						h_bkgtype[i][j]->SetBinError(k, 0.);
						negsFound = true;
					}
					if( h_evttype[i][j]->GetBinContent(k+2) < 0.0 ) {
						h_evttype[i][j]->SetBinContent(k+2, 0.);
						h_evttype[i][j]->SetBinError(k+2, 0.);
					}
				}
				// If any negative yields were found in any decay mode, recalculate the total yield
				if( j==0 && negsFound ) {
					double newYield, newErr;
					newYield = h_bkgtype[i][0]->IntegralAndError( 0, -1, newErr );
					h_yields->SetBinContent(i+1, newYield);
					h_yields->SetBinError(i+1, newErr);
				}
				// Add zeroed histograms to total histograms
				h_bkgtype_sum[i][j]->Add( h_bkgtype[i][j] );
				h_evttype_sum[i][j]->Add( h_evttype[i][j] );
			}
		}
		h_yields_sum->Add( h_yields );

	} // End loop over files in the chain

	cout << "Cutflow yields:                        (yield)  (gen evts)" << endl;

	printf("Total number of events:             %10.2f %9i\n",   yield_total    , yGen_total    );
	if( mySample->IsData() ) {
		printf("Events passing duplicate removal:   %10.2f %9i\n", yield_unique   , yGen_unique   );
		printf("Events passing filters and trigger: %10.2f %9i\n", yield_filter   , yGen_filter   );
	}
	printf("Events with 1st vertex good:        %10.2f %9i\n",   yield_vtx      , yGen_vtx      );
	printf("Events with at least 1 good lepton: %10.2f %9i\n",   yield_1goodlep , yGen_1goodlep );
	printf("Events passing lepton selection:    %10.2f %9i\n",   yield_lepSel   , yGen_lepSel   );

	printf("\nEvents passing 2-lep requirement:   %10.2f %9i\n", yield_2lepCR   , yGen_2lepCR   );
	printf("   Events with veto lepton:         %10.2f %9i\n",   yield_2lepveto , yGen_2lepveto );
	printf("   Events with isolated track:      %10.2f %9i\n",   yield_trkVeto  , yGen_trkVeto  );
	printf("   Events with identified tau:      %10.2f %9i\n\n", yield_tauVeto  , yGen_tauVeto  );

	printf("Events with at least 2 jets:        %10.2f %9i\n",   yield_njets    , yGen_njets    );
	printf("Events with at least 1 b-tag:       %10.2f %9i\n",   yield_1bjet    , yGen_1bjet    );
	printf("Events with MET > 250 GeV:          %10.2f %9i\n",   yield_METcut   , yGen_METcut   );
	printf("Events with MT > 150 GeV:           %10.2f %9i\n",   yield_MTcut    , yGen_MTcut    );
	printf("Events with min dPhi > 0.5:         %10.2f %9i\n",   yield_dPhi     , yGen_dPhi     );
	// printf("Events with chi2 < 10:              %10.2f %9i\n",   yield_chi2     , yGen_chi2     );
	printf("Yield after preselection:           %10.2f %9i\n",   yield_chi2     , yGen_chi2     );

	if ( nEventsChain != nEventsTotal ) {
		cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
	}


	///////////////////////////////////////////////////////////////////////////////
	// Store histograms and clean them up
	TFile* plotfile = new TFile( myAnalysis->GetPlotFileName(), "READ");
	TFile* systfile = new TFile( myAnalysis->GetSystFileName(), "READ");
	TFile* sourcefile;

	// Certain histograms are cumulative across multiple samples. For those histograms, add what the
	// looper has just collected to the cumulative version stored in our output files
	for( int j=0; j<=nVariations; j++ ) {

		if( j==0 ) sourcefile = plotfile;
		else       sourcefile = systfile;

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

			// Build up cumulative histo of SUSY scan yields
			TH2D* hTemp2 = (TH2D*)sourcefile->Get( h_sigyields[i][j]->GetName() );
			if( hTemp2 != 0 ) h_sigyields[i][j]->Add( hTemp2 );

			// Build up cumulative histo of yields by signal/background type
			TH1D* hTemp = (TH1D*)sourcefile->Get( h_evttype_sum[i][j]->GetName() );
			if( hTemp != 0 ) h_evttype_sum[i][j]->Add( hTemp );
		}
	}
	delete plotfile;
	delete systfile;

	// Take all histograms in histdir and write them to plotfile
	plotfile = new TFile( myAnalysis->GetPlotFileName(), "UPDATE");
	plotfile->cd();
	histdir->GetList()->Write( "", TObject::kOverwrite );
	delete plotfile;

	// Take all histograms in systdir and write them to systfile
	systfile = new TFile( myAnalysis->GetSystFileName(), "UPDATE");
	systfile->cd();
	systdir->GetList()->Write( "", TObject::kOverwrite );
	delete systfile;

	// Cleanup
	zerodir->Close();
	histdir->Close();
	systdir->Close();

	// return
	bmark->Stop("benchmark");
	cout << endl;
	cout << nEventsTotal << " Events Processed" << endl;
	cout << "------------------------------" << endl;
	cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
	cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
	cout << endl;
	delete bmark;
	return 0;
}
Example #10
0
void ptRatioTnP()
{
    TCanvas* cnv[3][2];

    gStyle->SetLegendBorderSize(0);
    gStyle->SetLegendFont(42);
    gStyle->SetOptStat("");
    gStyle->SetTitleSize(0.7, "X");
    gStyle->SetTitleOffset(0.7, "X");

    map<string, pair<string, int> > samples;
    map<string, TH1F*> histos[3];
    THStack* bkgStack[3];
    bkgStack[0] = new THStack("bkg_ptr", "p_T Ratio: 1 fb^{-1};p_T-ratio");
    bkgStack[1] = new THStack("bkg_m", "Invariant Mass: 1 fb^{-1};M_{e#gamma}");
    bkgStack[2] = new THStack("bkg_Xpt", "Tag and Probe pair boost: 1 fb^{-1};p_{T}");
    TH1F* voids[3];
    voids[0] = new TH1F("void_ptr", "p_T Ratio: 1 fb^{-1};p_T-ratio", 300, 0, 10);
    voids[1] = new TH1F("void_m", "Invariant Mass: 1 fb^{-1};M_{e#gamma}", 300, 0, 2000);
    voids[2] = new TH1F("void_Xpt", "Tag and Probe pair boost: 1 fb^{-1};p_{T}", 300, 0, 200);

    TLegend lg(0.6,0.5,0.95,0.8);
    lg.SetFillStyle(0);
    lg.SetTextSize(0.045);
    
    samples["TTjets_ALL"] = make_pair("tt+jets", kGreen+1);
    samples["ZZ4l_ALL"] = make_pair("ZZ", kCyan+1);
    samples["WZjets_ALL"] = make_pair("WZ", kBlue);
    samples["WW2L2nu_ALL"] = make_pair("WW", kBlue);
    samples["WJetsToLNu_HT-600To800_ALL"] = make_pair("W+jets", kRed+1);
    samples["WJetsToLNu_HT-800To1200_ALL"] = make_pair("W+jets", kRed+1);
    samples["WJetsToLNu_HT-1200To2500_ALL"] = make_pair("W+jets", kRed+1);
    samples["WJetsToLNu_HT-2500ToInf_ALL"] = make_pair("W+jets", kRed+1);
    samples["DYLL_all"] = make_pair("DY", kAzure-7);
    samples["singleEle_ALL"] = make_pair("Data", kBlack);

    TH1F* h_sumW;
    float lumiForW=1000;

    float          pu_weight=0;
    float          perEveW=0;
    float          totXsec=0;
    vector<float>* e_pt_ = new vector<float>;
    vector<float>* e_eta_ = new vector<float>;
    vector<float>* e_phi_ = new vector<float>;
    vector<float>* g_pt_ = new vector<float>;
    vector<float>* g_eta_ = new vector<float>;
    vector<float>* g_phi_ = new vector<float>;
    vector<bool>* e_match_ = new vector<bool>;
    vector<int>* g_presel_ = new vector<int>;
    vector<int>* e_idx_ = new vector<int>;
    vector<int>* g_idx_ = new vector<int>;
    vector<float>* invMass_ = new vector<float>;
    vector<float>* ptRatio_ = new vector<float>;

    for(auto& sample : samples)
    {
        cout << "/afs/cern.ch/work/c/crovelli/public/spring15_v3v8/"+sample.first+".root" << endl;
        TFile* file = TFile::Open(("/afs/cern.ch/work/c/crovelli/public/spring15_v3v8/"+sample.first+".root").c_str(), "READ");
        TTree* tree = (TTree*)file->Get("tnpAna/TaPtree");
        h_sumW = (TH1F*)file->Get("tnpAna/h_sumW");
        if(!file || !tree || !h_sumW)
            continue;

        if(!histos[0][sample.second.first])
        {
            histos[0][sample.second.first] = new TH1F((sample.second.first+"_ptr").c_str(), "", 300, 0, 10);
            histos[1][sample.second.first] = new TH1F((sample.second.first+"_m").c_str(), "", 300, 0, 2000);
            histos[2][sample.second.first] = new TH1F((sample.second.first+"_Xpt").c_str(), "", 300, 0, 200);
        }

        double sampleSumWeight = (double)h_sumW->Integral();       
        tree->SetBranchAddress("pu_weight", &pu_weight);
        tree->SetBranchAddress("perEveW", &perEveW);
        tree->SetBranchAddress("totXsec", &totXsec);
        tree->SetBranchAddress("electron_pt", &e_pt_);
        tree->SetBranchAddress("electron_eta", &e_eta_);
        tree->SetBranchAddress("electron_phi", &e_phi_);
        tree->SetBranchAddress("gamma_pt", &g_pt_);
        tree->SetBranchAddress("gamma_eta", &g_eta_);
        tree->SetBranchAddress("gamma_phi", &g_phi_);
        tree->SetBranchAddress("electron_matchHLT", &e_match_);
        tree->SetBranchAddress("gamma_presel", &g_presel_);
        tree->SetBranchAddress("eleIndex", &e_idx_);
        tree->SetBranchAddress("gammaIndex", &g_idx_);
        tree->SetBranchAddress("invMass", &invMass_);
        tree->SetBranchAddress("ptRatio", &ptRatio_);

        for(unsigned int iEntry=0; iEntry<tree->GetEntriesFast(); ++iEntry)
        {
            tree->GetEntry(iEntry);
            float ptr_tmp=-1;
            for(unsigned int iPair=0; iPair<invMass_->size(); ++iPair)
            {
                TLorentzVector ele, gam;
                ele.SetPtEtaPhiM(e_pt_->at(e_idx_->at(iPair)), e_eta_->at(e_idx_->at(iPair)),
                                 e_phi_->at(e_idx_->at(iPair)), 0);
                gam.SetPtEtaPhiM(g_pt_->at(g_idx_->at(iPair)), g_eta_->at(g_idx_->at(iPair)),
                                 g_phi_->at(g_idx_->at(iPair)), 0);
                float X_pt = (ele+gam).Pt();
                float weight = perEveW * lumiForW * totXsec / sampleSumWeight;
                // if(invMass_->at(iPair) > 150)
                //     histos[2][sample.second.first]->Fill(X_pt, weight);
                if(invMass_->at(iPair) > 150 && X_pt < 30 && 
                   g_presel_->at(g_idx_->at(iPair))==1 &&
                   e_match_->at(e_idx_->at(iPair)))
                {                    
                    ptr_tmp = ptRatio_->at(iPair);
                    if(sample.second.first == "Data")
                        weight = 1;
                    histos[0][sample.second.first]->Fill(ptr_tmp, weight);
                    histos[1][sample.second.first]->Fill(invMass_->at(iPair), weight);
                    histos[2][sample.second.first]->Fill(gam.Pt(), weight);
                }
            }
        }

        for(int i=0; i<3; ++i)
        {
            //histos[i][sample.second.first]->SetFillStyle(0);
            histos[i][sample.second.first]->SetLineColor(sample.second.second);
            histos[i][sample.second.first]->SetFillColor(sample.second.second);
            if(sample.second.first != "Data")
                bkgStack[i]->Add(histos[i][sample.second.first]);
        }
        cout << sample.second.first << " :"
             << histos[0][sample.second.first]->Integral(1, 30) << " / "
             << histos[0][sample.second.first]->Integral(31, 200) << endl;
    }

    lg.AddEntry(histos[0]["tt+jets"], "tt+jets", "f");
    lg.AddEntry(histos[0]["W+jets"], "W+jets", "f");
    lg.AddEntry(histos[0]["WW"], "WW", "f");
    lg.AddEntry(histos[0]["WZ"], "WZ", "f");
    lg.AddEntry(histos[0]["ZZ"], "ZZ", "f");
    lg.AddEntry(histos[0]["DY"], "DY", "f");
    
    for(int i=0; i<3; ++i)
    {
        cnv[i][0] = new TCanvas();
        cnv[i][1] = new TCanvas();
        cnv[i][0]->cd();
        bkgStack[i]->Draw("hist");
        lg.DrawClone("same");
        cnv[i][0]->Modified();
        //histos[i]["Data"]->Draw("Esame");
        cnv[i][1]->cd();
        bkgStack[i]->Draw("nostack");
        lg.DrawClone("same");
        cnv[i][1]->Modified();
    }
}
void number_of_events_table_xi1690_cc(TString inFile=""){

	//*** In file

	TFile * input = new TFile(inFile, "READ");

	TTree * ntpMC = (TTree*) input->Get("ntpMC");
	TTree * ntpPiMinus = (TTree*) input->Get("ntpPiMinus");
	TTree * ntpPiPlus = (TTree*) input->Get("ntpPiPlus");
	TTree * ntpkaonplus = (TTree*) input->Get("ntpKaonPlus");
	TTree * ntpProton = (TTree*) input->Get("ntpProton");
	TTree * ntpAntiProton = (TTree*) input->Get("ntpAntiProton");
	TTree * ntpLambda0 = (TTree*) input->Get("ntpLambda0");
	TTree * ntpAntiLambda0 = (TTree*) input->Get("ntpAntiLambda0");
	TTree * ntpXiPlus1690 = (TTree*) input->Get("ntpXiPlus1690");
	TTree * ntpXiMinus = (TTree*) input->Get("ntpXiMinus");
	TTree * ntpXiSys = (TTree*) input->Get("ntpXiSys");


	double nevents_mc = ntpMC->GetEntriesFast();
	TString cuts = " McTruthMatch && VtxFit_HowGood==1 && MassFit_prob>0.01";
	TString VtxCut = " McTruthMatch && VtxFit_HowGood==1 & HitTag==1";
	TString cut4c = "McTruthMatch && 4CFit_prob>0.01";


	cout << "particle|   #evts (uncut)|    #evts (ratio in %)|   MC ratio in %|   dp/p in %" << endl;


	//**** PiMinus(Lambda0)
	TH1D * h_piminus_tht_uncut = new TH1D("h_piminus_tht_uncut", "h_piminus_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus_tht_uncut", "piminus_tht", "McTruthMatch && Mother==3122");
	double piminus_uncut =  h_piminus_tht_uncut->GetEntries();

	TH1D * h_piminus_tht = new TH1D("h_piminus_tht", "h_piminus_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus_tht", "piminus_tht", "McTruthMatch && piminus_HitTag && Mother==3122");
	int piminus =  h_piminus_tht->GetEntries();

	TH1D * h_piminus_dp = new TH1D("h_piminus_dp", "h_piminus_dp", 250, -0.1,0.1);
	ntpPiMinus->Project("h_piminus_dp", "(piminus_p-piminus_MC_p)/piminus_MC_p", "McTruthMatch && piminus_HitTag && Mother==3122");

	Double_t param[6] = jenny::GetFitParameterDoubleFit(h_piminus_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piminus_dp, "","", false, false, false, 0.02,0.1, true);


	double ratio_piminus_cut = piminus/piminus_uncut;
	double ratio_piminus_mc = piminus/nevents_mc;

	cout << "PiMinus(L0)|   " <<  piminus_uncut << "|   " <<  piminus << "(" << ratio_piminus_cut*100 << ")|   " << ratio_piminus_mc*100 << endl;//<< "|   " << param[2]*100 << endl;



	//**** piminus (Xi)
	TH1D * h_piminus2_tht_uncut2 = new TH1D("h_piminus2_tht_uncut2", "h_piminus2_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus2_tht_uncut2", "piminus_tht", "McTruthMatch && Mother==3312");
	double piminus_uncut2 =  h_piminus2_tht_uncut2->GetEntries();

	TH1D * h_piminus2_tht = new TH1D("h_piminus2_tht", "h_piminus2_tht", 100, 0,10);
	ntpPiMinus->Project("h_piminus2_tht", "piminus_tht", "McTruthMatch && piminus_HitTag && Mother==3312");
	int piminus2 =  h_piminus2_tht->GetEntries();

	TH1D * h_piminus2_dp = new TH1D("h_piminus2_dp", "h_piminus2_dp", 250, -0.1,0.1);
	ntpPiMinus->Project("h_piminus2_dp", "(piminus_p-piminus_MC_p)/piminus_MC_p", "McTruthMatch && piminus_HitTag && Mother==3312");

	Double_t parampip2[6] = jenny::GetFitParameterDoubleFit(h_piminus2_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piminus2_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_piminus_cut2 = piminus2/piminus_uncut2;
	double ratio_piminus_mc2 = piminus2/nevents_mc;

	cout << "PiMinus(Xi)|   " <<  piminus_uncut2 << "|   " <<  piminus2 << "(" << ratio_piminus_cut2*100 << ")|   " << ratio_piminus_mc2*100<< endl;// << "|   " << parampip2[2]*100 << endl;


	//**** PiPlus (AntiLambda0)
	TH1D * h_piplus_tht_uncut = new TH1D("h_piplus_tht_uncut", "h_piplus_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus_tht_uncut", "piplus_tht", "McTruthMatch && Mother==-3122");
	double piplus_uncut =  h_piplus_tht_uncut->GetEntries();

	TH1D * h_piplus_tht = new TH1D("h_piplus_tht", "h_piplus_tht", 100, 0,10);
	ntpPiPlus->Project("h_piplus_tht", "piplus_tht", "McTruthMatch && piplus_HitTag && Mother==-3122");
	int piplus =  h_piplus_tht->GetEntries();

	TH1D * h_piplus_dp = new TH1D("h_piplus_dp", "h_piplus_dp", 250, -0.1,0.1);
	ntpPiPlus->Project("h_piplus_dp", "(piplus_p-piplus_MC_p)/piplus_MC_p", "McTruthMatch && piplus_HitTag && Mother==-3122");

	Double_t parampip[6] = jenny::GetFitParameterDoubleFit(h_piplus_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_piplus_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_piplus_cut = piplus/piplus_uncut;
	double ratio_piplus_mc = piplus/nevents_mc;

	cout << "PiPlus(AL0)|   " <<  piplus_uncut << "|   " <<  piplus << "(" << ratio_piplus_cut*100 << ")|   " << ratio_piplus_mc*100 << endl;//<< "|   " << parampip[2]*100 << endl;




	//**** kaonplus
	TH1D * h_kaonplus_tht_uncut = new TH1D("h_kaonplus_tht_uncut", "h_kaonplus_tht", 100, 0,10);
	ntpkaonplus->Project("h_kaonplus_tht_uncut", "kaonplus_tht", "McTruthMatch && Mother==-13314");
	double kaonplus_uncut =  h_kaonplus_tht_uncut->GetEntries();

	TH1D * h_kaonplus_tht = new TH1D("h_kaonplus_tht", "h_kaonplus_tht", 100, 0,10);
	ntpkaonplus->Project("h_kaonplus_tht", "kaonplus_tht", "McTruthMatch && kaonplus_HitTag && Mother==-13314");
	int kaonplus =  h_kaonplus_tht->GetEntries();

	TH1D * h_kaonplus_dp = new TH1D("h_kaonplus_dp", "h_kaonplus_dp", 250, -0.1,0.1);
	ntpkaonplus->Project("h_kaonplus_dp", "(kaonplus_p-kaonplus_MC_p)/kaonplus_MC_p", "McTruthMatch && kaonplus_HitTag && Mother==-13314");

	Double_t paramk[6] = jenny::GetFitParameterDoubleFit(h_kaonplus_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_kaonplus_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_kaonplus_cut = kaonplus/kaonplus_uncut;
	double ratio_kaonplus_mc = kaonplus/nevents_mc;

	cout << "kaonplus|   " <<  kaonplus_uncut << "|   " <<  kaonplus << "(" << ratio_kaonplus_cut*100 << ")|   " << ratio_kaonplus_mc*100 << endl;//<< "|   " << paramk[2]*100 << endl;



	//**** Proton
	TH1D * h_proton_tht_uncut = new TH1D("h_proton_tht_uncut", "h_proton_tht", 100, 0,10);
	ntpProton->Project("h_proton_tht_uncut", "proton_tht", "McTruthMatch && Mother==3122");
	double proton_uncut =  h_proton_tht_uncut->GetEntries();

	TH1D * h_proton_tht = new TH1D("h_proton_tht", "h_proton_tht", 100, 0,10);
	ntpProton->Project("h_proton_tht", "proton_tht", "McTruthMatch && proton_HitTag && Mother==3122");
	int proton =  h_proton_tht->GetEntries();

	TH1D * h_proton_dp = new TH1D("h_proton_dp", "h_proton_dp", 250, -0.1,0.1);
	ntpProton->Project("h_proton_dp", "(proton_p-proton_MC_p)/proton_MC_p", "McTruthMatch && proton_HitTag && Mother==3122");

	Double_t paramProt[6] = jenny::GetFitParameterDoubleFit(h_proton_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_proton_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_proton_cut = proton/proton_uncut;
	double ratio_proton_mc = proton/nevents_mc;

	cout << "proton|   " <<  proton_uncut << "|   " <<  proton << "(" << ratio_proton_cut*100 << ")|   " << ratio_proton_mc*100 << endl;//<< "|   " << paramProt[2]*100 << endl;




	//**** AntiProton
	TH1D * h_AntiProton_tht_uncut = new TH1D("h_AntiProton_tht_uncut", "h_AntiProton_tht", 100, 0,10);
	ntpAntiProton->Project("h_AntiProton_tht_uncut", "AntiProton_tht", "McTruthMatch");
	double AntiProton_uncut =  h_AntiProton_tht_uncut->GetEntries();

	TH1D * h_AntiProton_tht = new TH1D("h_AntiProton_tht", "h_AntiProton_tht", 100, 0,10);
	ntpAntiProton->Project("h_AntiProton_tht", "AntiProton_tht", "McTruthMatch && AntiProton_HitTag");
	int AntiProton =  h_AntiProton_tht->GetEntries();

	TH1D * h_AntiProton_dp = new TH1D("h_AntiProton_dp", "h_AntiProton_dp", 250, -0.1,0.1);
	ntpAntiProton->Project("h_AntiProton_dp", "(AntiProton_p-AntiProton_MC_p)/AntiProton_MC_p", "McTruthMatch && AntiProton_HitTag");

	Double_t paramAProt[6] = jenny::GetFitParameterDoubleFit(h_AntiProton_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_AntiProton_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_AntiProton_cut = AntiProton/AntiProton_uncut;
	double ratio_AntiProton_mc = AntiProton/nevents_mc;

	cout << "AntiProton|   " <<  AntiProton_uncut << "|   " <<  AntiProton << "(" << ratio_AntiProton_cut*100 << ")|   " << ratio_AntiProton_mc*100 << endl;//<< "|   " << paramAProt[2]*100 << endl;



	//**** lambda0
	TH1D * h_Lambda0_tht_uncut = new TH1D("h_Lambda0_tht_uncut", "h_Lambda0_tht", 100, 0,10);
	ntpLambda0->Project("h_Lambda0_tht_uncut", "Lambda0_tht", "McTruthMatch & HitTag==1");
	double Lambda0_uncut =  h_Lambda0_tht_uncut->GetEntries();

	TH1D * h_Lambda0_tht = new TH1D("h_Lambda0_tht", "h_Lambda0_tht", 100, 0,10);
	ntpLambda0->Project("h_Lambda0_tht", "Lambda0_tht", "HitTag && "+cuts);
	int lambda0 =  h_Lambda0_tht->GetEntries();

	TH1D * h_Lambda0_dp = new TH1D("h_Lambda0_dp", "h_Lambda0_dp", 250, -0.1,0.1);
	ntpLambda0->Project("h_Lambda0_dp", "(Lambda0_p-McTruth_p)/McTruth_p", "HitTag && "+cuts );

	Double_t paraml0[6] = jenny::GetFitParameterDoubleFit(h_Lambda0_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_Lambda0_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_Lambda0_cut = lambda0/Lambda0_uncut;
	double ratio_Lambda0_mc = lambda0/nevents_mc;

	cout << "lambda0|   " <<  Lambda0_uncut << "|   " <<  lambda0 << "(" << ratio_Lambda0_cut*100 << ")|   " << ratio_Lambda0_mc*100 << endl;//<< "|   " << paraml0[2]*100 << endl;



	//**** AntiLambda0
	TH1D * h_antiLambda0_tht_uncut = new TH1D("h_antiLambda0_tht_uncut", "h_antiLambda0_tht", 100, 0,10);
	ntpAntiLambda0->Project("h_antiLambda0_tht_uncut", "antiLambda0_tht", "McTruthMatch & HitTag==1");
	double antiLambda0_uncut =  h_antiLambda0_tht_uncut->GetEntries();

	TH1D * h_antiLambda0_tht = new TH1D("h_antiLambda0_tht", "h_antiLambda0_tht", 100, 0,10);
	ntpAntiLambda0->Project("h_antiLambda0_tht", "antiLambda0_tht", "HitTag && "+cuts);
	int AntiLambda0 =  h_antiLambda0_tht->GetEntries();

	TH1D * h_antiLambda0_dp = new TH1D("h_antiLambda0_dp", "h_antiLambda0_dp", 250, -0.1,0.1);
	ntpAntiLambda0->Project("h_antiLambda0_dp", "(antiLambda0_p-McTruth_p)/McTruth_p", "HitTag && "+cuts);

	Double_t paramAL0[6] = jenny::GetFitParameterDoubleFit(h_antiLambda0_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_antiLambda0_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_antiLambda0_cut = AntiLambda0/antiLambda0_uncut;
	double ratio_antiLambda0_mc = AntiLambda0/nevents_mc;

	cout << "AntiLambda0|   " <<  antiLambda0_uncut << "|   " <<  AntiLambda0 << "(" << ratio_antiLambda0_cut*100 << ")|   " << ratio_antiLambda0_mc*100<< endl;// << "|   " << paramAL0[2]*100 << endl;


	//**** XiPlus1690
	TH1D * h_xiplus_tht_uncut = new TH1D("h_xiplus_tht_uncut", "h_xiplus_tht", 100, 0,10);
	ntpXiPlus1690->Project("h_xiplus_tht_uncut", "xiplus_tht", "McTruthMatch & HitTag==1");
	double xiplus_uncut =  h_xiplus_tht_uncut->GetEntries();

	TH1D * h_xiplus_tht = new TH1D("h_xiplus_tht", "h_xiplus_tht", 100, 0,10);
	ntpXiPlus1690->Project("h_xiplus_tht", "xiplus_tht", VtxCut);
	int XiPlus =  h_xiplus_tht->GetEntries();

	TH1D * h_xiplus_dp = new TH1D("h_xiplus_dp", "h_xiplus_dp", 250, -0.1,0.1);
	ntpXiPlus1690->Project("h_xiplus_dp", "(xiplus_p-MCTruth_p)/MCTruth_p", VtxCut);

	Double_t paramxip[6] = jenny::GetFitParameterDoubleFit(h_xiplus_dp, false, 0.02,0.1, true);
	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_xiplus_dp, "","", false, false, false, 0.02,0.1, true);

	double ratio_xiplus_cut = XiPlus/xiplus_uncut;
	double ratio_XiPlus_McTruth = XiPlus/nevents_mc;

	cout << "XiPlus1690|   " <<  xiplus_uncut << "|   " <<  XiPlus << "(" << ratio_xiplus_cut*100 << ")|   " << ratio_XiPlus_McTruth*100<< endl;// << "|   " << paramxip[2]*100 << endl;


	//**** XiMinus
	TH1D * h_XiMinus_tht_uncut = new TH1D("h_XiMinus_tht_uncut", "h_XiMinus_tht", 100, 0,10);
	ntpXiMinus->Project("h_XiMinus_tht_uncut", "VtxFit_tht", "McTruthMatch & HitTag==1");
	double XiMinus_uncut =  h_XiMinus_tht_uncut->GetEntries();

	TH1D * h_XiMinus_tht = new TH1D("h_XiMinus_tht", "h_XiMinus_tht", 100, 0,10);
	ntpXiMinus->Project("h_XiMinus_tht", "VtxFit_tht", cuts+"& HitTag==1");
	int XiMinus1820 =  h_XiMinus_tht->GetEntries();

	TH1D * h_xiMinus_dp = new TH1D("h_xiMinus_dp", "h_xiMinus_dp", 250, -0.1,0.1);
	ntpXiMinus->Project("h_xiMinus_dp", "VtxFit_p-MCTruth_p");

	//jenny::CreateDrawAndSaveHistogramDoulbeFit(h_xiMinus_dp, " ", " ", false, false, false, 0.02 , 0.1, true);
	Double_t paramxim[6] = jenny::GetFitParameterDoubleFit(h_xiMinus_dp, false, 0.02,0.1, true);

	double ratio_XiMinus_cut = XiMinus1820/XiMinus_uncut;
	double ratio_XiMinus_mc = XiMinus1820/nevents_mc;

	cout << "XiMinus|   " <<  XiMinus_uncut << "|   " <<  XiMinus1820 << "(" << ratio_XiMinus_cut*100 << ")|   " << ratio_XiMinus_mc*100 << endl;// "|   " << paramxim[2]*100 << endl;


	//**** XiSys
	TH1D * h_XiSys_tht_uncut = new TH1D("h_XiSys_tht_uncut", "h_XiSys_tht", 100, 0,10);
	ntpXiSys->Project("h_XiSys_tht_uncut", "XiSys_tht", "McTruthMatch");
	double XiSys_uncut =  h_XiSys_tht_uncut->GetEntries();

	TH1D * h_XiSys_tht = new TH1D("h_XiSys_tht", "h_XiSys_tht", 100, 0,10);
	ntpXiSys->Project("h_XiSys_tht", "XiSys_tht", cut4c);
	int XiSys =  h_XiSys_tht->GetEntries();

	TH1D * h_XiSys_dp = new TH1D("h_XiSys_dp", "h_XiSys_dp", 250, -0.1,0.1);
	ntpXiSys->Project("h_XiSys_dp", "(XiSys_p-McTruth_p)/McTruth_p", cut4c);

	Double_t paramxisys[6] = jenny::GetFitParameterDoubleFit(h_XiSys_dp, false, 0.02,0.1, true);


	double ratio_XiSys_cut = XiSys/XiSys_uncut;
	double ratio_XiSys_mc = XiSys/nevents_mc;

	cout << "XiSys|   " <<  XiSys_uncut << "|   " <<  XiSys << "(" << ratio_XiSys_cut*100 << ")|   " << ratio_XiSys_mc*100<< endl;// << "|   " << paramxisys[2]*100 << endl;


}
Example #12
0
void simQdep()
{
    for(int x0=1; x0<12; x0++)
    {
	TCanvas* c1 = new TCanvas();
	c1->cd();
	char file_name[60];
	sprintf(file_name, "G4_sim/Pb_FascioDisperso_004/molteplice%d.root", x0);
	TFile* dataFile = TFile::Open("ntuples/reco_Scan4.root","r");
	TTree* nt = (TTree*)dataFile->Get("reco_tree");
	TH1F* hCharge = new TH1F("hCharge", "hCharge", 300, -25000, 2000);
	hCharge->SetLineColor(kRed);

	float thX[8]={113,95,127,118,94,134,133,160};
	float thY[8]={110,101,119,136,94,98,87,97};
	char cut_hodoX[300];
	char cut_hodoY[300];
	TCut cut_sig("-charge_MiB2 > -13.28*amp_max_MiB2 - 350");
        TCut cut_trig1("charge_MiB1 < th_SB_MiB1 && charge_Roma2 < th_SB_Roma2 && sci_front_adc > 500 && sci_front_adc < 1500");
	sprintf(cut_hodoX, "(fibreX[0] > %f || fibreX[1] > %f || fibreX[2] > %f || fibreX[3] > %f || fibreX[4] > %f || fibreX[5] > %f || fibreX[6\
] > %f || fibreX[7] > %f)", thX[0], thX[1], thX[2], thX[3], thX[4], thX[5], thX[6], thX[7]);
	sprintf(cut_hodoY, "(fibreY[0] > %f || fibreY[1] > %f || fibreY[2] > %f || fibreY[3] > %f || fibreY[4] > %f || fibreY[5] > %f || fibreY[6\
] > %f || fibreY[7] > %f)", thY[0], thY[1], thY[2], thY[3], thY[4], thY[5], thY[6], thY[7]);

	nt->Draw("charge_MiB2>>hCharge", cut_trig1 && cut_sig && cut_hodoX && cut_hodoY && "run_id == 261"); 

//	cout << hCharge->GetMean() << endl;

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

	TFile* simFile = TFile::Open(file_name, "r");
	TTree* inTree = (TTree*)simFile->Get("tree");

	TH1I* hMulti = new TH1I("hMulti","hMulti", 10, 0, 10);
	TH1F* hCorr = new TH1F("hCorr","hCorr", 300, -25000, 2000);
//	TH1F* hCorr = new TH1F("hCorr","hCorr", 10, 0, 10);
	inTree->Draw("number_0>>hMulti");	

	std::vector<float>* energy=0;
	inTree->SetBranchAddress("Energies_0", &energy);
	
	float eff=0;
	for(int iEntry=0; iEntry<inTree->GetEntriesFast(); iEntry++)
	{
	    //int count=0;
	    float corrQ=0;
	    inTree->GetEntry(iEntry);
	    //---simulazione molteplicità
	    // for(int iPart=0; iPart<energy->size(); iPart++)
	    // {
	    // 	corrQ += hCharge->GetRandom();
	    // }
	    // hCorr->Fill(corrQ);
	    //---simulazion eff
	    eff += 1-pow(0.55, energy->size());
	}

/*
	for(int iBin=1; iBin<11; iBin++)
	{
	    for(int j=0; j<hMulti->GetBinContent(iBin); j++)
	    {
		int tmp=0;
		for(int i=1; i<iBin; i++)
		{
		    if(gRandom->Uniform(0,1)<0.45)
			tmp++;
		}
		hCorr->Fill(tmp);
	    }
	}
*/
	// hCorr->Scale(hCharge->GetEntries()/hCorr->GetEntries());
	// hCorr->Draw();
	// hCharge->Draw("sames");
	// cout << x0*0.71 << "  " << hCorr->GetMean()/hCharge->GetMean() << endl;
	cout << x0 << "   " << eff/inTree->GetEntriesFast() << endl;
    }
}
Example #13
0
Double_t CalibTree::Loop(int loop) {
  char name[500];
  bool debug=false;
  if (fChain == 0) return 0;
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;
  std::map<unsigned int, std::pair<double,double> >SumW;
  std::map<unsigned int, unsigned int >nTrks;
  unsigned int mask(0xFF80), ntrkMax(0);
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
  //  for (Long64_t jentry=0; jentry<1000;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(debug) std::cout << "***Entry (Track) Number : " << ientry 
			<< " p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal 
			<< "/" << t_eMipDR << "/" << (*t_DetIds).size() 
			<< std::endl;
    if (goodTrack()) {
      if (loop == 0) hprof_ndets->Fill(t_ieta, (*t_DetIds).size());
      double Etot=0.0;
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	double hitEn=0.0;
        unsigned int detid = (*t_DetIds)[idet] & mask;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	Etot += hitEn;
      }
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	unsigned int detid = (*t_DetIds)[idet] & mask;
	double hitEn=0.0;
	if (debug) std::cout << "idet " << idet << " detid/hitenergy : " 
			     << std::hex << (*t_DetIds)[idet] << ":" << detid
			     << "/" << (*t_HitEnergies)[idet] << std::endl;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	double Wi = hitEn/Etot;
	double Fac = (Wi* t_p) / Etot;
	if( SumW.find(detid) != SumW.end() ) {
	  Wi  += SumW[detid].first;
	  Fac += SumW[detid].second;
	  SumW[detid] = std::pair<double,double>(Wi,Fac); 
	  nTrks[detid]++;
	} else {
	  SumW.insert( std::pair<unsigned int, std::pair<double,double> >(detid,std::pair<double,double>(Wi,Fac)));
	  nTrks.insert(std::pair<unsigned int,unsigned int>(detid, 1));
	}
	if (nTrks[detid] > ntrkMax) ntrkMax = nTrks[detid];
      }
    }
  }
  
  std::map<unsigned int, std::pair<double,double> >::iterator SumWItr = SumW.begin();
  unsigned int kount(0), mkount(0);
  double       sumfactor(0);
  double       dets[150], cfacs[150], wfacs[150], nTrk[150];
  unsigned int ntrkCut = ntrkMax/10;
  for (; SumWItr != SumW.end(); SumWItr++) {
    if (debug) 
      std::cout<< "Detid/SumWi/SumFac : " << SumWItr->first << " / "
	       << (SumWItr->second).first << " / " << (SumWItr->second).second
	       << std::endl;
    unsigned int detid = SumWItr->first;
    double factor = (SumWItr->second).second / (SumWItr->second).first;

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

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

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

  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, double>::iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (CprevItr=Cprev.begin(); CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int ieta = (detid>>7) & 0x3f;
    int zside= (detid&0x2000) ? 1 : -1;
    int depth= (detid>>14)&0x1F;
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") ( nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second << std::endl;
  }
  double mean = (mkount > 0) ? (sumfactor/mkount) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << mkount << ":"
	    << kount << " DetIds" << std::endl;
  return mean;
}
Example #14
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  TH1F *samplehisto = new TH1F("samplehisto", "Example histogram", 200,0,200);
  samplehisto->SetDirectory(rootdir);

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      StopBabies10012015::progress( nEventsTotal, nEventsChain );

      // Analysis Code

    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  samplehisto->Draw();
  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Example #15
0
Int_t integrateRatePlots()
{
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
  TGaxis::SetMaxDigits(3);

  const Int_t nFiles = 3;
  //  const Int_t nElectrons = 3;

  TFile * histoFile = new TFile("integratedRates-eta2p1-26Jan12.root","RECREATE");
  TFile * inputFile[nFiles]; 

  inputFile[0] = TFile::Open("RctEmTree-Rates-scaleV1-thr2p0-01Dec11.root"); // v1, 2.0, BOTH ISO AND NON-ISO
  inputFile[1] = TFile::Open("RctEmTree-Rates-scaleV3-thr1p0-12Jan12.root"); // v3, 1.0, iso
  inputFile[2] = TFile::Open("RctEmTree-Rates-HighPU-scaleV3-thr1p0-18Jan12.root"); // v3, 1.0, highPU, iso

  TH1F * h_rank[nFiles], * h_rankIntegrated[nFiles];
  TH1F * h_rankBarrel[nFiles], * h_rankBarrelIntegrated[nFiles];

  // scale factor here is 1./(total n LS * 23 s/LS) * (total lumi / effective lumi) to get from total event counts to rate (event count per second)
  Float_t scaleFactor[3];
  scaleFactor[0] = 14.2 * 1./(15379.*23.) * (713729./68.794); 
  scaleFactor[1] = 1./(15379.*23.) * (713729./68.794); 
  scaleFactor[2] = 1./(299. * 23.) * (299.556 / 49.926) * (201.78 / 4.3559); // scaled up to 2e33 inst lumi from 4e31 -- those last two numbers are times 10^31 

  // tree stuff
  TTree * tree;
  vector<int>     *emRank;
  vector<int>     *emIso;
  vector<int>     *emIeta;
  TBranch        *b_emRank;
  TBranch        *b_emIso;
  TBranch        *b_emIeta;

  // end tree stuff

//   Int_t nBins = 64;
//   Float_t xMin = 0., xMax = 64.;
  Int_t nBins = 52;
  Float_t xMin = 12., xMax = 64.;

  // |eta| < 1.5, barrel-only
//   Int_t barrelIEtaBoundaryLower = 7; // this is REGION ieta -- goes from 4 to 17, not including HF.  
//   Int_t barrelIEtaBoundaryUpper = 14; // this takes first four regions (last 3 are endcap)

// |eta| < 2.1  
  Int_t barrelIEtaBoundaryLower = 8; // this is REGION ieta -- goes from 4 to 17, not including HF.  
  Int_t barrelIEtaBoundaryUpper = 13; // this takes first three regions (first 24 towers), going to eta 2.1720
  
  TCanvas * rankCanvas = new TCanvas("rankCanvas","EM rank distribution");
  TCanvas * rankBarrelCanvas = new TCanvas("rankBarrelCanvas","EM rank distribution (|#eta| < 2.1)");

  TCanvas * integratedCanvas = new TCanvas("integratedCanvas","Rate by trigger threshold");
  integratedCanvas->cd();
  TPad * pad1 = new TPad("pad1","pad1",0.,0.35,1.0,1.0);
  pad1->SetBottomMargin(0);
  pad1->Draw();
  TPad * pad2 = new TPad("pad2","pad2",0.,0.,1.0,0.35);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(0.3);
  pad2->Draw();

  TCanvas * integratedBarrelCanvas = new TCanvas("integratedBarrelCanvas","Rate by trigger threshold (|#eta| < 2.1)");
  integratedBarrelCanvas->cd();
  TPad * pad1B = new TPad("pad1B","pad1B",0.,0.35,1.0,1.0);
  pad1B->SetBottomMargin(0);
  pad1B->Draw();
  TPad * pad2B = new TPad("pad2B","pad2B",0.,0.,1.0,0.35);
  pad2B->SetTopMargin(0);
  pad2B->SetBottomMargin(0.3);
  pad2B->Draw();


  for (Int_t file = 0; file < nFiles; file++)
    {
      std::cout << "File " << file << std::endl;
      
      inputFile[file]->cd();

      TString treeName = TString("rctAnalyzer/emTree;1");

      std::cout << "getting tree" << std::endl;
      gDirectory->GetObject(treeName,tree);

      //   std::cout << "X min = " << h_rank->GetXaxis()->GetXmin() << std::endl;
      //   std::cout << "X max = " << h_rank->GetXaxis()->GetXmax() << std::endl;
      
      //   Int_t nBins = h_rank->GetNbinsX();
      
      //   h_rank = new TH1F("h_rank","EM Rank",nBins,h_rank->GetXaxis()->GetXmin(),h_rank->GetXaxis()->GetXmax());
      //   h_rankIntegrated = new TH1F("h_rankIntegrated","Rates by trigger threshold",nBins,h_rank->GetXaxis()->GetXmin(),h_rank->GetXaxis()->GetXmax());
      std::cout << "making histograms" << std::endl;
      
      h_rank[file] = new TH1F(makeName("h_rank",file),"EM Rank",nBins,xMin,xMax);
      h_rankIntegrated[file] = new TH1F(makeName("h_rankIntegrated",file),"Rates by trigger threshold",nBins,xMin,xMax);
      h_rankBarrel[file] = new TH1F(makeName("h_rankBarrel",file),"EM Rank (|#eta| < 2.1)",nBins,xMin,xMax);
      h_rankBarrelIntegrated[file] = new TH1F(makeName("h_rankBarrelIntegrated",file),"Rates by trigger threshold (|#eta| < 2.1)",nBins,xMin,xMax);
      
      rankCanvas->cd();

      // tree stuff
      emRank = 0;
      emIso = 0;
      emIeta = 0;
      
      tree->SetBranchAddress("emRank", &emRank, &b_emRank);
      tree->SetBranchAddress("emIso", &emIso, &b_emIso);
      tree->SetBranchAddress("emIeta", &emIeta, &b_emIeta);
      b_emRank->SetAutoDelete(kTRUE);
      b_emIso->SetAutoDelete(kTRUE);
      b_emIeta->SetAutoDelete(kTRUE);

      tree->SetBranchStatus("*",0);
      tree->SetBranchStatus("emRank",1);
      tree->SetBranchStatus("emIso",1);
      tree->SetBranchStatus("emIeta",1);

      // loop over tree
      std::cout << "Looping over tree" << std::endl;
      Long64_t nentries = tree->GetEntriesFast();
      for (Long64_t jentry = 0; jentry < nentries; jentry++) 
	{
	  //std::cout << "entry " << jentry << std::endl;
	  //Long64_t ientry = tree->LoadTree(jentry);
	  //tree->LoadTree(jentry); // Set current entry.
	  tree->GetEntry(jentry); // Read all branches of entry and return total number of bytes read.
	  
	  Int_t elecSize = emRank->size();
	  for (Int_t elec = 0; elec < elecSize; elec++)
	    {
	      if (file == 0) // isolated and non-isolated
		{
		  h_rank[file]->Fill(emRank->at(elec));
		  if (emIeta->at(elec) >= barrelIEtaBoundaryLower &&
		      emIeta->at(elec) <= barrelIEtaBoundaryUpper)
		    {
		      h_rankBarrel[file]->Fill(emRank->at(elec));
		    }
		  break;
		}
	      else // isolated only
		{
		  if (emIso->at(elec) == 1)
		    {
		      h_rank[file]->Fill(emRank->at(elec));
		      if (emIeta->at(elec) >= barrelIEtaBoundaryLower &&
			emIeta->at(elec) <= barrelIEtaBoundaryUpper)
			{
			  h_rankBarrel[file]->Fill(emRank->at(elec));
			}
		      break;
		    }
		}
	    }
	}
      
      // end tree stuff
      
      // making pretty colors for the lines in the rank plots
      h_rank[file]->SetLineColor(file+1);
      if (file+1 == 3)
	{
	  h_rank[file]->SetLineColor(8);
	}
      if (file+1 == 5)
	{
	  h_rank[file]->SetLineColor(41);
	}
      h_rank[file]->SetLineWidth(2);

      h_rankBarrel[file]->SetLineColor(file+40);
      h_rankBarrel[file]->SetLineWidth(2);

      if (file == 0)
	{
	  h_rank[file]->Draw();
	}
      else
	{
	  h_rank[file]->Draw("same");
	  h_rankBarrel[file]->Draw("same");
	}

      rankBarrelCanvas->cd();
      if (file == 0)
	{
	  h_rankBarrel[file]->Draw();
	}
      else
	{
	  h_rankBarrel[file]->Draw("same");
	}

      // doing the integration      
      Int_t eventsAboveThreshold = 0;
      for (int i = nBins-1; i >= 0; i--)
	{
	  eventsAboveThreshold = eventsAboveThreshold + h_rank[file]->GetBinContent(i);
	  std::cout << "bin is " << i << ", bin content is " << h_rank[file]->GetBinContent(i)
		    << ", eventsAboveThreshold is " << eventsAboveThreshold << std::endl;
	  h_rankIntegrated[file]->Fill(xMin+i,eventsAboveThreshold);
	}
      eventsAboveThreshold = 0;
      for (int i = nBins-1; i >= 0; i--)
	{
	  eventsAboveThreshold = eventsAboveThreshold + h_rankBarrel[file]->GetBinContent(i);
	  std::cout << "bin is " << i << ", bin content is " << h_rankBarrel[file]->GetBinContent(i)
		    << ", eventsAboveThreshold is " << eventsAboveThreshold << std::endl;
	  h_rankBarrelIntegrated[file]->Fill(xMin+i,eventsAboveThreshold);
	}
      std::cout << "sumw2" << std::endl;
      h_rankIntegrated[file]->Sumw2();
      h_rankIntegrated[file]->Scale(scaleFactor[file]);
      h_rankBarrelIntegrated[file]->Sumw2();
      h_rankBarrelIntegrated[file]->Scale(scaleFactor[file]);
      
      // more pretty colors, this time for integrated plots
      h_rankIntegrated[file]->SetLineColor(file+1);
      if (file+1 == 3)
	{
	  h_rankIntegrated[file]->SetLineColor(8);
	}
      if (file+1 == 5)
	{
	  h_rankIntegrated[file]->SetLineColor(41);
	}
      h_rankIntegrated[file]->SetLineWidth(2);

      if (file == 1)
	{
	  h_rankBarrelIntegrated[file]->SetLineColor(kRed+2);
	}
      if (file == 2)
	{
	  h_rankBarrelIntegrated[file]->SetLineColor(kYellow+2);
	}
      h_rankBarrelIntegrated[file]->SetLineWidth(2);

      integratedCanvas->cd();
      pad1->cd();
      std::cout << "Draw" << std::endl;
      if(file == 0)
	{
	  h_rankIntegrated[file]->Draw();
	}
      else
	{
	  h_rankIntegrated[file]->Draw("same");
	  h_rankBarrelIntegrated[file]->Draw("same");
	}

      integratedBarrelCanvas->cd();
      pad1B->cd();
      std::cout << "Draw" << std::endl;
      if(file == 0)
	{
	  h_rankBarrelIntegrated[file]->Draw();
	}
      else
	{
	  h_rankBarrelIntegrated[file]->Draw("same");
	}
      std::cout << "Done drawing" << std::endl;
      
    }

  std::cout << "Making legend" << std::endl;

  TLegend legend(0.3,0.6,0.89,0.89);
  legend.AddEntry(h_rankIntegrated[0],"v1 scales, thr = 2.0, Relaxed");
  legend.AddEntry(h_rankIntegrated[1],"v3 scales, thr = 1.0, Isolated");
  legend.AddEntry(h_rankBarrelIntegrated[1],"v3 scales, thr = 1.0, Isolated, |#eta| < 2.1");
  legend.AddEntry(h_rankIntegrated[2],"High-PU, v3 scales, thr = 1.0, Isolated");
  legend.AddEntry(h_rankBarrelIntegrated[2],"High-PU, v3 scales, thr = 1.0, Isolated, |#eta| < 2.1");
  legend.SetFillColor(0);

  integratedCanvas->cd();
  pad1->cd();
  legend.Draw("same");

  integratedBarrelCanvas->cd();
  pad1B->cd();
  legend.Draw("same");


  std::cout << "Making ratio plots" << std::endl;

  integratedCanvas->cd();
  pad2->cd();
  TH1F * r_eff1;
  TH1F * r_eff2;
  r_eff1 = (TH1F*) h_rankIntegrated[1]->Clone("r_eff1");
  r_eff2 = (TH1F*) h_rankIntegrated[2]->Clone("r_eff2");
  r_eff1->Divide(h_rankIntegrated[0]);
  r_eff2->Divide(h_rankIntegrated[0]);
  r_eff1->SetTitle("");
  r_eff2->SetTitle("");
  r_eff1->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff2->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff1->SetMinimum(0.3);
  r_eff1->SetMaximum(1.0);
  r_eff2->SetMinimum(0.3);
  r_eff2->SetMaximum(1.0);
  r_eff1->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff1->GetXaxis()->SetLabelSize(0.07);
  r_eff1->GetXaxis()->SetTitleSize(0.07);
  r_eff1->GetYaxis()->SetLabelSize(0.07);
  r_eff2->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff2->GetXaxis()->SetLabelSize(0.07);
  r_eff2->GetXaxis()->SetTitleSize(0.07);
  r_eff2->GetYaxis()->SetLabelSize(0.07);
  r_eff1->Draw();
  r_eff2->Draw("same");

  integratedBarrelCanvas->cd();
  pad2B->cd();
  TH1F * r_eff1B;
  TH1F * r_eff2B;
  r_eff1B = (TH1F*) h_rankBarrelIntegrated[1]->Clone("r_eff1B");
  r_eff2B = (TH1F*) h_rankBarrelIntegrated[2]->Clone("r_eff2B");
  r_eff1B->Divide(h_rankIntegrated[0]);
  r_eff2B->Divide(h_rankIntegrated[0]);
  r_eff1B->SetTitle("");
  r_eff2B->SetTitle("");
  r_eff1B->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff2B->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff1B->SetMinimum(0.3);
  r_eff1B->SetMaximum(1.0);
  r_eff2B->SetMinimum(0.3);
  r_eff2B->SetMaximum(1.0);
  r_eff1B->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff1B->GetXaxis()->SetLabelSize(0.07);
  r_eff1B->GetXaxis()->SetTitleSize(0.07);
  r_eff1B->GetYaxis()->SetLabelSize(0.07);
  r_eff2B->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff2B->GetXaxis()->SetLabelSize(0.07);
  r_eff2B->GetXaxis()->SetTitleSize(0.07);
  r_eff2B->GetYaxis()->SetLabelSize(0.07);
  r_eff1B->Draw();
  r_eff2B->Draw("same");

  integratedCanvas->cd();
  r_eff1B->Draw("same");
  r_eff2B->Draw("same");

  TLine * unity;
  unity = new TLine(0.,1.0,64.,1.0);
  unity->SetX1(gPad->PadtoX(xMin));
  unity->SetX2(gPad->PadtoX(xMax));
  unity->SetLineColor(kBlue);

  integratedCanvas->cd();
  pad2->cd();
  r_eff1B->Draw("same");
  r_eff2B->Draw("same");
  unity->Draw("same");

  integratedBarrelCanvas->cd();
  pad2B->cd();
  unity->Draw("same");

  std::cout << "Writing canvases to file" << std::endl;
  histoFile->WriteTObject(rankCanvas);
  histoFile->WriteTObject(rankBarrelCanvas);
  histoFile->WriteTObject(integratedCanvas);
  histoFile->WriteTObject(integratedBarrelCanvas);

  std::cout << "Closing input files" << std::endl;
  for (Int_t i = 0; i < nFiles; i++)
    {
      inputFile[i]->Close();
    }

  std::cout << "Deleting canvases" << std::endl;

  delete rankCanvas;
  delete rankBarrelCanvas;
  delete pad1;
  delete pad2;
  delete integratedCanvas;
  delete pad1B;
  delete pad2B;
  delete integratedBarrelCanvas;

  return 0;

}
void TMVAClassificationApplication_cc1pcoh_bdt_ver3noveractFFFSI( TString myMethodList = "", TString fname)
{
#ifdef __CINT__
    gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif
    
    //---------------------------------------------------------------
    
    // This loads the library
    TMVA::Tools::Instance();
    
    // Default MVA methods to be trained + tested
    std::map<std::string,int> Use;
    //
    // --- Boosted Decision Trees
    Use["BDT"]             = 1; // uses Adaptive Boost
    
    
    std::cout << std::endl;
    std::cout << "==> Start TMVAClassificationApplication" << std::endl;
    
    // Select methods (don't look at this code - not of interest)
    if (myMethodList != "") {
        for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
        
        std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
        for (UInt_t i=0; i<mlist.size(); i++) {
            std::string regMethod(mlist[i]);
            
            if (Use.find(regMethod) == Use.end()) {
                std::cout << "Method \"" << regMethod
                << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
                for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
                    std::cout << it->first << " ";
                }
                std::cout << std::endl;
                return;
            }
            Use[regMethod] = 1;
        }
    }
    
    // --------------------------------------------------------------------------------------------------
    
    // --- Create the Reader object
    
    TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
    
    // Create a set of variables and declare them to the reader
    // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
    Float_t mumucl, pmucl;
    Float_t pang_t, muang_t;
    Float_t veract;
    Float_t ppe, mupe;
    Float_t range, coplanarity;
    Float_t opening;//newadd
    
    reader->AddVariable( "mumucl", &mumucl );
    reader->AddVariable( "pmucl", &pmucl );
    reader->AddVariable( "pang_t", &pang_t );
    reader->AddVariable( "muang_t", &muang_t );
    //reader->AddVariable( "veract", &veract );
    reader->AddVariable( "ppe", &ppe);
    reader->AddVariable( "mupe", &mupe);
    reader->AddVariable( "range", &range);
    reader->AddVariable( "coplanarity", &coplanarity);
    reader->AddVariable( "opening", &opening);//newadd
    
    // Spectator variables declared in the training have to be added to the reader, too
    Int_t fileIndex, inttype;
    Float_t nuE, norm, totcrsne;
    reader->AddSpectator( "fileIndex", &fileIndex );
    reader->AddSpectator( "nuE", &nuE );
    reader->AddSpectator( "inttype", &inttype );
    reader->AddSpectator( "norm", &norm );
    reader->AddSpectator( "totcrsne", &totcrsne );
    reader->AddSpectator( "veract", &veract );
    
    // --- Book the MVA methods
    
    TString dir    = "weights/";
    TString prefix = "TMVAClassification_ver3noveractFFFSI";//newchange
    
    // Book method(s)
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
        if (it->second) {
            TString methodName = TString(it->first) + TString(" method");
            TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml");
            reader->BookMVA( methodName, weightfile );
        }
    }
    
    // Prepare input tree (this must be replaced by your data source)
    // in this example, there is a toy tree with signal and one with background events
    // we'll later on use only the "signal" events for the test in this example.
    //
    

    
    
    //for prange/pang_t corrected and other information included
    
    //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/datamc_merged_ccqe_addpidFFnew.root";
    //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/datamc_genie_merged_ccqe_addpidFFnew.root";
    //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/mc_merged_ccqe_addpidFFnew.root";
    //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/mcgenie_merged_ccqe_tot_addpidFFnew.root";
    //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/merged_ccqe_forResponseFunction.root";
   //TString fname = "/home/cvson/scraid2/cc1picoh/FIT/datafsi/pmnue_merged_ccqe_tot_addpidFFnew.root"; 
    std::cout << "--- Selecting data sample" << std::endl;
    TFile *pfile = new TFile(fname,"update");
    TTree* theTree = (TTree*)pfile->Get("tree");
    theTree->SetBranchAddress( "mumucl", &mumucl );
    theTree->SetBranchAddress( "pmucl", &pmucl );
    theTree->SetBranchAddress( "pang_t", &pang_t );
    theTree->SetBranchAddress( "muang_t", &muang_t );
    theTree->SetBranchAddress( "veract", &veract );
    theTree->SetBranchAddress( "ppe", &ppe);
    theTree->SetBranchAddress( "mupe", &mupe);
    theTree->SetBranchAddress( "range", &range);
    theTree->SetBranchAddress( "coplanarity", &coplanarity);
    theTree->SetBranchAddress( "opening", &opening);
    
 
    
    Int_t Ntrack;
    theTree->SetBranchAddress( "Ntrack", &Ntrack );
    
    
    Float_t pidfsi;
    TBranch *bpidfsi = theTree->Branch("pidfsi",&pidfsi,"pidfsi/F");
    
    
    
    std::vector<Float_t> vecVar(9); // vector for EvaluateMVA tests
    
    Long64_t nentries = theTree->GetEntriesFast();
    Long64_t iprintProcess = Long64_t(nentries/100.);
    
    std::cout << "--- Processing: " << nentries << " events" << std::endl;
    
    TStopwatch sw;
    sw.Start();
    for (Long64_t ievt=0; ievt<nentries;ievt++) {
        
        if (ievt%iprintProcess == 0) cout<<"Processing "<<int(ievt*100./nentries)<<"% of events"<<endl;
        theTree->GetEntry(ievt);
        Float_t pidfsi_tem;
        if (Use["BDT"])      {
            //if (Ntrack!=2) pidfsi_tem = -999;//changehere
            if (Ntrack<2) pidfsi_tem = -999;
            else pidfsi_tem = reader->EvaluateMVA("BDT method");
        }
        pidfsi = pidfsi_tem;
        bpidfsi->Fill();
        
    }
    theTree->Write();
    delete pfile;
    // Get elapsed time
    sw.Stop();
    std::cout << "--- End of event loop: "; sw.Print();
    
    delete reader;
    
    std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
} 
int main(int argc, char** argv){

  // RETRIEVING LIST OF FILENAMES TO CHECK

  if (argc != 3) {

    cout << "Usage: ./TopTreeContentDump --inputfiles file1;file2;fileN\n\n" << endl;

    exit(0);

  } else if (argc == 3 && !strstr(argv[1],"--inputfiles")) {

    cout << "Usage: ./TopTreeContentDump --inputfiles file1;file2;fileN\n\n" << endl;

    exit(0);

  }

  vector<string> fileNames;
  
  Tokenize(argv[2], fileNames, ";");


  // CHECKING THE FILECONTENT FOR FILE 0 AND COUNT EVENTS FOR ALL FILES

  unsigned int nEvents = 0; 

  for (int fileID=0; fileID < fileNames.size(); fileID++) {
  
    //cout << fileNames.at(fileID) << endl;

    TFile* f = TFile::Open(fileNames.at(fileID).c_str());
    
    TTree* runTree = (TTree*) f->Get("runTree");
    TTree* eventTree = (TTree*) f->Get("eventTree");
    
    TBranch* run_br = (TBranch *) runTree->GetBranch("runInfos");
    TRootRun* runInfos = 0;
    run_br->SetAddress(&runInfos);
    
    TBranch* event_br = (TBranch *) eventTree->GetBranch("Event");
    TRootEvent* event = 0;
    event_br->SetAddress(&event);
    
    nEvents += eventTree->GetEntriesFast();

    if (fileID == 0) {

      cout << "* Dumping the event content of the TopTree" << endl;
      
      for (int i=1; i<eventTree->GetListOfBranches()->GetEntriesFast(); i++) {
	
	TBranch * branch = (TBranch *)eventTree->GetListOfBranches()->At(i);
	
	TObject* obj = branch->GetListOfLeaves()->At(0);
	
	std::string ObjName = obj->GetName();
	
	string::size_type position = ObjName.find_last_of("_");
	
	std::string className = "";
	
	if (strstr(ObjName.c_str(),"CaloJet"))
	  className="TopTree::TRootCaloJet";
	else if (strstr(ObjName.c_str(),"PFJet"))
	  className="TopTree::TRootPFJet";
	else if (strstr(ObjName.c_str(),"JPTJet"))
	  className="TopTree::TRootJPTJet";
	else if (strstr(ObjName.c_str(),"GenJet"))
	  className="TopTree::TRootGenJet";
	else if (strstr(ObjName.c_str(),"MCParticles"))
	  className="TopTree::TRootMCParticle";
	else if (strstr(ObjName.c_str(),"NPGenEvent"))
	  className="TopTree::TRootNPGenEvent";
	else if (strstr(ObjName.c_str(),"GenEvent"))
	  className="TopTree::TRootGenEvent";
	else if (strstr(ObjName.c_str(),"Muon"))
	  className="TopTree::TRootMuon";
	else if (strstr(ObjName.c_str(),"Electron"))
	  className="TopTree::TRootElectron";
	else if (strstr(ObjName.c_str(),"TCMET"))
	  className="TopTree::TRootMET";
	else if (strstr(ObjName.c_str(),"CaloMET"))
	  className="TopTree::TRootCaloMET";
	else if (strstr(ObjName.c_str(),"PFMET"))
	  className="TopTree::TRootPFMET";
	else if (strstr(ObjName.c_str(),"MET"))
	  className="TopTree::TRootMET";
	else if (strstr(ObjName.c_str(), "TrackMET"))
	  className="TopTree::TRootTrackMET";  
	else if (strstr(ObjName.c_str(),"MHT"))
	  className="TopTree::TRootMHT";
	else if (strstr(ObjName.c_str(),"PrimaryVertex"))
	  className="TopTree::TRootVertex";
	

	cout << "- " << className << setw(5) << " -> " << "\"" << ObjName.substr(0,position) << "\""  << endl;
   
	    }

     //runinfos

     runTree->GetEvent(0);

     if (runInfos->hltInputTag() != "")
       cout << "- " << "TopTree::TRootRun" << setw(5) << " -> " << "\"" << runInfos->hltInputTag() << "\""  << endl;

    }

  }

  //cout << "\n* The TopTree file contains " << nEvents << " events\n" << endl;


}
Example #18
0
template <class HolderClass> bool read(const char *dirname, const char *testname, int nEntry, bool current) {
   HolderClass *holder = 0;
   bool result = true;
   bool testingTopLevelVectors = true; 

   TString filename = gSystem->ConcatFileName(dirname, testname );
   filename += ".root";

   if (!current && gSystem->AccessPathName(filename, kFileExists)) {
      // when reading old directory a missing files is not an error.
      // For example this happens if the run of roottest at the time was done
      // with FAST=yes
      return true;
   }

   TFile file(filename,"READ");

   if (file.IsZombie()) return false;

   holder = dynamic_cast<HolderClass*>( file.Get("holder") );
   if (!holder) {
      TestError("Reading",Form("Missing object: holder"));
      result = false;
   } else {
      result &= holder->Verify(0,Form("%s: write in dir",testname),0);
   }

   TTree *chain = dynamic_cast<TTree*>( file.Get("stltree") );

   if (!chain) {
      TestError("treeReading",Form("Missing TTree: stltree"));
      return false;
   }

   if (nEntry==0 || nEntry>chain->GetEntriesFast()) nEntry = (Int_t)chain->GetEntriesFast();
   for ( Int_t entryInChain = 0, entryInTree = chain->LoadTree(0);
         entryInTree >= 0 && entryInChain<nEntry;
         entryInChain++, entryInTree = chain->LoadTree(entryInChain)
         ) {

      if ( chain->GetEntry(entryInChain) == 0 ) {
         TestError("treeReading",Form("Nothing read for entry #%d",entryInChain));
         break;
      }

      result &= verifyBranch<HolderClass>(testname,chain,"split_2.");
      result &= verifyBranch<HolderClass>(testname,chain,"split_1.");
      result &= verifyBranch<HolderClass>(testname,chain,"split0.");
      result &= verifyBranch<HolderClass>(testname,chain,"split1.");
      result &= verifyBranch<HolderClass>(testname,chain,"split2.");
      result &= verifyBranch<HolderClass>(testname,chain,"split99.");

      if (testingTopLevelVectors) {
         // we know that they all fail! (missing dictionary)
         result &= verifyBranch<HolderClass>(testname,chain,"scalar0",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar1",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar2",1);
         result &= verifyBranch<HolderClass>(testname,chain,"scalar99",1);
         
         result &= verifyBranch<HolderClass>(testname,chain,"object0",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object1",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object2",2);
         result &= verifyBranch<HolderClass>(testname,chain,"object99",2);
         
         result &= verifyBranch<HolderClass>(testname,chain,"nested0",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested1",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested2",3);
         result &= verifyBranch<HolderClass>(testname,chain,"nested99",3);  
      }
   }
   return result;
}
Example #19
0
void Dcurvature(const char *chargechoice = "plus", double ptmin=20){

  TString sign=chargechoice;

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

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


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

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

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

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

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

  TTree *tree;

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

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

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

  long nentries = tree->GetEntriesFast();

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



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

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

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

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




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

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

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


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

}
Example #20
0
int main(int argc, char** argv){

  // Set it to "true" if you do not want to see the histograms interactively
  gROOT->SetBatch(IS_BATCH);
  gStyle->SetOptStat(1111111);
  gStyle->SetOptFit(1111);

  // Open the input root file and set branches
  // On pcciet3a, pcciet3b, pccmscie6
  //TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/TTbar.root";
  // Just for some checks (there are selection cuts applied on the following file)
  //TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/TTbar_SSVHPNOMTNOISOreduced.root";
  // Stop file
//  TString sampleFile = "/data4/Fall11_WplusC_Trees_July2012/Stop.root";
  TString sampleFile = "dcap://gaeds015.ciemat.es:22125/pnfs/ciemat.es/data/cms/store/user/delacruz/STop2012/NTuplesFeb2013/v1/merge_stops_signalmc_T2tt_Mstop-225to1200_mLSP-0to1000_Pythia_new.root";

  Event ev;
  Event* pointerToEvent = &ev;
  printf("Processing sample '%s'...\n", sampleFile.Data());
  TFile input_sample(sampleFile,"READONLY");
  TTree* tree = 0;
  input_sample.GetObject("MUTREE/MUTREE",tree);
  if (!tree) input_sample.GetObject("MUTREE",tree);
  tree->SetBranchAddress("event", &pointerToEvent);

  int nentriesInTree = tree->GetEntriesFast();
  if (maxEventsUsed<0) maxEventsUsed = nentriesInTree;
  printf("\tThere are %d events in the file; running on %d events\n", nentriesInTree, maxEventsUsed);

  TH1D* hCosb = new TH1D("hCosb", "cos(#theta_{tb})", 50, -1.0, 1.0);

  printf("Input thetaEff for topPol %.3f is: %.3f\n", 1., GetThetaMixing(1., 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", 0.5, GetThetaMixing(0.5, 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", 0., GetThetaMixing(0., 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", -0.5, GetThetaMixing(-0.5, 950., 175., 425.));
  printf("Input thetaEff for topPol %.3f is: %.3f\n", -1., GetThetaMixing(-1., 950., 175., 425.));

  // Event loop
  for (int iEvent=0; iEvent<maxEventsUsed; iEvent++) {
    if (tree->LoadTree(iEvent)<0) break;
    tree->GetEntry(iEvent);

    if (ev.genInfos.size()<=0) {
      printf("This is not a MC file, EXIT!!!\n");
      return -1;
    }

    if (iEvent%1000000==0) printf("... event index %d\n", iEvent);
    
    unsigned int ngen = ev.genParticles.size();

    //double m_stop = 0.;
    //double m_chi0 = 0.;
    //double m_top = 0.;
    std::vector<SUSYGenParticle> genParticles;
    for (unsigned int ig=0; ig<ngen; ++ig) {
      GenParticle gen = ev.genParticles[ig];
      if (gen.status!=3) break;
      SUSYGenParticle part;
      part.pdgId = gen.pdgId;
      part.energy = gen.energy;
      part.pt = gen.pt;
      part.eta = gen.eta;
      part.phi = gen.phi;
      part.firstMother = -1; if (gen.mothers.size()>0) part.firstMother = gen.mothers[0];
      //if (abs(gen.pdgId)==1000006) m_stop = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));
      //if (abs(gen.pdgId)==1000022) m_chi0 = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));
      //if (abs(gen.pdgId)==6) m_top = sqrt(pow(gen.energy,2)-pow(gen.pt*cosh(gen.eta),2));

      genParticles.push_back(part);
    }
    //printf("m_stop: %.3f, m_top: %.3f, m_chi0: %.3f\n", m_stop, m_top, m_chi0);

    //double pol_new = POL;
    //double pol_new = AverageTopPolarization_Stop_to_TopChi0(-1.1, genParticles);
    //double weight = Reweight_Stop_to_TopChi0_TopOnshell (genParticles, 0., pol_new);

    // m_stop=950 GeV, m_chi0=425 GeV, m_top=175 GeV
    double thetaMixingTarget = -1.134; // Pol=-1
    //double thetaMixingTarget = -0.437; // Pol=+1
    double weight = Reweight_Stop_to_TopChi0_with_SUSYmodel (genParticles, thetaMixingTarget);

    for (unsigned int ig=0; ig<ngen; ++ig) {
      GenParticle gen = ev.genParticles[ig];
      if (gen.status!=3) break;
      if (abs(gen.pdgId)!=5) continue;
      if (gen.mothers.size()!=1) continue;
      GenParticle genTop = ev.genParticles[gen.mothers[0]];
      if (abs(genTop.pdgId)!=6) continue;

      if (genTop.pdgId*gen.pdgId<0) continue;

      double etop = genTop.energy;
      double pxtop = genTop.pt*cos(genTop.phi);
      double pytop = genTop.pt*sin(genTop.phi);
      double pztop = genTop.pt*sinh(genTop.eta);
      double ptop  = sqrt(pxtop*pxtop+pytop*pytop+pztop*pztop);
      double mtop  = sqrt(etop*etop-ptop*ptop);
      double pxb   = gen.pt*cos(gen.phi);
      double pyb   = gen.pt*sin(gen.phi);
      double pzb   = gen.pt*sinh(gen.eta);
      double pb    = sqrt(pxb*pxb+pyb*pyb+pzb*pzb);

      // We also need a stop
      if (genTop.mothers.size()==0) continue;
      GenParticle genStop = ev.genParticles[genTop.mothers[0]];
      if (abs(genStop.pdgId)!=1000006) continue;

      // Move top and fermion to the stop center-of-mass frame
      TLorentzVector stop4;
      stop4.SetPtEtaPhiE(genStop.pt, genStop.eta, genStop.phi, genStop.energy);
      TVector3 betaS(-stop4.Px()/stop4.Energy(),-stop4.Py()/stop4.Energy(),-stop4.Pz()/stop4.Energy());
      TLorentzVector topRef(pxtop,pytop,pztop,etop);
      topRef.Boost(betaS); // keept this vector to calculate costh
      TLorentzVector top4(pxtop,pytop,pztop,etop);
      top4.Boost(betaS);
      TLorentzVector b4(pxb,pyb,pzb,pb);
      b4.Boost(betaS);

      TVector3 betaV(-top4.Px()/top4.Energy(),-top4.Py()/top4.Energy(),-top4.Pz()/top4.Energy());
      top4.Boost(betaV);
      b4.Boost(betaV);

      double costh = (topRef.Px()*b4.Px()+topRef.Py()*b4.Py()+topRef.Pz()*b4.Pz())/topRef.P()/b4.P();

      hCosb->Fill(costh,weight);

    }

  }

  // To see things interactively (if IS_BATCH == false);
  TRint* app = new TRint("Wprime Analysis", &argc, argv);

  hCosb->SetMinimum(0.);
  hCosb->Draw();

  // Fitting slope
  TF1* f1 = new TF1("f1","[0]*(1+[1]*x)");
  f1->SetParName(0,"ValueAt0");
  f1->SetParName(1,"Slope");
  hCosb->Fit(f1,"","same");

  gROOT->GetListOfCanvases()->At(0)->SaveAs("costhb.jpg");

  app->Run();

  return 0;
}
void CosmicRateTool_Kinematics(const char* fileName)
{
        
   TString InputFile= Form("%s",fileName); 
   TFile *file = new TFile(InputFile);

   bool IsFileExist;
   IsFileExist = file->IsZombie();
   if(IsFileExist)
   {   
      cout<<endl<<"====================================================================================================="<<endl;
      cout<<fileName << " is not found. Check the file!"<<endl;
      cout<<"====================================================================================================="<<endl<<endl;
      exit (EXIT_FAILURE);
   }

   TTree *tree;
   tree = (TTree*)file->Get("cosmicRateAnalyzer/Event");
	
   vector<double>  *pt;
   vector<double>  *charge;
   vector<double>  *chi2;
   vector<double>  *chi2_ndof;
   vector<double>  *eta;
   vector<double>  *theta;
   vector<double>  *phi;
   vector<double>  *p;
   vector<double>  *d0;
   vector<double>  *dz;
   vector<double>  *nvh;
   vector<int>  *v_ntrk;
   
   pt = 0;
   charge = 0;
   chi2 = 0;
   chi2_ndof = 0;
   eta = 0;
   theta = 0;
   phi = 0;
   p = 0;
   d0 = 0;
   dz = 0;
   nvh = 0;

   tree->SetBranchAddress("pt", &pt);
   tree->SetBranchAddress("charge", &charge);
   tree->SetBranchAddress("chi2", &chi2);
   tree->SetBranchAddress("chi2_ndof", &chi2_ndof);
   tree->SetBranchAddress("eta", &eta);
   tree->SetBranchAddress("theta", &theta);
   tree->SetBranchAddress("phi", &phi);
   tree->SetBranchAddress("p", &p);
   tree->SetBranchAddress("d0", &d0);
   tree->SetBranchAddress("dz", &dz);
   tree->SetBranchAddress("nvh", &nvh);
//   tree->SetBranchAddress("v_ntrk", &v_ntrk);

   Long64_t n = tree->GetEntriesFast();

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//					Various Kinematical Histograms Declerations				
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

   TH1D h_pt 		("h_pt","h_pt",200,0,200);
   TH1D h_charge 	("h_charge","h_charge",10,-5,5);
   TH1D h_chi2 		("h_chi2","h_chi2",200,0,100);
   TH1D h_chi2_ndof 	("h_chi2_ndof","h_chi2_ndof",200,0,20);
   TH1D h_eta 		("h_eta","h_eta",500,-3,3);
   TH1D h_theta 	("h_theta","h_theta",500,-3,3);
   TH1D h_phi 		("h_phi","h_phi",400,-3.5,3.5);
   TH1D h_d0 		("h_d0","h_d0",1000,-85,85);
   TH1D h_dz 		("h_dz","h_dz",1500,-350,350);
//   TH1D *h_ntrk		= new TH1D("h_ntrk","h_ntrk",20,0,20);

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

   
   for (Long64_t jentry=0; jentry<n;jentry++) 
   {
     tree->GetEntry(jentry);

      for (int k = 0; k < pt->size() ; k++)			// Loop to calculate Kinematical distributions
      {
	h_pt.Fill(pt->at(k));
	h_charge.Fill(charge->at(k));
	h_chi2.Fill(chi2->at(k));
	h_chi2_ndof.Fill(chi2_ndof->at(k));
	h_eta.Fill(eta->at(k));
	h_theta.Fill(theta->at(k));
	h_phi.Fill(phi->at(k));
	h_d0.Fill(d0->at(k));
	h_dz.Fill(dz->at(k));


      }								// Loop Closed to calculate Kinematical distributions
     }								// Loop Closed to calculate rates


//++++++++++++++++++++++++++++++++++       Make Directory     ++++++++++++++++++++++++++++++++++++++

	gSystem->Exec("mkdir -p Kinematical_Plots");

//---------------------------------------------------------------------------------------------------
	
	TCanvas c("c","c",800,600);    // Declare canvas

//+++++++++++++++++++++++++++++++       pT Distribution      ++++++++++++++++++++++++++++++++++++++++     
	h_pt.SetLineColor(kBlue);
	h_pt.SetLineWidth(2);
	h_pt.SetTitle("pT distribution");
	h_pt.SetXTitle("pT (in GeV)");
	h_pt.Draw();
	h_pt.SetStats();
	c.SetGrid();
	c.SaveAs("pt.png");
	c.Clear();
	gSystem->Exec("mv pt.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       charge Distribution      ++++++++++++++++++++++++++++++++++++++++     

	h_charge.SetLineColor(kBlue);
	h_charge.SetLineWidth(2);
	h_charge.SetTitle("charge");
	h_charge.SetXTitle("");
	h_charge.Draw();
	c.SetGrid();
	c.SaveAs("charge.png");
	c.Clear();
	gSystem->Exec("mv charge.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       chi2 Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_chi2.SetLineColor(kBlue);
        h_chi2.SetLineWidth(2); 
        h_chi2.SetTitle("chi2 distribution");
        h_chi2.SetXTitle("");
        h_chi2.Draw();
        c.SetGrid();                         
        c.SaveAs("chi2.png");                                                                                                                  
        c.Clear();      
	gSystem->Exec("mv chi2.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       chi2/ndof Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_chi2_ndof.SetLineColor(kBlue);
        h_chi2_ndof.SetLineWidth(2); 
        h_chi2_ndof.SetTitle("chi2 per ndof");
        h_chi2_ndof.SetXTitle("");
        h_chi2_ndof.Draw();
        c.SetGrid();    
        c.SaveAs("chi2_ndof.png");                                                                                                                       c.Clear();      
	c.Clear();
	gSystem->Exec("mv chi2_ndof.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       eta Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_eta.SetLineColor(kBlue);
        h_eta.SetLineWidth(2); 
        h_eta.SetTitle("eta Distribution");
        h_eta.SetXTitle("#eta");
        h_eta.Draw();
        c.SetGrid();                            
        c.SaveAs("eta.png");                                                                                                                  
        c.Clear();      
	gSystem->Exec("mv eta.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       theta Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_theta.SetLineColor(kBlue);
        h_theta.SetLineWidth(2); 
        h_theta.SetTitle("theta distribution");
        h_theta.SetXTitle("#theta");
        h_theta.Draw();
        c.SetGrid();    
        c.SaveAs("theta.png");                                                                                                                  
        c.Clear();      
	gSystem->Exec("mv theta.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       phi Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_phi.SetLineColor(kBlue);
        h_phi.SetLineWidth(2); 
        h_phi.SetTitle("phi distribution");
        h_phi.SetXTitle("#phi");
        h_phi.Draw();
        c.SetGrid();    
        c.SaveAs("phi.png");                                                                                                                  
        c.Clear();      
	gSystem->Exec("mv phi.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       d0 Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_d0.SetLineColor(kBlue);
        h_d0.SetLineWidth(2); 
        h_d0.SetTitle("d0 distribution");
        h_d0.SetXTitle("d0");
        h_d0.Draw();
        c.SetGrid();                         
        c.SaveAs("d0.png");                                                                                                                  
        c.Clear();      
	gSystem->Exec("mv d0.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------


//+++++++++++++++++++++++++++++++       dz Distribution      ++++++++++++++++++++++++++++++++++++++++     

        h_dz.SetLineColor(kBlue);
        h_dz.SetLineWidth(2); 
        h_dz.SetTitle("dz distribution");
        h_dz.SetXTitle("dz");
        h_dz.Draw();
        c.SetGrid();                         
        c.SaveAs("dz.png");                                                                                                                  
        c.Close();      
	gSystem->Exec("mv dz.png Kinematical_Plots");
//---------------------------------------------------------------------------------------------------

}
void inflateTree(const char *name = "h42",
                 const char *in = "root://eospps.cern.ch///eos/ppsscratch/test/h1big.root",
                 const char *out = "/tmp/h1big.root",  Int_t fact = 1)
{
	TStopwatch sw;
	sw.Start();
	
   // Get the input tree from the input file
   TFile *fin = TFile::Open(in);
   if (!fin || fin->IsZombie()) {
      Printf("inflateTree", "could not open input file: %s", in);
      return;
   }
   TTree *tin = (TTree *) fin->Get(name);
   if (!tin) {
      Printf("inflateTree", "could not find tree '%s' in %s", name, in);
      delete fin;
      return;
   }
   Long64_t nin = tin->GetEntriesFast();
   Printf("Input tree '%s' has %lld entries", name, nin);
   // Create output file
   TFile *fout = TFile::Open(out, "RECREATE", 0, 1);
   if (!fout || fout->IsZombie()) {
      Printf("inflateTree", "could not open input file: %s", in);
      delete fin;
      return;
   }
   // Clone the header of the initial tree
   TTree *tout= (TTree *) tin->CloneTree(0);
   tout->SetMaxTreeSize(19000000000);


   // Duplicate all entries once
#if 0
   Int_t nc = fact;
   while (nc--) {
      Printf("Writing copy %d ...", fact - nc);
      tout->CopyEntries(tin);
   }
#else
   for (Long64_t i = 0; i < nin; ++i) {
      if (tin->LoadTree(i) < 0) {
         break;
      }
      tin->GetEntry(i);
      Int_t nc = fact;
      while (nc--) {
         tout->Fill();
      }
      if (i > 0 && !(i%1000)) {
         Printf("%d copies of %lld entries filled ...", fact, i);
      }
   }
#endif
   // Finalize the writing out
   tout->Write();
   
   // print perf stats
   

    sw.Stop();
    std::cout << "Drawing. Realtime: " <<      sw.RealTime()  << std::endl;
    std::cout << "Drawing. Cputime : " <<      sw.CpuTime()  << std::endl;
	tin->PrintCacheStats();   
   
   
   // Close the files
   fout->Close();
   fin->Close();
   // Cleanup
   delete fout;
   delete fin;
}
void DalitzplotXi1820_XiPlus_lambda_k(){


	//*** Data input
	TString inputFile = "/home/ikp1/puetz/panda/mysimulations/analysis/XiPlus_Lambda_K/output_ana.root";
	TFile * data = new TFile(inputFile, "READ");

	TString outPath = "/home/ikp1/puetz/panda/mysimulations/analysis/XiPlus_Lambda_K/plots";
	TFile * out = new TFile(outPath+"/root-files/Dalitzplot_MC.root", "RECREATE");


	TTree * sim = (TTree*) data->Get("ntpMC");
	int nevents = sim->GetEntriesFast();


	TH2D * dalitz_Xilk = new TH2D("dalitz_Xilk", "Dalitz plot for MC; m^{2}(#Lambda^{0},K^{-})/GeV^{2}/c^{4}; m^{2}(#bar{#Xi}, K^{-})/GeV^{2}/c^{4}", 150,2.5,3.8,150,3.2,4.8);
	gStyle->SetOptStat(0);

	TLorentzVector lXi, lk, lla, lXi1820;
	TLorentzVector PXiK, PlaK, PXil;

	for (int n=0; n<nevents; n++){

		sim->GetEntry(n);

		double Eaxi = sim->GetLeaf("e")->GetValue(xi);
		double Ek = sim->GetLeaf("e")->GetValue(kaon);
		double Ela = sim->GetLeaf("e")->GetValue(lambda0);

		double Pxaxi = sim->GetLeaf("px")->GetValue(xi);
		double Pxk = sim->GetLeaf("px")->GetValue(kaon);
		double Pxla = sim->GetLeaf("px")->GetValue(lambda0);

		double Pyaxi = sim->GetLeaf("py")->GetValue(xi);
		double Pyk = sim->GetLeaf("py")->GetValue(kaon);
		double Pyla = sim->GetLeaf("py")->GetValue(lambda0);

		double Pzaxi = sim->GetLeaf("pz")->GetValue(xi);
		double Pzk = sim->GetLeaf("pz")->GetValue(kaon);
		double Pzla = sim->GetLeaf("pz")->GetValue(lambda0);

		lXi.SetPxPyPzE(Pxaxi, Pyaxi, Pzaxi, Eaxi);
		lk.SetPxPyPzE(Pxk, Pyk, Pzk, Ek);
		lla.SetPxPyPzE(Pxla, Pyla, Pzla, Ela);


		PXiK = lXi + lk;
		PlaK = lla + lk;
		PXil = lXi + lla;


		dalitz_Xilk->Fill(PlaK.M2(),PXiK.M2());

	}

	setPandaStyle();

	out->cd();

	dalitz_Xilk->Write();

	out->Save();


	TCanvas * c = new TCanvas("c", "Dalitz plot PHSP model", 0,0,1500,1000);
	dalitz_Xilk->Draw("COLZ");


	PandaSmartLabel("L");

	//****write histograms
	c->Print(outPath+"/png-files/Dalitzplots_MC.png");
	c->Print(outPath+"/pdf-files/Dalitzplots_MC.pdf");


}
Example #24
0
void SimpleAna(int type , double E , TString filename , int nevt_max , int iTracking , double Ebinning , int evtSelIn , int irun)
{
  if(type==0) isMC = false;
  
  TString MCtype = "pythia";
  if(type == 20) MCtype = "phojet";
  if(type == 60) MCtype = "pythia8";
  
  //int nbinmulti = 110;
  
  if(Ebinning==0) Ebinning=E;
  
  //evtSelType = evtSelIn;
  
  #include "acceptanceMap.C"
  
  int nL1      = 0;
  int nHF      = 0;
  int nVtxQual = 0;
  int nVtx     = 0;
  int nNone    = 0;
  
    
  BasePlots* baseplot = new BasePlots("BasePlots");
    
  //----------------------  RECO  ----------------------
  vector<GenMultiPlots*> gmp_evtSel_reco(accMap.size(),0);
  vector<MultiPlots*> mp_evtSel_INC_reco(accMap.size(),0);
  
  vector<GenMultiPlots*> gmp_evtSel(accMap.size(),0);
  vector<MultiPlots*> mp_etaCut_noSel_NSD_gen(accMap.size(),0);
  vector<GenMultiPlots*> gmp_etaCut(accMap.size(),0);
  
  vector<MultiPlots*> mp_evtSel_PV(accMap.size(),0);
  vector<TrackPlots*> trp(accMap.size(),0);
  VertexPlots* vtxp = new VertexPlots("");
  vector<MatrixPlots*> mtxp_evtSel(accMap.size(),0);
  
  vector<TH1F*> L1_before(accMap.size(),0);
  vector<TH1F*> L1_after(accMap.size(),0);
  vector<TH1F*> hf_before(accMap.size(),0);
  vector<TH1F*> hf_after(accMap.size(),0);
  vector<TH1F*> vtxqual_before(accMap.size(),0);
  vector<TH1F*> vtxqual_after(accMap.size(),0);
  vector<TH1F*> vtx_before(accMap.size(),0);
  vector<TH1F*> vtx_after(accMap.size(),0);
  vector<TH1F*> evtSel_before(accMap.size(),0);
  vector<TH1F*> evtSel_after(accMap.size(),0);
  
  for(int acc = 0 ; acc < (signed) accMap.size() ; ++acc){
    vector< vector<double> > binning;
    //binning = getBins(1,0,1);//nch,pt,eta
    binning = getBins(acc,Ebinning);//nch,pt,eta
    baseplot->setBinning(binning);
    
    //----------------------  RECO  ----------------------
    gmp_evtSel_reco.at(acc)  = new GenMultiPlots(st("evtSel_reco",acc));
    mp_evtSel_INC_reco.at(acc)  = new MultiPlots(st("evtSel_INC_reco",acc));
  
  
    //----------------------   GEN  ----------------------
    gmp_evtSel.at(acc)           = new GenMultiPlots(st("evtSel",acc));
    mp_etaCut_noSel_NSD_gen.at(acc) = new MultiPlots(st("etaCut_noSel_NSD_gen",acc));
    gmp_etaCut.at(acc)           = new GenMultiPlots(st("etaCut",acc));
  
    //------------ MultiPlots ------------------
    mp_evtSel_PV.at(acc)     = new MultiPlots(st("evtSel_PV",acc));
    trp.at(acc) = new TrackPlots(st("",acc));  
  
  
    //------------ MatrixPlots ------------------
    mtxp_evtSel.at(acc) = new MatrixPlots(st("evtSel",acc));
  
    //return;
    //-----
    L1_before.at(acc) = new TH1F(st("L1_before",acc),st("L1_before",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    L1_after.at(acc) = new TH1F(st("L1_after",acc),st("L1_after",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    L1_before.at(acc)->Sumw2();
    L1_after.at(acc)->Sumw2();
    hf_before.at(acc) = new TH1F(st("hf_before",acc),st("hf_before",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    hf_after.at(acc) = new TH1F(st("hf_after",acc),st("hf_after",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    hf_before.at(acc)->Sumw2();
    hf_after.at(acc)->Sumw2();
    vtxqual_before.at(acc) = new TH1F(st("vtxqual_before",acc),st("vtxqual_before",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    vtxqual_after.at(acc) = new TH1F(st("vtxqual_after",acc),st("vtxqual_after",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    vtxqual_before.at(acc)->Sumw2();
    vtxqual_after.at(acc)->Sumw2();
    vtx_before.at(acc) = new TH1F(st("vtx_before",acc),st("vtx_before",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    vtx_after.at(acc) = new TH1F(st("vtx_after",acc),st("vtx_after",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    vtx_before.at(acc)->Sumw2();
    vtx_after.at(acc)->Sumw2();
    evtSel_before.at(acc) = new TH1F(st("evtSel_before",acc),st("evtSel_before",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    evtSel_after.at(acc) = new TH1F(st("evtSel_after",acc),st("evtSel_after",acc)+";Efficiency;N_{ch}^{gen}",binning.at(0).size()-1,&binning[0][0]);
    evtSel_before.at(acc)->Sumw2();
    evtSel_after.at(acc)->Sumw2();
  }
  
  
  //getting the list of files
  vector<TString>* vfiles = getListOfFiles(fileManager(0,type,E));

  TTree* tree = new TTree("evt","");
  
  MyEvtId* evtId      = NULL ;
  vector<MyGenPart>* genPart = NULL;
  MyGenKin* genKin = NULL;
  /*vector<MyTracks>*  generalTracks  = NULL;
  vector<MyTracks>*  minbiasTracks  = NULL;
  vector<MyVertex>*  offlinePV  = NULL;
  vector<MyVertex>*  ferencVtx  = NULL;
  vector<MyVertex>*  pixel3Vertex  = NULL;*/
  vector<MyTracks>*  tracks  = NULL;
  vector<MyVertex>*  vertex  = NULL;
  vector<MyVertex>*  vertexToCut  = NULL;
  MyL1Trig*     L1Trig    = NULL;
  MyHLTrig*     HLTrig    = NULL;
  MyMITEvtSel*  MITEvtSel = NULL;
  MyBeamSpot*   bs        = NULL;
  
  
  int i_tot = 0 , nevt_tot = 0;
  //starting Loop over files, stops at end of list of files or when reached nevt_max
  for(vector<TString>::iterator itfiles = vfiles->begin() ; itfiles != vfiles->end() && i_tot < nevt_max ; ++itfiles){

    TFile* file = TFile::Open(*itfiles,"READ");

    //getting the tree form the current file
    tree = (TTree*) file->Get("evt");

    tree->SetBranchAddress("EvtId",&evtId);
    if(isMC) tree->SetBranchAddress("GenPart",&genPart);
    if(isMC) tree->SetBranchAddress("GenKin",&genKin);
    
    /*tree->SetBranchAddress("generalTracks",&generalTracks); 
    tree->SetBranchAddress("minbiasTracks",&minbiasTracks);
    tree->SetBranchAddress("primaryVertex",&offlinePV);
    //tree->SetBranchAddress("ferencVtxFerTrk",&ferencVtx);*/
    if(iTracking==0){
      tree->SetBranchAddress("generalTracks",&tracks); 
      tree->SetBranchAddress("primaryVertex",&vertex);
    }
    else if(iTracking==1){
      tree->SetBranchAddress("minbiasTracks",&tracks); 
      tree->SetBranchAddress("ferencVtxFerTrk",&vertex);
    }
    
    tree->SetBranchAddress("pixel3Vertex",&vertexToCut);
    /*if(iTracking==0) tree->SetBranchAddress("ferencVtxFerTrk",&vertexToCut);
    else if(iTracking==1) vertexToCut = vertex;*/
    tree->SetBranchAddress("L1Trig",&L1Trig);
    tree->SetBranchAddress("HLTrig",&HLTrig);
    tree->SetBranchAddress("MITEvtSel",&MITEvtSel);
    tree->SetBranchAddress("beamSpot",&bs);
    
 
    //Just to put the good collection of vertex in vertexToCut
    vertexToCut = vertex;

    //Getting number of events
    int nev = int(tree->GetEntriesFast());
    nevt_tot += nev;
    cout <<"The current file has " << nev << " entries : "<< endl << *itfiles << endl;
    //cout<<"Running on: "<<min(nev,nevt_max)<<" events"<<endl;

    //starting loop over events, stops when reached end of file or nevt_max
    for(int i = 0; i < nev && i_tot < nevt_max; ++i , ++i_tot){

      //printing the % of events done every 10k evts
      if( ((i_tot+1) % 10000) == 0) cout <<int(double(i_tot+1)/1000)<<"k done"<<endl;

      //if(i>min(nev,nevt_max)) break;

      //Filling the variables defined setting branches
      tree->GetEntry(i);

    
      //Selection of good BX for data && MC
      //if(!isMC && !goodBX(evtId->Run,evtId->Bunch)) continue;
      
      if(!isMC)
        if(irun>0)
          if(irun!=(signed)evtId->Run)
	  continue;
      
      /*vector< bool > nPTr_inacc;
      for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
        int n = 0;
        if(iTracking==0) n = getnPrimaryTracks(tracks,vertex,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
        if(iTracking==1) n = getnPrimaryTracks(tracks,vertex,bs,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
        
        if(n>=1) nPTr_inacc.push_back(true);   
        else     nPTr_inacc.push_back(false);  
      }*/
      
      //----------------------------------------------------------------------
      //------------------- CHECKING #EVENTS AFTER EACH SEL ------------------
      //----------------------------------------------------------------------
      
      ++nNone;
   /* if(passVtxQual(*MITEvtSel,E)) ++nVtxQual;
      if(passL1(E,*L1Trig) &&
         passVtxQual(*MITEvtSel,E)) ++nL1;
      if(passHF(*MITEvtSel) &&
         passL1(E,*L1Trig)  &&
         passVtxQual(*MITEvtSel,E)) ++nHF;
      if(passVtx(vertexToCut) &&
         passHF(*MITEvtSel) &&
         passL1(E,*L1Trig)  &&
         passVtxQual(*MITEvtSel,E)) ++nVtx;*/
          
      //----------------------------------------------------------------------
      //----------------------- USED TO SUBSTRACT SD -------------------------
      //----------------------------------------------------------------------
      
      
      if(isEvtGood(E,*L1Trig ,*HLTrig , *MITEvtSel , vertexToCut)){
        for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
          //if(! nPTr_inacc.at(acc)) continue;
	
	if(acc==42 && vertex->size()!=1) continue;
	
          //Making a GenMulti for RECO
          vector<MyTracks> trcoll;
	if(iTracking==0) trcoll = getPrimaryTracks(*tracks,vertex,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
	if(iTracking==1) trcoll = getPrimaryTracks(*tracks,vertex,bs,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
          for(vector<MyTracks>::iterator it_tr = trcoll.begin() ; it_tr != trcoll.end() ; ++it_tr){
	  if(acc==41 && it_tr->nhit<5) continue;
            if(isMC) gmp_evtSel_reco.at(acc)->fill(*genKin , it_tr->Part , 1. , MCtype);
	  mp_evtSel_INC_reco.at(acc)->fill(it_tr->Part);
          }
          if(isMC) gmp_evtSel_reco.at(acc)->nextEvent(*genKin , MCtype);
          mp_evtSel_INC_reco.at(acc)->nextEvent();
	
	if(isMC){
            for(vector<MyGenPart>::iterator p=genPart->begin() ; p!=genPart->end() ; p++ )
              if ( isGenPartGood(*p) && isInAcceptance(p->Part,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4)) )//--->RECO acc cuts !!
                gmp_evtSel.at(acc)->fill(*genKin , p->Part , 1. , MCtype);
            gmp_evtSel.at(acc)->nextEvent(*genKin , MCtype);
          }
        
        }
      }
      
      //Skipping the SD events starting from here
      if(isMC)
        if(isSD(*genKin , MCtype) ) continue;
          
      //----------------------------------------------------------------------
      //----------------------- DOING THE SELECTIONS -------------------------
      //-----------------------          GEN         -------------------------
      //----------------------------------------------------------------------
      
      for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
        //if(! nPTr_inacc.at(acc)) continue;
        
        if(isMC){
          for(vector<MyGenPart>::iterator p=genPart->begin() ; p!=genPart->end() ; p++ )
            if ( isGenPartGood(*p) && isInAcceptance(p->Part,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)) )
              mp_etaCut_noSel_NSD_gen.at(acc)->fill(p->Part);
          mp_etaCut_noSel_NSD_gen.at(acc)->nextEvent();
        }
      
        if(isMC) evtSel_before.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
      /*
        //L1 CUT
        if(isMC) L1_before.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        if(passL1(E,*L1Trig))
          if(isMC) L1_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
      
        //HF CUT
        if(isMC) hf_before.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        if(passHF(*MITEvtSel))
          if(isMC) hf_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
      
        //vtxqual CUT
        if(isMC) vtxqual_before.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        if(passVtxQual(*MITEvtSel,E))
          if(isMC) vtxqual_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
      
        //Taking events with only 1 good vertex
        if(isMC) vtx_before.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        if(getBestVertex(vertexToCut)>-1)
          if(isMC) vtx_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
      */
        //if(!isEvtGood(E,*L1Trig , *MITEvtSel) || getBestVertex(vertexToCut)==-1) continue;
        if(acc==42){
          if(isEvtGood(E,*L1Trig , *HLTrig , *MITEvtSel , vertexToCut) && (vertex->size()==1))
            if(isMC) evtSel_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        }
        else{
          if(isEvtGood(E,*L1Trig , *HLTrig , *MITEvtSel , vertexToCut))
            if(isMC) evtSel_after.at(acc)->Fill(getnPrimaryGenPart(genPart,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4)));
        }
      }
      
      if(!isEvtGood(E,*L1Trig ,*HLTrig , *MITEvtSel , vertexToCut)) continue;
      
      //----------------------------------------------------------------------
      //-----------------------         GEN          -------------------------
      //----------------------------------------------------------------------
      
      
      if(isMC){
        for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
          if(acc==42 && vertex->size()!=1) continue;
          //if(! nPTr_inacc.at(acc)) continue;
	
          for(vector<MyGenPart>::iterator p=genPart->begin() ; p!=genPart->end() ; p++ ){
            if ( isGenPartGood(*p) && isInAcceptance(p->Part,accMap[acc].at(0),accMap[acc].at(1),accMap[acc].at(4))){
	    gmp_etaCut.at(acc)->fill(*genKin,p->Part , 1. , MCtype);
	    mtxp_evtSel.at(acc)->fillGen(p->Part);
	  }
          }
          gmp_etaCut.at(acc)->nextEvent(*genKin , MCtype);
        }
      }
      
      //----------------------------------------------------------------------
      //-----------------------         RECO         -------------------------
      //----------------------------------------------------------------------
      if(debug) cout<<"Starting the vertex collections ..."<<endl;
      int vtxId = getBestVertex(vertex);
      
      //------------- FILLING MULTI && MATRIX----------------------- 
      if(debug) cout<<"Starting to fill RECO ..."<<endl;
      
      vector<MyVertex>::iterator goodVtx = vertex->end();
      for(vector<MyVertex>::iterator it_vtx = vertex->begin();it_vtx != vertex->end();++it_vtx)
        if(vtxId==it_vtx->id)
          goodVtx = it_vtx;
      vtxp->fill(*goodVtx);
        
      //-----------------------------
      //FILLING THE MATRIX && MULTI
      
      for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
        if(acc==42 && vertex->size()!=1) continue;
        //if(! nPTr_inacc.at(acc)) continue;
        
        vector<MyTracks> trcoll;
        if(iTracking==0) trcoll = getPrimaryTracks(*tracks,vertex,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
        if(iTracking==1) trcoll = getPrimaryTracks(*tracks,vertex,bs,accMap[acc].at(2),accMap[acc].at(3),accMap[acc].at(4));
        for(vector<MyTracks>::iterator it_tr = trcoll.begin() ; it_tr != trcoll.end() ; ++it_tr){
	if(acc==41 && it_tr->nhit<5) continue;
	if(isMC)
	  mtxp_evtSel.at(acc)->fillReco(it_tr->Part);
	mp_evtSel_PV.at(acc)->fill(it_tr->Part);
	trp.at(acc)->fill(trcoll,*vertex,vtxId,bs);
        }
        if(isMC) mtxp_evtSel.at(acc)->nextEvent();
        mp_evtSel_PV.at(acc)->nextEvent();
      
      }
      
      
    }//end of loop over events

    //Closing current files
    file->Close();

  }//end of loop over files


  if(debug) cout<<"Starting to write to file ..."<<endl;
  
  //output file
  TFile* file2=new TFile(fileManager(2,type,E,iTracking,0,0,filename),"RECREATE");
  file2->cd();
  /*
  cout<<"mp : "<<mp_PV_gTr_oVtx->nbEvts<<endl;
  cout<<"mtxp : "<<mtxp_etaGenCut_L1_hf_VtxSel_PV_gTr_oVtx->nbEvts<<endl;
  cout<<"gmp NSD : "<<gmp_etaCut->mp_NSD->nbEvts<<endl<<endl;
  cout<<"gmp : "<<gmp_evtSel->mp_NSD->nbEvts<<endl;
  cout<<"gmp RECO : "<<gmp_evtSel_reco->mp_NSD->nbEvts<<endl;
  cout<<"mp INC RECO : "<<mp_evtSel_INC_reco->nbEvts<<endl;
  */
  
  for(int acc = 0 ; acc < (signed)accMap.size() ; ++acc){
    //TString dir = ""; 
    ostringstream dir("");
    dir << "ptGen" << accMap.at(acc).at(0) << "_etaGen" << accMap.at(acc).at(1) 
        << "_ptReco" << accMap.at(acc).at(2) << "_etaReco" << accMap.at(acc).at(3);
    if(accMap.at(acc).at(4)==-1)
      dir << "_chargemin";
    else if(accMap.at(acc).at(4)==1)
      dir << "_chargeplus";
     
    /*tmp<< accMap.[acc].at(1);
    dir+=tmp.str()+;tmp.str("");
    tmp<< accMap.[acc].at(2);
    dir+=tmp.str()+"_etaReco";tmp.str("");
    tmp<< accMap.[acc].at(3);*/
    gDirectory->mkdir(dir.str().c_str());
    gDirectory->cd(dir.str().c_str());

    bool scale = false;
    if(isMC){
      gmp_etaCut.at(acc)->write(scale);
      mtxp_evtSel.at(acc)->write(scale);
      mp_etaCut_noSel_NSD_gen.at(acc)->write(scale);
      gmp_evtSel.at(acc)->write(scale);
    
      gmp_evtSel_reco.at(acc)->write(scale);
    }
  
    mp_evtSel_INC_reco.at(acc)->write(scale);
    mp_evtSel_PV.at(acc)->write(scale);
    trp.at(acc)->write();
    vtxp->write();
  
    TH1F* eff_L1 = (TH1F*) L1_after.at(acc)->Clone(st("eff_L1",acc));
    eff_L1->Divide(eff_L1,L1_before.at(acc),1,1,"B");
    L1_before.at(acc)->Write();
    L1_after.at(acc)->Write();
    eff_L1->Write();
  
    TH1F* eff_hf = (TH1F*) hf_after.at(acc)->Clone(st("eff_hf",acc));
    eff_hf->Divide(eff_hf,hf_before.at(acc),1,1,"B");
    hf_before.at(acc)->Write();
    hf_after.at(acc)->Write();
    eff_hf->Write();
  
    TH1F* eff_vtxqual = (TH1F*) vtxqual_after.at(acc)->Clone(st("eff_vtxqual",acc));
    eff_vtxqual->Divide(eff_vtxqual,vtxqual_before.at(acc),1,1,"B");
    vtxqual_before.at(acc)->Write();
    vtxqual_after.at(acc)->Write();
    eff_vtxqual->Write();
  
    TH1F* eff_vtx = (TH1F*) vtx_after.at(acc)->Clone(st("eff_vtx",acc));
    eff_vtx->Divide(eff_vtx,vtx_before.at(acc),1,1,"B");
    vtx_before.at(acc)->Write();
    vtx_after.at(acc)->Write();
    eff_vtx->Write();
  
    TH1F* eff_evtSel = (TH1F*) evtSel_after.at(acc)->Clone(st("eff_evtSel",acc));
    eff_evtSel->Divide(eff_evtSel,evtSel_before.at(acc),1,1,"B");
    evtSel_before.at(acc)->Write();
    evtSel_after.at(acc)->Write();
    eff_evtSel->Write();
    
    gDirectory->cd("../");

  
  }
  
  TH1F* nEvts = new TH1F("nEvts","nEvts",5,0,5);
  nEvts->GetXaxis()->SetBinLabel(1,"NONE");
  nEvts->SetBinContent(1,nNone);
  nEvts->GetXaxis()->SetBinLabel(2,"+ VtxQual");
  nEvts->SetBinContent(2,nVtxQual);
  nEvts->GetXaxis()->SetBinLabel(3,"+ L1");
  nEvts->SetBinContent(3,nL1);
  nEvts->GetXaxis()->SetBinLabel(4,"+ HF");
  nEvts->SetBinContent(4,nHF);
  nEvts->GetXaxis()->SetBinLabel(5,"+ Vtx");
  nEvts->SetBinContent(5,nVtx);
  
  nEvts->Write();
  
  cout<<"---------- PRINTING #EVENTS ------------"<<endl;
  cout<<"No evt Sel : "<<nNone<<endl;
  cout<<"+ VtxQual  : "<<nVtxQual<<endl;
  cout<<"+ L1       : "<<nL1<<endl;
  cout<<"+ HF       : "<<nHF<<endl;
  cout<<"+ Vtx      : "<<nVtx<<endl;
  
  file2->Close();
}
Example #25
0
void Create_input::Loop()
{
	vector<pair<TFile *, double> > input;

        input.push_back(make_pair(new TFile("out_data.root","read"), 1.0)); //0
        input.push_back(make_pair(new TFile("out_wz.root","read"), 0.010324)); //0
        input.push_back(make_pair(new TFile("out_zz.root","read"), 0.00053296)); //0
        input.push_back(make_pair(new TFile("out_hww.root","read"), 0.000853667)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0
        input.push_back(make_pair(new TFile("out_htt125.root","read"), 0.0035901)); //0

	TFile* g1=new TFile ("input_emt_low.root","recreate");
	
	float bins[] = { 20,30,39.95,50,60,70,80,100,130,300};
        int  binnum = sizeof(bins)/sizeof(Float_t) - 1;

	TH1F *mvis_data=new TH1F ("data_obs","mvis",binnum,bins);
        TH1F *mvis_wz=new TH1F ("wz","mvis",binnum,bins);
        TH1F *mvis_zz=new TH1F ("zz","mvis",binnum,bins);
        TH1F *mvis_hww=new TH1F ("WH_hww125","mvis",binnum,bins);
        TH1F *mvis_htt110=new TH1F ("WH110","mvis",binnum,bins);
        TH1F *mvis_htt115=new TH1F ("WH115","mvis",binnum,bins);
        TH1F *mvis_htt120=new TH1F ("WH120","mvis",binnum,bins);
        TH1F *mvis_htt125=new TH1F ("WH125","mvis",binnum,bins);
        TH1F *mvis_htt130=new TH1F ("WH130","mvis",binnum,bins);
        TH1F *mvis_htt135=new TH1F ("WH135","mvis",binnum,bins);
        TH1F *mvis_htt140=new TH1F ("WH140","mvis",binnum,bins);
        TH1F *mvis_htt145=new TH1F ("WH145","mvis",binnum,bins);
        TH1F *mvis_fakes=new TH1F ("fakes","mvis",binnum,bins);

        TH1F *mvis[13]={mvis_data,mvis_wz,mvis_zz,mvis_hww,mvis_htt110,mvis_htt115,mvis_htt120,mvis_htt125,mvis_htt130,mvis_htt135,mvis_htt140,mvis_htt145,mvis_fakes};

	for (unsigned int p = 0; p < input.size(); ++p) {
		string infile(input[p].first->GetName());
		cout << "file " << infile << endl;
		TTree *thetree = (TTree*)input[p].first->Get("BG_Tree");
		Init(thetree);

		if (thetree == 0) return;

		Long64_t nentries = thetree->GetEntriesFast();
		cout<<nentries<<"nentries"<<endl;
		Long64_t nbytes = 0, nb = 0;

		// event loop
		for (Long64_t jentry=0; jentry<nentries;jentry++) {

			if (jentry % 100000 == 0 ) cout << "entry " << jentry << endl;
			Long64_t ientry = LoadTree(jentry);
			if (ientry < 0) break;
               		nb = thetree->GetEntry(jentry);   nbytes += nb;
			if (Cut(ientry) < 0) continue;
			//if (LT_>130) continue;

			if (p!=0){//MC
				mvis[p]->Fill(HMass_,weight_*input[p].second);
			}
			else if (p==0 && subChannel_==1)//Data
				mvis[p]->Fill(HMass_,weight_);
			else if (p==0 && subChannel_!=1){//Reducible
				if (subChannel_==2){
					mvis[12]->Fill(HMass_,-1.0*weight_);
				}
				else if (subChannel_==3 or subChannel_==4){
                                        mvis[12]->Fill(HMass_,1.0*weight_);
                                }
			}
		}
	}

	gStyle->SetOptStat(0);

	mvis[1]->SetFillColor(kPink-8);
	mvis[2]->SetFillColor(kGreen-6);
	mvis[3]->SetFillColor(kBlue+9);
	mvis[4]->SetFillColor(kOrange-4);
	mvis[12]->SetFillColor(kCyan-3);
	mvis[0]->SetMarkerStyle(20);
	mvis[0]->SetTitle(0);
	mvis[0]->GetXaxis()->SetTitle("m_{vis} [GeV]");
        mvis[0]->GetYaxis()->SetTitle("Events");
	TLegend *leg = new TLegend (0.60,0.70,0.88,0.85);
	leg->SetFillColor(0);
        leg->AddEntry(mvis[0],"data","pe");
	leg->AddEntry(mvis[4],"H tau tau","f");
	leg->AddEntry(mvis[3],"H WW","f");
	leg->AddEntry(mvis[1],"WZ","f");
	leg->AddEntry(mvis[2],"ZZ","f");
	leg->AddEntry(mvis[12],"fakes","f");
	TCanvas *c= new TCanvas("c1","A Simple Graph Example",200,10,600,500);
	c->cd();
	THStack* sta = new THStack("sta","sta");
	sta->Add(mvis[12]);
	sta->Add(mvis[2]);
	sta->Add(mvis[1]);
	sta->Add(mvis[3]);
	sta->Add(mvis[4]);
	mvis[0]->Draw("E");
	sta->Draw("same");
	mvis[0]->Draw("Esame");
	leg->Draw("same");
	g1->cd();
	TDirectory* dir1=g1->mkdir("emtCatLow");
	dir1->cd();
	for (int i=0; i<13; ++i){
		mvis[i]->Write();
	}
}
Example #26
0
File: scan.C Project: aminnj/WZ
// float scan(unsigned int njetsCut=0, int btagCut=9999, TString tag="", float manualScale=-1.0){
int scan(unsigned int njetsLow=0, unsigned int njetsHigh=9999, int btagCut=9999, int metLow=0, int metHigh=9999, int htLow=0, int htHigh=9999, TString tag=""){
    //njetsLow, njetsHigh, btagCut, metLow, metHigh, htLow, htHigh, tag, manualScale
    //

    // TH1F* h1D_dummy_data = new TH1F("dummy", "dummyhisto", 10, 0, 10); 

    TH1F* h1D_njets_data = new TH1F("njets", "", 15, 0, 15); 
    TH1F* h1D_ht_data = new TH1F("ht", "", 20, 0, 600); 
    TH1F* h1D_met_data = new TH1F("met", "", 20, 0, 300); 
    TH1F* h1D_mt_data = new TH1F("mt", "", 20, 0, 400); 
    TH1F* h1D_mtW_data = new TH1F("mtW", "", 40, 0, 200); 
    TH1F* h1D_zmass_data = new TH1F("zmass", "", 42, 70, 112); 
    TH1F* h1D_lepeta_data = new TH1F("lepeta", "", 50, -3.0, 3.0); 
    TH1F* h1D_leppt_data = new TH1F("leppt", "", 50, 0, 150); 
    TH1F* h1D_Wleppt_data = new TH1F("Wleppt", "", 30, 0, 150); 

    TH1F* h1D_nbtags_data = new TH1F("nbtags", "", 15, 0, 15); 
    TH1F* h1D_btagval_data = new TH1F("btagval", "", 20, 0, 1); 
    TH1F* h1D_ptZ_data = new TH1F("ptZ", "", 25, 0, 400);
    TH1F* h1D_st_data = new TH1F("st", "", 25, 100, 800);
    TH1F* h1D_minRLeadingJet_data = new TH1F("minRLeadingJet", "",10,0,5);
    TH1F* h1D_ptj1_data = new TH1F("ptj1", "", 25, 0, 300);
    TH1F* h1D_ptj2_data = new TH1F("ptj2", "", 25, 0, 300);
    TH1F* h1D_massZj1_data = new TH1F("massZj1", "", 25, 100, 600);
    TH1F* h1D_massZj2_data = new TH1F("massZj2", "", 25, 100, 600);
    TH1F* h1D_ptjj_data = new TH1F("ptjj", "", 25, 0, 400);
    TH1F* h1D_massjj_data = new TH1F("massjj", "", 25, 0, 600);

    TH1F* h1D_mtWeemu_data = new TH1F("mtWeem", "", 40, 0, 200); 
    TH1F* h1D_mtWmumue_data = new TH1F("mtWmme", "", 40, 0, 200); 
    TH1F* h1D_mtWeee_data = new TH1F("mtWeee", "", 40, 0, 200); 
    TH1F* h1D_mtWmumumu_data = new TH1F("mtWmmm", "", 40, 0, 200); 
    TH1F* h1D_lepetae_data = new TH1F("lepetae", "", 50, -3.0, 3.0); 
    TH1F* h1D_lepetamu_data = new TH1F("lepetamu", "", 50, -3.0, 3.0); 

    float luminosity = 19.407;
    float ptCut = 20; // threshold for "high-pT" in AN
    float zmassCut = 15; // line 212 of AN
    float btagDiscriminant = 0.679; // line 230 of AN

    map<int, vector<int> > runLumi;
    cout << ">>> tag is " << tag << endl;
    cout << ">>> excluding events with #btaggedjets>= " << btagCut << endl;
    cout << ">>> considering events with njets in [" << njetsLow << "," << njetsHigh << "]" << endl;
    cout << ">>> considering events with met in [" << metLow << "," << metHigh << "]" << endl;
    cout << ">>> considering events with ht in [" << htLow << "," << htHigh << "]" << endl;
    // cout << ">>> manualScale is " << manualScale << endl;
    // DATADATA
    {
        initCounter();

        clear_seen();

        TChain *ch = new TChain("tree");

        ch->Add("/home/users/namin/sandbox/condorTest/output/baby_2012ABCD.root");

        int nEventsTotal = ch->GetEntries();
        int nEventsSoFar = 0;
        int nGoodEvents = 0;
        float scale = 1.0;

        TFile *currentFile = 0;
        TObjArray *listOfFiles = ch->GetListOfFiles();
        TIter fileIter(listOfFiles);

        // File Loop
        while ( (currentFile = (TFile*)fileIter.Next()) ) { 
            TFile *file = new TFile( currentFile->GetTitle() );
            TTree *tree = (TTree*)file->Get("tree");
            cms2.Init(tree);
            // Set Good Run List
            if(evt_isRealData()) set_goodrun_file("final_19p49fb_cms2.txt");

            TString filename(currentFile->GetTitle());

            // Loop over Events in current file
            unsigned int nEventsTree = tree->GetEntriesFast();
            for( unsigned int event = 0; event < nEventsTree; ++event) {

                // if(event > 30000) break;

                // Get Event Content
                cms2.GetEntry(event);
                nEventsSoFar++;

                // Progress
                CMS2::progress( nEventsSoFar, nEventsTotal );

                // Select Good Runs
                if( evt_isRealData() && !goodrun( evt_run(), evt_lumiBlock() ) ) continue;

                if(evt_isRealData()){
                    DorkyEventIdentifier id = { evt_run(), evt_event(), evt_lumiBlock() };
                    if ( is_duplicate(id) ){
                        continue;
                    }
                }

                std::vector<LorentzVector> goodEls;
                std::vector<LorentzVector> goodMus;
                std::vector<JetStruct> maybeGoodJets;
                std::vector<JetStruct> goodJets;
                std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
                std::map<int, int> goodToP4MapMu;

                pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
                float met = p.first;
                float metPhi = p.second;
                // float met = pfmet_type1cor();
                // float metPhi = metphi();


                if(met < metLow || met > metHigh) continue;

                // make electron quality cuts
                for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                    if(!looseEl().at(iEl)) continue;
                    if(els_p4().at(iEl).pt() < ptCut) continue;
                    if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                    goodToP4MapEl[goodEls.size()] = iEl;
                    goodEls.push_back(els_p4().at(iEl));


                }
                // mirror for muons
                for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                    if(!looseMu().at(iMu)) continue;
                    if(mus_p4().at(iMu).pt() < ptCut) continue;
                    if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                    goodToP4MapMu[goodMus.size()] = iMu;
                    goodMus.push_back(mus_p4().at(iMu));

                }

                // require that we have 3 good leptons
                if(goodMus.size() + goodEls.size() != 3) continue;

                // select good jets
                for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                    if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                    if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                    if (!passesLoosePFJetID().at(iJet)) continue;

                    JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                    myJet.jet = pfjets_p4().at(iJet);
                    myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                    myJet.idx = iJet;

                    maybeGoodJets.push_back(myJet);
                }

                vector<int> closestJetsMu; 
                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsMu.push_back(iClosestJet);
                    }
                }
                vector<int> closestJetsEl; 
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsEl.push_back(iClosestJet);
                    }
                }
                float ht = 0;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    bool tooClose = false;
                    for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                        if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                    }
                    for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                        if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                    }
                    if(tooClose) continue;

                    goodJets.push_back(maybeGoodJets.at(iJet));
                    ht += maybeGoodJets.at(iJet).pt;
                }


                if(ht < htLow || ht > htHigh) continue;



                vector<int> pair = findZPair(goodEls, goodMus);
                vector<LorentzVector> leps;
                float mtW = 0.0, mass = 0.0;
                if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                        pair[3] != -1 && pair[4] != -1 ) {
                    if(pair[0] == 0) { // el
                        mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                        leps.push_back(goodEls.at(pair[1]));
                        leps.push_back(goodEls.at(pair[2]));
                    } else { // mu
                        mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                        leps.push_back(goodMus.at(pair[1]));
                        leps.push_back(goodMus.at(pair[2]));
                    }

                    if(pair[3] == 0) { // W lep is el
                        if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                        leps.push_back(goodEls.at(pair[4]));

                        mtW = MT(goodEls.at(pair[4]), met, metPhi);

                    } else { // W lep is mu
                        if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                        leps.push_back(goodMus.at(pair[4]));

                        mtW = MT(goodMus.at(pair[4]), met, metPhi);

                    }
                } else {
                    cout << "shouldn't end up with pair[i] == -1" << endl;
                }


                // XXX
                if(abs(mass - 91.2) > zmassCut) continue;
                if(goodJets.size() < njetsLow ||
                        goodJets.size() > njetsHigh ) continue;


                int nbtags = 0;
                float minRLeadingJet = 9999.0;
                std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
                for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                    float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                    if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                    // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                    float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                    fill(h1D_btagval_data, btagval, scale);
                    // fill(h1D_btagval_data, btagval, scale);

                    if(btagval > btagDiscriminant) {
                        nbtags++;
                    }
                }

                if(nbtags >= btagCut) continue; // FIXME


                // fill(h1D_dummy_data, 5.0,scale);

                // We are now in the region of interest


                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    fill(h1D_leppt_data,goodMus.at(iMu).pt(), scale);
                    fill(h1D_lepeta_data, goodMus.at(iMu).eta(), scale);
                    fill(h1D_lepetamu_data, goodMus.at(iMu).eta(), scale);
                }
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    fill(h1D_leppt_data,goodEls.at(iEl).pt(), scale);
                    fill(h1D_lepeta_data, goodEls.at(iEl).eta(), scale);
                    fill(h1D_lepetae_data, goodEls.at(iEl).eta(), scale);
                }




                // FIXME
                if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                    mtW = MT(goodEls[0], met, metPhi);
                    fill(h1D_mtWmumue_data, mtW, scale);


                } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                    mtW = MT(goodMus[0], met, metPhi);
                    fill(h1D_mtWeemu_data, mtW, scale);


                } else { 
                    if(goodMus.size() == 3) { //mumumu
                        fill(h1D_mtWmumumu_data, mtW, scale);
                    } else { // eee
                        fill(h1D_mtWeee_data, mtW, scale);
                    }
                }


                double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
                float ptZ = (leps[0]+leps[1]).pt();
                float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

                fill(h1D_ptZ_data, ptZ, scale);
                fill(h1D_Wleppt_data,leps[2].pt(), scale);
                if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_data, minRLeadingJet, scale);
                fill(h1D_st_data, st, scale);
                fill(h1D_mt_data,mt, scale);
                fill(h1D_mtW_data, mtW, scale);
                fill(h1D_zmass_data,mass, scale); 
                fill(h1D_njets_data,goodJets.size(), scale);
                fill(h1D_ht_data,ht, scale);
                fill(h1D_met_data,met, scale);
                fill(h1D_nbtags_data, nbtags, scale);

                nGoodEvents++;
                addToCounter(filename, scale);

                if(goodJets.size() < 1) continue;

                float ptj1 = goodJets[0].pt;
                float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptj1_data, ptj1, scale);
                fill(h1D_massZj1_data, massZj1, scale);

                if(goodJets.size() < 2) continue;

                float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
                float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
                float ptj2 = goodJets[1].pt;
                float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptjj_data, ptjj, scale);
                fill(h1D_massjj_data, massjj, scale);
                fill(h1D_ptj2_data, ptj2, scale);
                fill(h1D_massZj2_data, massZj2, scale);



            }//event loop

        }//file loop


        std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
        std::cout << "ASDF DATA " << tag << " " << nGoodEvents << std::endl;

        // std::cout << "This dataset (A+B+C+D) has 19.4 fb^-1 of data" << std::endl;
        // std::cout << " nGoodEvents scaled to 1/fb: " << nGoodEvents*(1.0/luminosity) << std::endl;
        // std::cout << " nGoodEvents scaled to 19.4/fb: " << nGoodEvents*(19.4/luminosity) << std::endl;

        printCounter();


    } // DATADATA

    // MCMC
    TChain *ch = new TChain("tree");

    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WZ.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_ZZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_DYJetsToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TBZToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTW.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_VVV.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WJetsToLNu.root");

    int nEventsTotal = ch->GetEntries();
    int nEventsSoFar = 0;
    int nGoodEvents = 0;
    float nGoodEventsWeighted = 0;

    TFile *currentFile = 0;
    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);


    // vector<TH1F*> h1D_dummy_vec;

    vector<TH1F*> h1D_njets_vec;
    vector<TH1F*> h1D_ht_vec;
    vector<TH1F*> h1D_met_vec;
    vector<TH1F*> h1D_mt_vec;
    vector<TH1F*> h1D_mtW_vec;
    vector<TH1F*> h1D_zmass_vec;
    vector<TH1F*> h1D_lepeta_vec;
    vector<TH1F*> h1D_leppt_vec;
    vector<TH1F*> h1D_Wleppt_vec;

    // btag+jet stuff
    vector<TH1F*> h1D_nbtags_vec;
    vector<TH1F*> h1D_btagval_vec;
    vector<TH1F*> h1D_ptZ_vec;
    vector<TH1F*> h1D_st_vec;
    vector<TH1F*> h1D_minRLeadingJet_vec;
    vector<TH1F*> h1D_ptj1_vec;
    vector<TH1F*> h1D_ptj2_vec;
    vector<TH1F*> h1D_massZj1_vec;
    vector<TH1F*> h1D_massZj2_vec;
    vector<TH1F*> h1D_ptjj_vec;
    vector<TH1F*> h1D_massjj_vec;

    // w mt debugging
    vector<TH1F*> h1D_mtWeemu_vec;
    vector<TH1F*> h1D_mtWmumue_vec;
    vector<TH1F*> h1D_mtWeee_vec;
    vector<TH1F*> h1D_mtWmumumu_vec;
    vector<TH1F*> h1D_lepetae_vec;
    vector<TH1F*> h1D_lepetamu_vec;

    vector<TH1F*> h1D_test_mete_vec;
    vector<TH1F*> h1D_test_dphie_vec;
    vector<TH1F*> h1D_test_pte_vec;

    vector<TH1F*> h1D_test_metm_vec;
    vector<TH1F*> h1D_test_dphim_vec;
    vector<TH1F*> h1D_test_ptm_vec;

    vector<TH1F*> h1D_test_dphinu_vec;

    vector<TH1F*> h1D_gen_dR_vec;
    vector<TH1F*> h1D_gen_id_vec;

    vector<TH1F*> h1D_metphie_vec;
    vector<TH1F*> h1D_metphim_vec;


    initCounter();
    TH1D* error = new TH1D("error","",1,0,1);
    // error->Sumw2();

    // File Loop
    int iFile = 0;
    while ( (currentFile = (TFile*)fileIter.Next()) ) { 

        // Get File Content
        TFile *file = new TFile( currentFile->GetTitle() );
        TTree *tree = (TTree*)file->Get("tree");
        cms2.Init(tree);

        iFile++; 
        TString filename(currentFile->GetTitle());


        // TH1F* h1D_dummy_file = new TH1F("dummy"+filename, "dummyhisto", 10, 0, 10); 

        TH1F* h1D_njets_file = new TH1F("njets"+filename, "Njets;;Entries", 15, 0, 15); 
        TH1F* h1D_ht_file = new TH1F("ht"+filename, "H_{T};GeV;Entries", 20, 0, 600); 
        TH1F* h1D_met_file = new TH1F("met"+filename, "#slash{E}_{T};GeV;Entries", 20, 0, 300); 
        TH1F* h1D_mt_file = new TH1F("mt"+filename, "M_{T};GeV;Entries", 20, 0, 400); 
        TH1F* h1D_mtW_file = new TH1F("mtW"+filename, "W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_zmass_file = new TH1F("zmass"+filename, "Z Mass;GeV;Entries", 42, 70, 112); 
        TH1F* h1D_lepeta_file = new TH1F("lepeta"+filename, "lepton #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_leppt_file = new TH1F("leppt"+filename, "lepton p_{T};p_{T} [GeV];Entries", 50, 0, 150); 
        TH1F* h1D_Wleppt_file = new TH1F("Wleppt"+filename, "W lepton p_{T};p_{T} [GeV];Entries", 30, 0, 150); 

        TH1F* h1D_nbtags_file = new TH1F("nbtags"+filename, "N btagged jets;;Entries", 15, 0, 15); 
        TH1F* h1D_btagval_file = new TH1F("btagval"+filename, "Value of csv bjet tag;;Entries", 20, 0, 1); 
        TH1F* h1D_ptZ_file = new TH1F("ptZ"+filename, "Z p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_st_file = new TH1F("st"+filename, "S_{T}=H_{T}+#Sigma p_{T,leps}+#slash{E}_{T};S_{T} [GeV];Entries", 25, 100, 800);
        TH1F* h1D_minRLeadingJet_file = new TH1F("minRLeadingJet"+filename, "Minimum dR between jet 1 and another jet",10,0,5);
        TH1F* h1D_ptj1_file = new TH1F("ptj1"+filename, "j1 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_ptj2_file = new TH1F("ptj2"+filename, "j2 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_massZj1_file = new TH1F("massZj1"+filename, "Zj1 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_massZj2_file = new TH1F("massZj2"+filename, "Zj2 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_ptjj_file = new TH1F("ptjj"+filename, "j1j2 p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_massjj_file = new TH1F("massjj"+filename, "j1j2 mass;[GeV];Entries", 25, 0, 600);

        TH1F* h1D_mtWeemu_file = new TH1F("mtWeem"+filename, "ee#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumue_file = new TH1F("mtWmme"+filename, "#mu#mue W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWeee_file = new TH1F("mtWeee"+filename, "eee W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumumu_file = new TH1F("mtWmmm"+filename, "#mu#mu#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_lepetae_file = new TH1F("lepetae"+filename, "e #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_lepetamu_file = new TH1F("lepetamu"+filename, "#mu #eta;#eta;Entries", 50, -3.0, 3.0); 

        TH1F* h1D_test_mete_file = new TH1F("testmete"+filename, "met for e;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphie_file = new TH1F("testphie"+filename, "dphi(met,e);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_pte_file = new TH1F("testpte"+filename, "pt for e;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_metm_file = new TH1F("testmetm"+filename, "met for mu;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphim_file = new TH1F("testphim"+filename, "dphi(met,mu);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_ptm_file = new TH1F("testptm"+filename, "pt for mu;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_dphinu_file = new TH1F("testphinu"+filename, "dphi(W lep,gen nu);;Entries", 40, 0, M_PI+0.1); 

        TH1F* h1D_gen_dR_file = new TH1F("gendr"+filename, "#DeltaR between reco W lepton and closest gen lepton", 60, 0, 0.4); 
        TH1F* h1D_gen_id_file = new TH1F("genid"+filename, "abs(mother id) for gen particle matched to reco W lept;;Entries", 40, 0, 40); 

        TH1F* h1D_metphie_file = new TH1F("metphie"+filename, "metphi for e from W;;Entries", 30, -3.2, 3.2); 
        TH1F* h1D_metphim_file = new TH1F("metphim"+filename, "metphi for m from W;;Entries", 30, -3.2, 3.2); 

        h1D_njets_vec.push_back(h1D_njets_file); 
        h1D_ht_vec.push_back(h1D_ht_file); 
        h1D_met_vec.push_back(h1D_met_file); 
        h1D_mt_vec.push_back(h1D_mt_file); 
        h1D_mtW_vec.push_back(h1D_mtW_file); 
        h1D_zmass_vec.push_back(h1D_zmass_file); 
        h1D_lepeta_vec.push_back(h1D_lepeta_file);
        h1D_leppt_vec.push_back(h1D_leppt_file); 
        h1D_Wleppt_vec.push_back(h1D_Wleppt_file); 

        h1D_nbtags_vec.push_back(h1D_nbtags_file);
        h1D_btagval_vec.push_back(h1D_btagval_file);
        h1D_ptZ_vec.push_back(h1D_ptZ_file);
        h1D_st_vec.push_back(h1D_st_file);
        h1D_minRLeadingJet_vec.push_back(h1D_minRLeadingJet_file);
        h1D_ptj1_vec.push_back(h1D_ptj1_file);
        h1D_ptj2_vec.push_back(h1D_ptj2_file);
        h1D_massZj1_vec.push_back(h1D_massZj1_file);
        h1D_massZj2_vec.push_back(h1D_massZj2_file);
        h1D_ptjj_vec.push_back(h1D_ptjj_file);
        h1D_massjj_vec.push_back(h1D_massjj_file);

        h1D_mtWeemu_vec.push_back(h1D_mtWeemu_file);
        h1D_mtWmumue_vec.push_back(h1D_mtWmumue_file);
        h1D_mtWeee_vec.push_back(h1D_mtWeee_file);
        h1D_mtWmumumu_vec.push_back(h1D_mtWmumumu_file);
        h1D_lepetae_vec.push_back(h1D_lepetae_file);
        h1D_lepetamu_vec.push_back(h1D_lepetamu_file);

        h1D_test_mete_vec.push_back(h1D_test_mete_file);
        h1D_test_dphie_vec.push_back(h1D_test_dphie_file);
        h1D_test_pte_vec.push_back(h1D_test_pte_file);

        h1D_test_metm_vec.push_back(h1D_test_metm_file);
        h1D_test_dphim_vec.push_back(h1D_test_dphim_file);
        h1D_test_ptm_vec.push_back(h1D_test_ptm_file);

        h1D_test_dphinu_vec.push_back(h1D_test_dphinu_file);

        h1D_gen_dR_vec.push_back(h1D_gen_dR_file);
        h1D_gen_id_vec.push_back(h1D_gen_id_file);

        h1D_metphie_vec.push_back(h1D_metphie_file);
        h1D_metphim_vec.push_back(h1D_metphim_file);

        // Loop over Events in current file
        unsigned int nEventsTree = tree->GetEntriesFast();
        for( unsigned int event = 0; event < nEventsTree; ++event) {

            // if(event > 30000) break;

            // Get Event Content
            cms2.GetEntry(event);
            nEventsSoFar++;

            if(event == 0) {
                std::cout << " evt_scale1fb(): " << evt_scale1fb() << " filename: " << filename << std::endl;
            }
            // Progress
            CMS2::progress( nEventsSoFar, nEventsTotal );

            std::vector<LorentzVector> goodEls;
            std::vector<LorentzVector> goodMus;
            std::vector<JetStruct> maybeGoodJets;
            std::vector<JetStruct> goodJets;
            std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
            std::map<int, int> goodToP4MapMu;

            float scale = evt_scale1fb()  * luminosity;

            pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
            float met = p.first;
            float metPhi = p.second;


            if(met < metLow || met > metHigh) continue;

            // make electron quality cuts
            for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                if(!looseEl().at(iEl)) continue;
                if(els_p4().at(iEl).pt() < ptCut) continue;
                if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                goodToP4MapEl[goodEls.size()] = iEl;
                goodEls.push_back(els_p4().at(iEl));


            }
            // mirror for muons
            for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                if(!looseMu().at(iMu)) continue;
                if(mus_p4().at(iMu).pt() < ptCut) continue;
                if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                goodToP4MapMu[goodMus.size()] = iMu;
                goodMus.push_back(mus_p4().at(iMu));

            }

            // require that we have 3 good leptons
            if(goodMus.size() + goodEls.size() != 3) continue;

            // select good jets
            for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                if (!passesLoosePFJetID().at(iJet)) continue;

                JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                myJet.idx = iJet;

                maybeGoodJets.push_back(myJet);
            }

            vector<int> closestJetsMu; 
            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsMu.push_back(iClosestJet);
                }
            }
            vector<int> closestJetsEl; 
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsEl.push_back(iClosestJet);
                }
            }
            float ht = 0;
            for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                bool tooClose = false;
                for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                    if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                }
                for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                    if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                }
                if(tooClose) continue;

                goodJets.push_back(maybeGoodJets.at(iJet));
                ht += maybeGoodJets.at(iJet).pt;
            }


            if(ht < htLow || ht > htHigh) continue;

            vector<int> pair = findZPair(goodEls, goodMus);
            vector<LorentzVector> leps;
            float mtW = 0.0, mass = 0.0;
            if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                    pair[3] != -1 && pair[4] != -1 ) {
                if(pair[0] == 0) { // el
                    mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                    leps.push_back(goodEls.at(pair[1]));
                    leps.push_back(goodEls.at(pair[2]));
                } else { // mu
                    mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                    leps.push_back(goodMus.at(pair[1]));
                    leps.push_back(goodMus.at(pair[2]));
                }

                if(pair[3] == 0) { // W lep is el
                    if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                    leps.push_back(goodEls.at(pair[4]));

                    mtW = MT(goodEls.at(pair[4]), met, metPhi);

                } else { // W lep is mu
                    if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                    leps.push_back(goodMus.at(pair[4]));

                    mtW = MT(goodMus.at(pair[4]), met, metPhi);

                }
            } else {
                cout << "shouldn't end up with pair[i] == -1" << endl;
            }


            // XXX
            if(abs(mass - 91.2) > zmassCut) continue;
            if(goodJets.size() < njetsLow ||
                    goodJets.size() > njetsHigh ) continue;


            int nbtags = 0;
            float minRLeadingJet = 9999.0;
            std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
            for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                fill(h1D_btagval_file, btagval, scale);
                // fill(h1D_btagval_file, btagval, scale);

                if(btagval > btagDiscriminant) {
                    nbtags++;
                }
            }

            if(nbtags >= btagCut) continue; // FIXME


            // We are now in the region of interest

            // try to match W lepton to genps
            float mindR = 9999.0;
            int brotherIdx = -1;
            for(unsigned int iLep = 0; iLep < genps_p4().size(); iLep++) {
                if( abs(genps_id().at(iLep)) != 11 && abs(genps_id().at(iLep)) != 13 ) continue;
                float dR = deltaR(genps_p4().at(iLep), leps[2]);
                if(dR <= mindR) {
                    mindR = dR;
                    brotherIdx = iLep;
                }

                // now try to find matching neutrino (id of same flavor neutrino = 1 + id of lepton)

                for(unsigned int iNu = 0; iNu < genps_p4().size(); iNu++) {
                    if( abs(genps_id().at(iNu)) == abs(genps_id().at(iLep)) + 1) {
                        // fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        break;
                    }
                }

            }
            if(brotherIdx >= 0) {
                fill(h1D_gen_dR_file, mindR, scale);
                if(mindR < 0.15) {
                    fill(h1D_gen_id_file, abs(genps_id_mother().at(brotherIdx)), scale);
                }
            } else {
                // cout << "ERROR: " << mindR << " " << brotherIdx << " " << endl;
            }


            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                fill(h1D_leppt_file,goodMus.at(iMu).pt(), scale);
                fill(h1D_lepeta_file, goodMus.at(iMu).eta(), scale);
                fill(h1D_lepetamu_file, goodMus.at(iMu).eta(), scale);
            }
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                fill(h1D_leppt_file,goodEls.at(iEl).pt(), scale);
                fill(h1D_lepeta_file, goodEls.at(iEl).eta(), scale);
                fill(h1D_lepetae_file, goodEls.at(iEl).eta(), scale);
            }




            // FIXME
            if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                mtW = MT(goodEls[0], met, metPhi);
                fill(h1D_mtWmumue_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_mete_file, met);
                    float dphi = deltaPhi(metPhi,goodEls.at(0).phi());
                    // cout << "electron " << " metPhi: " << metPhi << " elphi: " << goodEls.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphie_file, dphi, scale);
                    fill(h1D_test_pte_file, goodEls.at(0).pt(), scale);
                    fill(h1D_metphie_file, metPhi, scale);
                }

            } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                mtW = MT(goodMus[0], met, metPhi);
                fill(h1D_mtWeemu_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_metm_file, met);
                    float dphi = deltaPhi(metPhi,goodMus.at(0).phi());
                    // cout << "muon     " << " metPhi: " << metPhi << " muphi: " << goodMus.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphim_file, dphi, scale);
                    fill(h1D_test_ptm_file, goodMus.at(0).pt(), scale);
                    fill(h1D_metphim_file, metPhi, scale);
                }

            } else { 
                if(goodMus.size() == 3) { //mumumu
                    fill(h1D_mtWmumumu_file, mtW, scale);
                } else { // eee
                    fill(h1D_mtWeee_file, mtW, scale);
                }
            }


            double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
            float ptZ = (leps[0]+leps[1]).pt();
            float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

            fill(h1D_ptZ_file, ptZ, scale);
            fill(h1D_Wleppt_file,leps[2].pt(), scale);
            if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_file, minRLeadingJet, scale);
            fill(h1D_st_file, st, scale);
            fill(h1D_mt_file,mt, scale);
            fill(h1D_mtW_file, mtW, scale);
            fill(h1D_zmass_file,mass, scale); 
            fill(h1D_njets_file,goodJets.size(), scale);
            fill(h1D_ht_file,ht, scale);
            fill(h1D_met_file,met, scale);
            fill(h1D_nbtags_file, nbtags, scale);

            error->Fill(0.5,scale);
            addToCounter(filename, scale);
            nGoodEvents++;
            nGoodEventsWeighted+=scale*1.0;

            if(goodJets.size() < 1) continue;

            float ptj1 = goodJets[0].pt;
            float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptj1_file, ptj1, scale);
            fill(h1D_massZj1_file, massZj1, scale);

            if(goodJets.size() < 2) continue;

            float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
            float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
            float ptj2 = goodJets[1].pt;
            float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptjj_file, ptjj, scale);
            fill(h1D_massjj_file, massjj, scale);
            fill(h1D_ptj2_file, ptj2, scale);
            fill(h1D_massZj2_file, massZj2, scale);


        }//event loop

    }//file loop MCMC

    std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
    std::cout << " nGoodEventsWeighted to 19.4 1/fb: " << error->GetBinContent(1) << std::endl;

    // std::cout << " error->GetBinContent(1): " << error->GetBinContent(1) << " error->GetBinError(1): " << error->GetBinError(1) << std::endl;

    std::cout << "ASDF MC " << tag << " " << error->GetBinContent(1)  << " " << error->GetBinError(1) << std::endl;

    printCounter();

    TString prefix("plots");
    prefix += tag;
    prefix += "/";

    // stringstream ss; ss << njetsCut;
    // std::string common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq"+ss.str();
    // TString common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq" + TString::Itoa(njetsCut,10);
    // TString common = " --luminosity 19.4 --percentages ";
    TString common = " --luminosity 19.4 --percentages --scaletodata";
    // std::string common = " --luminosity 19.4 --percentages --label njets>="+ss.str();

    // drawStacked(h1D_dummy_data, h1D_dummy_vec,prefix+"h1D_dummy.pdf",""+common);

    drawStacked(h1D_njets_data, h1D_njets_vec, prefix+"h1D_njets.pdf", "--centerlabel --printbins"+common);
    drawStacked(h1D_ht_data, h1D_ht_vec,prefix+"h1D_ht.pdf","--logscale --binsize --centerlabel"+common);
    drawStacked(h1D_leppt_data, h1D_leppt_vec,prefix+"h1D_leppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_Wleppt_data, h1D_Wleppt_vec,prefix+"h1D_Wleppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_met_data, h1D_met_vec,prefix+"h1D_met.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mt_data, h1D_mt_vec,prefix+"h1D_mt.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mtW_data, h1D_mtW_vec,prefix+"h1D_mtW.pdf","--binsize "+common);
    drawStacked(h1D_lepeta_data, h1D_lepeta_vec,prefix+"h1D_lepeta.pdf",""+common);
    drawStacked(h1D_zmass_data, h1D_zmass_vec,prefix+"h1D_zmass.pdf","--binsize --reorderstack"+common);

    drawStacked(h1D_mtWeemu_data, h1D_mtWeemu_vec,prefix+"h1D_mtWeemu.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumue_data, h1D_mtWmumue_vec,prefix+"h1D_mtWmumue.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumumu_data, h1D_mtWmumumu_vec,prefix+"h1D_mtWmumumu.pdf","--binsize "+common);
    drawStacked(h1D_mtWeee_data, h1D_mtWeee_vec,prefix+"h1D_mtWeee.pdf","--binsize "+common);
    drawStacked(h1D_lepetae_data, h1D_lepetae_vec,prefix+"h1D_lepetae.pdf",""+common);
    drawStacked(h1D_lepetamu_data, h1D_lepetamu_vec,prefix+"h1D_lepetamu.pdf",""+common);

    drawStacked(h1D_btagval_data, h1D_btagval_vec, prefix+"h1D_btagval.pdf", "--centerlabel "+common);
    drawStacked(h1D_nbtags_data, h1D_nbtags_vec, prefix+"h1D_nbtags.pdf", "--centerlabel --logscale"+common);

    drawStacked(h1D_ptZ_data, h1D_ptZ_vec, prefix+"h1D_ptZ.pdf","--centerlabel "+common);
    drawStacked(h1D_st_data, h1D_st_vec, prefix+"h1D_st.pdf","--centerlabel "+common);
    drawStacked(h1D_minRLeadingJet_data, h1D_minRLeadingJet_vec, prefix+"h1D_minRLeadingJet.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj1_data, h1D_ptj1_vec, prefix+"h1D_ptj1.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj2_data, h1D_ptj2_vec, prefix+"h1D_ptj2.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj1_data, h1D_massZj1_vec, prefix+"h1D_massZj1.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj2_data, h1D_massZj2_vec, prefix+"h1D_massZj2.pdf","--centerlabel "+common);
    drawStacked(h1D_ptjj_data, h1D_ptjj_vec, prefix+"h1D_ptjj.pdf","--centerlabel "+common);
    drawStacked(h1D_massjj_data, h1D_massjj_vec, prefix+"h1D_massjj.pdf","--centerlabel "+common);

    TH1F* dog = new TH1F("dog","",1,0,1);

    drawStacked(dog, h1D_test_metm_vec,prefix+"h1D_test_metm.pdf",""+common);
    drawStacked(dog, h1D_test_dphim_vec,prefix+"h1D_test_dphim.pdf",""+common);
    drawStacked(dog, h1D_test_ptm_vec,prefix+"h1D_test_ptm.pdf",""+common);

    drawStacked(dog, h1D_test_dphinu_vec,prefix+"h1D_test_dphinu.pdf",""+common);

    drawStacked(dog, h1D_test_mete_vec,prefix+"h1D_test_mete.pdf",""+common);
    drawStacked(dog, h1D_test_dphie_vec,prefix+"h1D_test_dphie.pdf",""+common);
    drawStacked(dog, h1D_test_pte_vec,prefix+"h1D_test_pte.pdf",""+common);

    drawStacked(dog, h1D_gen_dR_vec,prefix+"h1D_gen_dR.pdf","--logscale --centerlabel "+common);
    drawStacked(dog, h1D_gen_id_vec,prefix+"h1D_gen_id.pdf",""+common);

    drawStacked(dog, h1D_metphie_vec,prefix+"h1D_metphie.pdf",""+common);
    drawStacked(dog, h1D_metphim_vec,prefix+"h1D_metphim.pdf",""+common);

    return 0;
}
void readNtuplesPostfilter_forAN(TString inputfilename="results.root", int sig=Sig::Prompt, int filt=filter::L3, 
				 std::string effmeasured="IterL3_NOHP_NOL1"){

  bool doingL1 = (filt==filter::L1); 

  TFile* outfile = TFile::Open(Form("%s_efficiency_post.root", effmeasured.c_str()),"RECREATE");
  std::cout << "output file: " << outfile -> GetName() << std::endl;

  //Create histograms  
  TH1F* dimuon_mass             = new TH1F("h_dimuon_mass"          ,"dimuon_mass"      , 1500,  0,  150 );
  TH1F* tagiso                  = new TH1F("h_tagiso"               ,"tagiso"           ,  100,  0,  1   );
  TH1F* tagMuonPt               = new TH1F("h_tagMuonPt"            ,"tagMuonPt"        ,  150,  0,  150 );
  TH1F* nvtx_event              = new TH1F("h_nvtx_event"           ,"nvtx_event"       ,   60,  0,   60 );
 
  TEfficiency* muonPt_barrel    = new TEfficiency("muonPt_barrel"   ,"muonPt_barrel"    ,   16,  pt_bins );
  TEfficiency* muonPt_endcap    = new TEfficiency("muonPt_endcap"   ,"muonPt_endcap"    ,   16,  pt_bins );
  TEfficiency* muonPt           = new TEfficiency("muonPt"          ,"muonPt"           ,   16,  pt_bins ); 
  TEfficiency* muonPtTurnOn     = new TEfficiency("muonPtTurnOn"    ,"muonPtTurnOn"     ,   16,  pt_bins ); 
  TEfficiency* muonEta          = new TEfficiency("muonEta"         ,"muonEta"          ,   15, eta_bins );
  TEfficiency* muonPhi          = new TEfficiency("muonPhi"         ,"muonPhi"          ,   20, -3.2, 3.2);
  TEfficiency* muonEff          = new TEfficiency("muonEff"         ,"muonEff"          ,    1,   0., 1.0);
  TEfficiency* muonDeltaR       = new TEfficiency("muonDeltaR"      ,"muonDeltaR"       ,   30,   0., 3.0);
  TEfficiency* muonDeltaPhi     = new TEfficiency("muonDeltaPhi"    ,"muonDeltaPhi"     ,   30,   0., 3.2); 

  // GLOBAL QUANTITIES//
  TEfficiency* muonchi2         = new TEfficiency("muonchi2"        , "muonchi2"        ,  60,    0.,  7.);
  TEfficiency* muondxy          = new TEfficiency("muondxy"         , "muondxy"         ,  100,  -0.3, 0.3);
  TEfficiency* muondz           = new TEfficiency("muondz"          , "muondz"          ,   10,   dz_bins);
  TEfficiency* muonPixHit       = new TEfficiency("muonPixHit"      , "muonPixHit"      ,   20,  -0.5,19.5);
  TEfficiency* muonLayHit       = new TEfficiency("muonLayHit"      , "muonLayHit"      ,   16,   2.5,18.5);
  TEfficiency* muonPixLay       = new TEfficiency("muonPixLay"      , "muonPixLay"      ,    7,  -0.5, 6.5);
  TEfficiency* muoninnerPt      = new TEfficiency("muoninnerPt"     , "muoninnerPt"     ,   16,   pt_bins );
  TEfficiency* muoninnerEta     = new TEfficiency("muoninnerEta"    , "muoninnerEta"    ,   15,   eta_bins);
  TEfficiency* muoninnerPhi     = new TEfficiency("muoninnerPhi"    , "muoninnerPhi"    ,   20,  -3.2, 3.2);

  TEfficiency* failingMuonPt    = new TEfficiency("failingMuonPt"   ,"failingMuonPt"    ,   16,  pt_bins ); 
  TEfficiency* failingMuonEta   = new TEfficiency("failingMuonEta"  ,"failingMuonEta"   ,   15, eta_bins );
  TEfficiency* failingMuonPhi   = new TEfficiency("failingMuonPhi"  ,"failingMuonPhi"   ,   20, -3.2, 3.2);
  TEfficiency* failingMuonEff   = new TEfficiency("failingMuonEff"  ,"failingMuonEff"   ,   1 ,   0., 1.0);

  TH1F* PassingProbePt          = new TH1F("h_PassingProbePt"       ,"PassingMuonPt"    ,  16,  pt_bins );
  TH1F* PassingProbeEta         = new TH1F("h_PassingProbeEta"      ,"PassingMuonEta"   ,  15, eta_bins );
  TH1F* PassingProbePhi         = new TH1F("h_PassingProbePhi"      ,"PassingMuonPhi"   ,  20, -3.2, 3.2);
  TH1F* PassingProbeMll         = new TH1F("h_PassingProbeMll"      ,"PassingMuonMll"   ,  20,  86., 96.); 

  TH1F* FailingProbePt          = new TH1F("h_FailingProbePt"       ,"FailingMuonPt"    ,  16,  pt_bins );
  TH1F* FailingProbeEta         = new TH1F("h_FailingProbeEta"      ,"FailingMuonEta"   ,  15, eta_bins );
  TH1F* FailingProbePhi         = new TH1F("h_FailingProbePhi"      ,"FailingMuonPhi"   ,  20, -3.2, 3.2);
  TH1F* FailingProbeMll         = new TH1F("h_FailingProbeMll"      ,"FailingMuonMll"   ,  20,  86., 96.);

  // di-muon efficiencies 
  TEfficiency* diMuonPt         = new TEfficiency("diMuonPt"      ,"diMuonPt"       ,   16,  pt_bins  , 16,  pt_bins ); 
  TEfficiency* diMuonEta        = new TEfficiency("diMuonEta"     ,"diMuonEta"      ,   15, eta_bins  , 15, eta_bins );
  TEfficiency* diMuonPhi        = new TEfficiency("diMuonPhi"     ,"diMuonPhi"      ,   20, -3.2, 3.2 , 20, -3.2, 3.2);
  TEfficiency* diMuonEff        = new TEfficiency("diMuonEff"     ,"diMuonEff"      ,    1,   0., 1.0);
  TEfficiency* diMuonDeltaR     = new TEfficiency("diMuonDeltaR"  ,"diMuonDeltaR"   ,   30,   0., 3.0);
  TEfficiency* diMuonLeadPt     = new TEfficiency("diMuonLeadPt"  ,"diMuonLeadPt"   ,   16,  pt_bins ); 
  TEfficiency* diMuonLeadEta    = new TEfficiency("diMuonLeadEta" ,"diMuonLeadEta"  ,   15,  eta_bins );
  TEfficiency* diMuonLeadPhi    = new TEfficiency("diMuonLeadPhi" ,"diMuonLeadPhi"  ,   20, -3.2, 3.2);
  TEfficiency* diMuonTrailPt    = new TEfficiency("diMuonTrailPt" ,"diMuonTrailPt"  ,   16,  pt_bins ); 
  TEfficiency* diMuonTrailEta   = new TEfficiency("diMuonTrailEta","diMuonTrailEta" ,   15, eta_bins );
  TEfficiency* diMuonTrailPhi   = new TEfficiency("diMuonTrailPhi","diMuonTrailPhi" ,   20, -3.2, 3.2);


  TEfficiency* nvtx             = new TEfficiency("nvtx"             ,"nvtx"             ,   60,    0,  60);
  TEfficiency* nvtx_barrel      = new TEfficiency("nvtx_barrel"      ,"nvtx_barrel"      ,   60,    0,  60);
  TEfficiency* nvtx_endcap      = new TEfficiency("nvtx_endcap"      ,"nvtx_endcap"      ,   60,    0,  60);
   
  
  TFile* inputfile = TFile::Open(inputfilename, "READ");
  std::cout << "input file: " << inputfile -> GetName() << std::endl;

  TTree *tree = (TTree*) inputfile -> Get("muonNtuples/muonTree"); 
  
  if (!tree) {
    std::cout << " *** tree not found *** " << std::endl;
    return;
  }
    
  MuonEvent* ev      = new MuonEvent(); 
  TBranch*  evBranch = tree->GetBranch("event"); 
  evBranch -> SetAddress(&ev);

  int nentries = tree->GetEntriesFast();
  std::cout << "Number of entries = " << nentries << std::endl;

  std::string theprobefilter = getProbeFilter(sig);
  std::string thepassfilter  = getPassFilter(sig,filt);
  offlinePtCut = getLeadingPtCut(sig);
  float ptcut1 = getLeadingPtCut(sig);
  float ptcut2 = getTrailingPtCut(sig);
  for (Int_t eventNo=0; eventNo < nentries; eventNo++)     {
    Int_t IgetEvent   = tree   -> GetEvent(eventNo);
    printProgBar((int)(eventNo*100./nentries));
    
    unsigned int nmuons = ev->muons.size(); 
    if (nmuons < 2) continue; 
    unsigned int nhltmuons = ev->hltmuons.size();
    
    //    if (!ev-> hltTag.find(hltname)) continue;
    nvtx_event-> Fill( ev -> nVtx   ); 
    
    for (int imu = 0; imu < nmuons; imu++){ 
      // select the tag muon        
      if (! selectTagMuon(ev -> muons.at(imu), tagiso)) continue; 
      
      if (! matchMuon(ev -> muons.at(imu), ev -> hltTag.objects, isofilterTag)) continue;
      tagMuonPt -> Fill ( ev -> muons.at(imu).pt) ; 
      
      for (int jmu = 0; jmu < nmuons; jmu++){
	bool pass   = false;
	
	// select the probe muon
	if (!selectProbeMuon(ev -> muons.at(jmu), ev -> muons.at(imu), dimuon_mass)) continue;
	  
	// match probe muon to filter
	if (!doingL1 && !(matchMuon(ev -> muons.at(jmu), ev -> hlt.objects, theprobefilter))) continue;
	if (matchMuon(ev -> muons.at(jmu), ev -> hlt.objects, thepassfilter))  pass = true;  
	
	muonPtTurnOn -> Fill( pass, ev -> muons.at(jmu).pt ); 
	
	if (ev -> muons.at(jmu).pt < offlinePtCut) continue;
	
	TLorentzVector mu1, mu2;
	mu1.SetPtEtaPhiM (ev->muons.at(imu).pt,ev->muons.at(imu).eta,ev->muons.at(imu).phi, muonmass); 
	mu2.SetPtEtaPhiM (ev->muons.at(jmu).pt,ev->muons.at(jmu).eta,ev->muons.at(jmu).phi, muonmass);
	double mumumass = (mu1 + mu2).M();
	double DeltaR   = mu1.DeltaR(mu2);
	double DeltaPhi = mu1.DeltaPhi(mu2);
	
	if (pass) { 
	  PassingProbePt  -> Fill( ev -> muons.at(jmu).pt  );
	  PassingProbeEta -> Fill( ev -> muons.at(jmu).eta );
	  PassingProbePhi -> Fill( ev -> muons.at(jmu).phi );
	  PassingProbeMll -> Fill( mumumass                );
	}	      
	else {       
	  FailingProbePt  -> Fill( ev -> muons.at(jmu).pt  );
	  FailingProbeEta -> Fill( ev -> muons.at(jmu).eta );
	  FailingProbePhi -> Fill( ev -> muons.at(jmu).phi );
	  FailingProbeMll -> Fill( mumumass                );
	}
	
	muonPt       -> Fill( pass, ev -> muons.at(jmu).pt );
	muonEta      -> Fill( pass, ev -> muons.at(jmu).eta);
	muonPhi      -> Fill( pass, ev -> muons.at(jmu).phi);
	muonEff      -> Fill( pass, 0.5                    );
	
	muoninnerPt  -> Fill( pass, ev -> muons.at(jmu).innerpt);
	muoninnerEta -> Fill( pass, ev -> muons.at(jmu).innereta); 
	muoninnerPhi -> Fill( pass, ev -> muons.at(jmu).innerphi); 
	
	muonchi2   -> Fill( pass, ev -> muons.at(jmu).innerchi2 );
	muondxy    -> Fill( pass, ev -> muons.at(jmu).innerdxy);
	muondz     -> Fill( pass, ev -> muons.at(jmu).innerdz);
	muonPixHit -> Fill( pass, ev -> muons.at(jmu).innerpixelHits);
	muonLayHit -> Fill( pass, ev -> muons.at(jmu).innerlayerHits);
	muonPixLay -> Fill( pass, ev -> muons.at(jmu).innerpixelLayers);
	
	failingMuonPt  -> Fill( !pass, ev->muons.at(jmu).pt );
	failingMuonEta -> Fill( !pass, ev->muons.at(jmu).eta);
	failingMuonPhi -> Fill( !pass, ev->muons.at(jmu).phi);
	failingMuonEff -> Fill( !pass, 0.5                    );
	
      } // nmuons
    }
      
    /// NOW FOR DIMUONS:
    for (int imu = 0; imu < nmuons; imu++){
      if (!selectMuon(ev -> muons.at(imu))) continue; 
      // pass L1: 
      if (!doingL1 && !(matchMuon(ev -> muons.at(imu), ev -> hlt.objects, theprobefilter))) continue;
      for (int jmu = imu+1; jmu < nmuons; jmu++){
	if (!selectMuon(ev -> muons.at(jmu))) continue; 
	if (!doingL1 && !(matchMuon(ev -> muons.at(jmu), ev -> hlt.objects, theprobefilter))) continue;
	// both should pass the L1 filter! 
	bool pass = false;
	double DeltaR = deltaR(ev->muons.at(imu).eta,ev->muons.at(imu).phi,ev->muons.at(jmu).eta,ev->muons.at(jmu).phi);
	diMuonPt       -> Fill( pass, ev->muons.at(imu).pt , ev->muons.at(jmu).pt  ); 
	diMuonLeadPt   -> Fill( pass, ev->muons.at(imu).pt ); 
	diMuonTrailPt  -> Fill( pass, ev->muons.at(jmu).pt ); 
	
	if (ev->muons.at(imu).pt < ptcut1) continue;
	if (ev->muons.at(jmu).pt < ptcut2) continue;
	diMuonEta      -> Fill( pass, ev->muons.at(imu).eta, ev->muons.at(jmu).eta );
	diMuonPhi      -> Fill( pass, ev->muons.at(imu).phi, ev->muons.at(jmu).phi );
	diMuonDeltaR   -> Fill( pass, DeltaR);
	diMuonEff      -> Fill( pass, 0.5);
	
	diMuonLeadEta  -> Fill( pass, ev->muons.at(imu).eta ); 
	diMuonTrailEta -> Fill( pass, ev->muons.at(jmu).eta ); 
	diMuonLeadPhi  -> Fill( pass, ev->muons.at(imu).phi ); 
	diMuonTrailPhi -> Fill( pass, ev->muons.at(jmu).phi ); 
      }
    }
  }  
  
  //Writing the histograms in a file.
  outfile           -> cd();
  tagMuonPt         -> Write();
  
  muonPt            -> Write();
  muonPtTurnOn      -> Write();
  muonEta           -> Write();
  muonPhi           -> Write();
  muonEff           -> Write();
  muonDeltaR        -> Write();
  muonDeltaPhi      -> Write();

  muonchi2     -> Write();
  muondxy      -> Write();
  muondz       -> Write();
  muonPixHit   -> Write();
  muonLayHit   -> Write();
  muonPixLay   -> Write();
  muoninnerPt  -> Write();
  muoninnerEta -> Write();
  muoninnerPhi -> Write();

  failingMuonPt   -> Write();
  failingMuonEta  -> Write();
  failingMuonPhi  -> Write();
  failingMuonEff  -> Write();

  PassingProbePt  -> Write();
  PassingProbeEta -> Write();
  PassingProbePhi -> Write();
  PassingProbeMll -> Write();
  
  FailingProbePt  -> Write();
  FailingProbeEta -> Write();
  FailingProbePhi -> Write();
  FailingProbeMll -> Write();
  
  /// Per-event (di-muon) efficiency.
  diMuonPt         -> Write();
  diMuonEta        -> Write();
  diMuonPhi        -> Write();
  diMuonDeltaR     -> Write();
  diMuonLeadPt     -> Write(); 
  diMuonLeadEta    -> Write();
  diMuonLeadPhi    -> Write();
  diMuonTrailPt    -> Write(); 
  diMuonTrailEta   -> Write();
  diMuonTrailPhi   -> Write();

  nvtx_event       -> Write();
  nvtx             -> Write();
  
  dimuon_mass      -> Write();
  tagiso           -> Write();
  
  outfile          -> Close();  
  
  return;
}
Example #28
0
void Plot_EE_mu_maps_2(){

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

//	TFile *outf = new TFile("/shome/haweber/ECAL/Laser/Analysis/Plots/20121126_EEmustd.root", "RECREATE");
	TFile *outf = new TFile("/shome/haweber/ECAL/DataLaser/20121116_EEmustd.root", "RECREATE");

	TFile *file = TFile::Open("/shome/haweber/ECAL/DataLaser/ana_rad_ecal_v3.root");
	TTree *tree = (TTree*)file->Get("EE");

	TH2D *mu_ECAL_EEp_russ = new TH2D("mu_ECAL_EEp_russ", "mu_ECAL_EEp_russ", 101, 0, 101, 101, 0, 101);
	TH2D *mu_ECAL_EEp_chin = new TH2D("mu_ECAL_EEp_chin", "mu_ECAL_EEp_chin", 101, 0, 101, 101, 0, 101);
	TH2D *mu_ECAL_EEm_russ = new TH2D("mu_ECAL_EEm_russ", "mu_ECAL_EEm_russ", 101, 0, 101, 101, 0, 101);
	TH2D *mu_ECAL_EEm_chin = new TH2D("mu_ECAL_EEm_chin", "mu_ECAL_EEm_chin", 101, 0, 101, 101, 0, 101);

	TH2D *mu_SIC_EEp_russ  = new TH2D("mu_SIC_EEp_russ",  "mu_SIC_EEp_russ",  101, 0, 101, 101, 0, 101);
	TH2D *mu_SIC_EEp_chin  = new TH2D("mu_SIC_EEp_chin",  "mu_SIC_EEp_chin",  101, 0, 101, 101, 0, 101);
	TH2D *mu_SIC_EEm_russ  = new TH2D("mu_SIC_EEm_russ",  "mu_SIC_EEm_russ",  101, 0, 101, 101, 0, 101);
	TH2D *mu_SIC_EEm_chin  = new TH2D("mu_SIC_EEm_chin",  "mu_SIC_EEm_chin",  101, 0, 101, 101, 0, 101);


	TH2D *mu_std_EEp       = new TH2D("mu_std_EEp",       "mu_std_EEp",       101, 0, 101, 101, 0, 101);
	TH2D *mu_std_EEm       = new TH2D("mu_std_EEm",       "mu_std_EEm",       101, 0, 101, 101, 0, 101);
	TH2D *mu_SIC_EEp       = new TH2D("mu_SIC_EEp",       "mu_SIC_EEp",       101, 0, 101, 101, 0, 101);
	TH2D *mu_SIC_EEm       = new TH2D("mu_SIC_EEm",       "mu_SIC_EEm",       101, 0, 101, 101, 0, 101);

	TH2D *VPT_gainqe_EEp   = new TH2D("VPT_gainqe_EEp",   "VPT_gainqe_EEp",   101, 0, 101, 101, 0, 101);
	TH2D *VPT_gainqe_EEm   = new TH2D("VPT_gainqe_EEm",   "VPT_gainqe_EEm",   101, 0, 101, 101, 0, 101);
	TH2D *VPT_gain_EEp     = new TH2D("VPT_gain_EEp",     "VPT_gain_EEp",     101, 0, 101, 101, 0, 101);
	TH2D *VPT_gain_EEm     = new TH2D("VPT_gain_EEm",     "VPT_gain_EEm",     101, 0, 101, 101, 0, 101);
	TH2D *VPT_qe_EEp       = new TH2D("VPT_qe_EEp",       "VPT_qe_EEp",       101, 0, 101, 101, 0, 101);
	TH2D *VPT_qe_EEm       = new TH2D("VPT_qe_EEm",       "VPT_qe_EEm",       101, 0, 101, 101, 0, 101);

	TH2D *EEp_producer     = new TH2D("EEp_producer",     "EEp_producer",     101, 0, 101, 101, 0, 101);
	TH2D *EEm_producer     = new TH2D("EEm_producer",     "EEm_producer",     101, 0, 101, 101, 0, 101);

	int nev;
	TString variable, var;
	TString selection, sel;

   	Long64_t nentries = tree->GetEntriesFast();
	cout << "Tree contains "<< nentries << " entries" << endl;

	int ix,iy,iz;
	double mu_ECAL, mu_SIC;
	float vpt_gain, vpt_qe, vpt_pg;
	int producer;
	TBranch *xx     = tree->GetBranch("ix");
	TBranch *yy     = tree->GetBranch("iy");
	TBranch *zz     = tree->GetBranch("iz");
	TBranch *muECAL = tree->GetBranch("mu_ECAL");
	TBranch *muSIC  = tree->GetBranch("mu_SIC");
	TBranch *prod   = tree->GetBranch("producer");
	TBranch *gain   = tree->GetBranch("vpt_gain");
	TBranch *qe     = tree->GetBranch("vpt_qe");
	TBranch *pg     = tree->GetBranch("vpt_pg");
	xx    ->SetAddress(&ix);
	yy    ->SetAddress(&iy);
	zz    ->SetAddress(&iz);
	muECAL->SetAddress(&mu_ECAL);
	muSIC ->SetAddress(&mu_SIC);
	prod  ->SetAddress(&producer);
	gain  ->SetAddress(&vpt_gain);
	qe    ->SetAddress(&vpt_qe);
	pg    ->SetAddress(&vpt_pg);

   	Long64_t nbytes = 0, nb = 0;
   	    for (Long64_t jentry=0; jentry<nentries;jentry++) {
      		//Long64_t ientry = tree->LoadTree(jentry);
      		//if (ientry < 0) break;
		//if(jentry%(nentries/25)==0) cout << "Processing event " << jentry << endl;
		nb = tree->GetEntry(jentry);   nbytes += nb;

	//	int iX = ix;
	//	int iY = iy;
	//	int iZ = iz;
	//	if(mu_ECAL>0){
	//	cout << "ix " << iX << " iy " << iY << " iz " << iZ << endl;
	//	cout << "mustd " << mu_ECAL << " muSIC " << mu_SIC << " producer " << producer << endl;
	//	}
		int bin = mu_ECAL_EEp_russ->FindBin(ix,iy);

		if(mu_ECAL>=0 && iz==1 && producer==1){//EE+, russian
			if(mu_ECAL_EEp_russ->GetBinContent(bin)>0) cout << "mu_ECAL: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_ECAL_EEp_russ->GetBinContent(bin) << " and now is filled with " << mu_ECAL << endl;
			mu_ECAL_EEp_russ->SetBinContent(bin, mu_ECAL);
		}
		if(mu_ECAL>=0 && iz==-1 && producer==1){//EE-, russian
			if(mu_ECAL_EEm_russ->GetBinContent(bin)>0) cout << "mu_ECAL: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_ECAL_EEm_russ->GetBinContent(bin) << " and now is filled with " << mu_ECAL << endl;
			mu_ECAL_EEm_russ->SetBinContent(bin, mu_ECAL);
		}
		if(mu_ECAL>=0 && iz==1 && producer==2){//EE+, chinese
			if(mu_ECAL_EEp_chin->GetBinContent(bin)>0) cout << "mu_ECAL: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_ECAL_EEp_chin->GetBinContent(bin) << " and now is filled with " << mu_ECAL << endl;
			mu_ECAL_EEp_chin->SetBinContent(bin, mu_ECAL);
		}
		if(mu_ECAL>=0 && iz==-1 && producer==2){//EE-, chinese
			if(mu_ECAL_EEm_chin->GetBinContent(bin)>0) cout << "mu_ECAL: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_ECAL_EEm_chin->GetBinContent(bin) << " and now is filled with " << mu_ECAL << endl;
			mu_ECAL_EEm_chin->SetBinContent(bin, mu_ECAL);
		}
		if(mu_SIC>=0 && iz==1 && producer==1){//EE+, russian
			if(mu_SIC_EEp_russ->GetBinContent(bin)>0) cout << "mu_SIC: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_SIC_EEp_russ->GetBinContent(bin) << " and now is filled with " << mu_SIC << endl;
			mu_SIC_EEp_russ->SetBinContent(bin, mu_SIC);
		}
		if(mu_SIC>=0 && iz==-1 && producer==1){//EE-, russian
			if(mu_SIC_EEm_russ->GetBinContent(bin)>0) cout << "mu_SIC: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_SIC_EEm_russ->GetBinContent(bin) << " and now is filled with " << mu_SIC << endl;
			mu_SIC_EEm_russ->SetBinContent(bin, mu_SIC);
		}
		if(mu_SIC>=0 && iz==1 && producer==2){//EE+, chinese
			if(mu_SIC_EEp_chin->GetBinContent(bin)>0) cout << "mu_SIC: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_SIC_EEp_chin->GetBinContent(bin) << " and now is filled with " << mu_SIC << endl;
			mu_SIC_EEp_chin->SetBinContent(bin, mu_SIC);
		}
		if(mu_SIC>=0 && iz==-1 && producer==2){//EE-, chinese
			if(mu_SIC_EEm_chin->GetBinContent(bin)>0) cout << "mu_SIC: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << mu_SIC_EEm_chin->GetBinContent(bin) << " and now is filled with " << mu_SIC << endl;
			mu_SIC_EEm_chin->SetBinContent(bin, mu_SIC);
		}
		if(iz==1 && (producer==1||producer==2)){
			if(EEp_producer->GetBinContent(bin)>0) cout << "producer: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << EEp_producer->GetBinContent(bin) << " and now is filled with " << producer << endl;
			EEp_producer->SetBinContent(bin, producer);
		}
		if(iz==-1 && (producer==1||producer==2)){
			if(EEm_producer->GetBinContent(bin)>0) cout << "producer: bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << EEm_producer->GetBinContent(bin) << " and now is filled with " << producer << endl;
			EEm_producer->SetBinContent(bin, producer);
		}

		if(vpt_pg>=0 && iz==1){
			if(VPT_gainqe_EEp->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_gainqe_EEp->GetBinContent(bin) << " and now is filled with " << vpt_pg << endl;
			VPT_gainqe_EEp->SetBinContent(bin, vpt_pg);
		}
		if(vpt_pg>=0 && iz==-1){
			if(VPT_gainqe_EEm->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_gainqe_EEm->GetBinContent(bin) << " and now is filled with " << vpt_pg << endl;
			VPT_gainqe_EEm->SetBinContent(bin, vpt_pg);
		}
		if(vpt_qe>=0 && iz==1){
			if(VPT_qe_EEp->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_qe_EEp->GetBinContent(bin) << " and now is filled with " << vpt_qe << endl;
			VPT_qe_EEp->SetBinContent(bin, vpt_qe);
		}
		if(vpt_qe>=0 && iz==-1){
			if(VPT_qe_EEm->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_qe_EEm->GetBinContent(bin) << " and now is filled with " << vpt_qe << endl;
			VPT_qe_EEm->SetBinContent(bin, vpt_qe);
		}
		if(vpt_gain>=0 && iz==1){
			if(VPT_gain_EEp->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_gain_EEp->GetBinContent(bin) << " and now is filled with " << vpt_gain << endl;
			VPT_gain_EEp->SetBinContent(bin, vpt_gain);
		}
		if(vpt_gain>=0 && iz==-1){
			if(VPT_gain_EEm->GetBinContent(bin)>0) cout << __LINE__ << ": bin " << bin << " (ix,iy,iz=" << ix <<","<<iy<<","<<iz<<") was filled with " << VPT_gain_EEm->GetBinContent(bin) << " and now is filled with " << vpt_gain << endl;
			VPT_gain_EEm->SetBinContent(bin, vpt_gain);
		}
	   }

	mu_std_EEp->Add(mu_ECAL_EEp_russ,1);
	mu_std_EEp->Add(mu_ECAL_EEp_chin,1);
	mu_std_EEm->Add(mu_ECAL_EEm_russ,1);
	mu_std_EEm->Add(mu_ECAL_EEm_chin,1);
	mu_SIC_EEp->Add(mu_SIC_EEp_russ, 1);
	mu_SIC_EEp->Add(mu_SIC_EEp_chin, 1);
	mu_SIC_EEm->Add(mu_SIC_EEm_russ, 1);
	mu_SIC_EEm->Add(mu_SIC_EEm_chin, 1);

	mu_std_EEp->SetMaximum(2.); mu_std_EEp->GetZaxis()->SetRangeUser(0.,2.);
	mu_std_EEm->SetMaximum(2.); mu_std_EEm->GetZaxis()->SetRangeUser(0.,2.);
	mu_SIC_EEp->SetMaximum(2.); mu_SIC_EEp->GetZaxis()->SetRangeUser(0.,2.);
	mu_SIC_EEm->SetMaximum(2.); mu_SIC_EEm->GetZaxis()->SetRangeUser(0.,2.);

	TString outputdir = "/shome/haweber/ECAL/Laser/Analysis/Plots";

	if(mu_ECAL_EEp_russ->GetEntries()>0){
	TCanvas *can1 = new TCanvas("can1", "mu_ECAL_EEp_russ", 0, 0, 900, 700);
	can1->cd();
	mu_ECAL_EEp_russ->Draw("COLZ");
	//Util::PrintNoEPS(can1, can1->GetTitle(), outputdir);
	Util::PrintEPS(can1, can1->GetTitle(), outputdir);
	} if(mu_ECAL_EEp_chin->GetEntries()>0){
	TCanvas *can2 = new TCanvas("can2", "mu_ECAL_EEp_chin", 0, 0, 900, 700);
	can2->cd();
	mu_ECAL_EEp_chin->Draw("COLZ");
	//Util::PrintNoEPS(can2, can2->GetTitle(), outputdir);
	Util::PrintEPS(can2, can2->GetTitle(), outputdir);
	} if(mu_ECAL_EEm_russ->GetEntries()>0){
	TCanvas *can3 = new TCanvas("can3", "mu_ECAL_EEm_russ", 0, 0, 900, 700);
	can3->cd();
	mu_ECAL_EEm_russ->Draw("COLZ");
	//Util::PrintNoEPS(can3, can3->GetTitle(), outputdir);
	Util::PrintEPS(can3, can3->GetTitle(), outputdir);
	} if(mu_ECAL_EEm_chin->GetEntries()>0){
	TCanvas *can4 = new TCanvas("can4", "mu_ECAL_EEm_chin", 0, 0, 900, 700);
	can4->cd();
	mu_ECAL_EEm_chin->Draw("COLZ");
	//Util::PrintNoEPS(can4, can4->GetTitle(), outputdir);
	Util::PrintEPS(can4, can4->GetTitle(), outputdir);
	} if(mu_SIC_EEp_russ->GetEntries()>0){
	TCanvas *can5 = new TCanvas("can5", "mu_SIC_EEp_russ", 0, 0, 900, 700);
	can5->cd();
	mu_SIC_EEp_russ->Draw("COLZ");
	//Util::PrintNoEPS(can5, can5->GetTitle(), outputdir);
	Util::PrintEPS(can5, can5->GetTitle(), outputdir);
	} if(mu_SIC_EEp_chin->GetEntries()>0){
	TCanvas *can6 = new TCanvas("can6", "mu_SIC_EEp_chin", 0, 0, 900, 700);
	can6->cd();
	mu_SIC_EEp_chin->Draw("COLZ");
	//Util::PrintNoEPS(can6, can6->GetTitle(), outputdir);
	Util::PrintEPS(can6, can6->GetTitle(), outputdir);	
	} if(mu_SIC_EEm_russ->GetEntries()>0){
	TCanvas *can7 = new TCanvas("can7", "mu_SIC_EEm_russ", 0, 0, 900, 700);
	can7->cd();
	mu_SIC_EEm_russ->Draw("COLZ");
	//Util::PrintNoEPS(can7, can7->GetTitle(), outputdir);
	Util::PrintEPS(can7, can7->GetTitle(), outputdir);
	} if(mu_SIC_EEm_chin->GetEntries()>0){
	TCanvas *can8 = new TCanvas("can8", "mu_SIC_EEm_chin", 0, 0, 900, 700);
	can8->cd();
	mu_SIC_EEm_chin->Draw("COLZ");
	//Util::PrintNoEPS(can8, can8->GetTitle(), outputdir);
	Util::PrintEPS(can8, can8->GetTitle(), outputdir);
	}

	TCanvas *c1 = new TCanvas("c1", "mu_SIC_EEm_chin", 0, 0, 900, 700);
	c1->cd();
	mu_std_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c1, mu_std_EEp->GetTitle(), outputdir);
	Util::PrintEPS(c1, mu_std_EEp->GetTitle(), outputdir);
//	c1->Clear();
	TCanvas *c2 = new TCanvas("c2", "mu_SIC_EEm_chin", 0, 0, 900, 700);
	c2->cd();
	mu_std_EEm->Draw("COLZ");
	//Util::PrintNoEPS(c2, mu_std_EEm->GetTitle(), outputdir);
	Util::PrintEPS(c2, mu_std_EEm->GetTitle(), outputdir);
//	c2->Clear();
	TCanvas *c3 = new TCanvas("c3", "mu_SIC_EEm_chin", 0, 0, 900, 700);
	c3->cd();
	mu_SIC_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c3, mu_SIC_EEp->GetTitle(), outputdir);
	Util::PrintEPS(c3, mu_SIC_EEp->GetTitle(), outputdir);
//	c3->Clear();
	TCanvas *c4 = new TCanvas("c4", "mu_SIC_EEm_chin", 0, 0, 900, 700);
	c4->cd();
	mu_SIC_EEm->Draw("COLZ");
	//Util::PrintNoEPS(c4, mu_SIC_EEm->GetTitle(), outputdir);
	Util::PrintEPS(c4, mu_SIC_EEm->GetTitle(), outputdir);

	TCanvas *c5 = new TCanvas("c5", "VPT_gainqe_EEp", 0, 0, 900, 700);
	c5->cd();
	VPT_gainqe_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c5, VPT_gainqe_EEp->GetTitle(), outputdir);
	Util::PrintEPS(c5, VPT_gainqe_EEp->GetTitle(), outputdir);
	TCanvas *c6 = new TCanvas("c6", "VPT_gainqe_EEm", 0, 0, 900, 700);
	c6->cd();
	VPT_gainqe_EEm->Draw("COLZ");
	//Util::PrintNoEPS(c6, VPT_gainqe_EEm->GetTitle(), outputdir);
	Util::PrintEPS(c6, VPT_gainqe_EEm->GetTitle(), outputdir);
	TCanvas *c7 = new TCanvas("c7", "VPT_gain_EEp", 0, 0, 900, 700);
	c7->cd();
	VPT_gain_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c7, VPT_gain_EEp->GetTitle(), outputdir);
	Util::PrintEPS(c7, VPT_gain_EEp->GetTitle(), outputdir);
	TCanvas *c8 = new TCanvas("c8", "VPT_gain_EEm", 0, 0, 900, 700);
	c8->cd();
	VPT_gain_EEm->Draw("COLZ");
	//Util::PrintNoEPS(c8, VPT_gain_EEm->GetTitle(), outputdir);
	Util::PrintEPS(c8, VPT_gain_EEm->GetTitle(), outputdir);
	TCanvas *c9 = new TCanvas("c9", "VPT_qe_EEp", 0, 0, 900, 700);
	c9->cd();
	VPT_qe_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c9, VPT_qe_EEp->GetTitle(), outputdir);
	Util::PrintEPS(c9, VPT_qe_EEp->GetTitle(), outputdir);
	TCanvas *c0 = new TCanvas("c0", "VPT_qe_EEm", 0, 0, 900, 700);
	c0->cd();
	VPT_qe_EEp->Draw("COLZ");
	//Util::PrintNoEPS(c0, VPT_qe_EEm->GetTitle(), outputdir);
	Util::PrintEPS(c0, VPT_qe_EEm->GetTitle(), outputdir);
//	c4->Clear();
	
	outf			->cd();
	mu_ECAL_EEp_russ	->Write();
	mu_ECAL_EEp_chin	->Write();
	mu_ECAL_EEm_russ	->Write();
	mu_ECAL_EEm_chin	->Write();
	mu_SIC_EEp_russ		->Write();
	mu_SIC_EEp_chin		->Write();
	mu_SIC_EEm_russ		->Write();
	mu_SIC_EEm_chin		->Write();
	EEp_producer		->Write();
	EEm_producer		->Write();
	mu_std_EEp		->Write();
	mu_std_EEm		->Write();
	mu_SIC_EEp		->Write();
	mu_SIC_EEm		->Write();
	VPT_gainqe_EEp		->Write();
	VPT_gainqe_EEm		->Write();
	VPT_gain_EEp		->Write();
	VPT_gain_EEm		->Write();
	VPT_qe_EEp		->Write();
	VPT_qe_EEm		->Write();
	cout << "saved histograms in: " << outf->GetName() << endl;
	outf->Close();

	PlotEtaProfile();

} 
Example #29
0
void LaserCalib(TTreeSRedirector & cstream, TTree * chain, Float_t tmin, Float_t tmax, Float_t fraction){
  ///

  const Double_t kMaxDelta=10;
  AliTPCParamSR param;
  param.Update();
  TFile fce("TPCsignal.root");
  TTree   * treece =(TTree*)fce.Get("Signalce");
  if (chain) treece=chain;
  //
  TBranch * brsector  = treece->GetBranch("Sector");
  TBranch * brpad     = treece->GetBranch("Pad");
  TBranch * brrow     = treece->GetBranch("Row");
  TBranch * brTimeStamp = treece->GetBranch("TimeStamp");
  //
  TBranch * brtime    = treece->GetBranch("Time");
  TBranch * brrms     = treece->GetBranch("RMS06");
  TBranch * brmax     = treece->GetBranch("Max");
  TBranch * brsum     = treece->GetBranch("Qsum");

  Int_t sector, pad, row=0;
  Double_t time=0, rms=0, qMax=0, qSum=0;
  UInt_t  timeStamp=0;
  brsector->SetAddress(&sector);
  brrow->SetAddress(&row);
  brpad->SetAddress(&pad);
  brTimeStamp->SetAddress(&timeStamp);
  
  brtime->SetAddress(&time);
  brrms->SetAddress(&rms);
  brmax->SetAddress(&qMax);
  brsum->SetAddress(&qSum);


  brsector->GetEntry(0);
  //
  Int_t firstSector  = sector;
  Int_t lastSector   = sector;
  Int_t fentry = 0;
  Int_t lentry = 0;
  //
  // find time offset for differnt events
  //
  Int_t count = 0;
  Double_t padTimes[500000];
  TRobustEstimator restim;
  Double_t meanS[72], sigmaS[72];
  Int_t   firstS[72], lastS[72];
  Double_t   sectorsID[72];
  for (Int_t isector=0;isector<72; isector++){
    firstS[isector]=-1; 
    lastS[isector] =-1;
  };
  TH1F  hisT("hisT","hisT",100,tmin,tmax);
  treece->Draw("Time>>hisT","");
  Float_t cbin = hisT.GetBinCenter(hisT.GetMaximumBin());

  for (Int_t ientry=0; ientry<treece->GetEntriesFast(); ientry++){
    treece->GetEvent(ientry);
    //
    if (sector!=lastSector && sector==firstSector){
      //if (sector!=lastSector){
      lentry = ientry;
      TTimeStamp stamp(timeStamp);
      stamp.Print();
      printf("\nEvent\t%d\tFirst\t%d\tLast\t%d\t%d\n",count, fentry, lentry, lentry-fentry);
      //
      //
      Int_t ngood=0;      
      for (Int_t ientry2=fentry; ientry2<lentry; ientry2++){
	//	brtime->GetEvent(ientry2);
	//  brsector->GetEvent(ientry2);
	treece->GetEvent(ientry2);
	if (time>tmin&&time<tmax && TMath::Abs(time-cbin)<kMaxDelta){
	  padTimes[ngood]=time;
	  ngood++;	
	  if (firstS[sector]<0)  firstS[sector]= ngood;
	  if (firstS[sector]>=0) lastS[sector] = ngood;
	}	
      }
      //
      //
      Double_t mean,sigma;
      restim.EvaluateUni(ngood,padTimes,mean, sigma,int(float(ngood)*fraction));
      printf("Event\t%d\t%f\t%f\n",count, mean, sigma);
      for (Int_t isector=0; isector<72; isector++){
	sectorsID[isector]=sector;
	if (firstS[isector]>=0 &&lastS[isector]>=0 && lastS[isector]>firstS[isector] ){
	  Int_t ngoodS = lastS[isector]-firstS[isector];
	  restim.EvaluateUni(ngoodS, &padTimes[firstS[isector]],meanS[isector], 
			     sigmaS[isector],int(float(ngoodS)*fraction));
	}
      }
      TGraph  graphM(72,sectorsID,meanS);
      TGraph  graphS(72,sectorsID,sigmaS);
      cstream<<"TimeS"<<
	"CBin="<<cbin<<
	"Event="<<count<<
	"GM="<<&graphM<<
	"GS="<<&graphS<<
	"\n";
      

      for (Int_t ientry2=fentry; ientry2<lentry-1; ientry2++){
	treece->GetEvent(ientry2);
	Double_t x      = param.GetPadRowRadii(sector,row);
	Int_t    maxpad = AliTPCROC::Instance()->GetNPads(sector,row);
	Double_t y = (pad - 2.5 - 0.5*maxpad)*param.GetPadPitchWidth(sector);
	Double_t alpha = TMath::DegToRad()*(10.+20.*(sector%18));	
	Double_t gx = x*TMath::Cos(alpha)-y*TMath::Sin(alpha);
	Double_t gy = y*TMath::Cos(alpha)+x*TMath::Sin(alpha);
	
	Int_t npadS = lastS[sector]-firstS[sector];
	cstream<<"Time"<<
	  "Event="<<count<<
	  "TimeStamp="<<timeStamp<<
	  "CBin="<<cbin<<
	  "x="<<x<<
	  "y="<<y<<
	  "gx="<<gx<<
	  "gy="<<gy<<
	  "Sector="<<sector<<
	  "Row="<<row<<
	  "Pad="<<pad<<
	  "Time="<<time<<
	  "RMS="<<rms<<
	  "Time0="<<mean<<
	  "Sigma0="<<sigma<< 
	  "TimeS0="<<meanS[sector]<<
	  "SigmaS0="<<sigmaS[sector]<<
	  "npad0="<<ngood<<
	  "npadS="<<npadS<<
	  "Max="<<qMax<<
	  "Sum="<<qSum<<
	  "\n";
      }
      treece->GetEvent(ientry);
      fentry = ientry;
      count++;      
      for (Int_t isector=0;isector<72; isector++){
	firstS[isector]=-1; 
	lastS[isector] =-1;
      }
    }
    lastSector=sector;
  }
}
Example #30
0
TF1* calibration_plot(float displacement = 0., int color = 1, char el_name[50] = "\"MQM.9R5.B1\"", string file  = "data/lpair_mumu_2gev.root") {

	vector<float> rec_e;
	vector<float> x_rp;

	H_BeamLine* beam1 = new H_BeamLine( 1,500);
	beam1->fill("data/LHCB1IR5_v6.500.tfs");
	H_RomanPot* rp = new H_RomanPot("RP",420.,3500.);
	beam1->add(rp);
	beam1->alignElement(el_name,displacement,0);

	
	// reading yanwen file
	TF1 * fake = new TF1("fake","1",0,1); // in case of trouble
	TFile* calfile = new TFile(file.c_str());
		if(calfile->IsZombie()) {cout << "Can not open the file : " << file << endl; return fake;}
	TTree* caltree = (TTree*) calfile->Get("h101");
		if(!caltree) {cout << "Can not open the tree.\n"; return fake;}
	delete fake; // forget about it
	

	float phep[4][5];
	caltree->SetBranchAddress("Phep",phep);
	/* phep[0] & phep[3] = protons
	 * phep[1] & phep[2] = muons */

	TLorentzVector mu1, mu2, cms;
	float m_mumu, pz_mumu;
	float gammae_1_central, gammae_2_central;
	float rho;
	int nentries = caltree->GetEntriesFast();
	for (int jentry=0; jentry<nentries;jentry++) {
		caltree->GetEntry(jentry);
		mu1.SetXYZM(phep[1][0],phep[1][1],phep[1][2],0);
		mu2.SetXYZM(phep[2][0],phep[2][1],phep[2][2],0);
		cms = mu1;
		cms += mu2;
		m_mumu = cms.M();
		pz_mumu = cms.Pz();
		rho = sqrt(m_mumu*m_mumu + pz_mumu*pz_mumu);
		gammae_1_central = (  pz_mumu + rho)/2.;
		gammae_2_central = ( -pz_mumu + rho)/2.;

		H_BeamParticle p1;
		p1.smearPos();
		p1.smearAng();
		p1.setE(phep[0][3]);
		p1.computePath(beam1,1);
		if(p1.stopped(beam1)) {
			if(p1.getStoppingElement()->getName()>="RP") {
				p1.propagate(420);
				rec_e.push_back(gammae_1_central);
				x_rp.push_back(p1.getX()/1000.);
			}
		}
	}
	const int npoints = rec_e.size();
	float rece[npoints];
	float xrp[npoints];
	for(int i = 0; i < npoints; i++) {
		rece[i] = rec_e[i];
		xrp[i]  = x_rp[i];
	}
	TGraph* correl = new TGraph(npoints,xrp,rece);
	char title[100];
	sprintf(title,"Calibration of roman pots from central objects variables - %d events",npoints);
	correl->SetTitle(title);
	correl->SetMarkerColor(color);

	correl->Draw("ap");

	sort(x_rp.begin(),x_rp.end());
	TF1* fit1 = new TF1("fit1","[0] + [1] * x + [2] * x * x",x_rp[0],x_rp[npoints-1]);
	correl->Fit("fit1","Q");
//	correl->GetYaxis()->SetTitle("Photon energy from central state (GeV)");
//	correl->GetXaxis()->SetTitle("X position of proton at RP (mm)");

	TCanvas * raoul = new TCanvas();
	correl->Draw("ap");
	return fit1;
}