Esempio n. 1
0
void ExpManager::GetExp1DGraphX(TString NameTitle, double zmin, double zmax, double ymin, double ymax, TString grid){   // do the same thing as for the polar interpolation

    TGraphErrors *fGraph = new TGraphErrors(); //= new TGraph2DErrors(np, x_array, y_array, bz_array, ex, ey, ez);
    fGraph->SetTitle("Experimental Data;X (mm);Magnetic Field (mT)");
    fGraph->SetMarkerSize(1.2);
    fGraph->SetMarkerStyle(20);
    fGraph->SetMarkerColor(kBlue);
    fGraph->SetLineColor(kBlue);
    fGraph->SetLineWidth(2);
       
    int graph_counter = 0 ; 
   for (unsigned i=0; i< fExpY.size(); i++)   {
    //cout <<  " X "  << fExpX.at(i) ;  
        if( (fExpY.at(i) >= ymin && fExpY.at(i) <= ymax) && (fExpZ.at(i) >= zmin && fExpZ.at(i) <= zmax)  && fGrid.at(i)== grid ){
            cout << "  < ----- " ; 
            fGraph->SetPoint(graph_counter,fExpX.at(i),fExpB.at(i));    // CHECK, add new the stuff for emag
            fGraph->SetPointError(graph_counter,fExpXErr.at(i),fExpBErr.at(i));   // CHECK, add new the stuff for emag
            graph_counter++;
        }
        cout << endl ; 
   }

    fGraph->SetTitle(NameTitle+Form(" Experimental Data : %.2f < Depth < %.2f mm  __  %.2f < Y < %.2f mm;X (mm);Magnetic Field (mT)",zmin,zmax,ymin,ymax));
    fGraph->SetName(NameTitle+Form("_Exp_Depth_%.2f_%.2fmm_Y_%.2f_%.2fmm",zmin,zmax,ymin,ymax));
    fGraph->Write();

}
Esempio n. 2
0
void ExpManager::GetSim1DGraphZ(TString NameTitle, double xmin, double xmax, double ymin, double ymax, TString grid ){   // do the same thing as for the polar interpolation

    TGraphErrors *fGraph = new TGraphErrors(); //= new TGraph2DErrors(np, x_array, y_array, bz_array, ex, ey, ez);
    fGraph->SetTitle("Simulated Data;Z (mm);Magnetic Field (mT)");
    fGraph->SetMarkerSize(1.2);
    fGraph->SetMarkerStyle(20);
    fGraph->SetMarkerColor(kBlue);
    fGraph->SetLineColor(kBlue);
    fGraph->SetLineWidth(2);
       
    int graph_counter = 0 ; 
   for (unsigned i=0; i< fExpY.size(); i++)   {
    //cout <<  " X "  << fExpX.at(i) ;  
        if( (fExpX.at(i) >= xmin && fExpX.at(i) <= xmax) && (fExpY.at(i) >= ymin && fExpY.at(i) <= ymax) &&  fGrid.at(i)==grid ){
            fGraph->SetPoint(graph_counter,fExpZ.at(i),fSimB.at(i));    
            fGraph->SetPointError(graph_counter,fExpZErr.at(i),0);   
            graph_counter++;
        } 
   }

    fGraph->SetTitle(NameTitle+Form(" Simulated Data : %.2f < X < %.2f mm  __  %.2f < Y < %.2f mm;Z (mm);Magnetic Field (mT)",xmin,xmax,ymin,ymax));
    fGraph->SetName(NameTitle+Form("_Sim_X_%.2f_%.2fmm_Y_%.2f_%.2fmm",xmin,xmax,ymin,ymax));
    fGraph->Write();

}
Esempio n. 3
0
void Timepix3VolcanoEdge::Finalize() {

	Log << MSG::INFO << "Finalize function !" << endreq;

	// X axis
	vector<double> xg(__max_tot_range, 0);
	vector<double> xg_err(__max_tot_range, 0);

	// Calculate the averages for each bin
	vector<double> Y(__max_tot_range, 0);
	vector<double> Y_err(__max_tot_range, 0);

	for(int i = 1 ; i <= __max_tot_range ; i++) {

		double mean;
		double stdv_sel;

		Log << MSG::INFO << "[" << i << "] --> " << m_TOTEnergyMap[i].size() << " entries" << endreq;
		//MAFTools::DumpVector( m_TOTEnergyMap[i] );

		if( !m_TOTEnergyMap[i].empty() ) {
			mean = MAFTools::CalcMean( m_TOTEnergyMap[i] );
			// As a measurement of the dispersion here I will consider only the point within 1 stdev from the mean
			stdv_sel = MAFTools::CalcStdDev( m_TOTEnergyMap[i] );
		} else {
			mean = 0.;
			stdv_sel = 0.;
		}

		// X
		xg[i-1] = i;

		// Y
		Y[i-1] = mean;
		Y_err[i-1] = stdv_sel;
		Log << MSG::INFO << "mean = " << mean << ", stdv_sel = " << stdv_sel << endreq;
	}

	TGraphErrors * gy = new TGraphErrors(__max_tot_range, &xg[0], &Y[0], &xg_err[0], &Y_err[0] );
	getMyROOTFile()->cd();
	gy->Write("TOTEnergy");

}
Esempio n. 4
0
File: merge.C Progetto: XuQiao/HI
void merge(){
	if (!TClass::GetDict("NBD")) {
		gROOT->ProcessLine(".L /afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/NBD_Glauber_fit/NBD/NBDclass.C++");
	}

	TFile *f;
	f=TFile::Open(Form("G.root"),"ReadOnly");
	TFile *fg = new TFile("graph.root","Update");
	TDirectory *dir;
	TList *def, *tl;
	TKey *key;
	TString dirname;
	for(int sth=0; sth<3; sth++){
	if(sth==0) dirname = "std";
        else if(sth==1) dirname ="Gri055";
        else  dirname ="Gri101";
	dir = f->GetDirectory(dirname);
	def = new TList();
	int iGlau=0;
	//int iGlau=atoi(getenv("GTH"));
	tl = dir->GetListOfKeys();
	for(iGlau=0; iGlau<nGlau; iGlau++){
		key = ((TKey*) tl->At(iGlau));
		NBD* temp = (NBD*)key->ReadObj();
		def->Add(temp);
	}
	
	NBD *n0 = (NBD*)def->At(0);
	n0->calcsys(def);
	TString op;
	for(int option=0;option<3;option++){
	if(option==0) op=Form("%s_Ncoll",dirname.Data());
	else if(option==1) op=Form("%s_Npart",dirname.Data());
	else op=Form("%s_B",dirname.Data());
	TGraphErrors* gr = n0->DrawGraph(option);
	gr->Write(op);
	}
	}
	fg->Close();
	f->Close();
}
Esempio n. 5
0
void draw_BR()
{
  gROOT->ProcessLine(".L ReadGraph.C");

  TFile *f = new TFile("particles.root");
  TH2 *h2_particles = (TH2*)f->Get("h2_particles");
  TH1* h_others = h2_particles->ProjectionX("h_others", 2, 3);
  TH1* h_pion = h2_particles->ProjectionX("h_pion", 1, 1);

  TCanvas *c = new TCanvas("c", "Canvas", 600, 600);
  gStyle->SetOptStat(0);

  TGraphAsymmErrors *gr = new TGraphAsymmErrors(h_others, h_pion);
  gr->SetTitle("Two photons acceptance");
  gr->GetXaxis()->SetTitle("p_{T} [GeV]");
  gr->GetYaxis()->SetTitle("#frac{#eta+#omega}{#pi^{0}}");
  gr->GetXaxis()->SetRangeUser(0., 12.);
  gr->GetYaxis()->SetRangeUser(0., 0.5);
  gr->Draw("AP");

  c->Print("BR.pdf");

  Double_t gx[30], gy[30], egy[30];
  ReadGraph(gr, gx, gy, egy);

  Double_t nothers = h_others->Integral(11,30);
  Double_t npion = h_pion->Integral(11,30);
  Double_t BRbar = nothers / npion;
  Double_t eBRbar = BRbar * sqrt( 1./nothers + 1./npion ); 
  for(Int_t ipt=10; ipt<30; ipt++)
  {
    gy[ipt] = BRbar;
    egy[ipt] = eBRbar;
  }

  TGraphErrors *grout = new TGraphErrors(30, gx, gy, 0, egy);
  grout->SetName("gr_0");
  TFile *fout = new TFile("BR.root", "RECREATE");
  grout->Write();
  fout->Close();
}
Esempio n. 6
0
void PolyFit::drawGraph(double a, double b, double c, double d){

  // Create arrays (which will be needed for feeding the TGraph)
  const unsigned int dataEntries=_xValue.size();
  double x[dataEntries];
  double y[dataEntries]; 
  double xerr[dataEntries];
  double yerr[dataEntries]; 

  // Convert vectors to arrays
  for(unsigned int i=0; i<dataEntries; i++) {
    x[i]=_xValue[i];
    y[i]=_yValue[i];
    xerr[i] = 0;
    yerr[i] = _sigma;
  }

  // Create ROOT file                                                                                                             
  //_theTFile = new TFile("myFit.root","RECREATE");

  // Create TGraph and write to ROOT file 
  TCanvas* c1=new TCanvas("c1","c1",1200,800);
  c1->cd();
  TGraphErrors* linDist = new TGraphErrors(100, x, y, xerr, yerr);
  linDist->SetMarkerStyle(6);
  linDist->Draw("AP");
  linDist->Write("myGraph");

  // Draw fit with calculated parameters
  TF1* fit1 = new TF1("fit1","pol3",0.,100.);
  fit1->SetParameters(a, b, c, d);
  fit1->SetLineColor(46);
  fit1->SetLineWidth(3);
  fit1->Draw();
  fit1->Write();

}
Esempio n. 7
0
void ExpManager::GetExp1DGraphPolar(TString NameTitle, double zmin, double zmax, double anglemin, double anglemax, TString grid) {

    TGraphErrors *fGraph = new TGraphErrors(); //= new TGraph2DErrors(np, x_array, y_array, bz_array, ex, ey, ez);
    fGraph->SetTitle("Experimental Data;Radius (mm);Magnetic Field (mT)");
    fGraph->SetMarkerSize(1.2);
    fGraph->SetMarkerStyle(20);
    fGraph->SetMarkerColor(kBlue);
    fGraph->SetLineColor(kBlue);
    fGraph->SetLineWidth(2);
       
    int graph_counter = 0 ; 
   for (unsigned i=0; i< fExpR.size(); i++)   {
        if( (fExpTheta.at(i) >= anglemin && fExpTheta.at(i) <= anglemax) && (fExpZ.at(i) >= zmin && fExpZ.at(i) <= zmax) && fGrid.at(i)== grid ){ 
            fGraph->SetPoint(graph_counter,fExpR.at(i),fExpB.at(i));    
            fGraph->SetPointError(graph_counter,fExpRErr.at(i),fExpBErr.at(i));   
            graph_counter++;
        }
   }

    fGraph->SetTitle(NameTitle+Form(" Experimental Data : %.2f < Depth < %.2f mm  __  %.2f#circ < Angle < %.2f#circ;Radius (mm);Magnetic Field (mT)",zmin,zmax,anglemin,anglemax));
    fGraph->SetName(NameTitle+Form("_Exp_Depth_%.2f_%.2fmm_Angle_%.2f_%.2fdeg",zmin,zmax,anglemin,anglemax));
    fGraph->Write();

}
Esempio n. 8
0
void sqrtBins(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = false;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = false;

	double PI = 3.14159265359;
	
	
	
	
	cout << "\n";
	if (useBlueBeam && useYellowBeam){cout << "using both beams-----" << endl;}
	if (useBlueBeam && !useYellowBeam){cout << "using blue beam------" << endl;}
	if (!useBlueBeam && useYellowBeam){cout << "using yellow beam----" << endl;}
	cout << "\n";
	if (randomizeSpin){cout << "randomizing spin-----" << endl;}
	//______________________________


  
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________


	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");

	string outFileName = "./resultsNew_4_22/yellowEtaGT0_pairs_4_2.root"; 

	
	
  //______________________________

	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	//SET UP HISTOGRAMS_____________
	//event variable histograms
	/*
	TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
	TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
	TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
	TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
	TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
	TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
	TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
	TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
	TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
	TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);
	*/
	
	//histos for asym analysis	
	double histMin = -PI;
	double histMax =  PI;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",nPhisrBins,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",nPhisrBins,histMin,histMax);
	
	TH1D * hNumberUp_Pt[nPtBins];
	TH1D * hNumberDown_Pt[nPtBins];
	
	TH1D * hNumberUp_Mass[nMassBins]; 
	TH1D * hNumberDown_Mass[nMassBins];

	TH1D * hNumberUp_Eta[nEtaBins];   
	TH1D * hNumberDown_Eta[nEtaBins];
	
	createFiveBins(hNumberUp_Pt,nPhisrBins,histMin,histMax,"hNumUp_Ptbin_");
	createFiveBins(hNumberDown_Pt,nPhisrBins,histMin,histMax,"hNumDwn_Ptbin_");
	createFiveBins(hNumberUp_Mass,nPhisrBins,histMin,histMax,"hNumUp_Massbin_");
	createFiveBins(hNumberDown_Mass,nPhisrBins,histMin,histMax,"hNumDwn_Massbin_");
	createFourBins(hNumberUp_Eta,nPhisrBins,histMin,histMax,"hNumUp_Etabin_");
	createFourBins(hNumberDown_Eta,nPhisrBins,histMin,histMax,"hNumDwn_Etabin_");
	
	TH1D* hAut_Pt[nPtBins];
	TH1D* hAut_Mass[nMassBins];
	TH1D* hAut_Eta[nEtaBins];

	createFiveBins(hAut_Pt, nPhisrBins, histMin, histMax, "hAut_Ptbin_");
	createFiveBins(hAut_Mass, nPhisrBins, histMin, histMax, "hAut_Massbin_");
	createFourBins(hAut_Eta, nPhisrBins, histMin, histMax, "hAut_Etabin_");
	
	
	/*
	TH1D* polOfBinUp_Pt[nPtBins][binNumber];
	TH1D* polOfBinDown_Pt[nPtBins][binNumber];
	TH1D* polOfBinUp_Mass[nMassBins][binNumber];
	TH1D* polOfBinDown_Mass[nMassBins][binNumber];
	TH1D* polOfBinUp_Eta[nEtaBins][binNumber];
	TH1D* polOfBinDown_Eta[nEtaBins][binNumber];
	createPolHists(polOfBinUp_Pt, 25, 0, 1, "hPolOfBinUp_Ptbin_");
	createPolHists(polOfBinDown_Pt, 25, 0, 1, "hPolOfBinDown_Ptbin_");
	createPolHists(polOfBinUp_Mass, 25, 0, 1, "hPolOfBinUp_Massbin_");
	createPolHists(polOfBinDown_Mass, 25, 0, 1, "hPolOfBinDown_Massbin_");
	createPolHists(polOfBinUp_Eta, 25, 0, 1, "hPolOfBinUp_Etabin_");
	createPolHists(polOfBinDown_Eta, 25, 0, 1, "hPolOfBinDown_Etabin_");
  */
	
	TH1D* polOfBin_Pt[nPtBins][nPhisrBins];
	TH1D* polOfBin_Mass[nMassBins][nPhisrBins];
	TH1D* polOfBin_Eta[nEtaBins][nPhisrBins];
	createPolHists(polOfBin_Pt, 25, 0, 1, "hPolOfBin_Ptbin_");
	createPolHists(polOfBin_Mass, 25, 0, 1, "hPolOfBin_Massbin_");
	createPolHistsEta(polOfBin_Eta, 25, 0, 1, "hPolOfBin_Etabin_");
	
	
	//HISTOGRAMS TO HOLD PT MASS AND ETA VALES
	TH1D* hPt[nPtBins];
	TH1D* hMass[nMassBins];
	TH1D* hEta[nEtaBins];
	createFiveBins(hPt, 500, 3.0, 50, "hPt_Ptbin_");
	createFiveBins(hMass, 1000, 0.0, 100, "hMass_Massbin_");
	createFourBins(hEta, 20, -1.4, 1.4, "hEta_Etabin_");
	
	
	//TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
	//TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);
	//______________________________
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	

	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[nPhisrBins];
	double polOfBinSumUp[nPhisrBins];
	
	double avgPerrorOfBinUp[nPhisrBins];
	double pErrorOfBinUp[nPhisrBins];
	
	double avgPolOfBinDown[nPhisrBins];
	double polOfBinSumDown[nPhisrBins];
	
	double avgPerrorOfBinDown[nPhisrBins];
	double pErrorOfBinDown[nPhisrBins];
	
	for (int i=0; i<nPhisrBins; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	//______________________________
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[0];
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	double blueLowLimitEta  = 0;
	double yellowLowLimitEta = 0;  //this is for testing individual beams
	
	
	//hiLimitEta = 0;
	
	if (fullEta)
	{
		assert(hiLimitEta > 0);
		assert(lowLimitEta < 0);
	}
	
	cout << "Pt  between " << lowLimitPt << " and " << hiLimitPt << endl;
	cout << "M   between " << lowLimitMass << " and " << hiLimitMass << endl;
	cout << "Eta between " << lowLimitEta << " and " << hiLimitEta << endl;
	//______________________________
	
	//*
	
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
		//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int test = 0;
	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+100000){break;}

		pairTree->GetEntry(iPair);

		
		if (pair1->withinRadius(0.05, 0.3))
		{

			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;

			StTriggerId trigId = pair1->triggerIds();
						
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 

				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				//blue low limit eta is 0 yellow high limit eta is 0 this is a test
				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= yellowLowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						fillCorrectPtBin(hNumberUp_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
			
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						fillCorrectPtBin(hNumberUp_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
	}//end pion tree loop
	

	
	
	//CALCULATE ASYMMETRY BIN BY BIN
	cout << "\n";
	cout << "<----CALCULATING ASYMMETRY---->" << endl;
	cout << "\n";
	
	
	
	double asymsPt[5]; 
	double asymsMass[5];
	double asymsEta[4];

	double asymsPtE[5];
	double asymsMassE[5];
	double asymsEtaE[4];
	
	cout << "\n";
	cout << "\n";

	cout << "\n \n calcing pt asym " << endl;
	calcAsym(hAut_Pt, hNumberUp_Pt, hNumberDown_Pt, polOfBin_Pt, asymsPt, asymsPtE);
	cout << "\n";
	cout << "\n";
	cout << "\n \n calcing mass asym " << endl;
	calcAsym(hAut_Mass, hNumberUp_Mass, hNumberDown_Mass, polOfBin_Mass, asymsMass, asymsMassE);
	cout << "\n";
	cout << "\n";
	if (fullEta)
	{
		cout << "\n \n calcing eta asym " << endl;	
		calcAsymEta(hAut_Eta, hNumberUp_Eta, hNumberDown_Eta, polOfBin_Eta, asymsEta, asymsEtaE);
	}

	
	
	
	//PLOT ASYMMETRIES
	cout << "\n";
	cout << "<----PLOTTING ASYMMETRIES---->" << endl;
	cout << "\n";
	
	double ptPoints[5];
	double ptPointsErr[5];
	double massPoints[5];
	double massPointsErr[5];
	double etaPoints[5];
	double etaPointsErr[5];
	
	
	getPtPoints(hPt, ptPoints, ptPointsErr);
	getMassPoints(hMass, massPoints, massPointsErr);
	if(fullEta){getEtaPoints(hEta, etaPoints, etaPointsErr);}
	
	
	TCanvas* cAsymPt = new TCanvas();
	TGraphErrors* gAsymPt = new TGraphErrors(nPtBins,ptPoints,asymsPt,ptPointsErr,asymsPtE);
	
	gAsymPt->Draw("AP");
	
	TCanvas* cAsymMass = new TCanvas();	
	TGraphErrors* gAsymMass = new TGraphErrors(nMassBins,massPoints,asymsMass,massPointsErr,asymsMassE);
	
	gAsymMass->Draw("AP");
	
	if (fullEta)
	{
		TCanvas* cAsymEta = new TCanvas();
		TGraphErrors* gAsymEta = new TGraphErrors(nEtaBins,etaPoints,asymsEta,etaPointsErr,asymsEtaE);
		gAsymEta->Draw("AP");
		
	}
	
	
	
	
	
	//DRAW HISTOGRAMS
	cout << "\n";
	cout << "<----DRAWING HISTOGRAMS---->" << endl;
	cout << "\n";
	
	
	
	
	TCanvas* cPt   = new TCanvas("cPt","cPt",1200,600);
	TCanvas* cMass = new TCanvas("cMass","cMass",1200,600);
	if(fullEta){TCanvas* cEta  = new TCanvas("cEta","cEta",800,600);}
	
	//drawAllBins(hPt, cPt);
	//drawAllBins(hMass, cMass);
	
	drawFiveBins(hAut_Pt, cPt);
	drawFiveBins(hAut_Mass, cMass);
  if(fullEta){drawFourBins(hAut_Eta, cEta);}
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");
	
	writeFiveBins(hPt);
	writeFiveBins(hMass);
	writeFourBins(hEta);
	writeFiveBins(hAut_Pt);
	writeFiveBins(hAut_Mass);
	if(fullEta){writeFourBins(hAut_Eta);}
	gAsymPt->Write();
	gAsymMass->Write();
	if(fullEta){gAsymEta->Write();}
	/*
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.png");
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.pdf");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.png");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.pdf");
	
	if(fullEta)
	{
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.png");
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.pdf");
	}
	*/
	
	
	for (int ibin = 1; ibin <= 16; ibin++)
	{
		
		cout << "bin " << ibin << endl;
		cout << "Nup   = " << hNumberUp_Mass[0]->GetBinContent(ibin) << endl;
		cout << "Ndown = " << hNumberDown_Mass[0]->GetBinContent(ibin) << endl;

	}
	
	

	cout << "<----END---->" << endl; 


}
Esempio n. 9
0
void histoLoader_new(char* arg){
	
	//Take the arguments and save them into respective strings
	std::string infileName, outfileName;
	std::string inF, outF;
	std::string inPrefix, outPrefix;
	std::string layers;
	std::istringstream stm(arg);
	
	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/analysisRoot/";
	outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/moliRoot/";
	
	outF = "moli_all.root";
	outfileName = outPrefix + outF;

	Double_t p0 = 248.5;
	Double_t p1 = 222;
	Double_t p2 = 275;

	int i = 0;
	Double_t thetaRMS[4];
	while(true){
		if( std::getline(stm, layers, ' ') ){
			inF        = "errorAnalysis_" + layers + "layers.root";
			infileName = inPrefix + inF;

			TFile *inFile = new TFile(infileName.c_str());
			TF1 *func = (TF1*)inFile->Get("gausFuncCuts");
			Double_t RMS1;
			Double_t RMS2;	
			RMS1 = TMath::Abs(func->GetParameter("Sigma1"));
			RMS2 = TMath::Abs(func->GetParameter("Sigma2"));
			std::cout << "RMS1_" << i << " = " << RMS1 << std::endl;
			std::cout << "RMS2_" << i << " = " << RMS2 << std::endl;
			if( RMS1 > RMS2 ){
				thetaRMS[i] = RMS2;
			} else thetaRMS[i] = RMS1;
			inFile->Close();
		}
		else break;
		i++;
	}
	
	TFile *outFile = new TFile(outfileName.c_str(), "RECREATE");

	Double_t x_data[4] = {2.54 / 4, 2.54 / 2, 2.54*3/4, 2.54};
	Double_t xerr[4]   = {0.005, 0.005, 0.005, 0.005};
	Double_t yerr[4]   = {0.197, 0.272, 0.351, 0.136};

	Double_t x0[20] = {0};
	Double_t y0[20] = {0};
	Double_t x1[20] = {0};
	Double_t y1[20] = {0};
	Double_t x2[20] = {0};
	Double_t y2[20] = {0};
	int j=1;
	for (Double_t h=0.15; j<20; j++) {
		x0[j] = h;
		y0[j] = moliFunc(x0[j], p0);
		h+=0.15;
		std::cout << "x0[" << j << "] = " << x0[j] << std::endl;
		std::cout << "y0[" << j << "] = " << y0[j] << std::endl;
	}
	int k=1;
	for (Double_t h=0.15; k<20; k++) {
		x1[k] = h;
		y1[k] = moliFunc(x1[k], p1);
		h+=0.15;
		std::cout << "x1[" << k << "] = " << x1[k] << std::endl;
		std::cout << "y1[" << k << "] = " << y1[k] << std::endl;
	}
	int l=1;
	for (Double_t h=0.15; l<20; l++) {
		x2[l] = h;
		y2[l] = moliFunc(x2[l], p2);
		h+=0.15;
		std::cout << "x2[" << l << "] = " << x2[l] << std::endl;
		std::cout << "y2[" << l << "] = " << y2[l] << std::endl;
	}
	
	TGraph *moliGraph0 = new TGraph(20, x0, y0);
	TGraph *moliGraph1 = new TGraph(20, x1, y1);
	TGraph *moliGraph2 = new TGraph(20, x2, y2);
	TGraphErrors *dataGraph = new TGraphErrors(4, x_data, thetaRMS, xerr, yerr);

	TF1 *moliFit = new TF1("moliFit", moliFunc_Fit, 0, 10, 1);
	moliFit->SetLineColor(6);
	moliFit->SetLineWidth(2);
	moliFit->SetParameters(0, 13.6);
	moliFit->SetParNames("Constant");
	moliFit->SetParLimits(0, 0, 30);
//	moliFit->SetParLimits(1, 0, 0.25);
	dataGraph->Fit("moliFit");

	std::cout << "thetaRMS[0] = " << thetaRMS[0] << std::endl;
	std::cout << "thetaRMS[1] = " << thetaRMS[1] << std::endl;
	std::cout << "thetaRMS[2] = " << thetaRMS[2] << std::endl;
	std::cout << "thetaRMS[3] = " << thetaRMS[3] << std::endl;
	//std::cout << "thetaRMS[4] = " << thetaRMS[4] << std::endl;

	moliGraph0->SetLineColor(2);
	moliGraph0->SetLineWidth(1.5);
	moliGraph1->SetLineColor(8);
	moliGraph1->SetLineWidth(1.5);
	moliGraph2->SetLineColor(9);
	moliGraph2->SetLineWidth(1.5);
	dataGraph ->SetMarkerStyle(22);		

	moliGraph0->Draw("AC");	
	moliGraph1->Draw("PC");	
	moliGraph2->Draw("PC");	
	dataGraph->Draw("P");
	//moliFit->Draw("*");	

	TLegend *leg = new TLegend(0.1, 0.7, 0.48, 0.9);
	leg->SetHeader("Legend");
//	gStyle->SetLegendFillColor(0);
	leg->AddEntry(moliGraph1, "Moliere Distribution for p = 222 MeV/c", "LP");
	leg->AddEntry(moliGraph0, "Moliere Distribution for p = 248.5 MeV/c", "LP");
	leg->AddEntry(moliGraph2, "Moliere Distribution for p = 275 MeV/c", "LP");
	leg->AddEntry(dataGraph, "The angular RMS for varying Pb thicknesses", "LP");
	leg->AddEntry(moliFit, "The angular RMS data fit to the Moliere Distribution", "LP");
	leg->Draw();

	moliGraph0->Write();	
	moliGraph1->Write();	
	moliGraph2->Write();	
	moliFit->Write();
	dataGraph->Write();
	
	outFile->Close();	
}
Esempio n. 10
0
void simul(int Nevents = 200000, double Twist_width = 0.04, double Asy_wdith   = 0.06){

    char name[200];

    TFile *OutFile=new TFile("Simu3.root","recreate");
    OutFile->cd();
    TRandom3 ran;

    //20-25% events have ~1092 multiplicity
    const int MEAN_MULT =1092,SIGMA_MULT=86 ;//Mean and rms of total multiplicity (det0+det1+det2)
    int min=MEAN_MULT-5*SIGMA_MULT;
    int max=MEAN_MULT+5*SIGMA_MULT;
    if(min<0) min=0;
    TF1 *Mult_func=new TF1("mult_func","exp(-(x-[0])*(x-[0])/(2*[1]*[1]))",min,max);
    Mult_func->SetParameter(0,MEAN_MULT );
    Mult_func->SetParameter(1,SIGMA_MULT);
    //

    TFile* fout = new TFile("toyout.root","recreate");
    TF1* v2_func=new TF1("v2_func","x*exp(-(x*x+[0]*[0])/(2*[1]))*TMath::BesselI0(x*[0]/[1])",0,0.40);
    v2_func->SetParameter(0,9.13212e-02);
    v2_func->SetParameter(1,1.20361e-03);
    //

    Float_t v2   =0          ;//true v2   at eta=0, this will be the refer
    Float_t Psi2 =0          ;//true Psi2 at eta=0
    
    float vncut[] = {0.00, 0.04, 0.06,0.1, 0.12, 0.14, 0.15};
    
    TProfile* hpr_qn[2];
    for (int iq=0; iq<2; iq++) {
        sprintf(name, "hpr_qn_%d", iq); hpr_qn[iq] = new TProfile(name,"", 7, 0, 7);
    }
    TH1* hebin = new TH1D("hebin","", 7, 0, 7);
    TH1* hmul = new TH1D("hmul","", 2000, 0, 2000);
    TH1* hmuleta = new TH1D("hmuleta","", NETA, -ETAMAX, ETAMAX);
    TH1* hmulphi = new TH1D("hmulphi","", 120 , -PI, PI);
    TH1* hv2 = new TH1D("hv2","",1000, 0, 0.5);
    TH1* hv4 = new TH1D("hv4","",1000, 0, 0.5);
    double q2[2];
    double q4[2];
    float qw;
    for(int iev=0; iev<Nevents; iev++){

        if(iev%10000==0) cout<<iev<<endl;

        v2     = v2_func->GetRandom();//0.05;//True v2
        Psi2   = ((ran.Rndm()-0.5)*2*PI)/2.0; //True Psi_2 angle
       
       // int ntrk =  1092;
        int ntrk =  8000;
        qw = 0;
        std::memset(q2, 0, sizeof(q2) );
        std::memset(q4, 0, sizeof(q4) );
        
        for(int itrk =0; itrk<ntrk; itrk++){

            float phi = (ran.Rndm()-0.5)*2*PI;//random angle for the particle

            float trk_vn   =  v2 ;
            float trk_psin =  Psi2;
            
            phi =add_flow(phi ,trk_vn, trk_psin);
            q2[0] += cos(2*phi); q2[1] += sin(2*phi);
            q4[0] += cos(4*phi); q4[1] += sin(4*phi);
            qw++;

        }//end of itrk
        
        double mv2 = sqrt(q2[0]*q2[0] + q2[1]*q2[1]);
        double mv4 = sqrt(q4[0]*q4[0] + q4[1]*q4[1]);
        
        
        mv2 = mv2/qw;
        mv4 = mv4/qw;
        
        int ebin = 0;

        for (int j=0; j<7; j++) {
            if(mv2>= vncut[7-1-j]){
                ebin = 7-1-j;
                break;
            }
        }
        
        hv2->Fill(  mv2 );
        hv4->Fill(  mv4 );
        
        hpr_qn[0]->Fill(ebin, mv2);
        hpr_qn[1]->Fill(ebin, mv4);
        hebin->Fill( ebin );
        
    }//end of iev
  
    
    float xx[7] = {0};
    float xxE[7] = {0};
    float yy[7] = {0};
    float yyE[7] = {0};
    
    for (int j=0; j<7; j++) {
        xx[j] =hpr_qn[0]->GetBinContent( j+1); xxE[j] =hpr_qn[0]->GetBinError( j+1);
        yy[j] =hpr_qn[1]->GetBinContent( j+1); yyE[j] =hpr_qn[1]->GetBinError( j+1);
    }
    
    TGraphErrors* gr = new TGraphErrors(7,xx, yy, xxE, yyE);
    
    hv2->Write();
    hv4->Write();
    gr->SetName("gr");
    gr->Write();
    hebin->Write();
    hpr_qn[0]->Write();
    hpr_qn[1]->Write();
    v2_func->Write();
    
    cout<<"Task ends"<<endl;
}//end of sim
Esempio n. 11
0
void sqrtByFill(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = true;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = true;
	
	double PI = 3.14159265359;
	
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________
	
	
	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");
	
	string outFileName = "./resultsNew_4_22/pairsFrom4_2ByFill.root"; 
	
	
	
  //______________________________
	
	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	

	
	double histMin = -PI;
	double histMax =  PI;
	const int binNumber = 16;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);
	TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);

	
	TH1D* polOfBin[16];
	for (int i = 0; i < 16; i++)
	{
		stringstream ss;
		ss << i;
				
		string fullname = "hPolOfBin_phiSRbin_" + ss.str();
		cout << fullname << endl;
		
		polOfBin[i] = new TH1D(fullname.c_str(),fullname.c_str(),25,0,1);
		
	}
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	
	
	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[binNumber];
	double polOfBinSumUp[binNumber];
	
	double avgPerrorOfBinUp[binNumber];
	double pErrorOfBinUp[binNumber];
	
	double avgPolOfBinDown[binNumber];
	double polOfBinSumDown[binNumber];
	
	double avgPerrorOfBinDown[binNumber];
	double pErrorOfBinDown[binNumber];
	
	for (int i=0; i<binNumber; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[3];  //set up do only do eta bin 3
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	
	
	
	//______________________________
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
	//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	
	vector<double> fillAsyms;
	vector<double> fillAsymsE;
	vector<double> fillVec;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int runsProcessed = 0;
	
	double currentFillNo = 0;
	double currentRunNo = 0;

	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+300000){break;}
		
		pairTree->GetEntry(iPair);
		
		//if (runsProcessed > 4){break;} 
		
		
		if (pair1->runInfo().beamFillNumber(1) != currentFillNo && currentFillNo != 0 && currentFillNo != 16427)
		//if (pair1->runInfo().runId() != currentRunNo && currentRunNo != 0)
		{
			runsProcessed++;

			cout << "runsProcessed " << runsProcessed << endl;
			
			double* asym = new double();
			double* asymE = new double();
			calcAsyms(hAut, hNumberUp, hNumberDown, polOfBin, asym, asymE);
						
			fillAsyms.push_back(*asym);
			fillAsymsE.push_back(*asymE);
			fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
			
		}
		else if (currentRunNo == 16427)
		{
			//fillAsyms.push_back(*asym);
			//fillAsymsE.push_back(*asymE);
			//fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
		
		}
		
		
		currentRunNo = pair1->runInfo().runId();
		currentFillNo = pair1->runInfo().beamFillNumber(1);
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 
				
				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= lowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						hNumberUp->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						/*if (iPair > 39000)
						{
							cout << "polarization = " << polarizationOfFill_B[blueFillNo] << "  " << blueFillNo << endl;
						}*/
						
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						hNumberDown->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						hNumberUp->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
						
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						hNumberDown->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
		
		
	}//end pion tree loop
	
	
	cout << "out of tree loop" << endl;
	
	
	cout << fillAsyms.size() << endl;
	
	
	TGraphErrors* gAsymVsFill = new TGraphErrors(fillAsyms.size(), &fillVec[0], &fillAsyms[0], 0, &fillAsymsE[0]);
	
	gAsymVsFill->Draw("AP");
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");

	gAsymVsFill->Write();

}
Esempio n. 12
0
map<int,vector<double> > RPCChambersCluster::getReconstructedHits(vector<unsigned> vectorOfReferenceChambers, const int & timeWindow,const int & timeReference,bool & isVerticalTrack,map<int,double> & scintilatorsCoordinates,const bool & keepRecoTrack,TFile * fileForRecoTracks,const int & eventNum,const double & correlationFactor, const ESiteFileType & fileType){
  
  // 
  
  map<int,vector<double> > mapOfHits; //
  // the default value for Chi2goodness is 20 
  //double best_chi2goodnes_value = Chi2goodness+10 ; // this variable is used as reference so that it holds the best chi2 found for a track, so its used only a track with better chi2 to be accepted
  double currentBestCorrFact = -2;
  
  int lastFitPoint = 0;
  
  for (int i = 0 ; i < this->getNumberOfChambers() ; i++){
    this->getChamberNumber(i+1)->findAllClustersForTriggerTimeReferenceAndTimeWindow(timeReference,timeWindow,5);
    //cout  << "Chamber is " << i+1 << endl;
  }
  
  vector<vector<int> > vectorOfClusterNumberCombinations;  
  
  if (fileType == kIsCERNrawFile ){
    
    assert(vectorOfReferenceChambers.size() == 3 );
    
    lastFitPoint = 9;
    
    for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){
      for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){
	for( int k = 0 ; k < this->getChamberNumber(vectorOfReferenceChambers[vectorOfReferenceChambers.size()-1])->getNumberOfClusters() ; k++ ){
	  
	  vector<int> singleCombination;
	  
	  singleCombination.push_back(i+1);
	  singleCombination.push_back(j+1);
	  singleCombination.push_back(k+1);
	  
	  for (int f = 0 ; f < singleCombination.size() ; f++){	  
	    if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue;	  
	    // don't insert combination if there is too big cluster. 
	  }
	  
	  vectorOfClusterNumberCombinations.push_back(singleCombination);
	  
	}
      }
    }
  }
  
  if (fileType == kIsBARCrawFile || fileType == kIsGENTrawFile ){
    // add implementation for BARC and Ghent stand . 
    lastFitPoint = 5;
    
    assert(vectorOfReferenceChambers.size() == 2);
    
    for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){
      for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){
      
	vector<int> singleCombination;
	singleCombination.push_back(i+1);
	singleCombination.push_back(j+1);
	
	for (int f = 0 ; f < singleCombination.size() ; f++){
	  if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue;
	  // don't insert combination if there is too big cluster. 
	}
	
	vectorOfClusterNumberCombinations.push_back(singleCombination);
      
      }
    }
  }
  
  string topScintToString, botScintToString;
  
  for (int combinationsVectorElement = 0 ; combinationsVectorElement < vectorOfClusterNumberCombinations.size() ; combinationsVectorElement ++){
    
    // the partition logic start  here - track could pass more than one partition
    
    int direction = 0 ; // direction should describe how the partition changes from one reference chamber to another. It 
    vector<int> RefChamberClusterPartition;
    bool positive = false;
    bool negative = false;
    int partitionPenetrated = 1;
    
    // the Y coordinate is the partition number (1 2 or 3 - A B or C)
    
    vector<int> clusterNum = vectorOfClusterNumberCombinations.at(combinationsVectorElement);
    
    for (int ii = 0; ii < clusterNum.size() ; ii++){
      RefChamberClusterPartition.push_back(this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum.at(ii)).at(1));
    }
    
    isVerticalTrack = true;
    
    for ( int ii = 0; ii < RefChamberClusterPartition.size() - 1 ; ii++ ){
      direction = (RefChamberClusterPartition.at(ii) - RefChamberClusterPartition.at(ii+1));
      if (direction != 0) { 
	direction = direction/abs(direction); 
	partitionPenetrated++;
      } // get only the sign ( +1 or -1)
      if (direction && direction == -1)  { positive = true; isVerticalTrack = false; }
      if (direction && direction == 1 )  { negative = true; isVerticalTrack = false; }
    }
    
    if ( positive && negative ) continue;
    // cannot have a track that goes in both direction
    
    /*
    TH1F * histXZ = new TH1F("fitHistogram","XZ plane",110,0,11);
    histXZ->GetYaxis()->SetRangeUser(-20,52);
    histXZ->SetMarkerColor(kBlue);
    histXZ->SetMarkerStyle(kCircle);
    histXZ->GetXaxis()->SetTitle("Shelf number");
    histXZ->GetYaxis()->SetTitle("Channel number");
    */
    
    TF1 * fitfunc = new TF1("FitTrack","[0]+x*[1]",0,lastFitPoint+1);
    
    TGraphErrors * graphXZ = new TGraphErrors();
    graphXZ->GetXaxis()->SetTitle("Shelf number");
    graphXZ->GetYaxis()->SetTitle("Channel number");
    //graphXZ->SetLineColor(0);
    graphXZ->SetMarkerColor(kBlack);
    graphXZ->SetMarkerStyle(kFullCircle);
    graphXZ->SetName("fit graph");
    graphXZ->SetTitle("XZ plane");
    graphXZ->GetXaxis()->SetTitle("Muon station");
    graphXZ->GetYaxis()->SetTitle("Channel number");
    
    fitfunc->SetLineColor(kBlue);        
    
    vector<double> coordinates;
    double xCoordinate = 0;
    int yCoordinate = 0;
    int zCoorinate = 0;
    
    
    for (int ii=0 ; ii < vectorOfReferenceChambers.size() ; ii++){
      
      coordinates = this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum[ii]);
      xCoordinate = coordinates.at(0);
      yCoordinate = coordinates.at(1);
      zCoorinate = 10*vectorOfReferenceChambers[ii];
      Double_t errorValue = this->getChamberNumber(vectorOfReferenceChambers[ii])->getSizeOfCluster(clusterNum[ii]);
//       histXZ->SetBinContent(zCoorinate,xCoordinate);  
//       histXZ->SetBinError(zCoorinate,errorValue/2);
      //cout << xCoordinate << " " << yCoordinate << endl;
      graphXZ->SetPoint(ii,vectorOfReferenceChambers[ii],xCoordinate);
      graphXZ->SetPointError(ii,0,errorValue/2);
    }
    
    Double_t params[2];
    graphXZ->Fit(fitfunc,"RFQ");
    fitfunc->GetParameters(params);
    
    //cout << "par1 " << params[0] << " par2 " << params[1] << " chi2 " << fitfunc->GetChisquare() << endl;
    // The resudials - difference between estimated fit value and the middle of the nearest cluster
    
    int prevReference = 0 , nextReference = 0 , prevReferencePartition = 0 , nextReferencePartition = 0; 
    bool currentChamberIsReference = false;
    int startCounter = 0, endCounter = 0;
    
    if ( abs(graphXZ->GetCorrelationFactor()) >= correlationFactor && abs(graphXZ->GetCorrelationFactor()) > currentBestCorrFact ) {
      // in case of only one partition, get the partition number of the first reference point
      currentBestCorrFact = abs(graphXZ->GetCorrelationFactor());
      
      int referenceChambersIncrementor = 0;
      bool negativeChannelNumberIsFound = false;
      
      // ---------
            
      for ( int currentChNumber = 0 ; currentChNumber < this->getNumberOfChambers() ; currentChNumber++ ) {
	// check where the chamber is according to the reference chambers
	vector<double> vectorOfpartitionsAndHit;
	double channelNum = fitfunc->Eval(currentChNumber+1);

	/** four cases 1. the chamber is before the first reference 2. the chamber is after the last reference 3. the chamber is between two references 4. the chamber is a reference */
	
	for(int refCheck = 0 ; refCheck < vectorOfReferenceChambers.size(); refCheck++){
	  // find the surounding references
	  if (currentChNumber+1 == vectorOfReferenceChambers.at(refCheck)){
	    currentChamberIsReference = true;
	    break;
	  }
	  if ( vectorOfReferenceChambers.at(refCheck) > currentChNumber+1 && refCheck == 0 ){
	    // its before the first reference chamber
	    nextReference = vectorOfReferenceChambers.at(refCheck);
	    nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    break;
	    
	  }
	  
	  if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && refCheck == vectorOfReferenceChambers.size() - 1 ){
	    // its after the last chamber
	    prevReference = vectorOfReferenceChambers.at(refCheck);
	    prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    break;    
	  }
	  if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && vectorOfReferenceChambers.at(refCheck+1) > currentChNumber+1 ){
	    // its between two references
	    prevReference = vectorOfReferenceChambers.at(refCheck) ;
	    nextReference = vectorOfReferenceChambers.at(refCheck+1);
	    prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck+1]).at(1);
	    break;    
	  }
	}
	
	// end of partition possibilities
	
	if(!currentChamberIsReference){
	  
	  if (nextReference && prevReference == 0){
	    if (positive){
	      prevReferencePartition = 1;      
	    }
	    if(negative){
	      prevReferencePartition = this->getChamberNumber(1)->getClones();      
	    }    
	  }
	  
	  if (prevReferencePartition && nextReferencePartition == 0){
	    if (positive){
	      nextReferencePartition = this->getChamberNumber(1)->getClones();      
	    }
	    if(negative){
	      nextReferencePartition = 1;      
	    }    
	  }
	  
	  if (partitionPenetrated == 1 ){
	    prevReferencePartition = yCoordinate;
	    nextReferencePartition = yCoordinate;    
	    
	    int firstRef = vectorOfReferenceChambers.at(0);
	    int lastRef = vectorOfReferenceChambers.at(vectorOfReferenceChambers.size() - 1);
	    int ccham =  currentChNumber+1;
	    
	    if(! (lastRef > ccham && firstRef < ccham) ){
	      // all partitions are possible, chambers are out of the reference scope
	      prevReferencePartition = this->getChamberNumber(1)->getClones(); 
	      nextReferencePartition = 1; // 3 in case of ecap chamber      
	    }
	  }
	  
	  if (positive){ startCounter = prevReferencePartition; endCounter = nextReferencePartition; }
	  else { startCounter = nextReferencePartition ; endCounter = prevReferencePartition ; }
	  
	  for (int currentCounter = startCounter ; currentCounter <= endCounter; currentCounter ++ ){
	    assert(currentCounter > 0 && currentCounter < 4);
	    vectorOfpartitionsAndHit.push_back(currentCounter);    
	  }
	}
	
	else{
	  vectorOfpartitionsAndHit.push_back(this->getChamberNumber(currentChNumber+1)->getXYCoordinatesOfCluster(clusterNum[referenceChambersIncrementor]).at(1));
	  referenceChambersIncrementor ++;
	}
	
	prevReference = 0 ; nextReference = 0 ; prevReferencePartition = 0 ; nextReferencePartition = 0; currentChamberIsReference = false;
	//cout << "Chamber " << l+1 << " " <<  coordinates.at(1) << " " << fitfunc->Eval(l+1) << " " << endl;
	
	int channelNumberToStore = channelNum;
	if (channelNumberToStore < 96/this->getChamberNumber(1)->getClones()){
	  channelNumberToStore += 1;
	} // add one to represent the fired channel, or none if the channel is on the right border
	
	vectorOfpartitionsAndHit.push_back(channelNumberToStore); // the last element is the number of the channel
	
	// Debug lines
	/**
	cout << "Chamber is " << currentChNumber+1 << " partitions " ;
	for (int thesize = 0 ; thesize < vectorOfpartitionsAndHit.size() - 1; thesize++){
	  cout << vectorOfpartitionsAndHit.at(thesize) << " " ;
	}
	
	cout << "channel " << vectorOfpartitionsAndHit.at(vectorOfpartitionsAndHit.size()-1) << endl;
	*/
	
	mapOfHits[currentChNumber+1] = vectorOfpartitionsAndHit;
	
      }      
      
      // ---------- scintilators coordinates estimate
      
      for (int scintNum = 0 ; scintNum < 31 ; scintNum++){
	if(this->getTriggerObjectNumber(1)->getChannel(scintNum+1)->hasHit() && vectorOfClusterNumberCombinations.size() == 1 ) {
	  if (scintNum < 10) { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(0); topScintToString = boost::lexical_cast<string>(scintNum+1); }
	  else { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(lastFitPoint+1); botScintToString = boost::lexical_cast<string>(scintNum+1); }
	}
      }      
    }
    
    // get only vertical tracks from the A partition if there are only two scint hits
    if (keepRecoTrack && isVerticalTrack && !mapOfHits.empty() && scintilatorsCoordinates.size() == 2){
      
      graphXZ->SetName(boost::lexical_cast<string>(eventNum).c_str());
      string partition;
      if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 1) partition = "A";
      else if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 2) partition = "B";
      else partition = "C";
      
      graphXZ->SetTitle(("Correlation factor is "+boost::lexical_cast<string>(graphXZ->GetCorrelationFactor()) + " trigger channels top: " + topScintToString + " bottom: " + botScintToString ).c_str());
      if(abs(graphXZ->GetCorrelationFactor()) >= correlationFactor) {
	
	string scintCombination="_"+topScintToString+"_"+botScintToString+"_"+partition;
	TDirectory * dir = fileForRecoTracks->GetDirectory(scintCombination.c_str(),true);
	
	if(!dir) {  
	  //fileForRecoTracks->ls();
	  fileForRecoTracks->mkdir(scintCombination.c_str()) ;
	  fileForRecoTracks->cd("");
	} 
	
	fileForRecoTracks->cd(scintCombination.c_str());
	//cout << fileForRecoTracks->GetPath() << endl;
      }
      else{ fileForRecoTracks->cd("") ; fileForRecoTracks->cd("badTracks") ; }
      
      graphXZ->Write(graphXZ->GetName(),TObject::kOverwrite);
      fileForRecoTracks->cd("");
      //fileForRecoTracks->Write(graphXZ->GetName(),TObject::kOverwrite);
    }
    
    fitfunc->Delete();
    //histXZ->Delete();
    graphXZ->Delete();
    
  }  
  
  return mapOfHits;
}
Esempio n. 13
0
void cetaflatHFP12(int nIterN=1, double Ethr1=10, double Ethr2=150) {
  
  gStyle->SetOptLogz(0);
  gStyle->SetMarkerSize(0.7);
  gStyle->SetMarkerStyle(20);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);
  gStyle->SetTitleOffset(1.7,"Y");
  gStyle->SetTitleOffset(0.9,"X");
  //gStyle->SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  gStyle->SetPadLeftMargin(0.18);
  //gStyle->SetNdivisions(516);
  gStyle->SetStatH(0.025);
  gStyle->SetStatW(0.3);
  gStyle->SetTitleW(0.4);
  gStyle->SetTitleX(0.28);
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  sprintf(ctit,"HFPo_%s_%d_%d.root",ftit,((int) Ethr1),((int) Ethr2));
  TFile *histf = new TFile(ctit,"RECREATE");
  hLcorr1D->Write(); 
  hScorr1D->Write();  
  hLmapP->Write(); 
  hLmapP0->Write(); 
  hLmapPc->Write(); 
  hSmapP->Write(); 
  hSmapP0->Write(); 
  hSmapPc->Write(); 
  grL->Write();
  grS->Write();
  histf->Close();
}
int main (int argc, char **argv)
{
  /// Mc Ntuplas
  TString input = Form("/data1/rgerosa/NTUPLES_FINAL_CALIB/MC/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_All.root"); 
  /// MC Calibration result E/p
  TString input2 = Form("/data1/rgerosa/L3_Weight/MC_WJets/EB_Z_recoFlag/WJetsToLNu_DYJetsToLL_7TeV-madgraph-tauola_Fall11_Z_noEP.root"); 

  TApplication* theApp = new TApplication("Application",&argc, argv);

  TFile *f = new TFile(input,"");
  TTree *inputTree = (TTree*)f->Get("ntu");

  TFile *f2 = new TFile(input2,"");
  TH2F *h_scale_EB = (TH2F*)f2->Get("h_scale_EB");
  TH2F *hcmap = (TH2F*) h_scale_EB->Clone("hcmap");
  
  hcmap -> Reset("ICEMS");
  hcmap -> ResetStats();
  
  /// Taking infos

  std::vector<float>* ele1_recHit_E=0;
  std::vector<float>* ele2_recHit_E=0;
  std::vector<int>* ele1_recHit_hashedIndex=0;
  std::vector<int>* ele2_recHit_hashedIndex=0;
  std::vector<int>* ele1_recHit_flag=0;
  std::vector<int>* ele2_recHit_flag=0;
  float ele1_E_true,ele2_E_true;
  float ele1_tkP,ele2_tkP;
  int ele1_isEB, ele2_isEB;
  float   ele1_fbrem,ele2_fbrem;
  int isW, isZ;
  
  inputTree->SetBranchAddress("ele1_recHit_E", &ele1_recHit_E);
  inputTree->SetBranchAddress("ele2_recHit_E", &ele2_recHit_E);
  inputTree->SetBranchAddress("ele1_recHit_hashedIndex", &ele1_recHit_hashedIndex);
  inputTree->SetBranchAddress("ele2_recHit_hashedIndex", &ele2_recHit_hashedIndex);
  inputTree->SetBranchAddress("ele1_recHit_flag", &ele1_recHit_flag);
  inputTree->SetBranchAddress("ele2_recHit_flag", &ele2_recHit_flag);
  inputTree->SetBranchAddress("ele1_E_true", &ele1_E_true);
  inputTree->SetBranchAddress("ele2_E_true", &ele2_E_true);
  inputTree->SetBranchAddress("ele1_tkP", &ele1_tkP);
  inputTree->SetBranchAddress("ele2_tkP", &ele2_tkP);
  inputTree->SetBranchAddress("ele1_isEB", &ele1_isEB);
  inputTree->SetBranchAddress("ele2_isEB", &ele2_isEB);
  inputTree->SetBranchAddress("ele1_fbrem", &ele1_fbrem);
  inputTree->SetBranchAddress("ele2_fbrem", &ele2_fbrem);
  inputTree->SetBranchAddress("isW", &isW);
  inputTree->SetBranchAddress("isZ", &isZ);
 
  TProfile2D* mapMomentum = new TProfile2D("mapMomentum","mapMomentum",360,0,360,170,-85,85);
  TProfile2D* mapfbrem = new TProfile2D("mapfbrem","mapfbrem",360,0,360,170,-85,85);

  /// Make fbrem and p/ptrue map cycling on MC --> all the events 

  for(Long64_t i=0; i< inputTree->GetEntries(); i++)
  {
   inputTree->GetEntry(i);
   if (!(i%100000))std::cerr<<i;
   if (!(i%10000)) std::cerr<<".";
       
   if (ele1_isEB == 1 && (isW==1 || isZ==1)) {
  
      double E_seed=0;
      int seed_hashedIndex, iseed;

      for (unsigned int iRecHit = 0; iRecHit < ele1_recHit_E->size(); iRecHit++ ) {
            
            if(ele1_recHit_E -> at(iRecHit) > E_seed &&  ele1_recHit_flag->at(iRecHit) < 4 ) /// control if this recHit is good
            {
              seed_hashedIndex=ele1_recHit_hashedIndex -> at(iRecHit);
              iseed=iRecHit;
              E_seed=ele1_recHit_E -> at(iRecHit);  ///! Seed search

            }
      }
    
   int eta_seed = GetIetaFromHashedIndex(seed_hashedIndex);
   int phi_seed = GetIphiFromHashedIndex(seed_hashedIndex);
   if(ele1_tkP>0 && ele1_E_true>0 && abs(ele1_tkP/ele1_E_true)<2. && abs(ele1_tkP/ele1_E_true)>0.5) mapMomentum->Fill(phi_seed,eta_seed,abs(ele1_tkP/ele1_E_true));
   mapfbrem->Fill(phi_seed,eta_seed,abs(ele1_fbrem)); 
   }
   
   if (ele2_isEB == 1 && isZ==1) {

      double E_seed=0;
      int seed_hashedIndex, iseed;

      for (unsigned int iRecHit = 0; iRecHit < ele2_recHit_E->size(); iRecHit++ ) {
            
            if(ele2_recHit_E -> at(iRecHit) > E_seed &&  ele2_recHit_flag->at(iRecHit) < 4 ) /// control if this recHit is good
            {
              seed_hashedIndex=ele2_recHit_hashedIndex -> at(iRecHit);
              iseed=iRecHit;
              E_seed=ele2_recHit_E -> at(iRecHit);  ///! Seed search

            }
      }
    
   int eta_seed = GetIetaFromHashedIndex(seed_hashedIndex);
   int phi_seed = GetIphiFromHashedIndex(seed_hashedIndex);
   if(ele2_tkP>0 && ele2_E_true>0 && abs(ele2_tkP/ele2_E_true)<2. && abs(ele2_tkP/ele2_E_true)>0.5) mapMomentum->Fill(phi_seed,eta_seed,abs(ele2_tkP/ele2_E_true));
   mapfbrem->Fill(phi_seed,eta_seed,abs(ele2_fbrem));

   }
 }

 /// Map of IC normalized in eta rings

 std::vector< std::pair<int,int> > TT_centre ;
 
 TT_centre.push_back(std::pair<int,int> (58,49));
 TT_centre.push_back(std::pair<int,int> (53,109));
 TT_centre.push_back(std::pair<int,int> (8,114));
 TT_centre.push_back(std::pair<int,int> (83,169));
 TT_centre.push_back(std::pair<int,int> (53,174));
 TT_centre.push_back(std::pair<int,int> (63,194));
 TT_centre.push_back(std::pair<int,int> (83,224));
 TT_centre.push_back(std::pair<int,int> (73,344));
 TT_centre.push_back(std::pair<int,int> (83,358));
 TT_centre.push_back(std::pair<int,int> (-13,18));
 TT_centre.push_back(std::pair<int,int> (-18,23));
 TT_centre.push_back(std::pair<int,int> (-8,53));
 TT_centre.push_back(std::pair<int,int> (-3,63));
 TT_centre.push_back(std::pair<int,int> (-53,128));
 TT_centre.push_back(std::pair<int,int> (-53,183));
 TT_centre.push_back(std::pair<int,int> (-83,193));
 TT_centre.push_back(std::pair<int,int> (-74,218));
 TT_centre.push_back(std::pair<int,int> (-8,223));
 TT_centre.push_back(std::pair<int,int> (-68,303));
 TT_centre.push_back(std::pair<int,int> (-43,328));
 
 /// Mean over phi corrected skipping dead channel 

 for (int iEta = 1 ; iEta < h_scale_EB->GetNbinsY()+1; iEta ++)
 {
   float SumIC = 0;
   int numIC = 0;
   
   for(int iPhi = 1 ; iPhi < h_scale_EB->GetNbinsX()+1 ; iPhi++)
   {
    bool isGood = CheckxtalIC(h_scale_EB,iPhi,iEta);
    bool isGoodTT = CheckxtalTT(iPhi,iEta,TT_centre);
 
     if(isGood && isGoodTT)
     {
      SumIC = SumIC + h_scale_EB->GetBinContent(iPhi,iEta);
      numIC ++ ;
     }
    }
   //fede: skip bad channels and bad TTs
   for (int iPhi = 1; iPhi< h_scale_EB->GetNbinsX()+1  ; iPhi++)
   { 
     if(numIC==0 || SumIC==0) continue;

     bool isGood = CheckxtalIC(h_scale_EB,iPhi,iEta);
     bool isGoodTT = CheckxtalTT(iPhi,iEta,TT_centre);
     if (!isGood || !isGoodTT) continue;

     hcmap->SetBinContent(iPhi,iEta,h_scale_EB->GetBinContent(iPhi,iEta)/(SumIC/numIC));
   }
  }

 /// ratio map

 TH2F* ratioMap = (TH2F*) hcmap -> Clone("ratioMap");
 ratioMap->Reset();

 for( int i =0 ; i<hcmap->GetNbinsX() ; i++){
  for( int j=0; j<hcmap->GetNbinsY() ; j++){
   if(hcmap->GetBinContent(i,j)!=0 && mapMomentum->GetBinContent(i,j)!=0)
    ratioMap->SetBinContent(i+1,j+1,mapMomentum->GetBinContent(i,j)/hcmap->GetBinContent(i,j));
  }
 }

 /// Profile along phi taking into account dead channels
 TGraphErrors *coeffEBp = new TGraphErrors();
 TGraphErrors *coeffEBm = new TGraphErrors();

 for (int iPhi =1; iPhi< hcmap->GetNbinsX()+1 ; iPhi++){
  double SumEBp =0, SumEBm=0;
  double iEBp=0, iEBm=0;
  for(int iEta = 1; iEta<hcmap->GetNbinsY()+1 ; iEta++){
     if(hcmap->GetBinContent(iPhi,iEta)==0)continue;
     if(iEta>85) {SumEBp=SumEBp+mapMomentum->GetBinContent(iPhi,iEta)/hcmap->GetBinContent(iPhi,iEta);
                  iEBp++;}
     else{ SumEBm=SumEBm+mapMomentum->GetBinContent(iPhi,iEta)/hcmap->GetBinContent(iPhi,iEta);
           iEBm++;}
     }
  coeffEBp->SetPoint(iPhi-1,iPhi-1,SumEBp/iEBp);
  coeffEBm->SetPoint(iPhi-1,iPhi-1,SumEBm/iEBm);

  }
     
 TFile* outputGraph = new TFile("output/GraphFor_P_Correction.root","RECREATE");
 outputGraph->cd();

 coeffEBp->Write("coeffEBp");
 coeffEBm->Write("coeffEBm");
 outputGraph->Close();
     
 gROOT->Reset();
 gROOT->SetStyle("Plain");

 gStyle->SetPadTickX(1);
 gStyle->SetPadTickY(1);
 gStyle->SetOptTitle(1); 
 gStyle->SetOptStat(0); 
 gStyle->SetOptFit(0); 
 gStyle->SetFitFormat("6.3g"); 
 gStyle->SetPalette(1); 
  
 gStyle->SetTextFont(42);
 gStyle->SetTextSize(0.05);
 gStyle->SetTitleFont(42,"xyz");
 gStyle->SetTitleSize(0.05);
 gStyle->SetLabelFont(42,"xyz");
 gStyle->SetLabelSize(0.05);
 gStyle->SetTitleXOffset(0.8);
 gStyle->SetTitleYOffset(1.1);
 gROOT->ForceStyle();
 
 TCanvas* c1 = new TCanvas("mapMomentum","mapMomentum",1);
 c1->cd();
 mapMomentum->GetXaxis()->SetTitle("#phi");
 mapMomentum->GetXaxis()->SetNdivisions(20);
 c1->SetGridx(); 
 mapMomentum->GetYaxis()->SetTitle("#eta");
 mapMomentum->GetZaxis()->SetRangeUser(0.7,1.3);
 mapMomentum->Draw("colz");

 TCanvas* c2 = new TCanvas("mapfbrem","mapfbrem",1);
 c2->cd();
 mapfbrem->GetXaxis()->SetTitle("#phi");
 mapfbrem->GetYaxis()->SetTitle("#eta");
 mapfbrem->GetXaxis()->SetNdivisions(20);
 c2->SetGridx(); 
 mapfbrem->GetZaxis()->SetRangeUser(0.,0.7);
 mapfbrem->Draw("colz");

 TCanvas* c3 = new TCanvas("ratioMap","ratioMap",1);
 c3->cd();
 ratioMap->GetXaxis()->SetTitle("#phi");
 ratioMap->GetYaxis()->SetTitle("#eta");
 ratioMap->GetXaxis()->SetNdivisions(20);
 c3->SetGridx(); 
 ratioMap->GetZaxis()->SetRangeUser(0.7,1.3);
 ratioMap->Draw("colz");

 TCanvas* c4 = new TCanvas("coeffEB","coeffEB",1);
 c4->cd();
 coeffEBp->GetXaxis()->SetTitle("#phi");
 coeffEBp->GetYaxis()->SetTitle("p/p_{true}");
 coeffEBp -> SetMarkerStyle(20);
 coeffEBp -> SetMarkerSize(1);
 coeffEBp -> SetMarkerColor(kRed+1); 
 coeffEBp -> SetLineColor(kRed+1); 
 c4->SetGridx(); 
 c4->SetGridy(); 
 ratioMap->Draw("ap");

 coeffEBm->GetXaxis()->SetTitle("#phi");
 coeffEBm->GetYaxis()->SetTitle("p/p_{true}");
 coeffEBm -> SetMarkerStyle(20);
 coeffEBm -> SetMarkerSize(1);
 coeffEBm -> SetMarkerColor(kBlue+1); 
 coeffEBm -> SetLineColor(kBlue+1); 
 coeffEBm->Draw("ap same");


 theApp->Run();
 return 0;
}
Esempio n. 15
0
int main(int argc, char** argv)
{
  // Set style options
  setTDRStyle();
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 


  float totDAevts = 0;
  float DAevtsHIHI = 0;
  
  // Set fitting options
  TVirtualFitter::SetDefaultFitter("Fumili2");
  

  /// Fitting functions
  /////////////// vs R9                                                                              
  //    TF1* R9_low_2011 = new TF1("R9_low_2011", "[0] + [1]*x + [2]*pow(x,2) + [3]*pow(x,3)", 0.7, 0.94);
  //    R9_low_2011->SetParameters(1.04602750038440662e-01, -5.12399137504689572e-01, 7.26103911422236403e-01, -3.14041397400686317e-01);
  //    TF1* R9_hig_2011 = new TF1("R9_hig_2011", "[0] + [1]*x + [2]*pow(x,2) ", 0.94, 1.02);
  //    R9_hig_2011->SetParameters(-2.65392390285653734e+00, 5.32070916148806727e+00, -2.65288628795334347e+00);
  

  //    TF1* R9_low_2012 = new TF1("R9_low_2012", "[0] + [1]*x + [2]*pow(x,2) + [3]*pow(x,3)", 0.7, 0.94);
  //    R9_low_2012->SetParameters(6.53048217081556359e-01, -2.41796796111481704e+00, 2.90336305058258182e+00, -1.13417753246979647e+00);
  
  // //    TF1* R9_low_2012 = new TF1("R9_low_2012", "[0] ", 0., 0.94);
  // //    R9_low_2012->SetParameter(0, 3.05197369770460669e-03);
  
  //    TF1* R9_hig_2012 = new TF1("R9_hig_2012", "[0] + [1]*x + [2]*pow(x,2) ", 0.94, 1.02);
  //    R9_hig_2012->SetParameters(-2.30712976989725455e-01, 2.92312432577749526e-01, -4.51976365389429174e-02);
  
  // //   ////////////// vs Et
  TF1* Et_highR9_2011 = new TF1("Et_highR9_2011", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  Et_highR9_2011->SetParameters(1.59984924630326465e-02, 4.14188316002253587e-02, -6.49126732859059939e-03);
  TF1* Et_lowR9_2011 = new TF1("Et_lowR9_2011", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  Et_lowR9_2011->SetParameters(2.20638739628473586e-02, 6.98744642383235803e-02, -1.85601207959524978e-02);
  
  TF1* Et_highR9_2012 = new TF1("Et_highR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  Et_highR9_2012->SetParameters(1.76747992064786620e-02, 3.73408739026924591e-02, -7.82929065282905561e-03);
  TF1* Et_lowR9_2012 = new TF1("Et_lowR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  Et_lowR9_2012->SetParameters(1.97205016874162468e-02, 4.41133183909690751e-02, -1.58915655671104904e-02);


  //MC 52X
  //stimate senza PU
  //   TF1* Et_highR9_2012 = new TF1("Et_highR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  //   Et_highR9_2012->SetParameters(1.71373322900473177e-02, 1.55744254105185699e-02,  -2.11477940336727904e-03);
  //   TF1* Et_lowR9_2012 = new TF1("Et_lowR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  //   Et_lowR9_2012->SetParameters(2.63075655765558566e-02, 4.57322846169432515e-02, -2.09413281975727485e-02);

  //stimate con PU
  //   TF1* Et_highR9_2012 = new TF1("Et_highR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  //   Et_highR9_2012->SetParameters(1.71373322900473177e-02, 1.55744254105185699e-02,  -2.11477940336727904e-03);
  //   TF1* Et_lowR9_2012 = new TF1("Et_lowR9_2012", "[0] * (1 - exp(-[1] * x) ) +[2] ",0., 100.);
  //   Et_lowR9_2012->SetParameters(1.69896128648113487e-02, 1.20797862827948261e-02, -5.86630884749932049e-03);
  
  
  // Settings for corrections
  //  bool UsePhotonRegression = false;
  bool UsePhotonRegression = true;
  
  //     bool correctEt = true;
  bool correctEt = false;
  
  //  bool useShCorr = false;
  bool useShCorr = true;
  
  //-----------------
  // Input parameters
  
  std::cout << "\n*******************************************************************************************************************" << std::endl;
  std::cout << "arcg: " << argc << std::endl;
  char* EBEE = argv[1];
  char* LOWHIGH = argv[2];
  char* ENE = argv[3];
  int PU = atoi(argv[4]);
  int evtsPerPoint = atoi(argv[5]);
  std::string string_year = argv[6];
  int year = atoi(argv[6]);
  std::string doVsEach = argv[7];
  char* SortVariable = argv[8];

  std::cout << "EBEE:         " << EBEE         << std::endl;
  std::cout << "LOWHIGH:      " << LOWHIGH       << std::endl;
  std::cout << "ENE:          " << ENE           << std::endl;
  std::cout << "PU:           " << PU            << std::endl;
  std::cout << "evtsPerPoint: " << evtsPerPoint  << std::endl;
  std::cout << "year:      " << year       << std::endl;
  std::cout << "doVsEach:      " << doVsEach       << std::endl;
  std::cout << "SortVariable:      " << SortVariable       << std::endl;
  

  TPileupReweighting* puReweighting;

  //   //2012 prompt           
  if(year == 2012) puReweighting =
    new TPileupReweighting("/afs/cern.ch/work/a/amartell/public/weights/PUweights_DYJetsToLL_Summer12_53X_ShSkim_ABC_TrueNumInteractions.root","hweights");
  //     new TPileupReweighting("/afs/cern.ch/work/a/amartell/public/weights/PUweights_DYJetsToLL_Summer12_ABC_TrueNumInteractions.root","pileup");
  //     new TPileupReweighting("/afs/cern.ch/work/a/amartell/public/weights/PUweights_DYJetsToLL_Summer12_Prompt_TrueNumInteractions.root","hweights");
  
  //   //2011                                                                                                                                          
  if(year == 2011) puReweighting =
    new TPileupReweighting("/afs/cern.ch/work/a/amartell/public/weights/PUweights_2011_DYJetsToLL_Fall2011_TrueNumInteractions.root", "hweights");
  
  
  std::string R9MOD = std::string(LOWHIGH);
  std::string ENERGY = std::string(ENE);
  std::string SortV = std::string(SortVariable);

  //-------------------
  // Define in/outfiles
  std::string folderName;
  if(PU == 0)
  	folderName = std::string(EBEE)+"_"+std::string(LOWHIGH)+"_"+std::string(ENE)+"_noPU";
  if(PU == 1)
        folderName = std::string(EBEE)+"_"+std::string(LOWHIGH)+"_"+std::string(ENE);
  //if( strcmp(LOWHIGH,"")==0 ) folderName = std::string(EBEE);
  //if( strcmp(EBEE,"")==0 ) folderName = std::string(LOWHIGH);
  
  
  // Get trees
  std::cout << std::endl;
  std::string nameNtuples = "simpleNtupleEoverP/SimpleNtupleEoverP";
  std::string nameNtuplesMC = "simpleNtupleEoverP/SimpleNtupleEoverP";
  //   if(year == 2011) nameNtuples = "ntu";  
  //   if(year == 2011) nameNtuplesMC = "ntu";  
  
  //  if(year == 2012) nameNtuplesMC = "simpleNtupleEoverPSh/SimpleNtupleEoverP";
  TChain* ntu_MC = new TChain(nameNtuplesMC.c_str());
  TChain* ntu_DA = new TChain(nameNtuples.c_str());
  


  if(year == 2012){
    ntu_MC->Add("/tmp/amartell/DYToEE_M-20_CT10_TuneZ2star_v2_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1_AODSIM.root");
    ntu_MC->Add("/tmp/amartell/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1_AODSIM_2.root");
    ntu_DA->Add("/tmp/amartell/DoubleElectronAB_13Jul2012.root");
    ntu_DA->Add("/tmp/amartell/DoubleElectron_C_Prompt.root");

//     ntu_MC->Add("/tmp/amartell/WJetsToLNu_START53_V7A.root");
//     ntu_DA->Add("/tmp/amartell/Single_AB_Prompt.root");
//     ntu_DA->Add("/tmp/amartell/Single_C_Prompt.root");
  }

  if(year == 2011){                                                                                                                      
    ntu_DA->Add("/tmp/amartell/DoubleElectron-RUN2011AB.root");          
    ntu_MC->Add("/tmp/amartell/DYJetsToLL_Fall11_START44_V9B.root");
  }                                                                                                                                      

  std::cout << "     REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  if(ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "Error: At least one file is empty" << std::endl; 
    return -1;
  }

  
  std::vector<int> run_DA, time_DA, Z_DA, PV_DA;
  std::vector<int> run_MC, time_MC, Z_MC, PV_MC;
  std::vector<float> scE_DA, scEt_reg_DA,scE_reg_DA, R9_DA, P_DA, EoP_DA, Et_DA, scEta_DA, elePhi_DA, ES_DA, isEB_DA, e3x3_DA,e5x5_DA, scERaw_DA;
  std::vector<float> scE_MC, scEt_reg_MC, scE_reg_MC, R9_MC, P_MC, EoP_MC, Et_MC, scEta_MC, elePhi_MC, ES_MC, isEB_MC, puRe, e3x3_MC, e5x5_MC, scERaw_MC;
  std::vector<float> cloneSortVar_DA;
  std::vector<float> cloneSortVar_MC;
  std::vector<float> scEtRaw_DA, scEt_3x3_DA, scEt_5x5_DA;
  std::vector<float> scEtRaw_MC, scEt_3x3_MC, scEt_5x5_MC;
  std::vector<float> ele1ele2_scM_DA, ele1ele2_scM_MC;
  std::vector<int> charge_DA, charge_MC;
  // Set branch addresses
  int isZ,runId,timeStamp,nVtx;
  float npu;
  
  ntu_DA->SetBranchStatus("*",0);
  ntu_DA->SetBranchStatus("runId",1);            ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchStatus("timeStampHigh",1);    ntu_DA->SetBranchAddress("timeStampHigh", &timeStamp);  
  ntu_DA->SetBranchStatus("isZ",1);              ntu_DA->SetBranchAddress("isZ", &isZ);
  ntu_DA->SetBranchStatus("PV_n",1);             ntu_DA->SetBranchAddress("PV_n",&nVtx);

 
  ntu_MC->SetBranchStatus("*",0);
  ntu_MC->SetBranchStatus("PUit_TrueNumInteractions", 1);      ntu_MC->SetBranchAddress("PUit_TrueNumInteractions", &npu);
  ntu_MC->SetBranchStatus("runId",1);                          ntu_MC->SetBranchAddress("runId", &runId);  
  ntu_MC->SetBranchStatus("timeStampHigh",1);                  ntu_MC->SetBranchAddress("timeStampHigh", &timeStamp);  
  ntu_MC->SetBranchStatus("isZ",1);                            ntu_MC->SetBranchAddress("isZ", &isZ);
  ntu_MC->SetBranchStatus("PV_n",1);                           ntu_MC->SetBranchAddress("PV_n",&nVtx);


  
  // Electron data
  float scEne1, scEneReg1, EoP1, scEt1, scEta1, elePhi1, ES1, P1, scERaw1, e3x31, e5x51, ele1ele2_scM;
  float scEne2, scEneReg2, EoP2, scEt2, scEta2, elePhi2, ES2, P2, scERaw2, e3x32, e5x52;
  //  float R9_pho1, R9_pho2;
  int isEB1,isEB2;
  int ele1_charge, ele2_charge; 

  ntu_DA->SetBranchStatus("ele1_scE", 1);       ntu_DA->SetBranchAddress("ele1_scE", &scEne1);
  ntu_DA->SetBranchStatus("ele1_scEt", 1);      ntu_DA->SetBranchAddress("ele1_scEt", &scEt1);
  ntu_DA->SetBranchStatus("ele1_scEta", 1);     ntu_DA->SetBranchAddress("ele1_scEta", &scEta1);
  ntu_DA->SetBranchStatus("ele1ele2_scM", 1);   ntu_DA->SetBranchAddress("ele1ele2_scM", &ele1ele2_scM);
  if(!UsePhotonRegression)  {
    ntu_DA->SetBranchStatus("ele1_scE_regression", 1);      ntu_DA->SetBranchAddress("ele1_scE_regression", &scEneReg1);
    ntu_DA->SetBranchStatus("ele2_scE_regression",1);       ntu_DA->SetBranchAddress("ele2_scE_regression", &scEneReg2);
  }
  else {
    ntu_DA->SetBranchStatus("ele1_scE_regression_PhotonTuned", 1);    ntu_DA->SetBranchAddress("ele1_scE_regression_PhotonTuned", &scEneReg1);
    ntu_DA->SetBranchStatus("ele2_scE_regression_PhotonTuned",1);     ntu_DA->SetBranchAddress("ele2_scE_regression_PhotonTuned", &scEneReg2);
  }
  ntu_DA->SetBranchStatus("ele1_scERaw",1);      ntu_DA->SetBranchAddress("ele1_scERaw",&scERaw1);
  ntu_DA->SetBranchStatus("ele1_e3x3",1);        ntu_DA->SetBranchAddress("ele1_e3x3", &e3x31);
  ntu_DA->SetBranchStatus("ele1_e5x5",1);        ntu_DA->SetBranchAddress("ele1_e5x5", &e5x51);
  ntu_DA->SetBranchStatus("ele1_EOverP",1);      ntu_DA->SetBranchAddress("ele1_EOverP",&EoP1);
  ntu_DA->SetBranchStatus("ele1_isEB",1);        ntu_DA->SetBranchAddress("ele1_isEB",&isEB1);
  ntu_DA->SetBranchStatus("ele1_es", 1);         ntu_DA->SetBranchAddress("ele1_es", &ES1);
  ntu_DA->SetBranchStatus("ele1_tkP",1);         ntu_DA->SetBranchAddress("ele1_tkP", &P1);
  ntu_DA->SetBranchStatus("ele1_charge",1);      ntu_DA->SetBranchAddress("ele1_charge", &ele1_charge);
  ntu_DA->SetBranchStatus("ele2_scE", 1);        ntu_DA->SetBranchAddress("ele2_scE", &scEne2);
  ntu_DA->SetBranchStatus("ele2_scEta", 1);      ntu_DA->SetBranchAddress("ele2_scEta", &scEta2);
  ntu_DA->SetBranchStatus("ele2_scEt", 1);       ntu_DA->SetBranchAddress("ele2_scEt", &scEt2);
  ntu_DA->SetBranchStatus("ele2_e3x3",1);        ntu_DA->SetBranchAddress("ele2_e3x3", &e3x32);
  ntu_DA->SetBranchStatus("ele2_e5x5",1);        ntu_DA->SetBranchAddress("ele2_e5x5", &e5x52);

  ntu_DA->SetBranchStatus("ele2_scERaw",1);      ntu_DA->SetBranchAddress("ele2_scERaw",&scERaw2);
  ntu_DA->SetBranchStatus("ele2_EOverP",1);      ntu_DA->SetBranchAddress("ele2_EOverP",&EoP2);
  ntu_DA->SetBranchStatus("ele2_isEB",1);        ntu_DA->SetBranchAddress("ele2_isEB",&isEB2);
  ntu_DA->SetBranchStatus("ele2_es", 1);         ntu_DA->SetBranchAddress("ele2_es", &ES2);
  ntu_DA->SetBranchStatus("ele2_tkP",1);         ntu_DA->SetBranchAddress("ele2_tkP", &P2);
  ntu_DA->SetBranchStatus("ele2_charge",1);      ntu_DA->SetBranchAddress("ele2_charge", &ele2_charge);

  ntu_DA->SetBranchStatus("ele1_phi", 1);   ntu_DA->SetBranchAddress("ele1_phi", &elePhi1);
  ntu_DA->SetBranchStatus("ele2_phi", 1);   ntu_DA->SetBranchAddress("ele2_phi", &elePhi2);
  
  ///////////////////////
  ntu_MC->SetBranchStatus("ele1_scE", 1);       ntu_MC->SetBranchAddress("ele1_scE", &scEne1);
  ntu_MC->SetBranchStatus("ele1_scEt", 1);      ntu_MC->SetBranchAddress("ele1_scEt", &scEt1);
  ntu_MC->SetBranchStatus("ele1_scEta", 1);     ntu_MC->SetBranchAddress("ele1_scEta", &scEta1);
  ntu_MC->SetBranchStatus("ele1ele2_scM", 1);   ntu_MC->SetBranchAddress("ele1ele2_scM", &ele1ele2_scM);
  if(!UsePhotonRegression)  {
    ntu_MC->SetBranchStatus("ele1_scE_regression", 1);      ntu_MC->SetBranchAddress("ele1_scE_regression", &scEneReg1);
    ntu_MC->SetBranchStatus("ele2_scE_regression",1);       ntu_MC->SetBranchAddress("ele2_scE_regression", &scEneReg2);
  }
  else {
    ntu_MC->SetBranchStatus("ele1_scE_regression_PhotonTuned", 1);    ntu_MC->SetBranchAddress("ele1_scE_regression_PhotonTuned", &scEneReg1);
    ntu_MC->SetBranchStatus("ele2_scE_regression_PhotonTuned",1);     ntu_MC->SetBranchAddress("ele2_scE_regression_PhotonTuned", &scEneReg2);
  }
  ntu_MC->SetBranchStatus("ele1_scERaw",1);      ntu_MC->SetBranchAddress("ele1_scERaw",&scERaw1);
  ntu_MC->SetBranchStatus("ele1_e3x3",1);        ntu_MC->SetBranchAddress("ele1_e3x3", &e3x31);
  ntu_MC->SetBranchStatus("ele1_e5x5",1);        ntu_MC->SetBranchAddress("ele1_e5x5", &e5x51);
  ntu_MC->SetBranchStatus("ele1_EOverP",1);      ntu_MC->SetBranchAddress("ele1_EOverP",&EoP1);
  ntu_MC->SetBranchStatus("ele1_isEB",1);        ntu_MC->SetBranchAddress("ele1_isEB",&isEB1);
  ntu_MC->SetBranchStatus("ele1_es", 1);         ntu_MC->SetBranchAddress("ele1_es", &ES1);
  ntu_MC->SetBranchStatus("ele1_tkP",1);         ntu_MC->SetBranchAddress("ele1_tkP", &P1);
  ntu_MC->SetBranchStatus("ele1_charge",1);      ntu_MC->SetBranchAddress("ele1_charge", &ele1_charge);
  ntu_MC->SetBranchStatus("ele2_scE", 1);        ntu_MC->SetBranchAddress("ele2_scE", &scEne2);
  ntu_MC->SetBranchStatus("ele2_scEta", 1);      ntu_MC->SetBranchAddress("ele2_scEta", &scEta2);
  ntu_MC->SetBranchStatus("ele2_scEt", 1);       ntu_MC->SetBranchAddress("ele2_scEt", &scEt2);
  ntu_MC->SetBranchStatus("ele2_e3x3",1);        ntu_MC->SetBranchAddress("ele2_e3x3", &e3x32);
  ntu_MC->SetBranchStatus("ele2_e5x5",1);        ntu_MC->SetBranchAddress("ele2_e5x5", &e5x52);

  ntu_MC->SetBranchStatus("ele2_scERaw",1);      ntu_MC->SetBranchAddress("ele2_scERaw",&scERaw2);
  ntu_MC->SetBranchStatus("ele2_EOverP",1);      ntu_MC->SetBranchAddress("ele2_EOverP",&EoP2);
  ntu_MC->SetBranchStatus("ele2_isEB",1);        ntu_MC->SetBranchAddress("ele2_isEB",&isEB2);
  ntu_MC->SetBranchStatus("ele2_es", 1);         ntu_MC->SetBranchAddress("ele2_es", &ES2);
  ntu_MC->SetBranchStatus("ele2_tkP",1);         ntu_MC->SetBranchAddress("ele2_tkP", &P2);
  ntu_MC->SetBranchStatus("ele2_charge",1);      ntu_MC->SetBranchAddress("ele2_charge", &ele2_charge);

  ntu_MC->SetBranchStatus("ele1_phi", 1);   ntu_MC->SetBranchAddress("ele1_phi", &elePhi1);
  ntu_MC->SetBranchStatus("ele2_phi", 1);   ntu_MC->SetBranchAddress("ele2_phi", &elePhi2);
  //////////////////////
  
  for(int ientry = 0; ientry < ntu_DA -> GetEntries(); ientry++)
  {
  	if( (ientry%100000 == 0) ) std::cout << "reading DATA entry " << ientry << "\r" << std::flush;
        ntu_DA->GetEntry(ientry);  

	if(isZ == 0) continue;

	++totDAevts;
	if(e3x31/scERaw1 > 0.94 && e3x32/scERaw2 > 0.94) ++DAevtsHIHI;

        run_DA.push_back(runId);

	float corrEtR9_1 = 1.;
	float corrEtR9_2 = 1.;

	if(correctEt == true){
 	  if(year == 2012){
   	    if(e3x31/scERaw1 < 0.94 ) corrEtR9_1 = corrEtR9_1 / (1. + Et_lowR9_2012->Eval(scEneReg1));
   	    if(e3x32/scERaw2 < 0.94 ) corrEtR9_2 = corrEtR9_2 / (1. + Et_lowR9_2012->Eval(scEneReg2));
	    if(e3x31/scERaw1 >= 0.94 ) corrEtR9_1 = corrEtR9_1 / (1. + Et_highR9_2012->Eval(scEneReg1));
 	    if(e3x32/scERaw2 >= 0.94 ) corrEtR9_2 = corrEtR9_2 / (1. + Et_highR9_2012->Eval(scEneReg2));
 	  }
 	  if(year == 2011){
 	    if(e3x31/scERaw1 < 0.94 ) corrEtR9_1 = corrEtR9_1 / (1. + Et_lowR9_2011->Eval(scEneReg1));
   	    if(e3x32/scERaw2 < 0.94 ) corrEtR9_2 = corrEtR9_2 / (1. + Et_lowR9_2011->Eval(scEneReg2));
	    if(e3x31/scERaw1 >= 0.94 ) corrEtR9_1 = corrEtR9_1 / (1. + Et_highR9_2011->Eval(scEneReg1));
 	    if(e3x32/scERaw2 >= 0.94 ) corrEtR9_2 = corrEtR9_2 / (1. + Et_highR9_2011->Eval(scEneReg2));
 	  }
	}

	if(useShCorr == true){
	  corrEtR9_1 = corrEtR9_1 * GetShervingCorrections(scEta1, e3x31/scERaw1, runId);
	  corrEtR9_2 = corrEtR9_2 * GetShervingCorrections(scEta2, e3x32/scERaw2, runId);
	}

	charge_DA.push_back(ele1_charge);
	charge_DA.push_back(ele2_charge);

        time_DA.push_back(timeStamp);
        Z_DA.push_back(isZ);
	PV_DA.push_back(nVtx);    

	scE_DA.push_back(scEne1);
	scE_DA.push_back(scEne2);

	scE_reg_DA.push_back(scEneReg1*corrEtR9_1);
	scE_reg_DA.push_back(scEneReg2*corrEtR9_2);

	float Rt1 = sin(2*atan(exp(-scEta1)) );
	float Rt2 = sin(2*atan(exp(-scEta2)) );

	scEt_reg_DA.push_back(scEneReg1*Rt1*corrEtR9_1);
 	scEt_reg_DA.push_back(scEneReg2*Rt2*corrEtR9_2);

	R9_DA.push_back(e3x31/scERaw1);
	R9_DA.push_back(e3x32/scERaw2);

	P_DA.push_back(P1);
	P_DA.push_back(P2);
	EoP_DA.push_back(EoP1);
	EoP_DA.push_back(EoP2);
	Et_DA.push_back(scEt1);
        Et_DA.push_back(scEt2);
	scEta_DA.push_back(scEta1);
	scEta_DA.push_back(scEta2);
        ES_DA.push_back(ES1);
	ES_DA.push_back(ES2);
	isEB_DA.push_back(isEB1);
	isEB_DA.push_back(isEB2);

	e3x3_DA.push_back(e3x31);
	e3x3_DA.push_back(e3x32);
	e5x5_DA.push_back(e5x51);
	e5x5_DA.push_back(e5x52);

	scERaw_DA.push_back(scERaw1);
	scERaw_DA.push_back(scERaw2);
	scEtRaw_DA.push_back(scERaw1*scEt1/scEne1);
	scEtRaw_DA.push_back(scERaw2*scEt2/scEne2);

	scEt_3x3_DA.push_back(e3x31*scEt1/scEne1);
	scEt_3x3_DA.push_back(e3x32*scEt2/scEne2);
	scEt_5x5_DA.push_back(e5x51*scEt1/scEne1);
	scEt_5x5_DA.push_back(e5x52*scEt2/scEne2);

	if(SortV == "Et"){
	  cloneSortVar_DA.push_back(scEneReg1*Rt1*corrEtR9_1);
	  cloneSortVar_DA.push_back(scEneReg2*Rt2*corrEtR9_2);
	}
	if(SortV == "R9"){
	  cloneSortVar_DA.push_back(e3x31/scERaw1);
	  cloneSortVar_DA.push_back(e3x32/scERaw2);
       	}

  }
  
  std::cout << std::endl;
  float ww = 1.;
  for(int ientry = 0; ientry < ntu_MC -> GetEntries(); ientry++)
  {
  	if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << "\r" << std::flush;
        ntu_MC->GetEntry(ientry);  
  
	if(isZ == 0) continue;
	//	if(nVtx > 20) continue;

	float R9_ele1 = e3x31/scERaw1;
	if(year == 2012 && isEB1 == 1) R9_ele1 = 0.0010 + 1.0045 * e3x31/scERaw1;
	if(year == 2012 && isEB1 == 0) R9_ele1 = -0.0007 + 1.0086 * e3x31/scERaw1;
	if(year == 2011) R9_ele1 = 1.0035 * e3x31/scERaw1;
	float R9_ele2 = e3x32/scERaw2;
	if(year == 2012 && isEB2 == 1) R9_ele2 = 0.0010 + 1.0045 * e3x32/scERaw2;
	if(year == 2012 && isEB2 == 0) R9_ele2 = -0.0007 + 1.0086 * e3x32/scERaw2;
	if(year == 2011) R9_ele2 = 1.0035 * e3x32/scERaw2;

	float energySmearing1 = gRandom->Gaus(1.,0.0075);
	float energySmearing2 = gRandom->Gaus(1.,0.0075);

	energySmearing1 = gRandom->Gaus(1., GetSmearings(scEta1, R9_ele1, year, isEB1));
	energySmearing2 = gRandom->Gaus(1., GetSmearings(scEta2, R9_ele2, year, isEB2));

	charge_MC.push_back(ele1_charge);
	charge_MC.push_back(ele2_charge);

	ww = puReweighting->GetWeight((int)npu);
        puRe.push_back(ww);

        run_MC.push_back(runId);
        time_MC.push_back(timeStamp);
        Z_MC.push_back(isZ);
	PV_MC.push_back(nVtx);    

	scE_MC.push_back(scEne1);
	scE_MC.push_back(scEne2);

	scE_reg_MC.push_back(scEneReg1 * energySmearing1);
	scE_reg_MC.push_back(scEneReg2 * energySmearing2);

	scEt_reg_MC.push_back(scEneReg1/scEne1*scEt1*energySmearing1);
 	scEt_reg_MC.push_back(scEneReg2/scEne2*scEt2*energySmearing2);

	P_MC.push_back(P1);
	P_MC.push_back(P2);
	EoP_MC.push_back(EoP1);
	EoP_MC.push_back(EoP2);

	Et_MC.push_back(scEt1);
        Et_MC.push_back(scEt2);
	scEta_MC.push_back(scEta1);
	scEta_MC.push_back(scEta2);
        ES_MC.push_back(ES1);
	ES_MC.push_back(ES2);
	isEB_MC.push_back(isEB1);
	isEB_MC.push_back(isEB2);

	e5x5_MC.push_back(e5x51);
	e5x5_MC.push_back(e5x52);

	scERaw_MC.push_back(scERaw1);
	scERaw_MC.push_back(scERaw2);

	R9_MC.push_back(R9_ele1);
	R9_MC.push_back(R9_ele2);

	scEtRaw_MC.push_back(scERaw1*scEt1/scEne1);
	scEtRaw_MC.push_back(scERaw2*scEt2/scEne2);

	scEt_5x5_MC.push_back(e5x51*scEt1/scEne1);
	scEt_5x5_MC.push_back(e5x52*scEt2/scEne2);

 	e3x3_MC.push_back(R9_ele1*scERaw1);
 	e3x3_MC.push_back(R9_ele2*scERaw2);
 	scEt_3x3_MC.push_back(R9_ele1*scERaw1*scEt1/scEne1);
 	scEt_3x3_MC.push_back(R9_ele2*scERaw2*scEt2/scEne2);

	if(SortV == "Et"){
	  cloneSortVar_MC.push_back(scEneReg1/scEne1*scEt1*energySmearing1);
	  cloneSortVar_MC.push_back(scEneReg2/scEne2*scEt2*energySmearing2);
	}
	if(SortV == "R9"){
	  cloneSortVar_MC.push_back(R9_ele1);
	  cloneSortVar_MC.push_back(R9_ele2);
       	}
  }
  

//   std::cout << "   totDAevts = " << totDAevts << std::endl;
//   std::cout << "   DAevtsHIHI = " << DAevtsHIHI << std::endl;
  //  return 200;


  // Loop and sort events
  std::cout << std::endl;
  std::cout << "***** Sort events and define bins *****" << std::endl;
  
  int nEntries = cloneSortVar_DA.size();
  int nSavePts = 0;
  std::vector<bool> isSavedEntries(nEntries);
  std::vector<SorterLC> sortedEntries;
  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    isSavedEntries.at(ientry) = false;

    // save only what is needed for the analysis!!!
    if(strcmp(EBEE,"EE")==0 && (fabs(scEta_DA.at(ientry)) < 1.566 || fabs(scEta_DA.at(ientry)) > 2.5 )) continue; 
    if(strcmp(EBEE,"EB")==0 && (fabs(scEta_DA.at(ientry)) > 1.4442 )) continue;

    if(std::string(EBEE) == "BC" && (fabs(scEta_DA.at(ientry)) > 1. )) continue;
    if(std::string(EBEE) == "B4" && (fabs(scEta_DA.at(ientry)) < 1. || fabs(scEta_DA.at(ientry)) > 1.4442)) continue;
    if(std::string(EBEE) == "EL" && (fabs(scEta_DA.at(ientry)) < 1.566 || fabs(scEta_DA.at(ientry)) > 2. )) continue;
    if(std::string(EBEE) == "EH" && (fabs(scEta_DA.at(ientry)) > 2.5 )) continue;

    //    if(R9_DA.at(ientry) < 0.7) continue;
    if(scEt_reg_DA.at(ientry) <  25.) continue;

    //to be fixed -> categories as in Hgg
    if(std::string(LOWHIGH) == "LOW" && R9_DA.at(ientry) >= 0.94) continue;
    if(std::string(LOWHIGH) == "HIGH" && R9_DA.at(ientry) < 0.94 ) continue;

    isSavedEntries.at(ientry) = true;

    SorterLC dummy;
    dummy.laserCorr = cloneSortVar_DA.at(ientry);
    dummy.entry = ientry;
    sortedEntries.push_back(dummy);
    nSavePts++;   
  }

  std::cout << " Effective entries = " << nSavePts << std::endl;
  std::cout << " Effective entries sortedEntries.size()= " << sortedEntries.size() << std::endl;

  std::sort(sortedEntries.begin(),sortedEntries.end(),SorterLC());
  std::cout << "Sorting variable vs " << SortV << std::endl;
  std::cout << "DATA sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
  
  
   std::map<int,int> antiMap;
   for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved)
   antiMap[sortedEntries.at(iSaved).entry] = iSaved; 
   
  // bins with evtsPerPoint events per bin
   std::cout << " nSavePts = " << nSavePts << std::endl;
   std::cout << " evtsPerPoint = " << evtsPerPoint << std::endl;
  int nBins = std::max(1, int(nSavePts/evtsPerPoint));
   std::cout << " nBins = " << nBins << std::endl;
  int nBinPts = int( nSavePts/nBins );
   std::cout << " nBinPts = " << nBinPts << std::endl;
  int nBinTempPts = 0;

  std::cout << "nBins = " << nBins << std::endl;
  
  std::vector<int> binEntryMax;
  binEntryMax.push_back(0);
  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
  {
    ++nBinTempPts;
    
    if( nBinTempPts == nBinPts )
    {
      binEntryMax.push_back( iSaved );      
      nBinTempPts = 0;
    }
  }
  binEntryMax.at(nBins) = nSavePts;
  
  std::cout << " fine : nBins = " << nBins << std::endl;
 
  TVirtualFitter::SetDefaultFitter("Fumili2");
  
  // histogram definition
  
  TH1F** h_EoP_DA = new TH1F*[nBins];
  TH1F** h_EoP_MC = new TH1F*[nBins];
  TH1F** h_SortV = new TH1F*[nBins];
  TH1F** h_SortV_MC = new TH1F*[nBins];

  TH1F* h_Et_allDA = new TH1F("h_Et_allDA", "", 5000, 0., 1000.);
  TH1F* h_Et_allMC = new TH1F("h_Et_allMC", "", 5000, 0., 1000.);
  TH1F* h_R9_allDA = new TH1F("h_R9_allDA", "", 2200, 0., 1.1);
  TH1F* h_R9_allMC = new TH1F("h_R9_allMC", "", 2200, 0., 1.1);

  TH1F* h_scE_DA = new TH1F("h_scE_DA", "", 4000, 0., 200.);
  TH1F* h_scReg_DA = new TH1F("h_scReg_DA", "", 4000, 0., 200.);
  TH1F* h_scRaw_DA = new TH1F("h_scRaw_DA", "", 4000, 0., 200.);

  TH1F* h_Vtx_DA = new TH1F("h_Vtx_DA", "", 200, 0., 200.);
  TH1F* h_Vtx_MC = new TH1F("h_Vtx_MC", "", 200, 0., 200.);

  TH2F* h_R9_vsET_MC = new TH2F("h_R9_vsET_MC", "", 200, 0., 200., 220, 0., 1.1);
  TH2F* h_R9_vsET_DA = new TH2F("h_R9_vsET_DA", "", 200, 0., 200., 220, 0., 1.1);
  TProfile* p_R9_vsET_MC = new TProfile("p_R9_vsET_MC", "", 200, 0., 200.);
  TProfile* p_R9_vsET_DA = new TProfile("p_R9_vsET_DA", "", 200, 0., 200.);


  h_Et_allDA->Sumw2();
  h_Et_allMC->Sumw2();
  h_R9_allDA->Sumw2();
  h_R9_allMC->Sumw2();
  h_scE_DA->Sumw2();
  h_scReg_DA->Sumw2();
  h_scRaw_DA->Sumw2();
  h_Vtx_DA->Sumw2();
  h_Vtx_MC->Sumw2();
  h_R9_vsET_MC->Sumw2();
  h_R9_vsET_DA->Sumw2();
  p_R9_vsET_MC->Sumw2();
  p_R9_vsET_DA->Sumw2();

  h_Et_allDA->SetLineColor(kRed+2);
  h_R9_allDA->SetLineColor(kRed+2);
  h_Vtx_DA->SetLineColor(kRed+2);

  h_Et_allMC->SetLineColor(kGreen+2);
  h_R9_allMC->SetLineColor(kGreen+2);
  h_Vtx_MC->SetLineColor(kGreen+2);

  std::vector<float> EtBinEdge;
  EtBinEdge.clear();
  std::vector<float> xNorm_single;


  for(int i = 0; i < nBins; ++i)
  {
    char histoName[80];    
      sprintf(histoName, "EoP_DA_%d", i);
      if(SortV == "Et") h_EoP_DA[i] = new TH1F(histoName, histoName, 600, 0., 3.);
      if(SortV == "R9") h_EoP_DA[i] = new TH1F(histoName, histoName, 400, 0., 2.);
      h_EoP_DA[i]->SetFillColor(kRed+2);
      h_EoP_DA[i]->SetFillStyle(3004);
      h_EoP_DA[i]->SetMarkerStyle(7);
      h_EoP_DA[i]->SetMarkerColor(kRed+2); 
      h_EoP_DA[i]->SetLineColor(kRed+2); 
    
      sprintf(histoName, "EoP_MC_%d", i);
      if(SortV == "Et") h_EoP_MC[i] = new TH1F(histoName, histoName, 600, 0., 3.);
      if(SortV == "R9") h_EoP_MC[i] = new TH1F(histoName, histoName, 400, 0., 2.);
      h_EoP_MC[i] -> SetFillColor(kGreen+2);
      h_EoP_MC[i] -> SetFillStyle(3004);
      h_EoP_MC[i] -> SetMarkerStyle(7);
      h_EoP_MC[i] -> SetMarkerColor(kGreen+2);
      h_EoP_MC[i] -> SetLineColor(kGreen+2);
      
      sprintf(histoName, (SortV+"_%d").c_str(), i);
      if(SortV == "Et") h_SortV[i] = new TH1F(histoName, histoName, 5000, 0., 1000.);
      if(SortV == "R9") h_SortV[i] = new TH1F(histoName, histoName, 2200, 0, 1.1);
      h_SortV[i]->SetLineColor(kRed+2);

      sprintf(histoName, (SortV+"_MC_%d").c_str(), i);
      if(SortV == "Et") h_SortV_MC[i] = new TH1F(histoName, histoName, 5000, 0., 1000.);
      if(SortV == "R9") h_SortV_MC[i] = new TH1F(histoName, histoName, 2200, 0, 1.1);
      h_SortV_MC[i]->SetLineColor(kGreen+2);
      
      h_EoP_DA[i]->Sumw2();
      h_EoP_MC[i]->Sumw2();
      h_SortV[i]->Sumw2();
      h_SortV_MC[i]->Sumw2();
  }

  std::cout << " cloneSortVar_DA.size() = " << cloneSortVar_DA.size() << std::endl;
  std::cout << " cloneSortVar_MC.size() = " << cloneSortVar_MC.size() << std::endl;


  std::vector<float> x;
  std::vector<float> ex;
  std::vector<float> y;
  std::vector<float> ey;
  
  TGraphErrors* finalGraph = new TGraphErrors();
  
  // function definition
  TF1** f_EoP = new TF1*[nBins];
 
  // loop on the saved and sorted events
  std::cout << std::endl;
  std::cout << "***** Fill and fit histograms *****" << std::endl;

  int DAEntries = cloneSortVar_DA.size();
  for(unsigned int ientry = 0; ientry < DAEntries; ++ientry){
    if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << std::endl;
      
    if( isSavedEntries.at(ientry) == false) continue;
     
    int iSaved = antiMap[ientry];
    int bin = -1;
    
    for(bin = 0; bin < nBins; ++bin)
      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
	break;

    h_EoP_DA[bin]->Fill((scE_reg_DA.at(ientry)-ES_DA.at(ientry))/(P_DA.at(ientry)-ES_DA.at(ientry)));
    h_SortV[bin]->Fill(cloneSortVar_DA.at(ientry) );
    h_Et_allDA->Fill(scEt_reg_DA.at(ientry) );
    h_R9_allDA->Fill(R9_DA.at(ientry));
    
    h_Vtx_DA->Fill(PV_DA.at(int(ientry/2)) );
    h_scE_DA->Fill(scE_DA.at(ientry) );
    h_scReg_DA->Fill(scE_reg_DA.at(ientry));
    h_scRaw_DA->Fill(scERaw_DA.at(ientry));

    h_R9_vsET_DA->Fill(scEt_reg_DA.at(ientry), R9_DA.at(ientry));
    p_R9_vsET_DA->Fill(scEt_reg_DA.at(ientry), R9_DA.at(ientry));
  }
  
  std::cout << " dati fillati " << std::endl;
  std::cout << std::endl;
  
  for(int bin = 0; bin < nBins; bin++)
  {
    std::cout << "h_SortV[bin]->GetEntries() =  " << h_SortV[bin]->GetEntries() << std::endl;
    std::cout << "h_EoP_DA[bin]->GetEntries() =  " << h_EoP_DA[bin]->GetEntries() << std::endl;
    for(int i = 1; i < h_SortV[bin]->GetNbinsX()+1; i++)
      {
	if(h_SortV[bin]->GetBinContent(i) > 0) {
	  EtBinEdge.push_back(h_SortV[bin]->GetBinCenter(i)-h_SortV[bin]->GetBinWidth(i) );
	  break;
	}  
      }
  }

  int MCEntries = cloneSortVar_MC.size();
  for(unsigned int ientry = 0; ientry < MCEntries; ++ientry)
    {    
      if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << std::endl;
      
      if (strcmp(EBEE,"EE")==0 && (fabs(scEta_MC.at(ientry)) < 1.566 || fabs(scEta_MC.at(ientry)) > 2.5 )) continue; 
      if (strcmp(EBEE,"EB")==0 && (fabs(scEta_MC.at(ientry)) > 1.4442 )) continue;
      
      //      if(R9_MC.at(ientry) < 0.7) continue;
      if(scEt_reg_MC.at(ientry) < 25.) continue;

      //to be fixed -> categories as in Hgg 
      if(std::string(EBEE) == "BC" && (fabs(scEta_MC.at(ientry)) > 1. )) continue; 
      if(std::string(EBEE) == "B4" && (fabs(scEta_MC.at(ientry)) < 1. || fabs(scEta_MC.at(ientry)) > 1.4442)) continue; 
      if(std::string(EBEE) == "EL" && (fabs(scEta_MC.at(ientry)) < 1.566 || fabs(scEta_MC.at(ientry)) > 2. )) continue; 
      if(std::string(EBEE) == "EH" && (fabs(scEta_MC.at(ientry)) > 2.5 )) continue; 
                                                                                                     
      if(std::string(LOWHIGH) == "LOW" && R9_MC.at(ientry) >= 0.94 ) continue;
      if(std::string(LOWHIGH) == "HIGH" && R9_MC.at(ientry) < 0.94 ) continue;

      for(unsigned int bin = 0; bin < EtBinEdge.size(); ++bin){
	if( (bin != EtBinEdge.size()-1 && cloneSortVar_MC.at(ientry) > EtBinEdge.at(bin) && cloneSortVar_MC.at(ientry) < EtBinEdge.at(bin+1)) ||
	    (bin == EtBinEdge.size()-1 && cloneSortVar_MC.at(ientry) > EtBinEdge.at(bin) ) ){
	  if(PU == 0)
	    {
	      h_EoP_MC[(int)bin]->Fill((scE_reg_MC.at(ientry)-ES_MC.at(ientry))/(P_MC.at(ientry)-ES_MC.at(ientry)));
	      h_SortV_MC[int(bin)]->Fill(cloneSortVar_MC.at(ientry));
	      break;
	  }
          if(PU == 1)
	    {
	      h_EoP_MC[(int)bin]->Fill((scE_reg_MC.at(ientry)-ES_MC.at(ientry))/(P_MC.at(ientry)-ES_MC.at(ientry)), puRe.at(int(ientry/2)));
	      h_SortV_MC[int(bin)]->Fill(cloneSortVar_MC.at(ientry), puRe.at(int(ientry/2)) );
	      break;
	    }
	} // get the ok bin
	}//loop over bins
      if(PU == 0){
    	h_Et_allMC->Fill(scEt_reg_MC.at(ientry));
	h_R9_allMC->Fill(R9_MC.at(ientry));
	h_Vtx_MC->Fill(PV_MC.at(int(ientry/2)));
    }
    if(PU == 1){
      h_Et_allMC->Fill(scEt_reg_MC.at(ientry), puRe.at(int(ientry/2)));
      h_R9_allMC->Fill(R9_MC.at(ientry), puRe.at(int(ientry/2)));
      h_Vtx_MC->Fill(PV_MC.at(int(ientry/2)), puRe.at(int(ientry/2)) );
      h_R9_vsET_MC->Fill(scEt_reg_MC.at(ientry), R9_MC.at(ientry), puRe.at(int(ientry/2)));
      p_R9_vsET_MC->Fill(scEt_reg_MC.at(ientry), R9_MC.at(ientry), puRe.at(int(ientry/2)));
    }
    }

  std::cout << " fino a qui ci sono = MC fillati" <<  std::endl;

  for(int i = 0; i < nBins; ++i){
    //------------------------------------
    // Fill the graph for uncorrected data
    // define the fitting function
    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )


    float xNorm = h_EoP_DA[i]->Integral()/h_EoP_MC[i]->Integral(); //  * h_EoP_DA[i]->GetBinWidth(1)/h_EoP_MC[i]->GetBinWidth(1);  
    h_EoP_MC[i]->Scale(xNorm);

    float xNorm_all = h_Et_allDA->Integral()/h_Et_allMC->Integral(); //* h_Et_allDA->GetBinWidth()/h_Et_allMC->GetBinWidth();
    if(SortV == "Et") xNorm_all = h_R9_allDA->Integral()/h_R9_allMC->Integral();
    h_Et_allMC->Scale(xNorm_all);
    h_R9_allMC->Scale(xNorm_all);
    h_Vtx_MC->Scale(xNorm_all);

    float xNormSV = h_SortV[i]->Integral()/h_SortV_MC[i]->Integral(); //*h_Et[i]->GetBinWidth()/h_Et_MC[i]->GetBinWidth();  
    h_SortV_MC[i]->Scale(xNormSV);
    
//     std::cout << " i = " << i << " h_EoP_DA[i]->Integral() = " << h_EoP_DA[i]->Integral() << std::endl;
//     std::cout << " i = " << i << " h_Et[i]->Integral() = " << h_Et[i]->Integral() << std::endl;
//     std::cout << " i = " << i << " h_EoP_MC[i]->Integral() = " << h_EoP_MC[i]->Integral() << std::endl;
//     std::cout << " i = " << i << " h_Et_MC[i]->Integral() = " << h_Et_MC[i]->Integral() << std::endl;

//     std::cout << " i = " << i << " h_EoP_DA[i]->Integral() = " << h_EoP_DA[i]->Integral() << std::endl;
//     std::cout << " i = " << i << " h_EoP_MC[i]->Integral() = " << h_EoP_MC[i]->Integral() << std::endl;
//     std::cout << " xNorm = " << xNorm << std::endl;
//     std::cout << " xNormEt = " << xNormEt << std::endl;


    //    h_EoP_MC[i]->Smooth(2);

    //    if(reweightZtoH  == false && reweightEta == false && reweightR9 == false){                              

    if(SortV == "Et"){
    if(std::string(EBEE) == "EB" && year == 2011 && std::string(LOWHIGH) == "HIGH"){h_EoP_MC[i]->Smooth(1); }
    if(std::string(EBEE) == "EB" && year == 2011 && std::string(LOWHIGH) == "LOW"){ h_EoP_MC[i]->Smooth(1); }
    if(std::string(EBEE) == "EB" && year == 2012 && std::string(LOWHIGH) == "HIGH"){ h_EoP_MC[i]->Smooth(2); }
    if(std::string(EBEE) == "EB" && year == 2012 && std::string(LOWHIGH) == "LOW"){h_EoP_MC[i]->Smooth(2); }

    if(std::string(EBEE) == "EE" && year == 2011 && std::string(LOWHIGH) == "HIGH")
      { h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2011 && std::string(LOWHIGH) == "LOW")
      { h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2012 && std::string(LOWHIGH) == "HIGH")
      {   h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2012 && std::string(LOWHIGH) == "LOW")
      {h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    }
                                                                                                     
    if(SortV == "R9"){
     //    h_EoP_DA[i]->Rebin(2); h_EoP_MC[i]->Rebin(2);                                                              
    //    if(reweightZtoH  == false && reweightEta == false && reweightR9 == false){                                 
    if(std::string(EBEE) == "EB" && year == 2011 && std::string(LOWHIGH) == "HIGH"){h_EoP_MC[i]->Smooth(1); }
    if(std::string(EBEE) == "EB" && year == 2011 && std::string(LOWHIGH) == "LOW"){ h_EoP_MC[i]->Smooth(1); }
    if(std::string(EBEE) == "EB" && year == 2012 && std::string(LOWHIGH) == "HIGH"){ h_EoP_MC[i]->Smooth(2); }
    if(std::string(EBEE) == "EB" && year == 2012 && std::string(LOWHIGH) == "LOW"){h_EoP_MC[i]->Smooth(2); }
    if(std::string(EBEE) == "EE" && year == 2011 && std::string(LOWHIGH) == "HIGH")
      { h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2011 && std::string(LOWHIGH) == "LOW")
      { h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2012 && std::string(LOWHIGH) == "HIGH")
      {   h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    if(std::string(EBEE) == "EE" && year == 2012 && std::string(LOWHIGH) == "LOW")
      {h_EoP_MC[i]->Smooth(150); h_EoP_DA[i]->Rebin(4); h_EoP_MC[i]->Rebin(4);}
    }                                                                                                        


    histoFunc* templateHistoFunc = new histoFunc(h_EoP_MC[i]);
    char funcName[50];
    sprintf(funcName,"f_EoP_%d",i);
    f_EoP[i] = new TF1(funcName, templateHistoFunc, 0.7, 1.3, 3, "histoFunc");
    if(std::string(EBEE) == "EE") f_EoP[i] = new TF1(funcName, templateHistoFunc, 0.5, 2.5, 3, "histoFunc");
    if(std::string(EBEE) == "EE" && SortV == "R9")  f_EoP[i] = new TF1(funcName, templateHistoFunc, 0.7, 1.4, 3, "histoFunc");    

    f_EoP[i]->SetParName(0,"Norm"); 
    f_EoP[i]->SetParName(1,"Scale factor"); 
    f_EoP[i]->SetLineWidth(1); 
    f_EoP[i]->SetNpx(10000);
    
    xNorm = 1.;    
    f_EoP[i]->FixParameter(0, xNorm);
    //    f_EoP[i] -> SetParameter(1, gRandom->Gaus(1.,0.005));
    f_EoP[i]->SetParameter(1, 0.99);
    f_EoP[i]->FixParameter(2, 0.);
    f_EoP[i]->SetLineColor(kRed+2); 

    TFitResultPtr rp = h_EoP_DA[i]->Fit(funcName, "QERLS+");
    int fStatus = rp;
    int nTrials = 0;
    while( (fStatus != 0) && (nTrials < 100) )
    {
      rp = h_EoP_DA[i]->Fit(funcName, "QERLS+");
      fStatus = rp;
      if(fStatus == 0) break;
      ++nTrials;
    }

    double eee = f_EoP[i]->GetParError(1); 
    double k = 1./f_EoP[i]->GetParameter(1);


    // Fill the graph      
    if (fStatus == 0 && eee*k > 0.1*h_EoP_DA[i]->GetRMS()/sqrt(evtsPerPoint))
    {
      x.push_back(h_SortV[i]->GetMean());
      ex.push_back((h_SortV[i]->GetRMS())/sqrt(h_SortV[i]->GetEntries()));
      y.push_back(k-1);
      ey.push_back(eee * k * k);
    }
    else
    std::cout << "Fitting uncorrected Et bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << std::endl;

  }
   
  for(unsigned int i = 0; i < x.size(); ++i)
  {
    finalGraph->SetPoint(i,  x.at(i) , y.at(i));
    finalGraph->SetPointError(i, ex.at(i), ey.at(i));
  }

  if(year == 2012) finalGraph->SetMarkerColor(kBlue);
  if(year == 2011) finalGraph->SetMarkerColor(kCyan);
  if(strcmp(LOWHIGH,"HIGH")==0 )  finalGraph->GetYaxis()->SetRangeUser(-0.004, 0.014);
  if(strcmp(LOWHIGH,"LOW")==0 )  finalGraph->GetYaxis()->SetRangeUser(-0.03, 0.03);
  finalGraph->GetYaxis()->SetTitle("E/p_{data} - E/p_{mc}");
  finalGraph->GetXaxis()->SetRangeUser(0., 130.);
  finalGraph->GetXaxis()->SetTitle(SortV.c_str());

//   std::cout << "   totDAevts = " << totDAevts << std::endl;
//   std::cout << "   DAevtsHIHI = " << DAevtsHIHI << std::endl;

  std::string plotFolderName = "PLOTS_vs"+SortV;
  if(doVsEach == "true") plotFolderName = "PLOTS_true"; 

  TFile pippo((plotFolderName+"/results_"+folderName+"_"+string_year+".root").c_str(),"recreate");
  finalGraph->Write("finalGraph");
  h_Et_allMC->Write();
  h_Et_allDA->Write();
  h_R9_allMC->Write();
  h_R9_allDA->Write();
  h_R9_vsET_MC->Write();
  h_R9_vsET_DA->Write();
  p_R9_vsET_MC->Write();
  p_R9_vsET_DA->Write();

  h_Vtx_DA->Write();
  h_Vtx_MC->Write();
  h_scE_DA->Write();
  h_scReg_DA->Write();
  h_scRaw_DA->Write();

  for(int i = 0; i < nBins; ++i){
    h_EoP_DA[i]->Write();
    h_EoP_MC[i]->Write();
    h_SortV[i]->Write();
    h_SortV_MC[i]->Write();
  }
  pippo.Close();
  
//   /*
//   // Drawings
//   TPaveStats** s_EoP = new TPaveStats*[nBins];
  
//   TCanvas *c1[100]; 
//   for(int i = 0; i < nBins; ++i)
//   {    
//     char canvasName[50];
//     sprintf(canvasName, "Fits-%0d", i); 
//     c1[i] = new TCanvas(canvasName, canvasName);
//     c1[i]->cd();
//     h_EoP_DA[i] -> GetXaxis() -> SetTitle("E/p");  
//     h_EoP_DA[i] -> GetYaxis() -> SetRangeUser(0., std::max(h_EoP_DA[i]->GetMaximum(), h_EoP_MC[i]->GetMaximum()) + 10.); 
//     h_EoP_DA[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
//     //    h_EoP_DA[i] -> Draw("e");
//     h_EoP_DA[i] -> Draw();
//     gPad->Update();
//     s_EoP[i]= (TPaveStats*)(h_EoP_DA[i]->GetListOfFunctions()->FindObject("stats"));
//     s_EoP[i]->SetTextColor(kRed+2);
//     f_EoP[i]->Draw("same");
    
//     h_EoP_MC[i] -> Draw("same");
    
//     char Name[100];
//     if(PU == 0)      sprintf(Name, (plotFolderName+"/"+folderName+"/noPU_fit_%d_"+string_year+".png").c_str(),i);
//     if(PU == 1)      sprintf(Name, (plotFolderName+"/"+folderName+"/fit_%d_"+string_year+".png").c_str(),i);
//     c1[i] -> Print(Name,".png");     
//   }
  
//   TCanvas *c2[100]; 
//   for(int i = 0; i < nBins; ++i)
//   {
//     char canvasName[50];
//     sprintf(canvasName, "Et_DA-%0d", i); 
//     c2[i] = new TCanvas(canvasName, canvasName);
//     c2[i]->cd();

//     h_Et[i]->GetXaxis() -> SetTitle("Et");
//     h_Et[i]->GetYaxis()->SetRangeUser(0, std::max(h_Et[i]->GetMaximum(), h_Et_MC[i]->GetMaximum()) + 10. ); 
//     if(i<nBins-1) h_Et[i]->GetXaxis()->SetRangeUser(EtBinEdge.at(i), EtBinEdge.at(i+1)); 
//     else h_Et[i]->GetXaxis()->SetRangeUser(EtBinEdge.at(i), 150.); 
//     //    h_Et[i] -> Draw("e");
//     h_Et[i]->Draw();
//     h_Et_MC[i]->Draw("same");
//     /*gPad->Update();
//     s_Las[i]= (TPaveStats*)(h_Et[i]->GetListOfFunctions()->FindObject("stats"));
//     s_Las[i]->SetTextColor(kBlack);*/
    
//     char Name[100];
//     if(PU == 0)      sprintf(Name, (plotFolderName+"/"+folderName+"/noPU_Et_%d_"+string_year+".png").c_str(),i);
//     if(PU == 1)      sprintf(Name, (plotFolderName+"/"+folderName+"/Et_%d_"+string_year+".png").c_str(),i);
//     c2[i]->Print(Name,".png");      
//   }



//   TCanvas* Et_spectrum = new TCanvas;
//   gPad->SetLogy();
//   //  h_Et_allDA->GetYaxis()->SetRangeUser(0.1, 10000.);
//   h_Et_allDA->GetXaxis()->SetRangeUser(0., 150.);
//   h_Et_allDA->GetXaxis()->SetTitle("Et ");
//   h_Et_allDA->SetMarkerColor(kRed+2);
//   h_Et_allDA->SetMarkerStyle(7);
//   h_Et_allDA->Draw("e");
//    for(int jj = 0; jj < nBins; ++jj){
//      h_Et_MC[jj]->GetXaxis()->SetRangeUser(0., 150.);
//      h_Et_MC[jj]->Draw("same");
//    }
//   TLegend *tspec = new TLegend(0.64,0.80,0.99,0.99);
//   tspec->SetFillColor(0);
//   tspec->SetTextFont(42); 
//   tspec->AddEntry(h_Et_allDA,"DATA","PL");
//   tspec->AddEntry(h_Et_MC[0],"MC ","PL");
//   tspec->Draw(); 
//   Et_spectrum->Print((plotFolderName+"/"+folderName+"/Et_spectrum_"+string_year+".png").c_str(), ".png");


//   TCanvas* cVtx = new TCanvas();
//   h_Vtx_DA->Draw();
//   h_Vtx_MC->SetLineColor(kGreen+2);
//   h_Vtx_MC->Draw("same");
//   cVtx->Print((plotFolderName+"/"+folderName+"/Vtx_"+string_year+".png").c_str(),".png");


//   std::sort(y.begin(), y.end());
//   std::sort(ey.begin(), ey.end());
//   TCanvas* cplot = new TCanvas("gplot", "gplot",100,100,725,500);
//   cplot->cd();

//   std::cout << " sortato range " << std::endl;

//   TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,1.00,1.00);
//   cLeft->SetLeftMargin(0.17); 
//   cLeft->SetRightMargin(0.025); 
//   cLeft->SetBottomMargin(0.17); 
  
//   cLeft->Draw();
 
//   float tYoffset = 1.75; 
//   float tXoffset = 1.6; 
//   float labSize = 0.04;
//   float labSize2 = 0.07;

//   cLeft->cd(); 
//   cLeft->SetGridx();
//   cLeft->SetGridy();
  
//   float x_min = x.at(0)-ex.at(ex.size()-1)-10;
//   float x_max = x.at(x.size()-1)+ex.at(ex.size()-1)+10;
// //   float y_min = y.at(0)-ey.at(ey.size()-1)-0.002;
// //   float y_max = y.at(y.size()-1)+ey.at(ey.size()-1)+0.002;

// //   float y_min = y.at(0)-ey.at(ey.size()-1)-0.005;
// //   float y_max = y.at(y.size()-1)+ey.at(ey.size()-1)+0.005;

//   float y_min = -0.004;
//   float y_max = 0.014;


//   // pad settings
//   TH1F *hPad = (TH1F*)gPad->DrawFrame(0,y_min,130,y_max);
//   hPad->GetXaxis()->SetTitle("E_{T}");
//   hPad->GetYaxis()->SetTitle("E/p_{data}-E/p_{mc}");
//   hPad->GetYaxis()->SetTitleOffset(tYoffset);
//   hPad->GetXaxis()->SetTitleOffset(tXoffset);
//   hPad->GetXaxis()->SetLabelSize(labSize);
//   hPad->GetXaxis()->SetTitleSize(labSize);
//   hPad->GetYaxis()->SetLabelSize(labSize);
//   hPad->GetYaxis()->SetTitleSize(labSize);
//   finalGraph->Draw("P");
//   cplot->Print((plotFolderName+"/"+folderName+"/EoP_vs_Et_"+string_year+".png").c_str(),".png");
// */
  
  std::cout << " plottato tutto " << std::endl;
  //std::cout << "CREATI I FILES" << std::endl;
  return (0);

}
Esempio n. 16
0
void casympp() {
  for (int filecounter = 0; filecounter < 5; filecounter++) {//FILE LOOP
    if (filecounter == 0) {  
      TFile *montecarlo = new TFile("relativeresponsemc1234.root", "Read"); // 40 TO 60 PT AVERAGE
      if (montecarlo->IsOpen()) printf("MonteCarlo File Opened Successfully.\n");
      montecarlo->ls();
      TGraphErrors *relrespmc = (TGraphErrors *)montecarlo->Get("Graph;1 Relative Response");
      TGraphErrors *meanetamc = (TGraphErrors *)montecarlo->Get("Graph;2 Mean Eta Per Bin");
      TFile *ppdata = new TFile("relativeresponse1234.root"); // 40 TO 60 PT AVERAGE
      if (ppdata->IsOpen()) printf ("PP Data File Opened Successfully.\n");
      ppdata->ls();
      TGraphErrors *relresp = (TGraphErrors *)ppdata->Get("Graph;1 Relative Response");
      TGraphErrors *meaneta = (TGraphErrors *)ppdata->Get("Graph;2 Mean Eta Per Bin");
      cout << "File 1 Opened Successfully" << endl;
    }
    if (filecounter == 1) {
      TFile *montecarlo = new TFile("relativeresponsemc123.root", "Read"); // 60 TO 80 PT AVERAGE
      if (montecarlo->IsOpen()) printf("MonteCarlo File Opened Successfully.\n");
      montecarlo->ls();
      TGraphErrors *relrespmc = (TGraphErrors *)montecarlo->Get("Graph;1 Relative Response");
      TGraphErrors *meanetamc = (TGraphErrors *)montecarlo->Get("Graph;2 Mean Eta Per Bin");
      TFile *ppdata = new TFile("relativeresponse123.root"); // 60 TO 80 PT AVERAGE
      if (ppdata->IsOpen()) printf ("PP Data File Opened Successfully.\n");
      ppdata->ls();
      TGraphErrors *relresp = (TGraphErrors *)ppdata->Get("Graph;1 Relative Response");
      TGraphErrors *meaneta = (TGraphErrors *)ppdata->Get("Graph;2 Mean Eta Per Bin");
      cout << "File 2 Opened Successfully" << endl;
    }
    if (filecounter == 2) {
      TFile *montecarlo = new TFile("relativeresponsemc1.root", "Read"); // 80 TO 100 PT AVERAGE
      if (montecarlo->IsOpen()) printf("MonteCarlo File Opened Successfully.\n");
      montecarlo->ls();
      TGraphErrors *relrespmc = (TGraphErrors *)montecarlo->Get("Graph;1 Relative Response");
      TGraphErrors *meanetamc = (TGraphErrors *)montecarlo->Get("Graph;2 Mean Eta Per Bin");
      TFile *ppdata = new TFile("relativeresponse1.root"); // 80 TO 100 PT AVERAGE
      if (ppdata->IsOpen()) printf ("PP Data File Opened Successfully.\n");
      ppdata->ls();
      TGraphErrors *relresp = (TGraphErrors *)ppdata->Get("Graph;1 Relative Response");
      TGraphErrors *meaneta = (TGraphErrors *)ppdata->Get("Graph;2 Mean Eta Per Bin");
      cout << "File 3 Opened Successfully" << endl;
    }
    if (filecounter == 3) {
      TFile *montecarlo = new TFile("relativeresponsemc.root", "Read"); // 100 TO 140 PT AVERAGE
      if (montecarlo->IsOpen()) printf("MonteCarlo File Opened Successfully.\n");
      montecarlo->ls();
      TGraphErrors *relrespmc = (TGraphErrors *)montecarlo->Get("Graph;1 Relative Response");
      TGraphErrors *meanetamc = (TGraphErrors *)montecarlo->Get("Graph;2 Mean Eta Per Bin");
      TFile *ppdata = new TFile("relativeresponse.root"); //100 TO 140 PT AVERAGE
      if (ppdata->IsOpen()) printf ("PP Data File Opened Successfully.\n");
      ppdata->ls();
      TGraphErrors *relresp = (TGraphErrors *)ppdata->Get("Graph;1 Relative Response");
      TGraphErrors *meaneta = (TGraphErrors *)ppdata->Get("Graph;2 Mean Eta Per Bin");
      cout << "File 4 Opened Successfully" << endl;
    }
    if (filecounter == 4) {
      TFile *montecarlo = new TFile("relativeresponsemc12.root", "Read"); // 140 TO 200 PT AVERAGE
      if (montecarlo->IsOpen()) printf("MonteCarlo File Opened Successfully.\n");
      montecarlo->ls();
      TGraphErrors *relrespmc = (TGraphErrors *)montecarlo->Get("Graph;1 Relative Response");
      TGraphErrors *meanetamc = (TGraphErrors *)montecarlo->Get("Graph;2 Mean Eta Per Bin");
      TFile *ppdata = new TFile("relativeresponse12.root"); // 140 TO 200 PT AVERAGE
      if (ppdata->IsOpen()) printf ("PP Data File Opened Successfully.\n");
      ppdata->ls();
      TGraphErrors *relresp = (TGraphErrors *)ppdata->Get("Graph;1 Relative Response");
      TGraphErrors *meaneta = (TGraphErrors *)ppdata->Get("Graph;2 Mean Eta Per Bin");
      cout << "File 5 Opened Successfully" << endl;
    }

  //TGraph *outermc = (TGraph *)montecarlo->Get("Graph;3");
  //TGraph *outerdata = (TGraph *)ppdata->Get("Graph;3");

  //TFile *myfile = new TFile("overlayrelresponse.root", "Recreate");
  Int_t N_pt = relrespmc->GetN();
  cout << N_pt << endl;
  Float_t casym[83];

  for (int ipt = 0; ipt < N_pt; ipt++)  {
    double x, y, xmc, ymc;
    relrespmc->GetPoint(ipt, xmc, ymc);
    relresp->GetPoint(ipt, x, y);
    casym[ipt] = ymc/y;
    cout << casym[ipt] << " and eta average is " << x << endl;
  }

  //OPEN FILE WITH PP DATA STORED IN MY TREE TO ASSIGN NEW BRANCHES WITH THE CORRECTION FACTOR APPLIED TO THE JETS
  if (filecounter == 0) {
    TFile *myfile = TFile::Open("outputrelresp1234.root"); // 40 TO 60 PT AVERAGE
    if (myfile->IsOpen()) printf("File Containing Tree Opened Successfully.\n");
    myfile->ls();
    TTree *mytree = (TTree *)myfile->Get("rr");
    TFile *outf = new TFile("outputrelrespcasym1234.root", "Recreate"); // 40 TO 60 PT AVERAGE
    cout << "File 1" << endl;
  }
  if (filecounter == 1) {
    TFile *myfile = TFile::Open("outputrelresp123.root"); // 60 TO 80 PT AVERAGE
    if (myfile->IsOpen()) printf("File Containing Tree Opened Successfully.\n");
    myfile->ls();
    TTree *mytree = (TTree *)myfile->Get("rr");
    TFile *outf = new TFile("outputrelrespcasym123.root", "Recreate"); // 60 TO 80 PT AVERAGE
    cout << "File 2" << endl;
  }
  if (filecounter == 2) {
    TFile *myfile = TFile::Open("outputrelresp1.root"); // 80 TO 100 PT AVERAGE
    if (myfile->IsOpen()) printf("File Containing Tree Opened Successfully.\n");
    myfile->ls();
    TTree *mytree = (TTree *)myfile->Get("rr");
    TFile *outf = new TFile("outputrelrespcasym1.root", "Recreate"); // 80 TO 100 PT AVERAGE
    cout << "File 3" << endl;
  }
  if (filecounter == 3) {
    TFile *myfile = TFile::Open("outputrelresp.root"); // 100 TO 140 PT AVERAGE
    if (myfile->IsOpen()) printf("File Containing Tree Opened Successfully.\n");
    myfile->ls();
    TTree *mytree = (TTree *)myfile->Get("rr");
    TFile *outf = new TFile("outputrelrespcasym.root", "Recreate"); // 100 TO 140 PT AVERAGE
    cout << "File 4" << endl;
  }
  if (filecounter == 4) {
    TFile *myfile = TFile::Open("outputrelresp12.root"); // 140 TO 200 PT AVERAGE
    if (myfile->IsOpen()) printf("File Containing Tree Opened Successfully.\n");
    myfile->ls();
    TTree *mytree = (TTree *)myfile->Get("rr");
    TFile *outf = new TFile("outputrelrespcasym12.root", "Recreate"); // 140 TO 200 PT AVERAGE
    cout << "File 5" << endl;
  }
 
  //INITIALIZING NECESSARY VARIABLES
  const int nEvents = mytree->GetEntries();
  Float_t etaprobe;
  Float_t ptprobe;
  Float_t etaref;
  Float_t ptref;
  Float_t ptprobecorr = -999;
  Float_t ptrefcorr = -999;
  Float_t myetaprobe2 = -999;
  Float_t myptprobe2 = -999;
  Float_t myetaref2 = -999;
  Float_t myptref2 = -999;
  Float_t myb2 = -999;
 
  //DECLARING BRANCHES
  TTree *rr2 = new TTree ("rr2", "rr2");
  rr2->Branch("ptprobecorr", &ptprobecorr, "ptprobecorr/F");
  rr2->Branch("ptrefcorr", &ptrefcorr, "ptrefcorr/F");
  
  rr2->Branch("myetaprobe2", &myetaprobe2, "myetaprobe2/F");
  rr2->Branch("myptprobe2", &myptprobe2, "myptprobe2/F");
  rr2->Branch("myetaref2", &myetaref2, "myetaref2/F");
  rr2->Branch("myptref2", &myptref2, "myptref2/F");
  rr2->Branch("myb2", &myb2, "myb2/F");

  cout << "Stage 1 Complete" << endl;
 Float_t cms_hcal_edge_pseudorapidity[] = {-5.191, -4.889, -4.716, -4.538, -4.363, -4.191, -4.013, -3.839, -3.664, -3.489, -3.314, -3.139, -2.964, -2.853, -2.650, -2.500, -2.322, -2.172, -2.043, -1.930, -1.830, -1.740, -1.653, -1.566, -1.479, -1.392, -1.305, -1.218, -1.131, -1.044, -0.957, -0.879, -0.783, -0.696, -0.609, -0.522, -0.435, -0.348, -0.261, -0.174, -0.087, 0.000, 0.087,  0.174,  0.261,  0.348,  0.435,  0.522,  0.609, 0.696,  0.783,  0.879,  0.957,  1.044,  1.131,  1.218, 1.305,  1.392,  1.479,  1.566,  1.653,  1.740,  1.830, 1.930,  2.043,  2.172,  2.322,  2.500,  2.650,  2.853, 2.964,  3.139,  3.314,  3.489,  3.664,  3.839,  4.013, 4.191,  4.363,  4.538,  4.716,  4.889,  5.191};
 cout << "a" << endl;
 Int_t bins = sizeof(cms_hcal_edge_pseudorapidity)/sizeof(Float_t);
 cout << bins << endl;
 cout << "b" << endl;
  mytree->SetMakeClass(1);
  mytree->SetBranchAddress("myetaprobe", &etaprobe);
  cout << "c" << endl;
  mytree->SetBranchAddress("myptprobe", &ptprobe);
  cout << "d" << endl;
  mytree->SetBranchAddress("myptref", &ptref);
  cout << "e" << endl;
  mytree->SetBranchAddress("myetaref", &etaref);
  mytree->Print();
  cout << "Stage 2 Complete" << endl;
  for (int i = 0; i < nEvents; i++)   {
    mytree->GetEntry(i);
    for (int bb = 0; bb < bins; bb++)  {
      if (cms_hcal_edge_pseudorapidity[bb] < etaprobe && etaprobe < cms_hcal_edge_pseudorapidity[bb+1]) {
        ptprobecorr = ptprobe*casym[bb];
        //cout << "Probe pt was " << ptprobe << " and corrected probe pt is " << ptprobecorr << " and my eta is " << etaprobe << " and my correction factor is " << casym[b] << endl;
      }
      if (cms_hcal_edge_pseudorapidity[bb] < etaref && etaref < cms_hcal_edge_pseudorapidity[bb+1]) {
        ptrefcorr = ptref*casym[bb];
        //cout << "Refence pt was " << ptref << " and corrected reference pt is " << ptrefcorr << " and my eta is " << etaref << " and my corection factor is " << casym[b] << endl;
      }
    }
    //cout << "Probe pt was " << ptprobe << " and corrected probe pt is " << ptprobecorr << " and my eta is " << etaprobe << endl;
    myb2 = 2*(ptprobecorr - ptrefcorr)/(ptprobecorr + ptrefcorr);
    myetaprobe2 = etaprobe;
    myptprobe2 = ptprobe;
    myetaref2 = etaref;
    myptref2 = ptref;
    rr2->Fill();
  }
  outf->Write();
  outf->Close();
  myfile->Close();
  montecarlo->Close();
  ppdata->Close();

  if (filecounter == 0) {
    TFile *ab = TFile::Open("outputrelrespcasym1234.root"); // 40 TO 60 PT AVERAGE
    TFile *outputf = new TFile("outputrelrespcasymplots1234.root", "Recreate"); // 40 TO 60 PT AVERAGE
    cout << "File 1" << endl;
  }
  if (filecounter == 1) {
    TFile *ab = TFile::Open("outputrelrespcasym123.root"); // 60 TO 80 PT AVERAGE
    TFile *outputf = new TFile("outputrelrespcasymplots123.root", "Recreate"); // 60 TO 80 PT AVERAGE
    cout << "File 2" << endl;
  }
  if (filecounter == 2) {
    TFile *ab = TFile::Open("outputrelrespcasym1.root"); //80 TO 100 PT AVERAGE
    TFile *outputf = new TFile("outputrelrespcasymplots1.root", "Recreate"); // 80 TO 100 PT AVERAGE
    cout << "File 3" << endl;
  }
  if (filecounter == 3) {
    TFile *ab = TFile::Open("outputrelrespcasym.root"); //100 TO 140 PT AVERAGE
    TFile *outputf = new TFile("outputrelrespcasymplots.root", "Recreate"); // 100 TO 140 PT AVERAGE
    cout << "File 4" << endl;
  }
  if (filecounter == 4) {
    TFile *ab = TFile::Open("outputrelrespcasym12.root"); // 140 TO 200 PT AVERAGE
    TFile *outputf = new TFile("outputrelrespcasymplots12.root", "Recreate"); // 140 TO 200 PT AVERAGE
    cout << "File 5" << endl;
  }

printf("About to Open Tree.\n");
TTree *mytree2 = (TTree *)ab->Get("rr2");
int nEvents2 = mytree2->GetEntries();
Float_t etaprobe2 = 0;
Float_t b2 = 0;

mytree2->SetBranchAddress("myetaprobe2", &etaprobe2);
mytree2->SetBranchAddress("myb2", &b2);


Float_t bin_edge_y[] = { -1.5, -1.44, -1.38, -1.32, -1.26, -1.2, -1.14, -1.08, -1.02, -0.96, -0.9, -0.84, -0.78, -0.72, -0.66, -0.6, -0.54, -0.48, -0.42, -0.36, -0.3, -0.24, -0.18, -0.12, -0.06, 0, 0.06, 0.12, 0.18, 0.24, 0.3, 0.36, 0.42, 0.48, 0.54, 0.6, 0.66, 0.72, 0.78, 0.84, 0.9, 0.96, 1.02, 1.08, 1.14, 1.2, 1.26, 1.32, 1.38, 1.44, 1.5};
Int_t bins_y = sizeof(bin_edge_y)/sizeof(Float_t) - 1;
cout << bins_y << endl;
//Float_t cms_hcal_edge_pseudorapidity[] = { -5.191, -4.889, -4.716, -4.538, -4.363, -4.191, -4.013, -3.839, -3.664, -3.489, -3.314, -3.139, -2.964, -2.853, -2.650, -2.500, -2.322, -2.172, -2.043, -1.930, -1.830, -1.740, -1.653, -1.566, -1.479, -1.392, -1.305, -1.218, -1.131, -1.044, -0.957, -0.879, -0.783, -0.696, -0.609, -0.522, -0.435, -0.348, -0.261, -0.174, -0.087, 0.000, 0.087,  0.174,  0.261,  0.348,  0.435,  0.522,  0.609, 0.696,  0.783,  0.879,  0.957,  1.044,  1.131,  1.218, 1.305,  1.392,  1.479,  1.566,  1.653,  1.740,  1.830, 1.930,  2.043,  2.172,  2.322,  2.500,  2.650,  2.853, 2.964,  3.139,  3.314,  3.489,  3.664,  3.839,  4.013, 4.191,  4.363,  4.538,  4.716,  4.889,  5.191};
Int_t binnum = sizeof(cms_hcal_edge_pseudorapidity)/sizeof(Float_t) - 1;
cout << binnum << endl;
TH2F*b = new TH2F("b", "B vs. Eta; Eta; B", binnum, cms_hcal_edge_pseudorapidity, bins_y, bin_edge_y);
b->Sumw2();

mytree2->Draw("myb2:myetaprobe2>>b", "", "");
Float_t mean2[83];
Float_t meanerror2[83];
Float_t etacoordinate2[83];
Float_t relativeresponse2[83];
Float_t relativeresponseerror2[83];
Float_t zero2[83];
TH1D*h1[84];
for (int c = 0; c < binnum; c++)  {
  mean2[c] = -999;
  etacoordinate2[c] = -999;
  zero2[c] = 0;
}

for (int count = 1; count <= binnum; count++)   {
  h1[count] = new TH1D(Form("h1_%d_py", count), Form("h1_%d_py", count), bins_y, bin_edge_y);
  h1[count] = (TH1D*)b->ProjectionY(Form("h1_%d_py", count), count - 1, count, "e");
  h1[count]->Sumw2();
  etacoordinate2[count - 1] = b->GetXaxis()->GetBinCenter(count);
  mean2[count - 1] = h1[count]->GetMean(1);
  meanerror2[count - 1] = h1[count]->GetMeanError(1);
  cout << "My etacoordinate is " << etacoordinate2[count - 1] << " and my count is " << count << " and my mean is " << mean2[count - 1] << " and my error is " << meanerror2[count - 1] << endl;
}

for (int counter = 0; counter < binnum; counter++)  {
  Float_t num = 2 + mean2[counter];
  Float_t den = 2 - mean2[counter];
  relativeresponse2[counter] = num/den;
  Float_t errornum = fabs(meanerror2[counter]/num);
  Float_t errorden = fabs(meanerror2[counter]/den);
  relativeresponseerror2[counter] = relativeresponse2[counter]*(errornum + errorden);
}
TGraphErrors *meanetaabc = new TGraphErrors(binnum + 1, etacoordinate2, mean2, zero2, meanerror2);
TGraphErrors *rrelabc = new TGraphErrors(binnum + 1, etacoordinate2, relativeresponse2, zero2, relativeresponseerror2);


//THIS IS TO PUT IN THE PLOT FOR C_ASYM FOR EACH RANGE
 if (filecounter == 0) {
   TFile *casymplotnew = new TFile("casym_output_new_1234.root", "Recreate"); //40 TO 60 PT AVERAGE
   cout << "Plot 1" << endl;
 }
 if (filecounter == 1) {
   TFile *casymplotnew = new TFile("casym_output_new_123.root", "Recreate"); //60 TO 80 PT AVERAGE
   cout << "Plot 2" << endl;
 }
 if (filecounter == 2) {
   TFile *casymplotnew = new TFile("casym_output_new_1.root", "Recreate"); //80 TO 100 PT AVERAGE
   cout << "Plot 3" << endl;
 }
 if (filecounter == 3) {
   TFile *casymplotnew = new TFile("casym_output_new.root", "Recreate"); //100 TO 140 PT AVERAGE
   cout << "Plot 4" << endl;
 }
 if (filecounter == 4) {
   TFile *casymplotnew = new TFile("casym_output_new_12.root", "Recreate"); //140 TO 200 PT AVERAGE
   cout << "Plot 5" << endl;
 }

TGraphErrors *casymabc = new TGraphErrors(binnum + 1, etacoordinate2, casym, zero2, zero2); 

casymabc->SetTitle("C_Asym v. Eta");
casymabc->GetXaxis()->SetTitle("Eta");
casymabc->GetYaxis()->SetTitle("R_{mc}/R_{data}");
casymabc->SetMarkerStyle(6);
casymabc->SetLineColor(1);

casymplotnew->cd();
casymabc->Write();
casymplotnew->Close();
//THIS IS THE END OF THE PLOTTING FOR C_ASYM FOR EACH RANGE

meanetaabc->SetTitle("Mean Eta Per Bin");
meanetaabc->GetXaxis()->SetTitle("Eta");
meanetaabc->GetYaxis()->SetTitle("Mean");
meanetaabc->SetMarkerStyle(6);
meanetaabc->SetLineColor(1);

rrelabc->SetTitle("Relative Response");
rrelabc->GetXaxis()->SetTitle("Probe Eta");
rrelabc->GetYaxis()->SetTitle("Relative Response");
rrelabc->SetMarkerStyle(6);
rrelabc->SetLineColor(1);

TCanvas *canvaseta = new TCanvas(1);
canvaseta->cd();
meanetaabc->Draw("AP");

TCanvas *canvasrelresp = new TCanvas(2);
canvasrelresp->cd();
rrelabc->Draw("AP");

outputf->cd();
rrelabc->Write();
meanetaabc->Write();
b->Write();
outputf->Close();
ab->Close();
  } //END FILE LOOP
}
Esempio n. 17
0
void ExtractOutputHistos(Bool_t onlyPrims=0,Bool_t onlyPion=0,Int_t plotFlag=0) {

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

  const Int_t nbins=20;
  Double_t ptmin=0.06;//04;
  Double_t ptmax=2.0;//GeV
  Double_t logxmin = TMath::Log10(ptmin);
  Double_t logxmax = TMath::Log10(ptmax);
  Double_t binwidth = (logxmax-logxmin)/(nbins+1);
  enum {nb=nbins+1};
  Double_t xbins[nb];
  xbins[0] = ptmin;
  for (Int_t i=1;i<=nbins;i++) {
    xbins[i] = ptmin + TMath::Power(10,logxmin+(i)*binwidth);
    //    cout<<xbins[i]<<endl;
  }
  //  TH1F *h = new TH1F("h","hist with log x axis",nbins,xbins);

  TH1F *hMultCount = new TH1F("mult","averaged multiplicity (charg. prim)",80,-4.,4.);
  hMultCount->GetXaxis()->SetTitle("eta");
  hMultCount->GetYaxis()->SetTitle("N/d#eta");

  TH1F *hAllMC = new TH1F("allMC","All Tracks MC primaries",nbins,xbins);
  TH1F *hAllFound = new TH1F("allFound","All Tracks found",nbins,xbins);
  TH1F *hImperfect = new TH1F("imperfect","Imperfect tracks",nbins,xbins);
  TH1F *hPerfect = new TH1F("perfect","Perfect tracks",nbins,xbins);
  TH1F *hEff = new TH1F("efficiency","Efficiency (Perfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hFake = new TH1F("fake","Fake tracks (Inperfect tracks in \"ALL MC\")",nbins,xbins);
  TH1F *hPurity = new TH1F("purity","Purity (Perfect tracks in \"All Found\")",nbins,xbins);
  TH1F *hAnna = new TH1F("annaEff","AnnalisaEff ",nbins,xbins);
  TH1F *hNoMCTrack = new TH1F("noMCtrack","noMCtrack ",nbins,xbins);

  TH1F *hEta = new TH1F("","",50,-2,2);
  //  TH1F *hEtaMC = new TH1F("","",50,-2,2);

  TH2D *h2Ddca = new TH2D("dca2D","DCAvsPt2D",nbins,xbins,50,-0.05,0.05);
  TH2D *h2Dpt = new TH2D("dPt2D","dPtdvsPt2D",nbins,xbins,50,-25,25);

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

  TFile* esdFile = TFile::Open("AliESDs.root");
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", "AliESDs.root");
    return;
  }
  AliESDEvent *esd = new AliESDEvent();
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return;
  }
  esd->ReadFromTree(tree);
  
  Int_t nTrackTotalMC = 0;
  Int_t nTrackFound = 0;
  Int_t nTrackImperfect = 0;
  Int_t nTrackPerfect = 0;
  Int_t nNoMCTrack = 0;

  
  for(Int_t iEv =0; iEv<tree->GetEntries(); iEv++){
    tree->GetEvent(iEv);
    runLoader->GetEvent(iEv);
    
    printf("+++ event %i (of %lld) +++++++++++++++++++++++  # ESDtracks: %d \n",iEv,tree->GetEntries()-1,esd->GetNumberOfTracks());
    Int_t nESDtracks = esd->GetNumberOfTracks();
    for (Int_t iTrack = 0; iTrack < nESDtracks; iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);
      if (!(iTrack%1000)) printf("event %i: ESD track count %d (of %d)\n",iEv,iTrack,nESDtracks);

      Int_t label = track->GetLabel();
  
      Int_t idx[12];
      //      Int_t ncl = track->GetITSclusters(idx);
   
      if(label<0) {
	//	cout<< " ESD track label " << label;
	//	cout<<"  ---> imperfect track (label "<<label<<"<0) !! -> track Pt: "<< track->Pt() << endl;
      }

      AliStack* stack = runLoader->Stack();
      //     nTrackTotalMC += stack->GetNprimary();
    

      TParticle* particle = stack->Particle(TMath::Abs(label)); 
      Double_t pt = track->Pt();
      
      if(particle) {

	if (TMath::Abs(particle->Eta())>etaCut) continue;

	Double_t ptMC = particle->Pt();

	// Efficiencies
	if (onlyPion && TMath::Abs(particle->GetPdgCode())!=211) continue;

	if ( (!onlyPrims) || stack->IsPhysicalPrimary(TMath::Abs(label))) {
	  //  cout<<" # clusters "<<ncl<<endl;

	  nTrackFound++;
	  hAllFound->Fill(ptMC);
	  hEta->Fill(track->Eta());
	  
	  if (label<0) {
	    nTrackImperfect++;
	    hImperfect->Fill(ptMC);
	  } else {
	    nTrackPerfect++;
	    hPerfect->Fill(ptMC);
	  }

	}


	// following only for "true tracks, pions

	if(particle->Pt() < 0.001)continue;
	if (TMath::Abs(particle->GetPdgCode())!=211) continue;
	if (label>0) {
	  
	  // Impact parameters for Pions only
	  Double_t dca = track->GetD(0,0,0.5);
	  h2Ddca->Fill(ptMC,dca);
	  
	  // Pt resolution for Pions only
	  Double_t dPt = (pt-ptMC)/ptMC*100;
	  h2Dpt->Fill(ptMC,dPt);
	}

      } else {
	nNoMCTrackFound++;
	hNoMCTrack->Fill(pt);
	cout<<" according MC particle not found"<<endl;
      }
      
    } //entries track esd
  

  }//entries tree
  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

 
  // Count trackable MC tracks
  CountTrackableMCs(hAllMC, onlyPrims, onlyPion);


  // Count trackable MC tracks
  CountPrimaries(hMultCount);

 


  // Get Errors right
  hMultCount->Sumw2();
  hAllMC->Sumw2();   
  hAllFound->Sumw2();
  hPerfect->Sumw2(); 
  hImperfect->Sumw2(); 
  h2Dpt->Sumw2();
  h2Ddca->Sumw2();

  // -- Global efficienies

  nTrackTotalMC = hAllMC->GetEntries();
  Double_t eff = ((Double_t)nTrackPerfect)/nTrackTotalMC;
  printf("-> Total number of events: %lld -> MCtracks %d -> nPerfect %d  -> Eff: %3.2lf \n",
	 tree->GetEntries(),nTrackTotalMC,nTrackPerfect,eff);

  Double_t purity = ((Double_t)nTrackPerfect)/nTrackFound;
  printf("-> Total number of events: %lld -> FoundTracks %d -> nPerfect %d  -> Purity: %3.2lf \n",
	 tree->GetEntries(),nTrackFound,nTrackPerfect,purity);

  // Efficiencies - and normalize to 100%

  TF1 f1("f1","100+x*0",0.,1.e3);

  hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
  hPurity->Multiply(&f1);
  hPurity->SetMarkerColor(kGreen);
  hPurity->SetMarkerStyle(21);
  hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hPurity->SetStats(0);

  hPurity->GetYaxis()->SetRangeUser(0,100);
  hPurity->SetTitle("Efficiency & Purity");

  hEff->Divide(hPerfect,hAllMC,1,1,"b");
  hEff->Multiply(&f1);
  hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hEff->SetMarkerColor(kBlue);
  hEff->SetMarkerStyle(21);
  hEff->SetStats(0);

  hFake->Divide(hImperfect,hAllMC,1,1,"b");
  hFake->Multiply(&f1);
  hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hFake->SetMarkerColor(kRed);
  hFake->SetMarkerStyle(21);
  hFake->SetStats(0);


  hAnna->Divide(hAllFound,hAllMC,1,1,"b");
  hAnna->Multiply(&f1);
  hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  hAnna->SetMarkerColor(kBlack);
  hAnna->SetMarkerStyle(21);
  hAnna->SetStats(0);

  TCanvas *c1 = new TCanvas("c1","NoMCTrackFound");//,200,10,900,900);
  TVirtualPad *pad =   c1->cd();
  pad->SetGridx();   pad->SetGridy();
  hNoMCTrack->Draw();

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  hPurity->Draw("E");
  hEff->Draw("Same E");
  hFake->Draw("Same E");
  hAnna->Draw("Same E");

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
  leg->Draw();


  if (plotFlag==1){
    hAllMC->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAllMC->Draw();  // MC pt distribution
    hAllFound->SetLineColor(2);
    hAllFound->Draw("same");  // MC pt distribution
  }
 
 
  /*

  .L ~/ITSupgrade/BuildDetector/DetectorK.cxx+
  
  // All NEW
  DetectorK its("ALICE","ITS");
  its.MakeAliceAllNew(0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,3,2);
  c->Draw("C");


  // Current
  DetectorK its("ALICE","ITS");
  its.MakeAliceCurrent(0,0);
  its.SetMaxRadiusOfSlowDetectors(0.01);
  its.SolveViaBilloir(0);
  TGraph *c = its.GetGraphRecoEfficiency(0,4,2);
  c->Draw("C");

  */

  TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
  c3->Divide(2,1); c3->cd(1);
  // Impact parameter

  // Impact parameter resolution ---------------
  h2Ddca->Draw("colz");
  h2Ddca->FitSlicesY() ;
  TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
  TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
  TGraphErrors *d0 = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
    d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
    d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
  }
  d0->SetMarkerStyle(21);
  d0->SetMaximum(200);  d0->SetMinimum(0);
  d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
  d0->SetName("dca");  d0->SetTitle("DCAvsPt");

  c3->cd(1);  h2Ddca->Draw("surf2");
  c3->cd(2);  d0->Draw("APE");

  // PT RESOLUTION ------------
  TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);
  c4->Divide(2,1); c4->cd(1);
  // Impact parameter
  h2Dpt->Draw("colz");
  h2Dpt->FitSlicesY() ;
  TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
  TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
  TGraphErrors *gPt = new TGraphErrors(); 
  for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
    gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
    gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
  }
  gPt->SetMarkerStyle(21);
  gPt->SetMaximum(20);  gPt->SetMinimum(0);
  gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
  gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
  gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");

  c4->cd(1);  h2Dpt->Draw("surf2");
  c4->cd(2);  gPt->Draw("APE");


  // EXPORT --------

  TFile f("histos.root","RECREATE");

  hMultCount->Write();
  hAllMC->Write();
  hAllFound->Write();
  hImperfect->Write();
  hPerfect->Write();
  hNoMCTrack->Write();

  hPurity->Write();
  hEff->Write();
  hFake->Write();
  hAnna->Write();

  h2Ddca->Write();
  d0->Write();

  h2Dpt->Write();
  gPt->Write();

  f.Close();

  return;

}
Esempio n. 18
0
void plotMerged(Bool_t onlyPlot=0) {

  gStyle->SetPalette(1);
 
  TFile f("histoSum.root","UPDATE");

  TH1F* hAllMC = f.Get("allMC");
  TH1F* hAllFound= f.Get("allFound");
  TH1F* hImperfect= f.Get("imperfect");
  TH1F* hPerfect= f.Get("perfect");
  TH1F* hNoMCTrack= f.Get("noMCtrack");
  
  
  // have to be recalculated
  TH1F* hPurity = f.Get("purity");
  TH1F* hEff= f.Get("efficiency");
  TH1F* hFake= f.Get("fake");
  TH1F* hAnna= f.Get("annaEff");

  TH2D* h2Ddca= f.Get("dca2D");
  TGraphErrors *d0= f.Get("dca");

  TH2D* h2Dpt= f.Get("dPt2D");
  TGraphErrors *gPt= f.Get("dPt");


  if (!onlyPlot) {
    /*    // Get Errors right
    hAllMC->Sumw2();   
    hAllFound->Sumw2();
    hPerfect->Sumw2(); 
    hImperfect->Sumw2(); 
    h2Dpt->Sumw2();
    h2Ddca->Sumw2();
    */

    // Efficiencies - and normalize to 100%
    
    TF1 f1("f1","100+x*0",0.,1.e3);
    
    hPurity->Divide(hPerfect,hAllFound,1,1,"b"); 
    hPurity->Multiply(&f1);
    hPurity->SetMarkerColor(kGreen);
    hPurity->SetMarkerStyle(21);
    hPurity->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hPurity->SetStats(0);
    
    hPurity->GetYaxis()->SetRangeUser(0,100);
    hPurity->SetTitle("Efficiency & Purity");
    
    hEff->Divide(hPerfect,hAllMC,1,1,"b");
    hEff->Multiply(&f1);
    hEff->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hEff->SetMarkerColor(kBlue);
    hEff->SetMarkerStyle(21);
    hEff->SetStats(0);
    
    hFake->Divide(hImperfect,hAllMC,1,1,"b");
    hFake->Multiply(&f1);
    hFake->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hFake->SetMarkerColor(kRed);
    hFake->SetMarkerStyle(21);
    hFake->SetStats(0);
    
    hAnna->Divide(hAllFound,hAllMC,1,1,"b");
    hAnna->Multiply(&f1);
    hAnna->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    hAnna->SetMarkerColor(kBlack);
    hAnna->SetMarkerStyle(21);
    hAnna->SetStats(0);
    
    
    // Impact parameter resolution ---------------
    TCanvas *c3 = new TCanvas("c3","impact");//,200,10,900,900);
    c3->Divide(2,1); c3->cd(1);
    h2Ddca->DrawCopy("colz");
    h2Ddca->FitSlicesY() ;
    TH2D *dcaM = (TH2D*)gDirectory->Get("dca2D_1"); dcaM->Draw("same");
    TH2D *dcaRMS = (TH2D*)gDirectory->Get("dca2D_2"); //dcaRMS->Draw();
    TGraphErrors *d0 = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dcaRMS->GetXaxis()->GetNbins(); ibin++) {
      d0->SetPoint(     ibin-1,dcaRMS->GetBinCenter(ibin),dcaRMS->GetBinContent(ibin)*1e4); // microns
      d0->SetPointError(ibin-1,0,dcaRMS->GetBinError(ibin)*1e4); // microns
    }
    d0->SetMarkerStyle(21);
    d0->SetMaximum(200);  d0->SetMinimum(0);
    d0->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    d0->GetYaxis()->SetTitle("R-#phi Pointing Resolution (#mum)");
    d0->SetName("dca");  d0->SetTitle("DCAvsPt");
    //  c3->cd(1);  h2Ddca->Draw("surf2");
    c3->cd(2);  d0->Draw("APE");
    
    // PT RESOLUTION ------------
    TCanvas *c4 = new TCanvas("c4","pt resolution");//,200,10,900,900);  
    c4->Divide(2,1); c4->cd(1);
    h2Dpt->DrawCopy("colz");
    h2Dpt->FitSlicesY() ;
    TH2D *dPtM = (TH2D*)gDirectory->Get("dPt2D_1"); dPtM->Draw("same");
    TH2D *dPtRMS = (TH2D*)gDirectory->Get("dPt2D_2"); // dPtRMS->Draw("");
    TGraphErrors *gPt = new TGraphErrors(); 
    for (Int_t ibin =1; ibin<=dPtRMS->GetXaxis()->GetNbins(); ibin++) {
      gPt->SetPoint(     ibin-1,dPtRMS->GetBinCenter(ibin),dPtRMS->GetBinContent(ibin)); 
      gPt->SetPointError(ibin-1,0,dPtRMS->GetBinError(ibin)); 
    }
    gPt->SetMarkerStyle(21);
    gPt->SetMaximum(20);  gPt->SetMinimum(0);
    gPt->GetXaxis()->SetTitle("transverse momentum p_{t} (GeV)");
    gPt->GetYaxis()->SetTitle("relative momentum resolution (%)");
    gPt->SetName("dPt");  gPt->SetTitle("DPTvsPt");
    //  c4->cd(1);  h2Dpt->Draw("surf2");
    c4->cd(2);  gPt->Draw("APE");


    // overwrite with normalized graphs
    hPurity->Write();
    hEff->Write();
    hFake->Write();
    hAnna->Write();
    h2Ddca->Write();
    d0->Write();
    h2Dpt->Write();
    gPt->Write();
   
  }
  
  // Plots

  TCanvas *c2 = new TCanvas("c2","Eff&Purity");//,200,10,900,900);
  TVirtualPad *pad =   c2->cd();
  pad->SetGridx();   pad->SetGridy();
  //  pad->SetLogx();

  TLegend *leg = new TLegend(0.1,0.8,0.6,0.9);leg->SetFillColor(0);
  leg->AddEntry(hPurity,"Purity (\"Perfect tracks\" within \"Found Tracks\")","PE");
  leg->AddEntry(hEff,"Efficiency (\"Perfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hFake,"Fake (\"Inperfect tracks\" within \"MC findable Tracks\")","PE");
  leg->AddEntry(hAnna,"AnnaLisa - Efficiency (\"Found tracks\" within \"MC findable Tracks\")","PE");
 

  hPurity->DrawCopy("E");
  hEff->DrawCopy("Same E");
  hFake->DrawCopy("Same E");
  hAnna->DrawCopy("Same E");
  leg->Draw();

  c2->SaveAs("EffPlot.png");

  f.Close();



}
Esempio n. 19
0
void vertexAssociationFit(TFile* input, TFile* output) {
  
  // style
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(111);
  gStyle->SetOptTitle(1);
  // margins
  gStyle->SetStatFormat("6.4g"); 
  gStyle->SetFitFormat("5.2g"); 
  gStyle->SetPadTopMargin(0.07);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.1);
  gStyle->SetPadRightMargin(0.02);

  // prepare the output
  // * canvas to put the fit per bin
  TCanvas* canvas_0 = new TCanvas("FitPerBin","Fit for each vertex bin",1200,900);
  canvas_0->Divide(4,4);
  // * canvas to put the plots per bin
  TCanvas* canvas_1 = new TCanvas("EffPerBin","Efficiency vs purity for each vertex bin",1200,900);
  canvas_1->Divide(4,4);
  // * canvas with other plots: slope vs nvertices, efficiency and purity for fixed cut, etc.
  TCanvas* canvas_2 = new TCanvas("jvAssociation","Efficiency vs purity summary plots",1000,600);
  canvas_2->Divide(4,2);
  // summary graphs
  TGraphErrors* slopeGraph  = new TGraphErrors(nbins);
  slopeGraph->SetNameTitle("slopeGraph","expo slope in each n_PU bin");
  TGraphErrors* constGraph  = new TGraphErrors(nbins);
  constGraph->SetNameTitle("constGraph","expo normalization in each n_PU bin");
  TGraphErrors* cuteffGraph = new TGraphErrors(nbins);
  cuteffGraph->SetNameTitle("cuteffGraph","Efficiency in each n_PU bin");
  TGraphErrors* cutpurGraph = new TGraphErrors(nbins);
  cutpurGraph->SetNameTitle("cutpurGraph","Purity in each n_PU bin");
  TGraphErrors* effcutGraph = new TGraphErrors(nbins);
  effcutGraph->SetNameTitle("effcutGraph","Cut for fixed efficiency in each n_PU bin");
  TGraphErrors* effpurGraph = new TGraphErrors(nbins);
  effpurGraph->SetNameTitle("effpurGraph","Purity for fixed efficiency in each n_PU bin");
  TGraphErrors* purcutGraph = new TGraphErrors(nbins);
  purcutGraph->SetNameTitle("purcutGraph","Cut for fixed purity in each n_PU bin");
  TGraphErrors* pureffGraph = new TGraphErrors(nbins);
  pureffGraph->SetNameTitle("pureffGraph","Efficiency for fixed purity in each n_PU bin");
  // loop over the directories
  double slope = 0.;
  double slopeError = -999.;

  double constnorm = 0.;
  double constError = -999.;

  TGraphErrors* result = NULL;
  TFitResultPtr fitRes(-1);
  double x,y, xe,ye;
  unsigned int index;
  TString histonames[nbins+1];
  TString labelnames[nbins+1];


  // get the histogram    
  TH1* evts_per_PUbin = (TH1*)input->Get("finaldistros_ssvhpt/GoodJet/GoodJet_nvertices");
  double sumTot(0), effTot(0);

  TLatex *latexLabel = new TLatex();
  latexLabel->SetTextSize(0.05);
  latexLabel->SetTextFont(42);
  latexLabel->SetLineWidth(2);
  latexLabel->SetNDC();
   
  TLatex *latexLabel2 = new TLatex();
  latexLabel2->SetTextSize(0.09);
  latexLabel2->SetTextFont(42);
  latexLabel2->SetLineWidth(2);
  latexLabel2->SetNDC();
   
  for(unsigned int i=0; i<=nbins; ++i) {
    // get the histogram  
    labelnames[i]=Form("n_PU = %d bin",i);
    std::cout<<"labelnames["<<i<<"]"<<labelnames[i]<<std::endl;
    histonames[i]=Form("finaldistros_ssvhpt/GoodJet/GoodJet_jetvtx_ratio2b_%d_PUvtx",i);
    std::cout<<"seizing: histonames["<<i<<"]:"<<histonames[i]<<std::endl;
    TH1* fraction = (TH1*)input->Get(histonames[i]);
    //fraction->Rebin(2);
    // do it
    canvas_0->cd(i+1);
    fraction->SetTitle("");
    MakeNiceHistoStyle(fraction);
    if(fraction) vertexAssociationAnalysis(fraction,i,slope,slopeError,constnorm,constError,result,fitRes);
    latexLabel2->DrawLatex(0.15, 0.85,labelnames[i]);
    latexLabel2->DrawLatex(0.15, 0.75,"CMS #sqrt{s}= 7 TeV");
    gPad->Draw();
    gPad->SetLogy();
    MakeNiceStatBox(fraction);
    output->cd();
    fraction->Write();
    // plot
    canvas_1->cd(i+1);
    result->SetTitle("");
    MakeNiceGraphStyle(result);
    result->Draw("alP");
    latexLabel->DrawLatex(0.05, 0.95,labelnames[i]);
    result->GetXaxis()->SetTitle("Purity");
    result->GetYaxis()->SetTitle("Efficiency");
    result->GetXaxis()->SetRangeUser(0.8,1.2);
    result->GetYaxis()->SetRangeUser(0.85,1.0);
    output->cd();
    result->Write(); 
    // extract other quantities
    slopeGraph->SetPoint(i,i,slope);
    slopeGraph->SetPointError(i,0,slopeError);
    slopeGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    constGraph->SetPoint(i,i,constnorm);
    constGraph->SetPointError(i,0,constError);
    constGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    index = unsigned(((defaultCut-cutmin)/(cutmax-cutmin)*nSteps)+0.5);
    findWorkingPoint(result,index,x,y,xe,ye,1);

    // to compute the weighted efficiency
    int ivtx_bin=evts_per_PUbin->FindBin(i+1); 
    sumTot+=evts_per_PUbin->GetBinContent(ivtx_bin);
    effTot+=y*evts_per_PUbin->GetBinContent(ivtx_bin);

    cuteffGraph->SetPoint(i,i,y);
    cuteffGraph->SetPointError(i,0,ye);
    cuteffGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    cutpurGraph->SetPoint(i,i,x);
    cutpurGraph->SetPointError(i,0,xe);
    cutpurGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    x = defaultPur;
    findWorkingPoint(result,index,x,y,xe,ye,2);
    purcutGraph->SetPoint(i,i,cutmin+(cutmax-cutmin)/nSteps*index);
    purcutGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    pureffGraph->SetPoint(i,i,y);
    pureffGraph->SetPointError(i,0,ye);
    pureffGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    y = defaultEff;
    findWorkingPoint(result,index,x,y,xe,ye,3);
    effcutGraph->SetPoint(i,i,cutmin+(cutmax-cutmin)/nSteps*index);
    effcutGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    effpurGraph->SetPoint(i,i,x);
    effpurGraph->SetPointError(i,0,xe);
    effpurGraph->GetXaxis()->SetTitle("n_{PU} vertices");
    std::cout<<"end of other quantities: bin["<<i<<"]"<<std::endl;
  }

  std::cout << "Weighted Efficiency" << effTot/sumTot << std::endl;

  // plot summary graphs
  TF1* f=NULL;
  canvas_2->cd(1);
  MakeNiceGraphStyle(slopeGraph);
  slopeGraph->Draw("alP");
  slopeGraph->Fit("pol1");
  f = slopeGraph->GetFunction("pol1");
  if(f->GetParError(1)>fabs(f->GetParameter(1))) slopeGraph->Fit("pol0");
  
  canvas_2->cd(2);
  MakeNiceGraphStyle(constGraph);
  constGraph->Draw("alP");
  constGraph->Fit("pol2");
  f = constGraph->GetFunction("pol2");
  
  canvas_2->cd(3);
  MakeNiceGraphStyle(cuteffGraph);
  cuteffGraph->Draw("alP");
  cuteffGraph->Fit("pol1");
  f = cuteffGraph->GetFunction("pol1");
  if(f->GetParError(1)>fabs(f->GetParameter(1))) cuteffGraph->Fit("pol0");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Jet Fraction cut: %.2f",defaultCut));
  
  canvas_2->cd(4);
  MakeNiceGraphStyle(cutpurGraph);
  cutpurGraph->Draw("alP");
  cutpurGraph->Fit("pol1");
  f = cutpurGraph->GetFunction("pol1");
  if(f->GetParError(1)>fabs(f->GetParameter(1))) cutpurGraph->Fit("pol0");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Jet Fraction cut: %.2f",defaultCut));
  
  canvas_2->cd(5);
  MakeNiceGraphStyle(effcutGraph);
  effcutGraph->Draw("alP");
  effcutGraph->Fit("expo");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Fixed efficiency: %.2f",defaultEff));
  
  canvas_2->cd(6);
  MakeNiceGraphStyle(effpurGraph);
  effpurGraph->Draw("alP");
  effpurGraph->Fit("pol1");
  f = effpurGraph->GetFunction("pol1");
  if(f->GetParError(1)>fabs(f->GetParameter(1))) effpurGraph->Fit("pol0");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Fixed efficiency: %.2f",defaultEff));
  
  canvas_2->cd(7);
  gPad->SetLeftMargin(0.12);
  MakeNiceGraphStyle(purcutGraph);
  purcutGraph->Draw("alP");
  purcutGraph->Fit("expo");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Fixed purity: %.3f",defaultPur));
  
  canvas_2->cd(8);
  MakeNiceGraphStyle(pureffGraph);
  pureffGraph->Draw("alP");
  pureffGraph->Fit("pol1");
  f = pureffGraph->GetFunction("pol1");
  if(f->GetParError(1)>fabs(f->GetParameter(1))) pureffGraph->Fit("pol0");
  latexLabel2->DrawLatex(0.15, 0.15,Form("Fixed purity: %.3f",defaultPur));
  
  // save
  output->cd();
  canvas_0->Write();
  canvas_1->Write();
  canvas_2->Write();

  canvas_0->SaveAs((TString)(canvas_0->GetName())+".png");
  canvas_1->SaveAs((TString)(canvas_1->GetName())+".png");
  canvas_2->SaveAs((TString)(canvas_2->GetName())+".png");

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

  TCanvas *ctemp = new TCanvas();

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

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

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

  unsigned colorcounter=38;

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

    if ( line == "" )
      continue;

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


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

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

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

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

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

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

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

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

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

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

  }

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

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

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

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

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

  fout->Close();

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

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

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

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

  return 0;
}
void minuitFit()
{

  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  cout << "Must Use Same Binning as previous Analysis!" << endl;

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  haveName = kFALSE;
  char fname[100];
  TFile* file;
  Bool_t makePDF = checkMakePDF();
  Bool_t makeROOT = checkMakeRoot();
  if(makeROOT){
    sprintf(fname,"/Users/zach/Research/pythia/200GeVTemplate/FFOutput/%s_FIT.root",FileNameR);
    file = new TFile(fname,"RECREATE");
    if (file->IsOpen()==kFALSE)
    {
      std::cout << "!!! Outfile Not Opened !!!" << std::endl;
      makeROOT = kFALSE;
    }
  }


  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/200GeVTemplate/currentTemplate.root");
  TFile *fT = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fT->IsOpen()==kFALSE || fD->IsOpen()==kFALSE)
  { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
    << "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
    exit(1); }

  // Set constants and projection bins (from header file anaConst, analysis constants)

  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;

  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  TCanvas* fitResultP = new TCanvas("fitResultP","RB Previous Analysis",150,0,1150,1000);
  TCanvas* scaleCheck = new TCanvas("scaleCheck","Check scale diff",150,0,1150,1000);
  TCanvas* prettyPlot = new TCanvas("prettyPlot","PrettyPlot",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);
  fitResultP->Divide(2,2);
  scaleCheck->Divide(1,2);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[4][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Double_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH2F*)fD->Get("histoNorms");
   // Get Previous Analysis
  TFile *file3 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_25_35.root");
  Hdphi[0]  = (TH1D*)file3->Get("fit_25_35");
  HpphiD[0] = (TH1D*)file3->Get("De_25_35");
  HpphiB[0] = (TH1D*)file3->Get("Be_25_35");
  TFile *file4 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_55_65.root");
  Hdphi[1]  = (TH1D*)file4->Get("fit_55_65");
  HpphiD[1] = (TH1D*)file4->Get("De_55_65");
  HpphiB[1] = (TH1D*)file4->Get("Be_55_65");

  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
  {
    bPtNorms[ptbin]   = (TH1F*)fT->Get(Form("beEventTally_%i",ptbin));
    cPtNorms[ptbin]   = (TH1F*)fT->Get(Form("ceEventTally_%i",ptbin));

    norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
    norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
    normB = bPtNorms[ptbin]->GetBinContent(1);
    normC = cPtNorms[ptbin]->GetBinContent(1);

    cout << ptbin << "; 0: " << norm0 << " 2: " << norm2 << endl;

    if( norm0 == 0)
    {
      cout << ptbin << " For this bin, some norm0 = 0" << endl;
      continue;
    }
    if( norm2 == 0 )
    {
      cout << ptbin << " For this bin, some norm2 = 0" << endl;
      continue;
    }
    if( normB == 0 )
    {
      cout << ptbin << " For this bin, some normB = 0" << endl;
      continue;
    }
    if( normC == 0)
    {
      cout << ptbin << " For this bin, some normC = 0" << endl;
      continue;
    }
    plotbin = ptbin;
    // Init necessary plotting tools
    lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
    sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
    lbl[ptbin]->AddText(textLabel);
    lbl[ptbin]->SetFillColor(kWhite);

    projB[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawbe_%i",ptbin));
    projC[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawce_%i",ptbin));
    projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
    projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
 
    pileupCorrect[ptbin][0] = (TH1D*)fD->Get(Form("pileupCorrection_%i_0",ptbin));
    pileupCorrect[ptbin][1] = (TH1D*)fD->Get(Form("pileupCorrection_%i_2",ptbin));
    pileupCorrect[ptbin][0]->Sumw2();
    pileupCorrect[ptbin][1]->Sumw2();

    // Do any rebinning
    Int_t RB = 1;
    projB[ptbin]->Rebin(RB);
    projC[ptbin]->Rebin(RB);
    projData0[ptbin]->Rebin(RB);
    projData2[ptbin]->Rebin(RB);

    // Clone to make plots without effecting fits
    plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
    plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
    plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

    // Set features that are the same in plots
    projData0[ptbin]->SetLineColor(kBlue);
    projData2[ptbin]->SetLineColor(kGreen+3);
    projB[ptbin]->SetLineColor(kRed);
    projC[ptbin]->SetLineColor(kBlack);
    projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
    plotD0[ptbin]->SetLineColor(kBlue);
    plotD2[ptbin]->SetLineColor(kGreen+3);
    plotD0[ptbin]->SetMarkerStyle(20);
    plotD0[ptbin]->SetMarkerColor(kBlue);
    plotD0[ptbin]->SetMarkerSize(0.4);
    plotB[ptbin]->SetLineColor(kRed);
    plotC[ptbin]->SetLineColor(kBlack);
    plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

    combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    combData[ptbin] -> Add(projData2[ptbin]);
    combData[ptbin]->SetLineColor(kBlue);
    combData[ptbin]->SetMarkerStyle(20);
    combData[ptbin]->SetMarkerColor(kBlue);
    combData[ptbin]->SetMarkerSize(0.4);
    combData[ptbin]->SetTitle("");

    // Normalize
    projB[ptbin]     -> Scale(1./normB);
    projC[ptbin]     -> Scale(1./normC);
    projData0[ptbin] -> Scale(1./norm0);
    projData2[ptbin] -> Scale(1./norm2);
    plotD0[ptbin]    -> Scale(1./norm0);
    plotD2[ptbin]    -> Scale(1./norm2);
    plotB[ptbin]     -> Scale(1./normB);
    plotC[ptbin]     -> Scale(1./normC);
    combData[ptbin]  -> Scale(1./(norm0+norm2));

    // Subtract Pileup correction (data only)
    projData0[ptbin]->Sumw2();projData2[ptbin]->Sumw2();
    //projData0[ptbin]->Add(pileupCorrect[ptbin][0],-1);
    //projData2[ptbin]->Add(pileupCorrect[ptbin][1],-1);

    // Draw Templates on own plots
    if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
    if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
    plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.8);
    plotC[ptbin]  -> Draw("hist");
    plotB[ptbin]  -> Draw("same hist");
    plotD0[ptbin] -> Draw("same");
    plotD2[ptbin] -> Draw("same");
    lbl[ptbin]    -> Draw("same");

    TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
    leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
    leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
    leg->AddEntry(projData0[ptbin],"HT0","lpe");
    leg->AddEntry(projData2[ptbin],"HT2","lpe");
    leg->Draw();

    deltaPhi->cd(1);
    Hdphi[0]->Draw("same");
    deltaPhi->cd(4);
    Hdphi[1]->Draw("same");

      if(ptbin == 1)
      {
        prettyPlot->cd();
        plotC[ptbin]->GetYaxis()->SetRangeUser(0,0.35);
        plotC[ptbin]->SetMarkerStyle(20);
        plotC[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerStyle(21);
        plotB[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerColor(kRed);
        plotD0[ptbin]->SetMarkerStyle(22);
        plotD0[ptbin]->SetMarkerSize(0.9);
        plotC[ptbin]->GetXaxis()->SetTitle("#Delta#phi_{NPE-h} (rad)");
        plotC[ptbin]->GetYaxis()->SetTitle("#frac{1}{N_{NPE}} #frac{dN}{d(#Delta#phi)}");
        plotC[ptbin]->DrawClone("P");
        plotB[ptbin]->DrawClone("same P");
        plotD0[ptbin]->DrawClone("same P");
        TLegend* legPret = new TLegend(0.65,0.6,0.85,0.85);
        legPret->AddEntry(plotB[ptbin],"B #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotC[ptbin],"D #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotD0[ptbin],"NPE-h 2012 STAR Data","LPE");
        lbl[ptbin]->Draw("same");
        legPret->Draw("same");
      }

    /*// Draw Scale Check
      scaleCheck->cd(1);
      TH1F* HT0 = (TH1F*) plotD0[0]->Clone();
      HT0->Divide(HT0,Hdphi[0],1,1);
      HT0->Draw();
      scaleCheck->cd(2);
      TH1F* HT2 = (TH1F*) plotD2[3]->Clone();
      HT2->Divide(HT2,Hdphi[1],1,1);
      HT0->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->Draw();
      lbl[ptbin]->Draw("same");
      TLegend* legSC = new TLegend(0.65,0.6,0.85,0.85);
      legSC->AddEntry(HT0,"HT0/prevdata","lpe");
      legSC->AddEntry(HT2,"HT2/prevdata","lpe");
      legSC->Draw();*/

    /////////////////////
    // Do the actual fits
    /////////////////////

    currentPtBin = ptbin;
    cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    TMinuit* gMinuit = new TMinuit(1);
    gMinuit->SetFCN(chi2_0);
    currentPtBin = ptbin;
    doFit(gMinuit,p01[ptbin],p00[ptbin],e01[ptbin],e00[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] < 6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      dx[plotCount0] = 0.;
      ptOFF1[plotCount0] = pT[ptbin];
      Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
      eb0[plotCount0] = e01[ptbin];
      plotCount0++;
    }

    // Plot results
    fitResult0->cd(ptbin+1);
    TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
    TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
    TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
    stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
    stat[0][ptbin]->InsertText(statLabel);
    stat[0][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[0][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");


    cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_2);
    doFit(gMinuit,p21[ptbin],p20[ptbin],e21[ptbin],e20[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] > 3.6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      ptOFF2[plotCount2] = pT[ptbin];
      Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
      eb2[plotCount2] = e21[ptbin];
      plotCount2++;
    }

    // Plot results
    fitResult2->cd(ptbin+1);
    dClone = (TH1D*) projData2[ptbin]->Clone();
    cClone = (TH1D*) projC[ptbin]->Clone();
    bClone = (TH1D*) projB[ptbin]->Clone();
    stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
    stat[2][ptbin]->InsertText(statLabel);
    stat[2][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[2][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");

    cout << "!!!!!!! HTC ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_C);
    doFit(gMinuit,pC1[ptbin],pC0[ptbin],eC1[ptbin],eC0[ptbin]);
    // assign to plotting variables
    pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
    RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
    ebC[plotCount] = eC1[ptbin];
    plotCount++;
  }

  cout << "!!!!!!! Previous Data: 0"<<" !!!!!!!"<< endl;

  //////////
  // 2.5-3.5 GeV Bin
  //////////

  gMinuit->SetFCN(chi2_P0);
  doFit(gMinuit,RbP[0],SF[0],EbP[0],eSF[0]);

  // assign plotting variables
  pTP[0] = 3.;

  // Plot results
  fitResultP->cd(1);
  /*TH1D* dClone = (TH1D*) Hdphi[0]->Clone();
    TH1D* cClone = (TH1D*) projC[0]->Clone();
    TH1D* bClone = (TH1D*) projB[0]->Clone();*/
  TH1D* dClone = (TH1D*) projData0[0]->Clone();
  TH1D* cClone = (TH1D*) HpphiD[0]->Clone();
  TH1D* bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][0] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][0]->InsertText(statLabel);
  stat[3][0]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[0])*SF[0]); bClone->Scale(RbP[0]*SF[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][0]->Draw("same");

  ////////
  // 5.5-6.5 GeV Bin
  ////////

  gMinuit->SetFCN(chi2_P1);
  doFit(gMinuit,RbP[1],SF[1],EbP[1],eSF[1]);

  // assign plotting variables
  pTP[1] = 6.;

  // Plot results
  fitResultP->cd(2);
  /*dClone = (TH1D*) Hdphi[1]->Clone();
    cClone = (TH1D*) projC[3]->Clone();
    bClone = (TH1D*) projB[3]->Clone();*/
  dClone = (TH1D*) projData2[3]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][1] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][1]->InsertText(statLabel);
  stat[3][1]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[1])*SF[1]); bClone->Scale(RbP[1]*SF[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][1]->Draw("same");

  ////////
  // Old Data, Old Template
  ///////
  gMinuit->SetFCN(chi2_PP);
  doFit(gMinuit,RbPP[0],SFPP[0],EbPP[0],eSFPP[0]);

  // assign plotting variables
  pTPP[0] = 3.;

  // Plot results
  fitResultP->cd(3);
  dClone = (TH1D*) Hdphi[0]->Clone();
  cClone = (TH1D*) HpphiD[0]->Clone();
  bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][2] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][2]->InsertText(statLabel);
  stat[3][2]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[0])*SFPP[0]); bClone->Scale(RbPP[0]*SFPP[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][2]->Draw("same");

  // Bin at 6 GeV
  gMinuit->SetFCN(chi2_PP1);
  doFit(gMinuit,RbPP[1],SFPP[1],EbPP[1],eSFPP[1]);

  // assign plotting variables
  pTPP[1] = 6.;

  // Plot results
  fitResultP->cd(4);
  dClone = (TH1D*) Hdphi[1]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][3] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][3]->InsertText(statLabel);
  stat[3][3]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[1])*SFPP[1]); bClone->Scale(RbPP[1]*SFPP[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][3]->Draw("same");


  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/200GeVTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/200GeVTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);
  TGraphErrors *grPr    = new TGraphErrors(2,pTP,RbP,0,EbP);
  TGraphErrors *grPPr   = new TGraphErrors(2,pTPP,RbPP,0,EbPP);


  c1->cd(1);

  grP->SetTitle("");
  grP->GetXaxis()->SetTitle("NPE p_{T} (GeV/c)");
  grP->GetYaxis()->SetTitle("r_{B}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  grP->GetXaxis()->SetLimits(0,10);
  grP->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  grPr->SetMarkerStyle(29);
  grPr->SetMarkerColor(9);
  grPr->SetLineColor(9);
  grPPr->SetMarkerStyle(29);
  grPPr->SetMarkerColor(49);
  grPPr->SetLineColor(49);


  grP->Draw("AP");
  //grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  gr0->Draw("same P");
 // grPr->Draw("same P");
  //grPPr->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.48,0.85);
  leg2->AddEntry(gr0,"STAR Run 12 - Low p_{T} Analysis","pe");
  leg2->AddEntry(gr2,"STAR Run 12 - High p_{T} Analysis","pe");
  //leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grP,"STAR Run 6 Analysis (Stat. Uncertainty)","pe");
//  leg2->AddEntry(grPr,"Run 12 Data, Run 5/6 Templates)","pe");
  //leg2->AddEntry(grPPr,"Run 5/6 Refit (prev Template)","pe");
  leg2->AddEntry(grF,"FONLL Calculation","l");
  leg2->Draw("same");

  // Write to Root File if open
  if(makeROOT){
    file3->Close();
    file4->Close();
    file->cd();
    grP->Write("PreviousData");
    //grC->Write("same P");
    gr2->Write("HT2");
    grF->Write("FONLL");
    grFmax->Write("FONLLmax");
    grFmin->Write("FONLLmin");
    gr0->Write("HT0");
    // grPr->Write("PrevTempMyData");
    //grPPr->Write("PrevTempPreData");
  }

  // Make PDF with output canvases
  if(makePDF)
  {
    //Set front page
    TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
    fp->cd();
    TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
    bLabel->SetFillColor(38);
    bLabel->Draw();
    TLatex tl;
    tl.SetNDC();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.033);
    char tlName[100];
    char tlName2[100];

    TString titlename = FileName;
    int found = titlename.Last('/');
    if(found >= 0){
      titlename.Replace(0, found+1, "");
    } 
    sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
    tl.SetTextSize(0.05);
    tl.SetTextColor(kWhite);
    tl.DrawLatex(0.05, 0.92,tlName);

    TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
    bFoot->SetFillColor(38);
    bFoot->Draw();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.05);
    tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
    tl.SetTextColor(kBlack);
    tl.SetTextSize(0.03);
    tl.DrawLatex(0.1, 0.14, titlename);
    sprintf(tlName,"TEST");
    tl.DrawLatex(0.1, 0.8,tlName);

    // Place canvases in order
    TCanvas* temp = new TCanvas();
    sprintf(name, "FFOutput/%s.pdf[", FileName);
    temp->Print(name);
    sprintf(name, "FFOutput/%s.pdf", FileName);

    temp = deltaPhi; 
    temp->Print(name);
    temp = fitResult0;
    temp->Print(name);
    temp = fitResult2;
    temp->Print(name);
    // temp = fitResultC;
    // temp->Print(name);
    temp = c1;
    temp->Print(name);

    sprintf(name, "FFOutput/%s.pdf]", FileName);
    temp->Print(name);
  }
  if(makeROOT)
  {
    file->Write();
    file->Close();
  }
}
Esempio n. 22
0
int main(int argc, char **argv)
{
	TString xvar = "TMath::Power(J_psi_1S_MM/1000,2)";
	TString xvarname = "q2";
	TString type = "All";
	TCut extCut = "";
	
	string drawopt = "";
	TString outFileName = "";
	bool rel = false, doSys = false, percent = false, jpsi = false, pythia6 = false;
	
	int xnbins = 12;
	double def_xbins[] = {0.1, 2.0, 4.0, 6.0, 8.0, 9.1, 10.1, 11.0, 12.5, 15.0, 16.0, 18.0, 20.0};
	//double def_xbins[] = {1.1, 6.0, 15.0, 20.0};
	double * xbins = &def_xbins[0];
	
	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);
			
			if(arg.find("-t") != string::npos) type = (TString)str;
			if(arg == "-r") rel = true;
			if(arg.find("-b") != string::npos ) xbins = decodeBinning(str,&xnbins);
			if(arg.find("-c") != string::npos ) xbins = decodeBinning(str,&xnbins,"custom");
			if(arg.find("-C") != string::npos ) extCut = (TCut)((TString)str);
			if(arg == "-highq2Cut") extCut = (TCut)"( TMath::Power(J_psi_1S_MM/1000,2) > 15. && TMath::Power(J_psi_1S_MM/1000,2) < 20. )";
			if(arg == "-Pythia6") pythia6 = true;
			if(arg.find("-X") != string::npos) { xvar = str; xvarname = xvar; }
			if(arg.find("-D") != string::npos) drawopt = str;
			if(arg.find("-sys") != string::npos) doSys = true;
			if(arg.find("-percent") != string::npos) percent = true;
			if(arg.find("-o") != string::npos) outFileName = str;
			if(arg.find("-jpsi") != string::npos) jpsi = true;
		}
	}
	
	if(jpsi) { if(xvarname=="q2") xbins = decodeBinning("[1,0,25]",&xnbins); rel = false; doSys = false; }

	// Set trees of cancdidates previously created

	TString mctype = "MC_Pythia8_NBweighted";
	if(pythia6) mctype = "MC_Pythia6_NBweighted"; 
	TString weight = "MCnorm*(lifeTimeW > 0)*(physRate_pol0_noDecay > 0)";
	cout << "Using: " << mctype << endl;
	cout << "Plotting: " << xvar << endl;
	cout << "Binning: [";
	for(int i = 0; i < xnbins; i++) cout << xbins[i] << ",";
	cout << xbins[xnbins] << "]" << endl;	

	TString namefileMCgeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_geom"+mctype+".root";
	TString namefileMC = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_"+mctype+".root";
	TString namefileMCjpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_"+mctype+".root";
	TString namefileMCjpsiGeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_geom"+mctype+".root";
	TString namefileDataJpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_CL_NBweighted.root";

	TString nameGeomTree = "MCtree";
	if(xvar=="cosThetaB") nameGeomTree = "MCtreeDecay";
	TFile * MCfile = TFile::Open(namefileMCgeom);
	TTree * treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
	MCfile = TFile::Open(namefileMC);
	TTree * treeMC = (TTree *)MCfile->Get("tree");
	TTree * treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
	TTree * treeMCAllGen = (TTree *)MCfile->Get("MCtree");
	MCfile = TFile::Open("/afs/cern.ch/work/p/pluca/weighted/Lmumu/trainingSamples.root");
	TTree * treeMCmva = (TTree *)MCfile->Get("sigTestSample");

	TTree * treeMCjpsi = NULL, * treeMCjpsi_Gen = NULL, * treeMCjpsi_AllGen = NULL, * treeMCjpsi_geom = NULL;
	if(rel || jpsi)
	{
		
		MCfile = TFile::Open(namefileMCjpsi);
		if(jpsi) {
		treeMC = (TTree *)MCfile->Get("tree");
		treeMCmva = (TTree *)MCfile->Get("tree");
		treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCAllGen = (TTree *)MCfile->Get("MCtree");	}
		else {
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	}
		
		MCfile = TFile::Open(namefileMCjpsiGeom);		
		if(jpsi) treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
		else treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);

	
/*	
		MCfile = TFile::Open(namefileMC);
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	
		
		MCfile = TFile::Open(namefileMCgeom);		
		treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);
*/

	}
	
	TCut geomCut = CutsDef::geomCut;
	TCut baseCut = extCut + CutsDef::baseCutMuMu;
	if(jpsi) baseCut = extCut + CutsDef::baseCutJpsi;
	TCut baseJpsiCut = extCut + CutsDef::baseCutJpsi;
	TCut binCut = "TMath::Power(J_psi_1S_MM/1000,2) > 9.1 && TMath::Power(J_psi_1S_MM/1000,2) < 10.1";
	if(type == "DD") { baseCut += CutsDef::DDcut; baseJpsiCut += CutsDef::DDcut; }
	else if(type == "LL") { baseCut += CutsDef::LLcut; baseJpsiCut += CutsDef::LLcut; }
	cout << "Analysisng " << type << " events" << endl;

	//TCut simpleEffCut = geomCut + (TCut)"TMath::Sqrt(TMath::Power(pplus_TRUEP_X,2) + TMath::Power(pplus_TRUEP_Y,2) + TMath::Power(pplus_TRUEP_Z,2)) > 6000 && TMath::Sqrt(TMath::Power(piminus_TRUEP_X,2) + TMath::Power(piminus_TRUEP_Y,2) + TMath::Power(piminus_TRUEP_Z,2)) > 2000 && TMath::Sqrt(TMath::Power(muminus_TRUEP_X,2) + TMath::Power(muminus_TRUEP_Y,2) + TMath::Power(muminus_TRUEP_Z,2)) > 3000 && TMath::Sqrt(TMath::Power(muplus_TRUEP_X,2) + TMath::Power(muplus_TRUEP_Y,2) + TMath::Power(muplus_TRUEP_Z,2)) > 3000 && pplus_TRUEPT > 400 && muplus_TRUEPT > 100 && muminus_TRUEPT > 100";


	TString myName = "Lbeff";
	if(rel) myName = "Lbreleff";
	if(doSys) myName += "AndSys";
	if(jpsi) myName += "_Jpsi"; 
	myName += ("vs"+xvarname+"_"+type+".root");
	if(outFileName!="") myName = outFileName;
	TFile * histFile = new TFile(myName,"recreate");

	/**      Calc efficiencies and systematics        */

	vector <TString> effnames;
	effnames.push_back("geom");
	effnames.push_back("det");
	effnames.push_back("reco");
	effnames.push_back("mva");
	effnames.push_back("trig");

	vector <TH1F * >  hdefault;
	vector <TH1F * >  lfsys_plus, lfsys_minus;
	vector <TH1F * >  decaysys, DDsys;
	vector <TH1F * >  polsys_minus, polsys_plus;
	vector <TH1F * >  poljpsi1, poljpsi2, poljpsi3, poljpsi4, poljpsi5, poljpsi6, poljpsi7, poljpsi8;
	
	cout << "Analysing GEO sys" << endl;
	getAllEffSys("GEO", xvar, xnbins, xbins, weight,
			treeMCgeom, geomCut+extCut, treeMCgeom, extCut,
			treeMCjpsi_geom, geomCut+extCut+binCut, treeMCjpsi_geom, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "-f0.5", jpsi);

	cout << "Analysing DET sys" << endl;
	if(xvar=="cosThetaB")
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCgeom, geomCut+extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, geomCut+extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );	
	else
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCAllGen, extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing RECO sys" << endl;
	getAllEffSys("RECO", xvar, xnbins, xbins, weight,
			treeMC, baseCut, treeMCGen, extCut,
			treeMCjpsi, baseJpsiCut+binCut, treeMCjpsi_Gen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing MVA sys" << endl;
	getAllEffSys("MVA", xvar, xnbins, xbins, weight,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut, treeMCjpsi, baseJpsiCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );

	cout << "Analysing TRIG sys" << endl;
	getAllEffSys("TRIG", xvar, xnbins, xbins, weight,
			treeMC, baseCut+CutsDef::MVAcut+CutsDef::TrigPassed, treeMC, baseCut+CutsDef::MVAcut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+CutsDef::TrigPassed+binCut, treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	TH1F * toteff_lowSel = NULL;
	if(rel || jpsi)
	{
		TString polweight = "physRate_polp006";
		if(jpsi) polweight = "physRate_pol0";
		TH1F * mva_lowSel = getEff("UPPER", xvar, xnbins, xbins,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			weight+"*lifeTimeW*pt_weight*"+polweight,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut_lowSel+binCut, treeMCjpsi, baseJpsiCut+binCut,
			weight+"*lifeTimeW*physRate_pol0*pt_weight" );
		mva_lowSel->Write("hmvaeff_lowSel");
		TH1F * uppereff_lowSel = (TH1F *)hdefault[2]->Clone("huppereff_lowSel");
		uppereff_lowSel->Multiply(hdefault[3]);
		uppereff_lowSel->Multiply(mva_lowSel);
		toteff_lowSel = (TH1F *)hdefault[0]->Clone("htoteff_lowSel");
		toteff_lowSel->Multiply(hdefault[1]);
		toteff_lowSel->Multiply(uppereff_lowSel);
		uppereff_lowSel->Write("huppereff_lowSel");
		toteff_lowSel->Write("htoteff_lowSel");
	}

	//Simply model
	//TH1F * simpleeff = getEff("SIMPLY", xvar, xnbins, xbins,
	//		treeMCgeom, simpleEffCut, treeMCgeom, "", weight);


			
	TCanvas * c = new TCanvas();
	gStyle->SetOptStat(0);
	gStyle->SetOptFit();
	TH1F * uppereff = (TH1F *)hdefault[2]->Clone("huppereff");
	uppereff->Multiply(hdefault[3]);
	uppereff->Multiply(hdefault[4]);

	TH1F * toteff = (TH1F *)hdefault[0]->Clone("htoteff");
	if(xvar=="cosThetaB") hdefault[1]->Scale(1./hdefault[1]->Integral());
	toteff->Multiply(hdefault[1]);
	toteff->Multiply(uppereff);
	toteff->SetTitle("Total eff");
	//toteff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_tot.pdf");
	toteff->Write("htoteff");
	//uppereff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_upper.pdf");
	uppereff->Write("huppereff");
	TH1F * tot_nodet_eff = (TH1F *)hdefault[0]->Clone("htot_nodet_eff");
	tot_nodet_eff->Multiply(uppereff);
	tot_nodet_eff->Write("htot_nodet_eff");
	//simpleeff->Write("simplified_eff");
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		//hdefault[i]->Fit("pol2");
		if(!jpsi)
		for(int b = 0; b < hdefault[i]->GetNbinsX(); b++)
		{
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(10.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(10.5),0);
		}
		if(rel) hdefault[i]->SetMinimum(0.5);
		if(rel) hdefault[i]->SetMaximum(1.5);
		hdefault[i]->Draw();
		c->Print("effvs"+xvarname+"_"+type+"_"+effnames[i]+".pdf");
		hdefault[i]->Write("h"+effnames[i]+"eff");
	}

	gStyle->SetOptFit(0);



	/** Printing out efficiencies and systematics **/

	vector <TString> sysnames;
	sysnames.push_back("Lifetime");
	sysnames.push_back("Decay Model");
	sysnames.push_back("Polarization");
	if(type=="DD") sysnames.push_back("DD vtx");
	
	/** Print efficiencies */ 

	cout << "\n\n" << xvarname << " bin " << " \t\t\t& ";
	for(unsigned s = 0; s < effnames.size(); s++) cout << effnames[s] << " \t\t\t\t& ";
	cout << "Upper \t\t\t\t& Total  \\\\" << endl;

	TGraphErrors * grtoteff = new TGraphErrors();
	TGraphErrors * grtoteff_lowSel = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << fixed << setprecision(1) << "eff " << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";

		for(unsigned i = 0; i < hdefault.size(); i++)	
			cout << "$" << hdefault[i]->GetBinContent(j) << " \\pm " << hdefault[i]->GetBinError(j) << "$ \t & ";

		cout << "$" << uppereff->GetBinContent(j) << " \\pm " << uppereff->GetBinError(j) << "$ \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << toteff->GetBinError(j) << "$ \\\\ " << endl;

		grtoteff->SetPoint(j,toteff->GetBinCenter(j),toteff->GetBinContent(j));
		grtoteff->SetPointError(j,toteff->GetBinWidth(j)/2.,toteff->GetBinError(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPoint(j,toteff_lowSel->GetBinCenter(j),toteff_lowSel->GetBinContent(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPointError(j,toteff_lowSel->GetBinWidth(j)/2.,toteff_lowSel->GetBinError(j));
	}

	grtoteff->Write("toteff");
	if(toteff_lowSel) grtoteff_lowSel->Write("toteff_lowSel");
	if(!doSys) { delete MCfile; delete histFile; return 0; }


	/** Print sys separate in efficiency */
	
	vector < TH1F * > tmp;
	vector < vector < TH1F * > > sys_eff(4,tmp);
	vector < TH1F * > tot_sys_eff;

	cout << endl << endl << endl;
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << "\t& " << sysnames[s];
	cout << " \\\\" << endl;

	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << endl;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		if(!percent) cout << fixed << setprecision(5);

		for(unsigned i = 0; i < effnames.size(); i++)
		{
			if(j==1)
			{
				sys_eff[0].push_back((TH1F*)toteff->Clone("sys_lf_"+effnames[i]));
				sys_eff[1].push_back((TH1F*)toteff->Clone("sys_decay_"+effnames[i]));
				sys_eff[2].push_back((TH1F*)toteff->Clone("sys_pol_"+effnames[i]));
				sys_eff[3].push_back((TH1F*)toteff->Clone("sys_DD_"+effnames[i]));
				tot_sys_eff.push_back((TH1F*)toteff->Clone("tot_sys_eff"));
				sys_eff[0][i]->Reset();
				sys_eff[1][i]->Reset();
				sys_eff[2][i]->Reset();
				sys_eff[3][i]->Reset();
				tot_sys_eff[i]->Reset();
			}

			double lf_sys = createSys(j,hdefault[i], lfsys_minus[i], lfsys_plus[i]);
			double decay_sys = createSys(j,hdefault[i], decaysys[i], decaysys[i]);
			double DD_sys = 0;
			double pol_sys = createSys(j, hdefault[i], polsys_minus[i], polsys_plus[i]);
			pol_sys = createSys(j, hdefault[i], poljpsi1[i], poljpsi2[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi3[i], poljpsi4[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi5[i], poljpsi6[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi7[i], poljpsi8[i], pol_sys);
			double cureff = hdefault[i]->GetBinContent(j);
			double curerr = hdefault[i]->GetBinError(j);
			double tot_eff_sys = TMath::Sqrt( TMath::Power(lf_sys,2) + TMath::Power(pol_sys,2) + TMath::Power(decay_sys,2) );
			
			if(type=="DD")
			{
				DD_sys = createSys(j, hdefault[i], DDsys[i], DDsys[i]);
				tot_eff_sys = TMath::Sqrt( TMath::Power(tot_eff_sys,2) + TMath::Power(DD_sys,2) );
				sys_eff[3][i]->SetBinContent(j,DD_sys);
			}

			cout << effnames[i] << " \t  & ";
			if(percent)
			{
				cout << lf_sys*100 << "\\% \t & " << decay_sys*100 << "\\% \t & " << pol_sys*100 << "\\% \t";
				if(type=="DD") cout << " & " << DD_sys*100 << " \t ";	
			}	
			else
			{
				cout << cureff << " \t & " << curerr << " \t & ";
				cout << lf_sys*cureff << " \t & " << decay_sys*cureff << " \t & " << pol_sys*cureff << " \t";
				if(type=="DD") cout << " & " << DD_sys*cureff << " \t";	
			}	
			cout << " \\\\ " << endl;
			sys_eff[0][i]->SetBinContent(j,lf_sys);
			sys_eff[1][i]->SetBinContent(j,decay_sys);
			sys_eff[2][i]->SetBinContent(j,pol_sys);
			tot_sys_eff[i]->SetBinContent(j,tot_eff_sys);
		}
	}


		/** Print total sys */

	vector< TH1F * > sys;
	TH1F * tot_sys = getErrHist(toteff);

	for(unsigned s = 0; s < sysnames.size(); s++)
	{
		TH1F * tmp_sys = NULL;
		
		for(unsigned i = 0; i < effnames.size(); i++)
			tmp_sys = sqSum(tmp_sys,sys_eff[s][i]); 
		
		sys.push_back( tmp_sys );
		tmp_sys->Write("sys_"+sysnames[s]);
		tot_sys = sqSum(tot_sys,tmp_sys);
	}
	tot_sys->Write("sys_tot");

	cout << endl << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t & " << sysnames[s];
	cout << " \t & Total \\\\" << endl;
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		TGraphErrors * grtot_eff = new TGraphErrors();
		cout << endl << effnames[i] << endl;

		for(int j = 1; j <= toteff->GetNbinsX(); j++)
		{
			if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
			cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << "  \t & ";
		
			double cureff = hdefault[i]->GetBinContent(j);
			if(!percent) cout << fixed << setprecision(5) << cureff << " \t & " << hdefault[i]->GetBinError(j) << "   \t & ";
		
			for(unsigned s = 0; s < sysnames.size(); s++)
				if(percent) cout << sys_eff[s][i]->GetBinContent(j)*100 << "\\% \t & ";
				else cout << sys_eff[s][i]->GetBinContent(j)*cureff << " \t & ";
			
			if(percent) cout << tot_sys_eff[i]->GetBinContent(j)*100 << "\\%";
			else cout << tot_sys_eff[i]->GetBinContent(j)*cureff;
			cout << " \\\\ " << endl;

			grtot_eff->SetPoint(j,tot_sys_eff[i]->GetBinCenter(j),tot_sys_eff[i]->GetBinContent(j));
			grtot_eff->SetPointError(j,tot_sys_eff[i]->GetBinWidth(j)/2.,0.);
		}

		grtot_eff->Write(effnames[i]+"sys");
	}

	cout << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t\t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t\t & " << sysnames[s];
	cout << " \\\\" << endl;

	TGraphErrors * grtot = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3);
		double cureff = toteff->GetBinContent(j);
		if(!percent) cout << fixed << setprecision(5) << cureff << " \t\t & " << toteff->GetBinError(j);
		
		for(unsigned s = 0; s < sysnames.size(); s++)
			if(percent) cout << "  \t\t\t & " << sys[s]->GetBinContent(j)*100 << "\\% ";
			else cout << " \t\t\t & " << sys[s]->GetBinContent(j)*cureff;
			
		cout << " \\\\ " << endl;

		grtot->SetPoint(j,tot_sys->GetBinCenter(j),tot_sys->GetBinContent(j));
		grtot->SetPointError(j,tot_sys->GetBinWidth(j)/2.,0.);
	}
	
	grtot->Write("totsys");

/*
	cout << "\n\n" << xvarname << " bin\t\t& Value \\\\" << endl;
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << tot_sys->GetBinContent(j)*toteff->GetBinContent(j) << "$ \\\\ " << endl;
	}
*/
	delete MCfile;
	delete histFile;
	return 0;
}
Esempio n. 23
0
File: merge.C Progetto: XuQiao/HI
void merge(){
	TFile *f=TFile::Open(outG,"Update");
	TString dirname;
        TVectorD Ncoll,B,Npart;
        TVectorD Ncollerr1,Berr1,Nparterr1;
        TVectorD Ncollerr2,Berr2,Nparterr2;
        TVectorD Ncollerr,Berr,Nparterr;
	TVectorD *NcollAver[nGlau+2], *NpartAver[nGlau+2], *BAver[nGlau+2];
        ofstream output("sys.txt");   output<<setprecision(2)<<fixed;
	Ncoll.ResizeTo(nGlau+2);Npart.ResizeTo(nGlau+2);B.ResizeTo(nGlau+2);
	Ncollerr1.ResizeTo(N-1);Nparterr1.ResizeTo(N-1);Berr1.ResizeTo(N-1);
	Ncollerr2.ResizeTo(N-1);Nparterr2.ResizeTo(N-1);Berr2.ResizeTo(N-1);
	Ncollerr.ResizeTo(N-1);Nparterr.ResizeTo(N-1);Berr.ResizeTo(N-1);
	if(method==0){
        output<<"kpoint_simu\t"<<"kpoint_data\t"<<"centbin\t"<<"<Ncoll>"<<"\t"<<"<Ncoll> err1"<<"\t"<<"<Ncoll> err2"<<"\t"<<"<Ncoll> err"<<"\t"<<endl;
        }
	else{
        output<<"kpoint\t"<<"centbin_data\t"<<"centbin_simu\t"<<"<Ncoll>"<<"\t"<<"<Ncoll> err1"<<"\t"<<"<Ncoll> err2"<<"\t"<<"<Ncoll> err"<<"\t"<<endl;
        }
	//<<"<Npart>"<<"\t"<<"<Npart> err"<<"\t\t"<<"<B>"<<"\t"<<"<B> err"<<endl;
	TString name;
        TVectorD* kpoint; TVectorD* kpoint_; TVectorD* centbin; TVectorD* centbin_;
	for(int sth=0;sth<1;sth++){
		Ncollerr1.Zero();Nparterr1.Zero();Berr1.Zero();
		Ncollerr2.Zero();Nparterr2.Zero();Berr2.Zero();
		Ncollerr.Zero();Nparterr.Zero();Berr.Zero();
		if(sth==0){dirname = "std";}
        	else if(sth==1){dirname ="Gri055";}
	        else {dirname ="Gri101";}
        	output<<dirname<<endl;
		centbin = (TVectorD*)f->Get(Form("%s/G0/centbin",dirname.Data()));
		kpoint = (TVectorD*)f->Get(Form("%s/G0/kpoint",dirname.Data()));
		if(method==0)
		kpoint_ = (TVectorD*)f->Get(Form("%s/G0/kpoint_",dirname.Data()));
		else
		centbin_ = (TVectorD*)f->Get(Form("%s/G0/centbin_",dirname.Data()));
        	for(int i=0;i<N-1;i++){
                	for(int iGlau=0;iGlau<nGlau+2; iGlau++){
        			if(iGlau==0)
                			name = "G0";
        			else if(iGlau<nGlau && iGlau>0)
                			name = Form("Glau_%d",iGlau);
       				else
                			name = Form("bin_%d",iGlau-nGlau+1);
				NcollAver[iGlau] = (TVectorD*)f->Get(Form("%s/%s/NcollAver",dirname.Data(),name.Data()));
				NpartAver[iGlau] = (TVectorD*)f->Get(Form("%s/%s/NpartAver",dirname.Data(),name.Data()));
				BAver[iGlau] = (TVectorD*)f->Get(Form("%s/%s/BAver",dirname.Data(),name.Data()));
                       		Ncoll[iGlau]=(*NcollAver[iGlau])[i]/(*NcollAver[0])[i];
                       		Npart[iGlau]=(*NpartAver[iGlau])[i]/(*NpartAver[0])[i];
                       		B[iGlau]=(*BAver[iGlau])[i]/(*BAver[0])[i];
			}
                	for(int iGlau=0;iGlau<nGlau+2; iGlau++){
                        	if(iGlau%2==1){
                                	double Ncoll_err_add=(TMath::Abs(Ncoll[iGlau]-1)>TMath::Abs(Ncoll[iGlau+1]-1))?Ncoll[iGlau]-1:Ncoll[iGlau+1]-1;
                                	double Npart_err_add=(TMath::Abs(Npart[iGlau]-1)>TMath::Abs(Npart[iGlau+1]-1))?Npart[iGlau]-1:Npart[iGlau+1]-1;
                                	double B_err_add=(TMath::Abs(B[iGlau]-1)>TMath::Abs(B[iGlau+1]-1))?B[iGlau]-1:B[iGlau+1]-1;
                                	if(iGlau<nGlau){
						Ncollerr1[i]+=TMath::Power(Ncoll_err_add,2);
                               			Nparterr1[i]+=TMath::Power(Npart_err_add,2);
                                		Berr1[i]+=TMath::Power(B_err_add,2);
					}
					else{	
						Ncollerr2[i]+=TMath::Power(Ncoll_err_add,2);
                               			Nparterr2[i]+=TMath::Power(Npart_err_add,2);
                                		Berr2[i]+=TMath::Power(B_err_add,2);
					}
						
						Ncollerr[i]+=TMath::Power(Ncoll_err_add,2);
                               			Nparterr[i]+=TMath::Power(Npart_err_add,2);
                                		Berr[i]+=TMath::Power(B_err_add,2);
				}
			}
        		Ncollerr1[i]=TMath::Sqrt(Ncollerr1[i])*100;//(*NcollAver[0])[i];
        		Ncollerr2[i]=TMath::Sqrt(Ncollerr2[i])*100;//(*NcollAver[0])[i];
        		Nparterr1[i]=TMath::Sqrt(Nparterr1[i])*100;//(*NpartAver[0])[i];
        		Nparterr2[i]=TMath::Sqrt(Nparterr2[i])*100;//(*NpartAver[0])[i];
        		Berr1[i]=TMath::Sqrt(Berr1[i])*100;//(*BAver[0])[i];
        		Berr2[i]=TMath::Sqrt(Berr2[i])*100;//(*BAver[0])[i];
			if(method==0)
        		output<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*kpoint_)[i]<<" to "<<(*kpoint_)[i+1]<<"\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"%:"<<"\t"<<(*NcollAver[0])[i]<<"\t"<<Ncollerr1[i]<<"%\t"<<Ncollerr2[i]<<"%\t"<<TMath::Sqrt(Ncollerr[i])*100<<"%"<<endl;
			else
        		output<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*centbin_)[i]*100<<"% to "<<(*centbin_)[i+1]*100<<"%\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"%:"<<"\t"<<(*NcollAver[0])[i]<<"\t"<<Ncollerr1[i]<<"%\t"<<Ncollerr2[i]<<"%\t"<<TMath::Sqrt(Ncollerr[i])*100<<"%"<<endl;
        		//output<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"%:"<<"\t"<<(*NcollAver[0])[i]<<"\t"<<Ncollerr1[i]<<"\t"<<Ncollerr2[i]<<"\t"<<Ncollerr[i]<<endl;
//<<(*NpartAver[0])[i]<<"\t"<<Nparterr[i]<<"\t\t"<<(*BAver[0])[i]<<"\t"<<Berr[i]<<endl;
	output<<endl;
        }
	if(method==0)
        output<<"kpoint_simu\t"<<"kpoint_data\t"<<"centbin\t"<<"<Npart>"<<"\t"<<"<Npart> err1"<<"\t"<<"<Npart> err2"<<"\t"<<"<Npart> err"<<"\t"<<endl;
	else
        output<<"kpoint\t"<<"centbin_data\t"<<"centbin_simu\t"<<"<Ncoll>"<<"\t"<<"<Ncoll> err1"<<"\t"<<"<Ncoll> err2"<<"\t"<<"<Ncoll> err"<<"\t"<<endl;
        for(int i=0;i<N-1;i++){
	if(method==0)
        output<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*kpoint_)[i]<<" to "<<(*kpoint_)[i+1]<<"\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"%:"<<"\t"<<(*NpartAver[0])[i]<<"\t"<<Nparterr1[i]<<"%\t"<<Nparterr2[i]<<"%\t"<<TMath::Sqrt(Nparterr[i])*100<<"%"<<endl;
        else
        output<<(*kpoint)[i]<<" to "<<(*kpoint)[i+1]<<"\t"<<(*centbin_)[i]*100<<"% to "<<(*centbin_)[i+1]*100<<"%\t"<<(*centbin)[i]*100<<"% to "<<(*centbin)[i+1]*100<<"%:"<<"\t"<<(*NpartAver[0])[i]<<"\t"<<Nparterr1[i]<<"%\t"<<Nparterr2[i]<<"%\t"<<TMath::Sqrt(Ncollerr[i])*100<<"%"<<endl;
	output<<endl;
        }
	for(int i=0;i<N-1;i++){
        	Ncollerr[i]=TMath::Sqrt(Ncollerr[i])*(*NcollAver[0])[i];
        	Nparterr[i]=TMath::Sqrt(Nparterr[i])*(*NpartAver[0])[i];
        	Berr[i]=TMath::Sqrt(Berr[i])*(*BAver[0])[i];
	}
	f->cd(dirname);
	Ncollerr.Write("Ncollerr",TObject::kOverwrite);
	Nparterr.Write("Nparterr",TObject::kOverwrite);
	Berr.Write("Berr",TObject::kOverwrite);	

	std::vector<double> xbin(N-1);
        for(int i=0;i<N-1;i++)
		//xbin[i]=(centbin[N-i]+centbin[N-i-1])*100/2;
        	xbin[i]=0.5+i;
		double *axbin = &xbin[0];
        TGraphErrors *gr;
       		double* aNcollAver  = NcollAver[0]->GetMatrixArray();
        	double* aNcollerr  = Ncollerr.GetMatrixArray();
        	double* aNpartAver  = NpartAver[0]->GetMatrixArray();
        	double* aNparterr  = Nparterr.GetMatrixArray();
        	double* aBAver  = BAver[0]->GetMatrixArray();
        	double* aBerr = Berr.GetMatrixArray();
	TString op;
	for(int option=0; option<3; option++){
        	if(option==0){   gr = new TGraphErrors(N-1,axbin,aNcollAver,0,aNcollerr); op="Ncoll_graph";}
        	else if(option==1){      gr = new TGraphErrors(N-1,axbin,aNpartAver,0,aNparterr);	op="Npart_graph";}
        	else    {gr = new TGraphErrors(N-1,axbin,aBAver,0,aBerr);	op="B_graph";}
		gr->Write(op,TObject::kOverwrite);
	}

	}

	f->Close();
}
Esempio n. 24
0
void all(int channels=0, int categ=-1, int sample=2012 /*,bool doSfLepton=true*/){

  double bwSigma[40];
  int mass[40]; int id[40]; double xLow[40]; double xHigh[40];  
  int maxMassBin;

    float masses[1] = {125};
    for(int i=0;i<1;++i) {
      mass[i] = masses[i]; 
      id[i]=masses[i]; 
      xLow[i] = 105.; // getFitEdge(masses[i],width,true); 
      xHigh[i] = 140.; // getFitEdge(masses[i],width,false); 
      //cout << "For mass = " << masses[i] << " width = " << width << "; => Fit Range = [" << xLow[i] << "," << xHigh[i] << "]" << endl;
      bwSigma[i] = 0.004;
    }
    maxMassBin = 1;   // 29;
  // -----------------------



  double massV[40],massE[40];
  for(int i=0; i<maxMassBin;++i){
    massV[i]=mass[i];
    massE[i]=0;
  }
  double A1Val[40],A1Err[40];
  double A2Val[40],A2Err[40];
  double a1Val[40],a1Err[40];
  double a2Val[40],a2Err[40];
  double n1Val[40],n1Err[40];
  double n2Val[40],n2Err[40];
  double meanCBVal[40],meanCBErr[40];
  double sigmaCBVal[40],sigmaCBErr[40];
  double meanBWVal[40],meanBWErr[40];
  double covQualVal[40];

  double fitValues[10];
  double fitErrors[10];
  double covQual[1];

  
  for(int i=0; i<maxMassBin;++i){
    fitSignalShapeW(mass[i],id[i],channels,categ, sample,/* 10.,doSfLepton,*/xLow[i],xHigh[i],bwSigma[i],
		    fitValues,fitErrors,covQual);  

    cout << "a1 value,error: " << fitValues[0] << " , " << fitErrors[0] << endl; 
    a1Val[i]=fitValues[0]; a1Err[i]=fitErrors[0];

    cout << "a2 value,error: " << fitValues[1] << " , " << fitErrors[1] << endl; 
    a2Val[i]=fitValues[1]; a2Err[i]=fitErrors[1];

    cout << "n1 value,error: " << fitValues[4] << " , " << fitErrors[4] << endl; 
    n1Val[i]=fitValues[4]; n1Err[i]=fitErrors[4];

    cout << "n2 value,error: " << fitValues[5] << " , " << fitErrors[5] << endl; 
    n2Val[i]=fitValues[5]; n2Err[i]=fitErrors[5];

    cout << "meanCB value,error: " << fitValues[2] << " , " << fitErrors[2] << endl;
    meanCBVal[i]=fitValues[2]; meanCBErr[i]=fitErrors[2];
    
    cout << "sigmaCB value,error: " << fitValues[6] << " , " << fitErrors[6] << endl; 
    sigmaCBVal[i]=fitValues[6]; sigmaCBErr[i]=fitErrors[6];

    cout << "meanBW value,error: " << fitValues[3] << " , " << fitErrors[3] << endl; 
    meanBWVal[i]=fitValues[3]; meanBWErr[i]=fitErrors[3];

    cout << "A1 value,error: " << fitValues[7] << " , " << fitErrors[7] << endl;
    A1Val[i]=fitValues[7]; A1Err[i]=fitErrors[7];

    cout << "A2 value,error: " << fitValues[8] << " , " << fitErrors[8] << endl;
    A2Val[i]=fitValues[8]; A2Err[i]=fitErrors[8];

    cout << "covQual of the fit: " << covQual[0] << endl;
    covQualVal[i] = covQual[0];

  }
  

  stringstream namefile;
  namefile << "parameters_channel" << channels<< categ << ".root";
  TFile *resultfile = TFile::Open(namefile.str().c_str(),"RECREATE");
 
  TGraphErrors* gA1 = new TGraphErrors(maxMassBin,massV,a1Val,massE,a1Err);
  TGraphErrors* gA2 = new TGraphErrors(maxMassBin,massV,a2Val,massE,a2Err);
  TGraphErrors* gN1 = new TGraphErrors(maxMassBin,massV,n1Val,massE,n1Err);
  TGraphErrors* gN2 = new TGraphErrors(maxMassBin,massV,n2Val,massE,n2Err);
  TGraphErrors* gMeanCB = new TGraphErrors(maxMassBin,massV,meanCBVal,massE,meanCBErr);
  TGraphErrors* gSigmaCB = new TGraphErrors(maxMassBin,massV,sigmaCBVal,massE,sigmaCBErr);
  TGraphErrors* gMeanBW = new TGraphErrors(maxMassBin,massV,meanBWVal,massE,meanBWErr);
  TGraphErrors* gAA1 = new TGraphErrors(maxMassBin,massV,A1Val,massE,A1Err);
  TGraphErrors* gAA2 = new TGraphErrors(maxMassBin,massV,A2Val,massE,A2Err);
  TGraph* gCovQual = new TGraph(maxMassBin,massV,covQualVal);

  gA1->SetName("gA1");  gA1->SetMarkerStyle(20);   gA1->SetMarkerSize(1);
  gA2->SetName("gA2");  gA2->SetMarkerStyle(20);   gA2->SetMarkerSize(1);
  gN1->SetName("gN1");  gN1->SetMarkerStyle(20);   gN1->SetMarkerSize(1);
  gN2->SetName("gN2");  gN2->SetMarkerStyle(20);   gN2->SetMarkerSize(1);
  gMeanCB->SetName("gMeanCB"); gMeanCB->SetMarkerStyle(20);   gMeanCB->SetMarkerSize(1);
  gSigmaCB->SetName("gSigmaCB"); gSigmaCB->SetMarkerStyle(20);   gSigmaCB->SetMarkerSize(1);
  gMeanBW->SetName("gMeanBW"); gMeanBW->SetMarkerStyle(20);   gMeanBW->SetMarkerSize(1);
  gAA1->SetName("gAA1");  gAA1->SetMarkerStyle(20);   gAA1->SetMarkerSize(1);
  gAA2->SetName("gAA2");  gAA2->SetMarkerStyle(20);   gAA2->SetMarkerSize(1);

  gCovQual->SetName("gCovQual"); gCovQual->SetMarkerStyle(20);   gCovQual->SetMarkerSize(1);
  
  gA1->SetTitle("");
  gA1->GetXaxis()->SetTitle("mass (GeV)");
  gA1->GetYaxis()->SetTitle("CB a-parameter");

  gA2->SetTitle("");
  gA2->GetXaxis()->SetTitle("mass (GeV)");
  gA2->GetYaxis()->SetTitle("CB a-parameter");

  gN1->SetTitle("");
  gN1->GetXaxis()->SetTitle("mass (GeV)");
  gN1->GetYaxis()->SetTitle("CB n-parameter");

  gN2->SetTitle("");
  gN2->GetXaxis()->SetTitle("mass (GeV)");
  gN2->GetYaxis()->SetTitle("CB n-parameter");

  gMeanCB->SetTitle("");
  gMeanCB->GetXaxis()->SetTitle("mass (GeV)");
  gMeanCB->GetYaxis()->SetTitle("CB mean");

  gSigmaCB->SetTitle("");
  gSigmaCB->GetXaxis()->SetTitle("mass (GeV)");
  gSigmaCB->GetYaxis()->SetTitle("CB sigma");

  gMeanBW->SetTitle("");
  gMeanBW->GetXaxis()->SetTitle("mass (GeV)");
  gMeanBW->GetYaxis()->SetTitle("BW mean");

  gAA1->SetTitle("");
  gAA1->GetXaxis()->SetTitle("mass (GeV)");
  gAA1->GetYaxis()->SetTitle("Chebyshev a1-parameter");

  gAA2->SetTitle("");
  gAA2->GetXaxis()->SetTitle("mass (GeV)");
  gAA2->GetYaxis()->SetTitle("Chebyshev a2-parameter");


  gCovQual->SetTitle("");
  gCovQual->GetXaxis()->SetTitle("mass (GeV)");
  gCovQual->GetYaxis()->SetTitle("cov. matrix qual.");
  
  resultfile->cd();
  gA1->Fit("pol0"); gA1->Draw("Ap"); gA1->Write();
  gA2->Fit("pol0"); gA2->Draw("Ap"); gA2->Write();
  gN1->Fit("pol1"); gN1->Draw("Ap"); gN1->Write();
  gN2->Fit("pol1"); gN2->Draw("Ap"); gN2->Write();
  gMeanCB->Fit("pol1"); gMeanCB->Draw("Ap"); gMeanCB->Write();
  gSigmaCB->Fit("pol1"); gSigmaCB->Draw("Ap"); gSigmaCB->Write();
  gAA1->Fit("pol0"); gAA1->Draw("Ap"); gAA1->Write();
  gAA2->Fit("pol0"); gAA2->Draw("Ap"); gAA2->Write(); 
  gCovQual->Write();

  resultfile->Close();

}
Esempio n. 25
0
void fitDstar5pMinpt(Bool_t genmatchpoint=true)
{
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);

  void clean0(TH1D* h);  
  TF1* fitDstar(TTree* nt, TTree* ntMC, Float_t ptmin, Bool_t plotgenmatch);

  TFile* infData = new TFile(infnameData5p[isData].Data());
  TFile* infMC = new TFile(infnameMC5p[isData].Data());

  TTree* ntData = (TTree*)infData->Get("ntDD0kpipipipi");
  TTree* ntMC = (TTree*)infMC->Get("ntDD0kpipipipi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  
  ntData->AddFriend("ntHlt");
  if(isData!=Data_MB&&isData!=Data) ntData->AddFriend("ntHi");
  ntMC->AddFriend("ntHlt");
  ntMC->AddFriend("ntHi");
  ntGen->AddFriend("ntHlt");
  ntGen->AddFriend("ntHi");

  Float_t aZero[nBins];
  for(int i=0;i<nBins;i++) aZero[i]=0;
  Float_t aPt[nBins],aPtErr[nBins],aGen[nBins],aGenErr[nBins];
  TH1F* hPt = new TH1F("hPt","",nBins,ptBinsPlus);
  TH1F* hGen = new TH1F("hGen","",nBins,ptBinsPlus);

  for(int i=0;i<nBins;i++)
    {
      TF1* fData = fitDstar(ntData,ntMC,ptBins[i],genmatchpoint);
      Float_t yieldData = fData->Integral(BINMIN,BINMAX)/BINWID;
      Float_t yieldDataErr = fData->Integral(BINMIN,BINMAX)/BINWID*fData->GetParError(0)/fData->GetParameter(0);      
      aPt[i] = yieldData;
      aPtErr[i] = yieldDataErr;
      hPt->SetBinContent(i+1,aPt[i]);
      hPt->SetBinError(i+1,aPtErr[i]);
      TH1D* hGenFill = new TH1D(Form("hGenFill_%.0f",ptBins[i]),"",1,ptBins[i],1.e+3);
      hGenFill->Sumw2();
      ntGen->Project(Form("hGenFill_%.0f",ptBins[i]),"Gpt",TCut("%s",weightmc[isData].Data())*Form("%s&&%s",selgen5p.Data(),triggerselectionmc[isData].Data()));
      aGen[i] = hGenFill->GetBinContent(1);
      aGenErr[i] = hGenFill->GetBinError(1);
      hGen->SetBinContent(i+1,aGen[i]);
      hGen->SetBinError(i+1,aGenErr[i]);
    }

  TGraphErrors* gPt = new TGraphErrors(nBins,ptBins,aPt,aZero,aPtErr);
  gPt->SetName("gPt");
  TGraphErrors* gGen = new TGraphErrors(nBins,ptBins,aGen,aZero,aGenErr);
  gGen->SetName("gGen");

  TFile* outputfile = new TFile(Form("outputfiles/output_5p_%s_Minpt.root",texData[isData].Data()),"recreate");
  outputfile->cd();
  gPt->Write();
  gGen->Write();
  hPt->Write();
  hGen->Write();
  outputfile->Close();
}
Esempio n. 26
0
void DrawCosmicResult(){
  
  TFile* tf = new TFile("Cosmic3Out.root");
  TTree* trin = (TTree*)tf->Get("trOut");


  const int nCSI = 2716;
  Int_t    RunNumber;
  Int_t    EventNumber;
  Double_t ScintiSignal = 0;
  Double_t ScintiHHTime = -500.;
  Double_t ScintiTime   =-500.;
  Int_t    nCSIDigi     = 0;
  Double_t CSIDigiE[nCSI];//nCSIDigi
  Double_t CSIDigiTime[nCSI];//nCSIDigi
  Double_t CSIDigiHHTime[nCSI];//nCSIDigi
  Int_t    CSIDigiID[nCSI];//nCSIDigi
  Double_t CSIDigiSignal[nCSI];//nCSIDigi
  Double_t FitP0[2];
  Double_t FitP1[2];
  Double_t FitChisq[2];
  Double_t CSIDigiDeltaT0[nCSI];//nCSIDigi
  Double_t CSIDigiDeltaT1[nCSI];//nCSIDigi
  Int_t    CosmicTrigUp;
  Int_t    CosmicTrigDn;
  Double_t Roh;
  Double_t Theta;

  trin->SetBranchAddress( "RunNumber"     , &RunNumber      );
  trin->SetBranchAddress( "EventNumber"   , &EventNumber    );
  trin->SetBranchAddress( "ScintiSignal"  , &ScintiSignal   );
  trin->SetBranchAddress( "ScintiHHTimne" , &ScintiHHTime   );
  trin->SetBranchAddress( "ScintiTime"    , &ScintiTime     );
  trin->SetBranchAddress( "nCSIDigi"      , &nCSIDigi       );
  trin->SetBranchAddress( "CSIDigiE"      , CSIDigiE        );
  trin->SetBranchAddress( "CSIDigiTime"   , CSIDigiTime     );
  trin->SetBranchAddress( "CSIDigiHHTime" , CSIDigiHHTime   );
  trin->SetBranchAddress( "CSIDigiID"     , CSIDigiID       );
  trin->SetBranchAddress( "CSIDigiSignal" , CSIDigiSignal   );
  trin->SetBranchAddress( "CSIDigiDeltaT0" , CSIDigiDeltaT0 );
  trin->SetBranchAddress( "CSIDigiDeltaT1" , CSIDigiDeltaT1 );
  trin->SetBranchAddress( "FitP0"         , FitP0           );
  trin->SetBranchAddress( "FitP1"         , FitP1           );
  trin->SetBranchAddress( "FitChisq"      , FitChisq        );
  trin->SetBranchAddress( "CosmicTrigUp"  , &CosmicTrigUp   );
  trin->SetBranchAddress( "CosmicTrigDn"  , &CosmicTrigDn   );
  trin->SetBranchAddress( "Roh"           , &Roh            );
  trin->SetBranchAddress( "Theta"         , &Theta          );

  TFile* tfout = new TFile("CosmicOut_hist3.root", "recreate");
  TH2D* hisDeltaChannel = new TH2D("hisDeltaChannel","hisDeltaChannel",2716,0,2716,100,-10,10);
  TH1D* hisDelta[2716];
  TGraphErrors* grDelta = new TGraphErrors();
  TGraphErrors* grRES   = new TGraphErrors(); 
  TCanvas *can = new TCanvas("can","",800,800);


  for( int i = 0; i< 2716; i++){
    hisDelta[i] = new TH1D(Form("hisDelta%d",i ),Form("hisDelta%d",i),100,-10,10);
  }

  for( int ievent = 0; ievent < trin->GetEntries(); ievent++){

    trin->GetEntry(ievent);
    
    for( int idigi = 0; idigi < nCSIDigi ; idigi++){
      hisDelta[ CSIDigiID[ idigi ] ]->Fill( CSIDigiDeltaT1[ idigi ] );
      hisDeltaChannel->Fill( CSIDigiID[ idigi  ] , CSIDigiDeltaT1[ idigi ] );
      //std::cout  << CSIDigiID[ idigi ] << std::endl;
    }
  }
  for( int i = 0; i< 2716; i++){
    //std::cout << hisDelta[i]->GetEntries() << std::endl;
    if( hisDelta[i]->GetEntries() > 10){
      int rst = hisDelta[i]->Fit("gaus","Q","",hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() ) - 3, hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() )+3);
      TF1* func = NULL;
      func = hisDelta[i]->GetFunction("gaus");
      if( func != NULL ){
	grDelta->SetPoint( grDelta->GetN(), i, func->GetParameter(1));
	grDelta->SetPointError( grDelta->GetN()-1, 0, func->GetParError(2));
	grRES->SetPoint( grRES->GetN() , i , func->GetParameter(2));
      }
    }
    /*
    hisDelta[i]->Draw();
    can->Modified();
    can->Update();
    getchar();
    */
    hisDelta[ i ]  ->Write(); 
  }

  std::ofstream ofs("TimeResolutionCosmic3.dat");
  int    ID[2716];
  double Delta[2716];
  double Resolution[2716];
  for( int i = 0; i< 2716; i++){
    Resolution[i] = 0xFFFF;
    Delta[i]      = 0xFFFF;
  }
  for( int i = 0; i< grRES->GetN(); i++){
    Delta[(int)(grDelta->GetX()[i])] = grDelta->GetY()[i];
    Resolution[(int)(grRES->GetX()[i])] = grRES->GetY()[i] ;
  }
  for( int i = 0; i< 2716; i++){
    ofs << i             << "\t" 
	<< Delta[i]      << "\t"
	<< Resolution[i] << "\n";
  }
  
  grDelta->SetNameTitle("grDelta","grDelta");
  grRES->SetNameTitle("grRES","grRES");
  grDelta->Write();
  grRES->Write();
  hisDeltaChannel->Write();
  tfout->Close();
  ofs.close();
}
Esempio n. 27
0
void countMuonsPerRunD3PD(){

  //gInterpreter->GenerateDictionary("map<int, double >","map.h;map");
  int cutValue = 11;
  float ptmin = 10.0;
  //float ptmin = 4.;
  //TString fileNameMuonIn = "/afs/cern.ch/user/t/tbalestr/public/16.6.2.5/WorkArea/run/HISingleMuon.root";

///7.3 ub^-1 2010 data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_Aug4_v2.root";
  ///2011 PbPb data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_merged_26May.root";
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_30May.root";

  TString baseString = "/mnt/Lustre/cgrp/atlas_hi/tbalestri/";
  TString fileNameMuonIn = baseString+"HardProbesFiles/HISingleMuonHardProbesData.04.17.2013.root";  
  TFile* fMuIn = new TFile(fileNameMuonIn, "READ");
  if ( !fMuIn->IsOpen() ) {
    std::cout << fMuIn << " not found!" << std::endl;
  }

  TFile* outFile = new TFile("muonsPerRun.root","recreate");
  
  ///lumi in ub^-1
  std::vector<double> vLumi;
  vLumi.push_back(0.0137422);
  vLumi.push_back(0.126333);
  vLumi.push_back(1.28605451);
  vLumi.push_back(0.08307752);
  vLumi.push_back(3.948807);
  vLumi.push_back(2.766361);
  vLumi.push_back(3.606919);
  vLumi.push_back(3.809249);
  vLumi.push_back(4.11709);
  vLumi.push_back(4.88581);
  vLumi.push_back(2.50513);
  vLumi.push_back(0.0619227);
  vLumi.push_back(0.9694949);
  vLumi.push_back(0.582203);
  vLumi.push_back(5.42834);
  vLumi.push_back(4.20247);
  vLumi.push_back(0.38549);
  vLumi.push_back(5.50425);
  vLumi.push_back(3.15969);
  vLumi.push_back(4.19951);
  vLumi.push_back(5.24396);
  vLumi.push_back(5.30817);
  vLumi.push_back(0.0433861);
  vLumi.push_back(5.29888);
  vLumi.push_back(5.30346);
  vLumi.push_back(0.757212);
  vLumi.push_back(5.985104);
  vLumi.push_back(5.1515);
  vLumi.push_back(6.57761);
  vLumi.push_back(1.75062);
  vLumi.push_back(5.43771);
  vLumi.push_back(3.13928);
  vLumi.push_back(5.14981);
  vLumi.push_back(4.90751);
  vLumi.push_back(2.521785);
  vLumi.push_back(6.45269);
  vLumi.push_back(3.59951);
  vLumi.push_back(5.33795);
  vLumi.push_back(6.16766);
  vLumi.push_back(1.77379);
  vLumi.push_back(0.923454);
  vLumi.push_back(2.07656);

  std::vector<int> vRun;
  vRun.push_back(193211);
  vRun.push_back(193270);
  vRun.push_back(193291);
  vRun.push_back(193295);
  vRun.push_back(193321);
  vRun.push_back(193403);
  vRun.push_back(193412);
  vRun.push_back(193447);
  vRun.push_back(193463);
  vRun.push_back(193481);
  vRun.push_back(193491);
  vRun.push_back(193492);
  vRun.push_back(193493);
  vRun.push_back(193494);
  vRun.push_back(193546);
  vRun.push_back(193558);
  vRun.push_back(193599);
  vRun.push_back(193604);
  vRun.push_back(193641);
  vRun.push_back(193655);
  vRun.push_back(193662);
  vRun.push_back(193679);
  vRun.push_back(193687);
  vRun.push_back(193718);
  vRun.push_back(193795);
  vRun.push_back(193823);
  vRun.push_back(193825);
  vRun.push_back(193826);
  vRun.push_back(193834);
  vRun.push_back(193890);
  vRun.push_back(194017);
  vRun.push_back(194060);
  vRun.push_back(194061);
  vRun.push_back(194121);
  vRun.push_back(194160);
  vRun.push_back(194163);
  vRun.push_back(194179);
  vRun.push_back(194192);
  vRun.push_back(194193);
  vRun.push_back(194370);
  vRun.push_back(194374);
  vRun.push_back(194382);
  const int nRuns = vRun.size(); 

  TGraphErrors* grLumi = new TGraphErrors(nRuns);
  TGraphErrors* grMuPerLumi = new TGraphErrors(nRuns);

  int valNt[30], EF_mu4_MSonly_L1TE50_Matched20[30],EF_mu4_L1VTE50_Matched20[30],runNt, mu_muid_nNt;
  int EF_mu10_MSonly_EFFS_L1ZDC_Matched20[30], EF_mu10_MSonly_EFFS_L1TE10_Matched20[30],EF_mu10_MSonly_EFFS_L1TE20_Matched20[30];
  int EF_mu10_MSonly_EFFS_L1ZDC, EF_mu10_MSonly_EFFS_L1TE10, EF_mu10_MSonly_EFFS_L1TE20, EF_mu4_MSonly_L1TE50, EF_mu4_L1VTE50;
  float ptNt[30], centralityNt,etaNt[30],eLossNt[30],scatNt[30];

  TChain* tree = new TChain("tree","tree");
  std::cout << "Filling the tree for " << fileNameMuonIn << std::endl;
  tree->Add(fileNameMuonIn);
  // --- Set branch adresses ---
  tree->SetBranchAddress("val", &valNt);
  tree->SetBranchAddress("pt", &ptNt);
  tree->SetBranchAddress("eta", &etaNt);
  tree->SetBranchAddress("eLoss",&eLossNt);
  tree->SetBranchAddress("scat",&scatNt);
  tree->SetBranchAddress("mu_muid_n", &mu_muid_nNt);
  tree->SetBranchAddress("run", &runNt);
  tree->SetBranchAddress("centrality", &centralityNt); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50", &EF_mu4_MSonly_L1TE50); 
  tree->SetBranchAddress("EF_mu4_L1VTE50", &EF_mu4_L1VTE50); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50_Matched20", &EF_mu4_MSonly_L1TE50_Matched20); 
  tree->SetBranchAddress("EF_mu4_L1VTE50_Matched20", &EF_mu4_L1VTE50_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC", &EF_mu10_MSonly_EFFS_L1ZDC); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10", &EF_mu10_MSonly_EFFS_L1TE10); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20", &EF_mu10_MSonly_EFFS_L1TE20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", &EF_mu10_MSonly_EFFS_L1ZDC_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10_Matched20", &EF_mu10_MSonly_EFFS_L1TE10_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20_Matched20", &EF_mu10_MSonly_EFFS_L1TE20_Matched20); 

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("val", 1);
  tree->SetBranchStatus("pt", 1);
  tree->SetBranchStatus("eta", 1);
  tree->SetBranchStatus("eLoss",1);
  tree->SetBranchStatus("scat",1);
  tree->SetBranchStatus("mu_muid_n", 1);
  tree->SetBranchStatus("run", 1);
  tree->SetBranchStatus("centrality", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20_Matched20", 1); 

 std::cout << "Number of entries: " << tree->GetEntries() << std::endl; 
 
 ///map runnumber to #mu
 ///need to used multimap since >1 muon 
 ///value for each run number key
 std::multimap < int, int> runMap;

  ///loop over all events
  for ( int i = 0; i < tree->GetEntries(); ++i ) {
 //   if(i>10000) break;
    tree->LoadTree(i);
    tree->GetEntry(i);

    if(i%10000==0) std::cout << "Event " << i << std::endl;

        for(int imu = 0; imu<mu_muid_nNt; imu++){
            if (
                (valNt[imu]>cutValue) 
                && abs(etaNt[imu])>0.1 
                && abs(etaNt[imu])<2.4 
                && ptNt[imu]>ptmin 
                && centralityNt>=0. 
                && centralityNt<=0.8
                && ( (EF_mu10_MSonly_EFFS_L1ZDC&&EF_mu10_MSonly_EFFS_L1ZDC_Matched20[imu]) ||
                    (EF_mu10_MSonly_EFFS_L1TE10&&EF_mu10_MSonly_EFFS_L1TE10_Matched20[imu])
                    ||(EF_mu10_MSonly_EFFS_L1TE20&&EF_mu10_MSonly_EFFS_L1TE20_Matched20[imu]) )	
		        ){
                ///count number of muons in this run that pass
                runMap.insert(make_pair (runNt,1) );
               }
         } //imu
   } //i
                
   std::cout << std::endl;
   std::cout << "-------------------------  " << std::endl;
   std::cout << " S U M M A R Y " << std::endl;
   std::cout << "-------------------------  " << std::endl;

   TString spreadSheetName = "muonCountingSpreadSheet.csv";
   std::ofstream spreadSheet;
   spreadSheet.open(spreadSheetName);

   double totLumi = 0.0, totalMu = 0;
   for(int iRun = 0; iRun<nRuns; ++iRun){

        int muonsPassed = runMap.count( vRun[iRun] );
        ///Muons per nb^-1
        double muPerLumi = (double)muonsPassed/vLumi[iRun]/1000.0;
        ///Number of muons passed in run iRun
        std::cout << "Index: " << iRun+1 << "\tRun: " << vRun[iRun] << 
            "\tLumi: " << vLumi[iRun]/1000.0 << "\tMuons: " << muonsPassed << "\tMuons/nb^-1: " 
            << muPerLumi << std::endl;

        totLumi += vLumi[iRun]/1000.0;
        totalMu += muonsPassed;

        grMuPerLumi->SetPoint(iRun,vRun[iRun],muPerLumi);
        grMuPerLumi->SetPointError(iRun,0.5, TMath::Sqrt(muonsPassed)/vLumi[iRun]/1000.0);

        grLumi->SetPoint(iRun,totLumi,totalMu);
        grLumi->SetPointError(iRun, 0.0, 0.0);

        writeToSpreadsheet(spreadSheet,iRun+1,vRun[iRun],vLumi[iRun]/1000.,muonsPassed);
   }

   grMuPerLumi->Draw("ape");
   grLumi->Draw("ape");

   outFile->cd();
   grLumi->Write("muonLumiDependence");
   grMuPerLumi->Write("muonPerLumi");

   std::cout << " Total Luminosity: " << totLumi << " nb^-1 " << std::endl;
   std::cout << " Total Muons passed: " << totalMu << std::endl;

   spreadSheet.close();
                
/*
            
  cout << "Number of runs: " << runMap.size() << endl;
  cout << "Run \t" << "Luminosity(ub^-1) \t" << " #muons \t" << "muons/lumi" << endl;
  ///map run lumi to #mu
  //std::map < int, double> lumiMap;
  for (unsigned int j = 0; j<runMap.size(); ++j){
    int runTemp = vRun.at(j);
    double lumiTemp = vLumi.at(j);
    map <int,int>::const_iterator iPairFound = runMap.find(runTemp);
    cout << iPairFound->first << " \t " << lumiTemp << " \t " << " \t " << iPairFound->second << " \t " << " \t " << (double)iPairFound->second/lumiTemp << endl; 
    sum += runMap[runTemp];
  }

  cout << "Total Luminosity = " << totLumi << endl;
  cout << "Total = " << sum << endl;
  */
}
Esempio n. 28
0
void theoryBin(TDirectory *din, TDirectory *dth, TDirectory *dout) {

  float etamin, etamax;
  assert(sscanf(din->GetName(),"Eta_%f-%f",&etamin,&etamax)==2);
  sscanf(din->GetName(),"Eta_%f-%f",&etamin,&etamax);
  int ieta = int((0.5*(etamin+etamax))/0.5);
  int jeta = (_jp_algo=="AK7" ? min(4,ieta) : ieta);

  // inclusive jets
  TH1D *hpt = (TH1D*)din->Get("hpt"); assert(hpt);

  // theory curves
  // http://www-ekp.physik.uni-karlsruhe.de/~rabbertz/fastNLO_LHC/InclusiveJets/
  // -> fnl2342_cteq66_aspdf_full.root
  // Numbering scheme explained in
  // https://twiki.cern.ch/twiki/bin/view/CMS/CMSfastNLO
  // 2-point to 6-point theory uncertainty:
  // h200X00->h300X09, h400X00->h300X08
  TH1D *hnlo(0);//, *hpdfup(0), *hpdfdw(0), *hscup(0), *hscdw(0);//, *herr(0);

  cout << din->GetName() << " ieta="<<ieta<< " jeta="<<jeta << endl;

  TH1D *hmc = (TH1D*)dth->Get("hpt_g0tw");
  assert(hmc);
  
  /*
  int S = (_jp_algo=="AK7" ? 1 : 3);
  TH1D *hnlo_cteq = (TH1D*)dnlo0->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_cteq);

  hnlo_cteq->Scale(1000.);

  // CTEQ10
  TH1D *hnlo_ct10 = (TH1D*)dnlo1->Get(Form("h300%d00",jeta+1));
  TH1D *hpdfup_ct10 = (TH1D*)dnlo1->Get(Form("h300%d02",jeta+1));
  TH1D *hpdfdw_ct10 = (TH1D*)dnlo1->Get(Form("h300%d01",jeta+1));
  TH1D *hscup_ct10 = (TH1D*)dnlo1->Get(Form("h300%d09",jeta+1));
  TH1D *hscdw_ct10 = (TH1D*)dnlo1->Get(Form("h300%d08",jeta+1));
  assert(hnlo_ct10); assert(hpdfup_ct10); assert(hpdfdw_ct10);
  assert(hscup_ct10); assert(hscdw_ct10);

  hnlo_ct10->Scale(1000.);
  hpdfup_ct10->Scale(1./1.65);
  hpdfdw_ct10->Scale(1./1.65);

  // MSTW2008
  TH1D *hnlo_mstw = (TH1D*)dnlo2->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_mstw);

  hnlo_mstw->Scale(1000.);

  // NNPDF2010
  TH1D *hnlo_nnpdf = (TH1D*)dnlo3->Get(Form("h%d00%d00",S,jeta+1));
  assert(hnlo_nnpdf);

  hnlo_nnpdf->Scale(1000.);

  // HERA10
  TH1D *hnlo_hera = (TH1D*)dnlo4->Get(Form("h%d00%d00",S,jeta+1));
  TH1D *hpdfup_hera = (TH1D*)dnlo4->Get(Form("h%d00%d02",S,jeta+1));
  TH1D *hpdfdw_hera = (TH1D*)dnlo4->Get(Form("h%d00%d01",S,jeta+1));
  assert(hnlo_hera); assert(hpdfup_hera); assert(hpdfdw_hera);

  hnlo_hera->Scale(1000.);

  // alpha-S
  TH1D *hasup = (TH1D*)das->Get(Form("h300%d02",ieta+1));
  TH1D *hasdw = (TH1D*)das->Get(Form("h300%d01",ieta+1));
  assert(hasup); assert(hasdw);

  TH1D *hnp = (TH1D*)dnp->Get(Form("corr%d",min(int(etamin/0.5+0.5),5)));

  if (!hnp) cout << "eta: " << etamin << " " << etamax << endl;
  assert(hnp);
  */


  // make sure new histograms get created in the output file
  dout->cd();

  /*
  TH1D *hnpup(0), *hnpdw(0), *hsysup(0), *hsysdw(0);
  {
    // Move CTEQ6.6
    hnlo_cteq = (TH1D*)hnlo_cteq->Clone("hnlo0_ct10k");
    hnlo_ct10 = (TH1D*)hnlo_ct10->Clone("hnlo0_ct10");
    hnlo_mstw = (TH1D*)hnlo_mstw->Clone("hnlo0_mstw");
    hnlo_nnpdf = (TH1D*)hnlo_nnpdf->Clone("hnlo0_nnpdf");
    hnlo_hera = (TH1D*)hnlo_hera->Clone("hnlo0_hera");
    
    // Determine PDF4LHC from CT10, MSTW08, NNPDF10
    hnlo = (TH1D*)hnlo_ct10->Clone("hnlo0"); // central PDF again later
    hpdfup = (TH1D*)hpdfup_ct10->Clone("hpdfup"); // central PDF
    hpdfdw = (TH1D*)hpdfdw_ct10->Clone("hpdfdw"); // central PDF
    for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {
      
      // Sanity checks
      assert(hpdfup_ct10->GetBinContent(i)>=0);
      assert(hpdfdw_ct10->GetBinContent(i)<=0);
    }
    hscup = (TH1D*)hscup_ct10->Clone("hscup"); // central PDF
    hscdw = (TH1D*)hscdw_ct10->Clone("hscdw"); // central PDF
    hasup = (TH1D*)hasup->Clone("hasup");
    hasdw = (TH1D*)hasdw->Clone("hasdw");
    
    hnp = (TH1D*)hnp->Clone("hnpcorr");
    
    hnpup = (TH1D*)hnlo->Clone("hnpup");
    hnpdw = (TH1D*)hnlo->Clone("hnpdw");
    
    hsysup = (TH1D*)hnlo->Clone("hsysup");
    hsysdw = (TH1D*)hnlo->Clone("hsysdw");
  }
  */

  /*
  // Patch up the hnp to adapt the wrong binning at low pT
  if (true) { // patch hnp

    TH1D *hnp_tmp = (TH1D*)hnlo->Clone("hnp_tmp");
    for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

      double x = hnlo->GetBinCenter(i);
      int j1 = hnp->FindBin(x);
      double x1 = hnp->GetBinCenter(j1);
      double y1 = hnp->GetBinContent(j1);
      double ey1 = hnp->GetBinError(j1);
      int j2 = (x>x1? j1+1 : j1-1);
      double x2 = hnp->GetBinCenter(j2);
      double y2 = hnp->GetBinContent(j2);
      double ey2 = hnp->GetBinError(j2);
      double y = y1 + (y2-y1) / (x2-x1) * (x-x1);
      double ey = ey1 + (ey2-ey1) / (x2-x1) * (x-x1);
      hnp_tmp->SetBinContent(i, y); 
      hnp_tmp->SetBinError(i, ey); 
    } // for i
    delete hnp;
    hnp = hnp_tmp;
    hnp->SetName("hnpcorr");
  } // patch hnp
  */

  /*
  // Turn NP uncertainty into uncertainty histogram
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    int j = hnp->FindBin(hnlo->GetBinCenter(i));
    hnpup->SetBinContent(i, +hnp->GetBinError(j)/hnp->GetBinContent(j));
    hnpup->SetBinError(i, 0.);
    hnpdw->SetBinContent(i, -hnp->GetBinError(j)/hnp->GetBinContent(j));
    hnpdw->SetBinError(i, 0.);
    if (!(hnp->GetBinLowEdge(j)>=hnlo->GetBinLowEdge(i)) ||
	!(hnp->GetBinLowEdge(j+1)<=hnlo->GetBinLowEdge(i+1))) {
      cout << Form("hnlo = [%1.0f,%1.0f]; hnp = [%1.0f,%1.0f]",
		   hnlo->GetBinLowEdge(i), hnlo->GetBinLowEdge(i+1),
		   hnp->GetBinLowEdge(j), hnp->GetBinLowEdge(j+1)) << endl;
      if (hnlo->GetBinLowEdge(i)>100 && hnlo->GetBinLowEdge(i)<2500.) {
	assert(hnp->GetBinLowEdge(j)>=hnlo->GetBinLowEdge(i));
	assert(hnp->GetBinLowEdge(j+1)<=hnlo->GetBinLowEdge(i+1));
      }
    }
  } // for i
  */

  /*
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    double x = hnlo->GetBinCenter(i);
    int i1 = hnpup->FindBin(x);
    double y1a = hnpup->GetBinContent(i1);
    double y1b = hnpdw->GetBinContent(i1);
    int i2 = hscup->FindBin(x);
    double y2a = hscup->GetBinContent(i2);
    double y2b = hscdw->GetBinContent(i2);
    int i3 = hpdfup->FindBin(x);
    double y3a = hpdfup->GetBinContent(i3);
    double y3b = hpdfdw->GetBinContent(i3);
    int i4 = hasup->FindBin(x);
    double y4a = hasup->GetBinContent(i4);
    double y4b = hasdw->GetBinContent(i4);
    double errup = sqrt(pow(max3(y1a,y1b,0),2) + pow(max3(y2a,y2b,0),2)
			+ pow(max3(y3a,y3b,0),2) + pow(max3(y4a,y4b,0),2));
    double errdw = sqrt(pow(min3(y1a,y1b,0),2) + pow(min3(y2a,y2b,0),2)
			+ pow(min3(y3a,y3b,0),2) + pow(min3(y4a,y4b,0),2));
    hsysup->SetBinContent(i, errup);
    hsysup->SetBinError(i, 0.);
    hpdfup->SetBinError(i, 0.);
    hscup->SetBinError(i, 0.);
    hasup->SetBinError(i, 0);
    hsysdw->SetBinContent(i, -errdw);
    hsysdw->SetBinError(i, 0.);
    hpdfdw->SetBinError(i, 0.);
    hscdw->SetBinError(i, 0.);
    hasdw->SetBinError(i, 0);
  } // for i
  */

  /*
  for (int i = 1; i != hnlo_ct10->GetNbinsX()+1; ++i) {

    double x = hnlo_ct10->GetBinCenter(i);
    int jnp = hnp->FindBin(x);
    double np = hnp->GetBinContent(jnp);
    int j = hnlo_ct10->FindBin(x);
    hnlo->SetBinContent(j, 1e-3*hnlo->GetBinContent(j)*np);
    int jc = hnlo_ct10->FindBin(x);
    hnlo_ct10->SetBinContent(jc, 1e-3*hnlo_ct10->GetBinContent(jc)*np);
    int jk = hnlo_cteq->FindBin(x);
    hnlo_cteq->SetBinContent(jk, 1e-3*hnlo_cteq->GetBinContent(jk)*np);
    int jm = hnlo_mstw->FindBin(x);
    hnlo_mstw->SetBinContent(jm, 1e-3*hnlo_mstw->GetBinContent(jm)*np);
    int jn = hnlo_nnpdf->FindBin(x);
    hnlo_nnpdf->SetBinContent(jn, 1e-3*hnlo_nnpdf->GetBinContent(jn)*np);
    int jh = hnlo_hera->FindBin(x);
    hnlo_hera->SetBinContent(jh, 1e-3*hnlo_hera->GetBinContent(jh)*np);
    //
    hnlo->SetBinError(j, 0.);
    hnlo_ct10->SetBinError(jc, 0.);
    hnlo_cteq->SetBinError(jk, 0.);
    hnlo_mstw->SetBinError(jm, 0.);
    hnlo_nnpdf->SetBinError(jn, 0.);
    hnlo_hera->SetBinError(jh, 0.);
  }
  */

  // initial fit of the NLO curve
  TF1 *fnlo = new TF1("fnlo",
		      "[0]*exp([1]/x)*pow(x,[2])"
		      "*pow(1-x*cosh([4])/3500.,[3])", 10., 1000.);
  fnlo->SetParameters(2e14,-18,-5.2,8.9,0.5*ieta);
  fnlo->FixParameter(4,0.5*ieta);

  hnlo = hmc;
  hnlo->Fit(fnlo,"QRN");
  
  // Graph of theory points with centered bins
  const double minerr = 0.02;
  TGraphErrors *gnlo = new TGraphErrors(0);
  TGraphErrors *gnlo2 = new TGraphErrors(0); // above + minerr
  TGraphErrors *gnlocut = new TGraphErrors(0); // only up to expected pT
  gnlo->SetName("gnlo");
  gnlo2->SetName("gnlo2");
  gnlocut->SetName("gnlocut");
  for (int i = 1; i != hnlo->GetNbinsX()+1; ++i) {

    double y = hnlo->GetBinContent(i);
    double dy = hnlo->GetBinError(i);
    double ptmin = hnlo->GetBinLowEdge(i);
    double ptmax = hnlo->GetBinLowEdge(i+1);

    double y0 = fnlo->Integral(ptmin, ptmax) / (ptmax - ptmin);
    double x = fnlo->GetX(y0, ptmin, ptmax);

    int n = gnlo->GetN();
    tools::SetPoint(gnlo, n, x, y, 0, dy);
    tools::SetPoint(gnlo2, n, x, y, 0, tools::oplus(dy, minerr*y));
    if (y*(ptmax-ptmin) > 0.0001) { // for 10/fb
      int m = gnlocut->GetN();
      tools::SetPoint(gnlocut, m, x, y, 0, 0);
    }
  }

  gnlo2->Fit(fnlo,"QRN");

  // Divide graph with fit to check stability
  TGraphErrors *gnlofit = new TGraphErrors(0);
  gnlofit->SetName("gnlofit");
  for (int i = 0; i != gnlo->GetN(); ++i) {
    
    double x, y, ex, ey;
    tools::GetPoint(gnlo, i, x, y, ex, ey);
    double f = fnlo->Eval(x);
    tools::SetPoint(gnlofit, i, x, y/f, ex, ey/f);
  }

  // Rebin theory to match data bins
  TH1D *hnlo0 = hnlo;
  hnlo0->SetName("hnlo0");
  hnlo = tools::Rebin(hnlo0, hpt);
  hnlo->SetName("hnlo");

  // Same for earlier 2010 and 2011 studies to get a matching theory set
  // (moved from PDF4LHC to CT10 since 2010)
  if (false) {

    // Match this to drawSummary.C inputs
    TDirectory *curdir = gDirectory;
    TFile *fin2010 = new TFile("../pfjet/output-DATA-4c.root","READ");
    assert(fin2010 && !fin2010->IsZombie());
    assert(fin2010->cd("Standard"));
    fin2010->cd("Standard");
    assert(gDirectory->cd(din->GetName()));
    gDirectory->cd(din->GetName());
    TDirectory *din2010 = gDirectory;
    TH1D *hpt2010 = (TH1D*)din2010->Get("hpt");
    curdir->cd();
    TH1D *hnlo2010 = tools::Rebin(hnlo0, hpt2010);
    hnlo2010->SetName("hnlo2010");
    hnlo2010->Write();
  }
  if (false) {
    // Match this to drawSummary.C inputs
    TDirectory *curdir = gDirectory;
    TFile *fin2011 = new TFile("backup/oct26/output-DATA-4c.root","READ");
    assert(fin2011 && !fin2011->IsZombie());
    assert(fin2011->cd("Standard"));
    fin2011->cd("Standard");
    assert(gDirectory->cd(din->GetName()));
    gDirectory->cd(din->GetName());
    TDirectory *din2011 = gDirectory;
    TH1D *hpt2011 = (TH1D*)din2011->Get("hpt");
    curdir->cd();
    TH1D *hnlo2011 = tools::Rebin(hnlo0, hpt2011);
    hnlo2011->SetName("hnlo2011");
    hnlo2011->Write();
  }

  /*
  {
    TH1D *hnlo0_cteq = hnlo_cteq;
    hnlo0_cteq->SetName("hnlo0_ct10k");
    hnlo_cteq = tools::Rebin(hnlo0_cteq, hpt);
    hnlo_cteq->SetName("hnlo_ct10k");
    //
    TH1D *hnlo0_ct10 = hnlo_ct10;
    hnlo0_ct10->SetName("hnlo0_ct10");
    hnlo_ct10 = tools::Rebin(hnlo0_ct10, hpt);
    hnlo_ct10->SetName("hnlo_ct10");
    //
    TH1D *hnlo0_mstw = hnlo_mstw;
    hnlo0_mstw->SetName("hnlo0_mstw");
    hnlo_mstw = tools::Rebin(hnlo0_mstw, hpt);
    hnlo_mstw->SetName("hnlo_mstw");
    //
    TH1D *hnlo0_nnpdf = hnlo_nnpdf;
    hnlo0_nnpdf->SetName("hnlo0_nnpdf");
    hnlo_nnpdf = tools::Rebin(hnlo0_nnpdf, hpt);
    hnlo_nnpdf->SetName("hnlo_nnpdf");
    //
    TH1D *hnlo0_hera = hnlo_hera;
    hnlo0_hera->SetName("hnlo0_hera");
    hnlo_hera = tools::Rebin(hnlo0_hera, hpt);
    hnlo_hera->SetName("hnlo_hera");
  }
  */

  dout->cd();
  gnlo->Write();
  gnlocut->Write();
  gnlofit->Write();
  fnlo->Write();

  din->cd();
} // theoryBin
Esempio n. 29
0
// The actual job
void signalEfficiency_w(int channel, double sqrts, int process, double JES, ofstream* txtYields) 
{
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << channel << endl;

  TString schannelFilename = (schannel=="2e2mu"?"2mu2e":schannel); // adapt to naming convention of tree files

  TString sprocess;
  if      (process == ggH) sprocess = "ggH";
  else if (process == qqH) sprocess = "qqH";
  else if (process == ZH) sprocess = "ZH";
  else if (process == WH) sprocess = "WH";
  else if (process == ttH) sprocess = "ttH";
  else cout << "Not a valid channel: " << process << endl;  

  TString sjes;
  if      (JES==0.) sjes="";
  else if (JES>0.)  sjes="_up";
  else if (JES<0.)  sjes="_down";

  TString ssqrts = (long) sqrts + TString("TeV");


  // Print table with yields
  (*txtYields) << endl << endl 
	       << left << setw(7) << "*** Summary: " << sprocess << " process, sqrts = " << fixed << setprecision(0) <<sqrts << " TeV, channel = " << schannel << " ***" << endl << endl;
  (*txtYields) << left << setw(7) << "mH" << setw(13) << "XS*BR" << setw(13) 
	       << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" 
	       << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" 
	       << setw(13) << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" 
	       << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" 
	       << setw(13) << "n. raw" << setw(13) << "n. W pwg" << setw(13) << "n. W PU" 
	       << setw(13) << "n. W eff" << setw(13) 
	       << endl << left << setw(7) << " " << setw(13) << " " << setw(13)
	       << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" 
	       << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" 
	       << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" 
	       << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" 
	       << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" 
	       << endl << endl;

  cout << "process = " << sprocess << " schannel = " << schannel << "  sqrts = " << sqrts << " JES = " << JES <<endl;

  TString totoutfile = "CardFragments/signalEfficiency_"  + ssqrts + "_" + schannel + sjes + ".txt";
  TString ratiooutfile = "CardFragments/signalEfficiency_" + ssqrts + "_" + schannel + sjes + "_ratio.txt";
  TString jetyieldoutfile = "CardFragments/signalEfficiency_"  + ssqrts + "_" + schannel + sjes + "_jetyields.txt";

  // Create card fragments using new powheg samples
  ofstream oftot;
  ofstream ofrat;

  if (process==ggH) {
    oftot.open(totoutfile,ios_base::out);
    ofrat.open(ratiooutfile,ios_base::out);
  } else {
    oftot.open(totoutfile,ios_base::out | ios_base::app);
    ofrat.open(ratiooutfile,ios_base::out | ios_base::app);
  }

  ftot = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? ".root" : "_oldPwg.root"),"RECREATE");
  fratio = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? "_ratio.root" : "_ratio_oldPwg.root"),"RECREATE");

  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  setTDRStyle(false);
  gStyle->SetStatX(-0.5);

  int nPoints=0;
  int* masses=0;
  double* mHVal=0;

  // Pick the correct set of mass points, set subpath
  TString filepath;
  if (process==ggH){
    if (useNewGGHPowheg) {
      if (sqrts==7) {
	nPoints = nPoints7TeV_p15;
	masses  = masses7TeV_p15;
	mHVal   = mHVal7TeV_p15;
	filepath = filePath7TeV;
      } else if (sqrts==8) {
	nPoints = nPoints8TeV_p15;
	masses  = masses8TeV_p15;
	mHVal   = mHVal8TeV_p15;
	filepath = filePath8TeV;
      }
    } else { // OLD powheg samples
      if (sqrts==7) {
	nPoints = nPoints7TeV;
	masses  = masses7TeV;
	mHVal   = mHVal7TeV;
	filepath = filePath7TeV;
      } else if (sqrts==8) {
	nPoints = nPoints8TeV;
	masses  = masses8TeV;
	mHVal   = mHVal8TeV;
	filepath = filePath8TeV;
      }
    }
  } else if (process==qqH) {
    if (sqrts==7) {
      nPoints = nVBFPoints7TeV;
      masses  = VBFmasses7TeV;
      mHVal   = mHVBFVal7TeV;
      filepath = filePath7TeV;
    } else if (sqrts==8) {
      nPoints = nVBFPoints8TeV;
      masses  = VBFmasses8TeV;
      mHVal   = mHVBFVal8TeV;
      filepath = filePath8TeV;
    }
  } else if (process==ZH || process==WH || process==ttH) {
    if (sqrts==7) {
      nPoints = nVHPoints7TeV;
      masses  = VHmasses7TeV;
      mHVal   = mHVHVal7TeV;
      filepath = filePath7TeV;
    } else if (sqrts==8) {
      nPoints = nVHPoints8TeV;
      masses  = VHmasses8TeV;
      mHVal   = mHVHVal8TeV;
      filepath = filePath8TeV;
    }
  }  


  float xMax = masses[nPoints-1]+10;


  const int arraySize=200;
  assert (arraySize>=nPoints);
  double totefficiencyVal[arraySize];
  double totefficiencyErr[arraySize];
  double dijetratioVal[arraySize];
  double dijetratioErr[arraySize];
  double totefficiencyValInMW[arraySize];
  double totefficiencyErrInMW[arraySize];
  double dijetratioValInMW[arraySize];
  double dijetratioErrInMW[arraySize];


  // Define the object to compute XS and BRs
  HiggsCSandWidth *myCSW = new HiggsCSandWidth(gSystem->ExpandPathName("$CMSSW_BASE/src/Higgs/Higgs_CS_and_Width/txtFiles/"));
	
  TString infile;

  TGraph gJys(nPoints);

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

    // Compute XS and BR
    double xsTimesBR = 0.;
    double BRH4e = myCSW->HiggsBR(12,masses[i]);
    double BRH2e2mu = myCSW->HiggsBR(13,masses[i]);
    double BRHZZ = myCSW->HiggsBR(11,masses[i]);
    double BR = BRHZZ;
    if (process==ggH || process==qqH) { 
      if (channel==fs4mu || channel==fs4e) BR = BRH4e;
      else BR = BRH2e2mu;
    }

    if (process==ggH)      xsTimesBR = BR*myCSW->HiggsCS(1,masses[i],sqrts);
    else if (process==qqH) xsTimesBR = BR*myCSW->HiggsCS(2,masses[i],sqrts);
    else if (process==ZH)  xsTimesBR = BR*myCSW->HiggsCS(3,masses[i],sqrts);
    else if (process==WH)  xsTimesBR = BR*myCSW->HiggsCS(4,masses[i],sqrts);
    else if (process==ttH) xsTimesBR = BR*myCSW->HiggsCS(5,masses[i],sqrts); 


    if (process==ggH) {
      if (useNewGGHPowheg){ 
	infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_powheg15" + (masses[i]>200?"H":"jhuGenV3H") + (long)masses[i] + ".root";
      } else {
	infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_H" + (long)masses[i] + ".root";
      }
    }
    
    else if (process==qqH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_VBFH" + (long)masses[i] + ".root";
    else if (process==WH || process==ZH || process==ttH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_" + sprocess + (long)masses[i] + ".root";    

    TFile *f = TFile::Open(infile) ;
    TTree *t1 = (TTree*) f->Get("SelectedTree");
    float MC_weight_norm, MC_weight_PUWeight, MC_weight_powhegWeight,  MC_weight_dataMC;
    float MC_weight_noxsec;
    float GenHPt;
    //int NJets;
    short genProcessId=0;
    //    short NJets30;
    vector<double> *JetPt=0;
    vector<double> *JetSigma=0;
    float ZZMass;
    t1->SetBranchAddress("MC_weight_norm",&MC_weight_norm); // For efficiency vs "proper" final state
    t1->SetBranchAddress("MC_weight_noxsec",&MC_weight_noxsec); // For efficiency vs all gen events
    t1->SetBranchAddress("MC_weight_powhegWeight",&MC_weight_powhegWeight);
    t1->SetBranchAddress("MC_weight_PUWeight",&MC_weight_PUWeight);
    t1->SetBranchAddress("MC_weight_dataMC",&MC_weight_dataMC);
    //t1->SetBranchAddress("NJets",&NJets);
    t1->SetBranchAddress("genProcessId",&genProcessId);
    t1->SetBranchAddress("JetPt",&JetPt);
    t1->SetBranchAddress("JetSigma",&JetSigma);
    //    t1->SetBranchAddress("NJets30",&NJets30);
    t1->SetBranchAddress("GenHPt",&GenHPt);
    t1->SetBranchAddress("ZZMass",&ZZMass);

    //Initialize counters for non-dijet events
    Counts* untagInMW = new Counts(); Counts* untagAll = new Counts();
    Counts* dijetInMW = new Counts(); Counts* dijetAll = new Counts();

    // Find window width // FIXME move to external function
    double valueWidth = myCSW->HiggsWidth(0,masses[i]);
    double windowVal = max(valueWidth,1.);
    
    double lowside = 100.;
    double highside = 1000.0;
      
    if (masses[i] >= 275){
      lowside = 180.0;
      highside = 650.0;
    }
    if (masses[i] >= 350){
      lowside = 200.0;
      highside = 900.0;
    }
    if (masses[i] >= 500){
      lowside = 250.0;
      highside = 1000.0;
    }
    if (masses[i] >= 700){
      lowside = 350.0;
      highside = 1400.0;
    }
    double low_M = max( (masses[i] - 20.*windowVal), lowside);
    double high_M = min((masses[i] + 15.*windowVal), highside);


    // // Load Higgs pT weights for old powheg
    //     TFile* fW; TH1D* h_HPtWeight; 
    //     TString fW_str = "./HPtWeights/weight_";
    //     fW_str += (long)masses[i];
    //     fW_str += (TString)".root";
    //     cout << fW_str << endl;
    //     if (process==ggH) {
    //       fW = TFile::Open(fW_str,"READ");
    //       h_HPtWeight = (TH1D*)fW->Get("h_weight");
    //     }


    for (int a = 0; a < t1->GetEntries(); a++){ 
      t1->GetEntry(a);
      // Skip VH events that do not belong to the right gen prod mechanism. This is no longer necessary with the proper VH samples
      if ((process==ZH && genProcessId!=24) || (process==WH && genProcessId!=26) || (process==ttH && (genProcessId!=121 && genProcessId!=122))) continue; 


      // We use the efficiency vs. generated events in the proper FS for ggH, VBF, and the efficiency vs all generated events for VH, ttH
      float effw = MC_weight_norm;
      if (process==ZH) {
	effw = MC_weight_noxsec*filter_eff_ZH_8TeV;
      }
      else if (process==WH){
	effw = MC_weight_noxsec*filter_eff_WH_8TeV;
      }
      else if (process==ttH){
	effw = MC_weight_noxsec*filter_eff_ttH_8TeV;
      }      

//       double HPtWeight = 1.;
//       if (process==ggH) HPtWeight = h_HPtWeight->GetBinContent(h_HPtWeight->FindBin(GenHPt));
//       //cout << "Higgs pT weight = " << HPtWeight << endl;
//       effw*=HPtWeight;
      

      int NJets=0;
      double jetptc=0;
      for (unsigned int j=0; j<JetPt->size();j++){
	if (JES==0.) jetptc=JetPt->at(j);
	else if (JES!=0.) jetptc=JetPt->at(j)*(1+JES*JetSigma->at(j));
	if (jetptc>30.) NJets++;
      }

      // Untagged
      if (NJets<2){
	untagAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
	if ( (ZZMass>low_M && ZZMass<high_M) ) untagInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
      }
      else{ // Dijet
	dijetAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
	if ( (ZZMass>low_M && ZZMass<high_M) ) dijetInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
      }
      
    }

    // FIXME: the 7TeV old samples are assumed to have the ad-hoc correction factor for the mll>12 gen cut,
    // except for the 124,125,126 new samples. As this factor is accounted for in the x-section, we have to 
    // apply it here.
    float m = masses[i];
    if (!useNewGGHPowheg && process==ggH && sqrts==7 && m>=123.9 &&  m<=126.1) {
      float mllCorr = 0.5 + 0.5*erf((m-80.85)/50.42);
      untagAll->totalCtr = untagAll->totalCtr/mllCorr;
      untagAll->eff_noweight=untagAll->eff_noweight/mllCorr;
      untagInMW->totalCtr = untagInMW->totalCtr/mllCorr;
      untagInMW->eff_noweight=untagInMW->eff_noweight/mllCorr;
      dijetAll->totalCtr = dijetAll->totalCtr/mllCorr;
      dijetAll->eff_noweight=dijetAll->eff_noweight/mllCorr;
      dijetInMW->totalCtr = dijetInMW->totalCtr/mllCorr;
      dijetInMW->eff_noweight=dijetInMW->eff_noweight/mllCorr;
    }

    if (verbose) {
      cout << " m = " << masses[i] 
	   << " :" <<endl;
      cout << "Selected non-dijet events (all) = " << untagAll->numEventsRaw 
	   << " Powheg Wtd= " << untagAll->numEventsPowheg
	   << " PU Wtd= " << untagAll->numEventsPU
	   << " Data/MC Wtd= " << untagAll->numEventsDataMC
	   << " Efficiency= " << untagAll->totalCtr
	   << endl;
      cout << "Selected non-dijet events (in mass window) = " << untagInMW->numEventsRaw 
	   << " Powheg Wtd= " << untagInMW->numEventsPowheg
	   << " PU Wtd= " << untagInMW->numEventsPU
	   << " Data/MC Wtd= " << untagInMW->numEventsDataMC
	   << " Efficiency= " << untagInMW->totalCtr
	   << endl;
      cout << "Selected dijet events (all) = " << dijetAll->numEventsRaw 
	   << " Powheg Wtd= " << dijetAll->numEventsPowheg
	   << " PU Wtd= " << dijetAll->numEventsPU
	   << " Data/MC Wtd= " << dijetAll->numEventsDataMC
	   << " Efficiency= " << dijetAll->totalCtr
	   << endl;
      cout << "Selected dijet events (in mass window) = " << dijetInMW->numEventsRaw 
	   << " Powheg Wtd= " << dijetInMW->numEventsPowheg
	   << " PU Wtd= " << dijetInMW->numEventsPU
	   << " Data/MC Wtd= " << dijetInMW->numEventsDataMC
	   << " Efficiency= " << dijetInMW->totalCtr
	   << endl;
    }

    // All events
    totefficiencyVal[i] = untagAll->totalCtr + dijetAll->totalCtr;
    cout << "All events:            " << sprocess << " " << m << " " << totefficiencyVal[i]<<endl;
    totefficiencyErr[i] = sqrt(untagAll->sumw2 + dijetAll->sumw2);
    dijetratioVal[i]=dijetAll->totalCtr/totefficiencyVal[i];
    dijetratioErr[i]=sqrt(pow(untagAll->totalCtr,2)*dijetAll->sumw2 + pow(dijetAll->totalCtr,2)*untagAll->sumw2)/pow(totefficiencyVal[i],2); // FIXME: misses 1 term 

    // Events inside the mass window
    totefficiencyValInMW[i] = untagInMW->totalCtr + dijetInMW->totalCtr;
    cout << "Events in mass window: " << sprocess << " " << m << " " << totefficiencyValInMW[i]<<endl;
    totefficiencyErrInMW[i] = sqrt(untagInMW->sumw2 + dijetInMW->sumw2);
    dijetratioValInMW[i]=dijetInMW->totalCtr/totefficiencyValInMW[i];
    dijetratioErrInMW[i]=sqrt(pow(untagInMW->totalCtr,2)*dijetInMW->sumw2 + pow(dijetInMW->totalCtr,2)*untagInMW->sumw2)/pow(totefficiencyValInMW[i],2);
    
    
    // Write yields to output file
    double lumi = -1.;
    sqrts == 7 ? lumi = lumi7TeV*1000 : lumi = lumi8TeV*1000;
    double yieldTot = xsTimesBR*lumi*totefficiencyVal[i];
    double yieldTag = xsTimesBR*lumi*dijetratioVal[i]*totefficiencyVal[i];
    double yieldUnt = xsTimesBR*lumi*untagAll->totalCtr;
    double yieldTotInMW = xsTimesBR*lumi*totefficiencyValInMW[i];
    double yieldTagInMW = xsTimesBR*lumi*dijetratioValInMW[i]*totefficiencyValInMW[i];
    double yieldUntInMW = xsTimesBR*lumi*untagInMW->totalCtr;

    int prec = 3;
    if (process>=3) prec=5;
    (*txtYields) << left << setw(7) << fixed << setprecision(0) << masses[i] << setw(13) << fixed << setprecision(7) << xsTimesBR 
		 << setw(13) << fixed << setprecision(prec) << untagInMW->totalCtr << setw(13) << yieldUntInMW << setw(13) << dijetratioValInMW[i]*totefficiencyValInMW[i] 
		 << setw(13) << yieldTagInMW << setw(13) << fixed << setprecision(prec) << totefficiencyValInMW[i] << setw(13) << yieldTotInMW 
		 << setw(13) << fixed << setprecision(prec) << untagAll->totalCtr << setw(13) << yieldUnt << setw(13) << dijetratioVal[i]*totefficiencyVal[i] 
		 << setw(13) << yieldTag << setw(13) << totefficiencyVal[i] << setw(13) << yieldTot 
		 << setw(13) << fixed << setprecision(0) << untagAll->numEventsRaw + dijetAll->numEventsRaw
		 << setw(13) << fixed << setprecision(2) << untagAll->numEventsRaw + dijetAll->numEventsPowheg
		 << setw(13) << untagAll->numEventsPU + dijetAll->numEventsPU
		 << setw(13) << untagAll->numEventsDataMC + dijetAll->numEventsDataMC
		 << endl;
     
  
    f->Close();
    gJys.SetPoint(i,masses[i],yieldTagInMW/yieldUntInMW);
  }  
  TF1 *fitJys = new TF1("fitJys","pol3",100,1000);
  gJys.Fit(fitJys);

  (*txtYields) << endl << endl << endl;
	
  TGraphErrors* totgrEff;
  TGraphErrors* ratgrEff;

  if (process==ggH || process==qqH){
    totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyVal, 0, totefficiencyErr);
    ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioVal, 0, dijetratioErr);
  }
  else {
    totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyValInMW, 0, totefficiencyErrInMW);
    ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioValInMW, 0, dijetratioErrInMW);
  }
  totgrEff->SetMarkerStyle(20);
  ratgrEff->SetMarkerStyle(20);

  //ICHEP parametrization	
  //TF1 *polyFunc= new TF1("polyFunc","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)", 110., xMax);
  //polyFunc->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07);


  TF1 *polyFunctot= new TF1("polyFunctot","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)+[7]*TMath::Gaus(x,[8],[9])", 110., xMax);
  polyFunctot->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07, 0.03, 200, 30);
  polyFunctot->SetParLimits(7,0,0.2);
  polyFunctot->SetParLimits(8,160,210);
  polyFunctot->SetParLimits(9,10,70);

  if (process!=ggH && process!=qqH) {
    polyFunctot->FixParameter(7,0);
    polyFunctot->FixParameter(8,0);
    polyFunctot->FixParameter(9,1);
  }

//   if (channel==fs4mu && sqrts==7) {    
//     polyFunctot->SetParLimits(7,0,0.035);
//     polyFunctot->SetParLimits(8,160,210);
//     polyFunctot->SetParLimits(9,30,50);
//   }

  polyFunctot->SetLineColor(4);      
  TString cname = "eff" + sprocess + ssqrts + "_" + schannel;
  TCanvas *ctot = new TCanvas(cname,cname);
  ctot->SetGrid();

  TString outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes;
  if (!useNewGGHPowheg) outname+="_oldPwg";

  totgrEff->Fit(polyFunctot,"Rt"); 
  TString xaxisText = "m_{" + schannel + "}";
  totgrEff->GetXaxis()->SetTitle(xaxisText);
  TString yaxisText = "Efficiency, " + sprocess + ", " + schannel;
  totgrEff->GetYaxis()->SetTitle(yaxisText);
  totgrEff->SetMinimum(0.0);
  totgrEff->SetMaximum(1.0);
  if (process>=3) totgrEff->SetMaximum(0.0035);
  totgrEff->Draw("AP");
  polyFunctot->Draw("sames");
  ctot->Print(outname+".eps");
  //ctot->Print(outname+".png"); // Does not work in batch?
  ctot->Print(outname+".pdf"); 
  //ctot->Print(outname+".root"); 
  ftot->cd();
  totgrEff->Write("TotalEfficiency");
  ftot->Close();

  cout << endl;
  cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl;
  cout << "   a1 = " << polyFunctot->GetParameter(0) << endl;
  cout << "   a2 = " << polyFunctot->GetParameter(1) << endl;
  cout << "   a3 = " << polyFunctot->GetParameter(2) << endl;
  cout << "   a4 = " << polyFunctot->GetParameter(3) << endl;
  cout << "   b1 = " << polyFunctot->GetParameter(4) << endl;
  cout << "   b2 = " << polyFunctot->GetParameter(5) << endl;
  cout << "   b3 = " << polyFunctot->GetParameter(6) << endl;
  cout << "   g1 = " << polyFunctot->GetParameter(7) << endl;
  cout << "   g2 = " << polyFunctot->GetParameter(8) << endl;
  cout << "   g3 = " << polyFunctot->GetParameter(9) << endl;
  cout << "---------------------------" << endl << endl;


  // Create card fragments using new powheg samples
  string oftotprocess;
  if (process==ggH) oftotprocess="";
  else oftotprocess=sprocess;

  if (process==ggH) {
    oftot << endl;
    oftot << "## signal efficiency ##" << endl;
  }
  oftot << "signalEff " << oftotprocess << "a1  " << polyFunctot->GetParameter(0) << endl;
  oftot << "signalEff " << oftotprocess << "a2  " << polyFunctot->GetParameter(1) << endl;
  oftot << "signalEff " << oftotprocess << "a3  " << polyFunctot->GetParameter(2) << endl;
  oftot << "signalEff " << oftotprocess << "a4  " << polyFunctot->GetParameter(3) << endl;
  oftot << "signalEff " << oftotprocess << "b1  " << polyFunctot->GetParameter(4) << endl;
  oftot << "signalEff " << oftotprocess << "b2  " << polyFunctot->GetParameter(5) << endl;
  oftot << "signalEff " << oftotprocess << "b3  " << polyFunctot->GetParameter(6) << endl;
  oftot << "signalEff " << oftotprocess << "g1  " << polyFunctot->GetParameter(7) << endl;
  oftot << "signalEff " << oftotprocess << "g2  " << polyFunctot->GetParameter(8) << endl;
  oftot << "signalEff " << oftotprocess << "g3  " << polyFunctot->GetParameter(9) << endl;
  oftot << endl;
  oftot.close();

  
  cname = "eff" + sprocess + ssqrts + "_" + schannel + "_ratio";
  TCanvas *crat = new TCanvas(cname,cname);
  crat->SetGrid();

  outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes + "_ratio";
  if (!useNewGGHPowheg) outname+="_oldPwg";

  TF1 *ratiofit=0;
  if (process==ggH || process==qqH) ratiofit = new TF1("ratiofit","([0]+[1]*x+[2]*x*x)",110.,xMax);
  if (process==ZH || process==WH || process==ttH ) ratiofit = new TF1("ratiofit","([0]+[1]*x)",110.,xMax);

  ratgrEff->Fit(ratiofit,"Rt");
  ratgrEff->GetXaxis()->SetTitle(xaxisText);
  TString yaxisratio = "Dijet ratio, " + sprocess + ", " + schannel;
  ratgrEff->GetYaxis()->SetTitle(yaxisratio);
  ratgrEff->SetMinimum(0.0);
  ratgrEff->SetMaximum(1.0);
  ratgrEff->Draw("AP");
  crat->Print(outname+".eps");
  //crat->Print(outname+".png"); // Does not work in batch?
  crat->Print(outname+".pdf");
  //crat->Print(outname+".root");
  fratio->cd();
  ratgrEff->Write("Ratio");
  fratio->Close();
  
  cout << endl;
  cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl;
  cout << "   a1 = " << ratiofit->GetParameter(0) << endl;
  cout << "   a2 = " << ratiofit->GetParameter(1) << endl;
  if (process==ggH || process==qqH) cout << "   a3 = " << ratiofit->GetParameter(2) << endl;
  cout << "---------------------------" << endl << endl;

  if (process==ggH) {
    ofrat<<"## jet tagged/untagged ratio"<<endl;
    ofrat<<"jetYieldRatio "<<fitJys->GetParameter(0)<<"+("<<fitJys->GetParameter(1)<<"*@0)+("<<fitJys->GetParameter(2)<<"*@0*@0)+("<<fitJys->GetParameter(3)<<"*@0*@0*@0)"<< endl <<endl;
    ofrat << "## signal efficiency ratios ##" << endl;
  }
  ofrat << "signalEff tagged_" << sprocess << "_ratio " << ratiofit->GetParameter(0) << "+(" << ratiofit->GetParameter(1) << "*@0)";
  if (process==ggH || process==qqH) ofrat << "+(" << ratiofit->GetParameter(2) << "*@0*@0)" << endl;
  else if (process==ZH || process==WH ) ofrat << endl;
  else if (process==ttH) ofrat << endl << endl;
  ofrat.close();

  // deviations
  cout << "Deviations..." << endl;
  double maxResidual=0;
  for (int i = 0; i < nPoints; i++){
    double eval = polyFunctot->Eval(masses[i]);
    double residual = (eval - totefficiencyVal[i]);
    maxResidual = max(maxResidual,fabs(residual));
    if (verbose)    cout << "For mass, " << masses[i] << ": measured value is " << totefficiencyVal[i] << " and difference from function is " << residual <<endl;
  }
  cout << "Largest residual= " << maxResidual << endl;

  delete fitJys;
  delete myCSW;
  delete polyFunctot;
  delete ratiofit;
}
Esempio n. 30
0
int main(int argc, char *argv[]){

  TGraphErrors *gr = new TGraphErrors();
  
  bool x = true;
  const float MAX1 = atof(argv[1]), MAX2 = atof(argv[2]), STEP = atof(argv[3]);
  
  TCanvas *can = new TCanvas("can", "can", 600, 600);
  
  float xmin = -1*MAX1, xmax = MAX1, ymin = -1*MAX2, ymax = MAX2, varmin, varmax;
  
  for(int i = 0; i < 2; i++){
    
    char slice;
    
    if(i == 0) slice = 'X';
    else{
      slice = 'Y';
      swap(xmin, ymin);
      swap(xmax, ymax);
    }
    
    char buffer[100];
    sprintf(buffer,"mkdir -p /afs/cern.ch/user/w/wbenoit/work/PlotTools/EnergyResolution/Resolution%c/%g_%g_%g", slice, MAX1, MAX2, STEP);
    system(buffer);
    
    int num = 0;
    for(float pos = -1*MAX1; pos <= MAX1-STEP; pos+=STEP){
      varmin = pos;
      varmax = pos+STEP;
      
      vector<float> point;
      
      if(x){
	point = getSlopeRatio(slice, MAX1, MAX2, STEP, varmin, varmax, ymin, ymax);
	if(pos == MAX1-STEP) x = false;
      }
      else point = getSlopeRatio(slice, MAX1, MAX2, STEP, xmin, xmax, varmin, varmax);
      
      gr->SetPoint(num, (varmin+varmax)/4, point.at(0));
      gr->SetPointError(num, (float) STEP/4, point.at(1));
      num++;
    }
    
    TString grTitle;
    grTitle.Form("Hodoscope %c Position (mm)", slice);
    
    gr->SetMarkerStyle(21);
    gr->GetXaxis()->SetTitle(grTitle.Data());
    gr->GetYaxis()->SetTitle("m2/m1");
    gr->GetYaxis()->SetTitleOffset(2);
    
    gr->Draw("apl");
    
    can->SetLeftMargin(0.15);
    
    TString title;
    title.Form("./Resolution%c/%g_%g_%g/resolution%c_%g_%g_%g.png", slice, MAX1, MAX2, STEP, slice, MAX1, MAX2, STEP);
    can->SaveAs(title.Data());
    
    title.Form("./Resolution%c/%g_%g_%g/resolution%c_%g_%g_%g.root", slice, MAX1, MAX2, STEP, slice, MAX1, MAX2, STEP);
    TFile *resFile = new TFile(title.Data(), "RECREATE");
    gr->Write("gr");
  }
  
  //chi2->SaveAs("chi2.root");
  
  return 1;
}