Beispiel #1
0
//Return a graph of the llscan
TGraph * LLscanResult::GetGraph() 
{
	double*  pvs = new double[parameterValues.size()] ;
	double* llvs = new double[parameterValues.size()] ;
	double llmax = 0 ;	
	for(unsigned int i=0; i< parameterValues.size() ; ++i ){
		pvs[i] = parameterValues[i] ;
		llvs[i] = llvalues_offset[i] ;
		if( llvs[i] > llmax ) llmax = llvs[i] ;
	}	

	TGraph* gr = new TGraph( Int_t(parameterValues.size()), pvs, llvs ) ;
	//gr->SetTitle("LL Scan for Parameter xxx");	
	gr->SetMarkerStyle(1);
	gr->SetLineWidth(2);
	gr->SetMarkerColor(4);
	gr->SetLineColor(4);
	gr->GetYaxis()->SetRangeUser( 0., llmax*1.2 );
	gr->GetYaxis()->SetLimits( 0., llmax*1.2 );
	gr->SetMinimum( 0.0 );
	gr->SetMaximum( llmax*1.2 );
	gr->Draw("ALP");
	string title("LL Scan for Parameter ") ;
	title+=parameterName.c_str();
	gr->SetTitle(title.c_str());	
	gr->GetXaxis()->SetTitle(parameterName.c_str());

	return gr ;
}
Beispiel #2
0
void histos_pde_two(){
	std::string material[3] = {"lxe","lxe_tpb","lyso"};
	std::string interaction[3] = {"","_noCher","_noScint"};

	double sigmas[3][3][20]; // [mat][inter][pde]
	double pdeValues[20];
	char pde[5];

	TCanvas *c1 = new TCanvas("c1","multipads",900,700);


	for(int mat=0; mat<3;mat++){
		for(int inter=0; inter<2;inter++){
			for(int i=5;i<=100;i+=5){
				pdeValues[i/5-1] = i;

				//There is an error with lsyo noScint pde 0.05
				if((mat==2 && inter==2) && i==5)){
					continue;
				}

				sprintf(pde, "%.2lf", i/100.0);
				if(i==100){
					sprintf(pde, "0%.2lf", i/100.0);
				}

				std::string path = "/home/jmbenlloch/next/petalo/work/histo/pde/";
				std::string fileName = path + material[mat] + interaction[inter] + std::string("_PHYS_QE_") + std::string(pde) + std::string("_SPTR_0_ASIC_0_DT300_histos.root"); std::string(Form("%d", 1));
				std::cout << fileName << std::endl;

				TFile *fIn = new TFile(fileName.c_str(), "read");

				TH1F *h1 = (TH1F*) fIn->Get("DTOF.DTOF3");
				TF1* gauF1 = new TF1("gauF1","gaus",-20,20);
				TF1* gauF2 = new TF1("gauF2","gaus",-60,60);

				TF1 *total = new TF1("total","gaus(0)+gaus(3)",-50,50);

				h1->Scale(1/h1->Integral(), "width");

				Double_t par[6];
				h1->Fit(gauF1,"R");
				h1->Fit(gauF2,"R+");
				//Do not plot
				h1->GetFunction("gauF1")->SetBit(TF1::kNotDraw);
				h1->GetFunction("gauF2")->SetBit(TF1::kNotDraw);
				gauF1->GetParameters(&par[0]);
				gauF2->GetParameters(&par[3]);
				total->SetParameters(par);
				h1->Fit(total,"R+");
				h1->Draw();

				std::string histo = path + material[mat] + interaction[inter] + std::string("_pde_") + pde + std::string(".png");
				std::cout << histo << std::endl;
				c1->Print(histo.c_str());

				std::cout << "PDE: " << pde << "sigma: "  << h1->GetFunction("gauF1")->GetParameter(2) << std::endl;
				sigmas[mat][inter][i/5-1] = h1->GetFunction("gauF1")->GetParameter(2);

				fIn->Close();
			}
		}
	}
	c1->Close();

	TCanvas *c2 = new TCanvas("c2","multipads",900,700);
	TGraph *gLxe = new TGraph(20, pdeValues, sigmas[0][0]);
	gLxe->SetLineColor(kRed);
	gLxe->SetLineWidth(2);

	TGraph *gTpb = new TGraph(20, pdeValues, sigmas[1][0]);
	gTpb->SetLineColor(kBlue);
	gTpb->SetLineWidth(2);

	TGraph *gLyso = new TGraph(20, pdeValues, sigmas[2][0]);
	gLyso->SetLineColor(kGreen);
	gLyso->SetLineWidth(2);

	gLyso->Draw();
	gLyso->SetTitle("");
	gLyso->GetXaxis().SetTitle("PDE (%)");
	gLyso->GetXaxis()->SetLimits(0.,100.);
	gLyso->GetYaxis().SetTitle("CRT (ps)");
	gLyso->SetMinimum(0.);
	gLyso->SetMaximum(50.);
	gTpb->Draw("same");
	gLxe->Draw("same");

	TLegend *leg = new TLegend(0.7, 0.7, 0.9, 0.9);
	leg->SetFillColor(0);
	leg->AddEntry(gLxe, "LXe", "lp");
	leg->AddEntry(gTpb, "LXe-TPB", "lp");
	leg->AddEntry(gLyso, "LYSO", "lp");
	leg->Draw("same");

	c2->Print("/home/jmbenlloch/next/petalo/work/histo/pde/pde.png");


	TCanvas *c3 = new TCanvas("c3","multipads",900,700);
	TGraph *gLxe_noCher = new TGraph(20, pdeValues, sigmas[0][1]);
	gLxe_noCher->SetLineColor(kRed);
	gLxe_noCher->SetLineWidth(2);

	TGraph *gTpb_noCher = new TGraph(20, pdeValues, sigmas[1][1]);
	gTpb_noCher->SetLineColor(kBlue);
	gTpb_noCher->SetLineWidth(2);

	TGraph *gLyso_noCher = new TGraph(20, pdeValues, sigmas[2][1]);
	gLyso_noCher->SetLineColor(kGreen);
	gLyso_noCher->SetLineWidth(2);

	gLyso_noCher->Draw();
	gLyso_noCher->SetTitle("noCher");
	gLyso_noCher->GetXaxis().SetTitle("PDE (%)");
	gLyso_noCher->GetXaxis()->SetLimits(0.,100.);
	gLyso_noCher->GetYaxis().SetTitle("CRT (ps)");
	gLyso_noCher->SetMinimum(0.);
	gLyso_noCher->SetMaximum(50.);
	gTpb_noCher->Draw("same");
	gLxe_noCher->Draw("same");

	TLegend *leg_noCher = new TLegend(0.7, 0.7, 0.9, 0.9);
	leg_noCher->SetFillColor(0);
	leg_noCher->AddEntry(gLxe, "LXe", "lp");
	leg_noCher->AddEntry(gTpb, "LXe-TPB", "lp");
	leg_noCher->AddEntry(gLyso, "LYSO", "lp");
	leg_noCher->Draw("same");

	c3->Print("/home/jmbenlloch/next/petalo/work/histo/pde/pde_noCher.png");

}
void plotFittedValueHPOL(){


  AnitaGeomTool *myGeomTool = AnitaGeomTool::Instance();

  double x[MAX_ANTENNAS] = {0.};
  double y[MAX_ANTENNAS] = {0.};
  double z[MAX_ANTENNAS] = {0.};
  double r[MAX_ANTENNAS] = {0.};
  double phi[MAX_ANTENNAS] = {0.};

  double zFit[MAX_ANTENNAS] = {0.};
  double rFit[MAX_ANTENNAS] = {0.};
  double phiFit[MAX_ANTENNAS] = {0.};

  double zFit2[MAX_ANTENNAS] = {0.};
  double rFit2[MAX_ANTENNAS] = {0.};
  double phiFit2[MAX_ANTENNAS] = {0.};

  Double_t deltaR[MAX_ANTENNAS]={0};  
  Double_t deltaZ[MAX_ANTENNAS]={0};  
  Double_t deltaPhi[MAX_ANTENNAS]={0};  
  Double_t deltaCableDelays[MAX_ANTENNAS]={0};

  Double_t antArray[MAX_ANTENNAS] = {0.};
  Double_t cableDelays[MAX_ANTENNAS]={0};

  AnitaPol::AnitaPol_t pol = AnitaPol::kHorizontal;

   for (unsigned int ant=0; ant<MAX_ANTENNAS; ++ant){
     antArray[ant] = (ant+1)*1.;
     // myGeomTool->getAntXYZ(ant, x[ant], y[ant], z[ant], pol);
     
     // r[ant] = myGeomTool->getAntR(ant, pol);
     // phi[ant] = myGeomTool->getAntPhiPosition(ant, pol);

   }

  TLegend *leg = new TLegend(0.6, 0.75, 0.89, 0.89);
  leg->SetFillColor(kWhite);

 
  TGraph *gphotoR = new TGraph(48, antArray, r);
  gphotoR->SetMarkerStyle(22);
  TGraph *gphotoZ = new TGraph(48, antArray, z);
  gphotoZ->SetMarkerStyle(22);
  TGraph *gphotoPHI = new TGraph(48, antArray, phi);
  gphotoPHI->SetMarkerStyle(22);
  TGraph *gphotoCableDelay = new TGraph(48, antArray, cableDelays);
  gphotoCableDelay->SetMarkerStyle(22);

  const int numfile = 2;

  //  string filename[numfile]={"newLindaNumbers_4steps_zDisplaced_VPOL_10kVSeavey_2015_11_05_time_19_47_53.txt", "newLindaNumbers_4steps_zDisplaced_VPOL_10kVSeavey_2015_11_06_time_10_42_48.txt", "newLindaNumbers_4steps_zDisplaced_VPOL_10kVSeavey_2015_11_11_time_15_38_30.txt", "newLindaNumbers_4steps_2015_10_13_time_14_30_54.txt"};
  string filename[numfile]={"final/newLindaNumbers_4steps_HPOL_2015_11_13_time_17_19_58.txt", "newLindaNumbers_4steps_LDBHPOL_10kVSeavey_2015_11_19_time_10_16_23.txt"};

  string which[numfile] = {"FIT WAIS H-POL", "FIT LDB H-POL"};

  
  TCanvas *c1 = new TCanvas("c1", "", 1200, 750);
  gphotoR->SetTitle(";Antenna;#Delta r [m]");  
  gphotoR->Draw("Ap");
  gphotoR->SetMinimum(-0.2);
  gphotoR->SetMaximum(+0.2);
  gphotoR->Draw("Ap");

  TCanvas *c2 = new TCanvas("c2", "", 1200, 750);
  gphotoZ->SetTitle(";Antenna;#Delta z [m]");
  gphotoZ->Draw("Ap");
  gphotoZ->SetMinimum(-0.2);
  gphotoZ->SetMaximum(+0.2);
  gphotoZ->Draw("Ap");

  TCanvas *c3 = new TCanvas("c3", "", 1200, 750);
  gphotoPHI->SetTitle(";Antenna;#Delta phi [rad]");  
  gphotoPHI->Draw("Ap");
  gphotoPHI->SetMinimum(-0.2);
  gphotoPHI->SetMaximum(+0.2);
  gphotoPHI->Draw("Ap");

  TCanvas *c4 = new TCanvas("c4", "", 1200, 750);
  gphotoCableDelay->SetTitle(";Antenna;Time offset [ns]");
  gphotoCableDelay->Draw("Ap");
  gphotoCableDelay->SetMinimum(-0.5);
  gphotoCableDelay->SetMaximum(+0.5);
  gphotoCableDelay->Draw("Ap");

  leg->AddEntry(gphotoR, "Photogrammetry", "p");

  Color_t colors[5]={kRed, kOrange, kGreen, kBlue, kCyan};

  for (int i=0;i<numfile;i++){
    
    ifstream myInput(Form("/home/lindac/ANITA/Software/EventCorrelator/macros/lindaMacros/%s", filename[i].c_str()));
    
    if (myInput.is_open()){
      for (int i=0;i<48;i++){
	myInput >> antArray[i] >> deltaR[i] >> deltaZ[i] >> deltaPhi[i] >> deltaCableDelays[i];
	cout << antArray[i] << " " << deltaR[i] << endl;
      }
    }
    
   for (unsigned int ant=0; ant<MAX_ANTENNAS; ++ant){
     
    rFit[ant] = r[ant] + deltaR[ant];
    zFit[ant] = z[ant] + deltaZ[ant];
    phiFit[ant] = phi[ant] + deltaPhi[ant];
    antArray[ant] = (ant+1)*1.;
    
    
   }
    
   TGraph *gfitR = new TGraph(48, antArray, rFit);
   gfitR->SetMarkerStyle(22);
   gfitR->SetMarkerColor(colors[i]);

   TGraph *gfitZ = new TGraph(48, antArray, zFit);
   gfitZ->SetMarkerStyle(22);
   gfitZ->SetMarkerColor(colors[i]);

   TGraph *gfitPHI = new TGraph(48, antArray, phiFit);
   gfitPHI->SetMarkerStyle(22);
   gfitPHI->SetMarkerColor(colors[i]);

   TGraph *gfitT = new TGraph(48, antArray, deltaCableDelays);
   gfitT->SetMarkerStyle(22);
   gfitT->SetMarkerColor(colors[i]);

   leg->AddEntry(gfitR, Form("Fitted w/ %s", which[i].c_str()), "p");

   c1->cd();
   gfitR->Draw("p same");

   c2->cd();
   gfitZ->Draw("p same");

   c3->cd();
   gfitPHI->Draw("p same");

   c4->cd();
   gfitT->Draw("p same");

   
  }

  c1->cd();
  leg->Draw();
  c1->Print("FittedValues_HPOL_R_4steps_compare.png");
  c1->Print("FittedValues_HPOL_R_4steps_compare.pdf");

  c2->cd();
  leg->Draw();
  c2->Print("FittedValues_HPOL_Z_4steps_compare.png");
  c2->Print("FittedValues_HPOL_Z_4steps_compare.pdf");

  c3->cd();
  leg->Draw();
  c3->Print("FittedValues_HPOL_PHI_4steps_compare.png");
  c3->Print("FittedValues_HPOL_PHI_4steps_compare.pdf");

  c4->cd();
  leg->Draw();
  c4->Print("FittedValues_HPOL_CableDelay_4steps_compare.png");
  c4->Print("FittedValues_HPOL_CableDelay_4steps_compare.pdf");


  }
void ExtractSignalYield(string ModelName, string decayMode, float natural_width, bool dependsOnKtilde=0)
{
  
  string dir = "/usr/users/dschaefer/root/results/";
  string outputfile = ModelName+"_"+decayMode+"_signalYield.root";
  //float natural_width =0.05;
  std::stringstream s;
      if(int(natural_width*100+0.5) == 10 or int(100*natural_width+0.5)==20 or int(natural_width*100+0.5)==30)
      {
	s << std::fixed << std::setprecision(1) << natural_width;
      }
      else
      {
	s << std::fixed << std::setprecision(2) << natural_width;
      }
  string swidth = s.str();
  float ktilde;
  string sktilde;
  if(dependsOnKtilde)
  {
   ktilde = natural_width;
   sktilde = swidth;
  }
  
  TGraph* limit = getObservedLimit(ModelName,decayMode,natural_width,dependsOnKtilde);
  TGraph* limitUP = getLimitUp(ModelName,decayMode,natural_width,1,dependsOnKtilde);
  TGraph* limitDOWN = getLimitDown(ModelName,decayMode,natural_width,1,dependsOnKtilde);
  TGraph* limitUP2 = getLimitUp(ModelName,decayMode,natural_width,2,dependsOnKtilde);
  TGraph* limitDOWN2 = getLimitDown(ModelName,decayMode,natural_width,2,dependsOnKtilde);
  
  
  int number;
  float* masses;
  if(decayMode.find("lvjj")!=string::npos)
  {
    masses = new float[38];
    number =38;
    float array[38] = {800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700,2800,2900,3000,3100,3200,3300,3400,3500,3600,3700,3800,3900,4000,4100,4200,4300,4400,4500};
    masses = array;
  }
  else
  {
   number = 29;
   masses = new float[29];
   float array[29] = {1200,1300,1400,1500,1600,1700,1800,1900,2000,2100,2200,2300,2400,2500,2600,2700,2800,2900,3000,3100,3200,3300,3400,3500,3600,3700,3800,3900,4000};
   masses = array;
  }
  TGraph* gryellow = new TGraph(2*number);
  TGraph* grgreen  = new TGraph(2*number);
  
  for(int m=0;m<number;m++)
  {
    gryellow->SetPoint(m,masses[m],limitUP->Eval(masses[m]));
    gryellow->SetPoint(number+m,masses[number-m-1],limitDOWN->Eval(masses[number-m-1]));
    grgreen->SetPoint(m,masses[m],limitUP2->Eval(masses[m]));
    grgreen->SetPoint(number+m,masses[number-m-1],limitDOWN2->Eval(masses[number-m-1]));
    
  }
  gryellow->SetFillColor(kYellow);
  grgreen->SetFillColor(kGreen);
  
  TCanvas* test = new TCanvas("test","test",400,400);
  test->SetLogy();
  limitUP->SetFillColor(kGreen+2);
  limitUP->SetLineColor(kGreen+2);
  limitUP->SetLineWidth(-1504);
  
  //limitUP->Draw("ACP");
  limitDOWN->SetFillColor(kBlue);
  limitDOWN->SetLineColor(kGreen+2);
  limitDOWN->SetLineWidth(-1504);
  //limitDOWN->Draw("CPsame");
  gryellow->Draw("AFsame");
  grgreen->Draw("Fsame");
  limit->SetLineColor(kBlue);
  limit->SetLineWidth(3);
  limit->Draw("Lsame");
  test->Update();
  
  float lumi = 2.10*1000;  //pb^-1
  if(decayMode.find("jjjj")!=string::npos){lumi = 2.6*1000;}//pb^-1
  
  
  
  
  //float *xs = getTheoryCrossSection(ModelName,0.1);
  
  //x values for which a theory prediction for production cross section exists
  float m_xs[10]  =  {800,900,1000,1500,1800,2000,2500,3000,3500,4500};
  float BR_G_to_WW[10];
  float BR_G_to_ZZ[10];
  float *acceptance;
  float *N_expected;
  //float xs = 0.01;
  float *xs = new float[10];
  
  if(dependsOnKtilde)
  {
    xs = getTheoryCrossSection(ModelName,ktilde);
  }
  else
  {
    for(int i=0;i<10;i++)
    {
    if(natural_width!=0)
    {
      ktilde = getKtilde(ModelName,m_xs[i],natural_width);
      //std::cout << m_xs[i] << " k = " << ktilde <<std::endl;
      xs[i] = getTheoryCrossSection(ModelName,m_xs[i],ktilde);
    }
    else
    {
      ktilde = getKtilde(ModelName,m_xs[i],0.02);
      //std::cout <<  m_xs[i] << " k = " << ktilde <<std::endl;
      xs[i] = getTheoryCrossSection(ModelName,m_xs[i],ktilde);
    }
    }
  }
  
 
 
 
  
  TGraph* production_xs = new TGraph(10,m_xs,xs);
  
  // TCanvas* c_xs = new TCanvas("c_xs","c_xs",400,400);
  // c_xs->SetLogy();
  // production_xs->SetMarkerColor(1);
  // production_xs->GetXaxis()->SetTitle("m_G [GeV]");
  // production_xs->GetYaxis()->SetTitle("theory production cross section");
  // production_xs->Draw("AL");
  
  
  
  if(!dependsOnKtilde)
  {
  acceptance = getAcceptance(ModelName,decayMode,m_xs,10);
  }
  else
  {
   acceptance = getAcceptance(decayMode,ktilde); 
  }
  
  N_expected = getNumberOfExpectedEvents(xs,m_xs,acceptance,ModelName,decayMode);
  

 std::cout << "production cross section : "<< std::endl;
  for(int i=0;i<10;i++)
    {
      std::cout << m_xs[i] <<  " " << xs[i]<< std::endl;
    }
  std::cout << " acceptance : "<<std::endl;
  for(int i=0;i<10;i++)
    {
      std::cout << m_xs[i] << " "<<acceptance[i]<<std::endl;
    }
  float br[10];
  std::cout << "Branching Ratios : "<<std::endl;
  for(int i=0;i<10;i++)
    {
      float BR_W_to_lv = 0.327;
      float BR_W_to_jj = 0.674;
      float BR_Z_to_jj = 0.6991;
      br[i] = getBranchingRatioToWW(ModelName,m_xs[i])*std::pow(BR_W_to_jj,2)*2 + getBranchingRatioToZZ(ModelName,m_xs[i])*std::pow(BR_Z_to_jj,2)*2;
      if(decayMode.find("lvjj")!=std::string::npos)
	{
	  br[i] = getBranchingRatioToWW(ModelName,m_xs[i])*2*BR_W_to_lv*BR_W_to_jj;
	}
      std::cout << m_xs[i] << " "<< br[i] << std::endl;
    }
  std::cout << lumi <<std::endl;
  std::cout << " N expected : "<<std::endl;
  for(int i=0;i<10;i++)
    {
      std::cout << m_xs[i] << " "<<N_expected[i] << " " <<xs[i]*lumi*br[i]*acceptance[i] << std::endl;
    }

  
  TGraph* N = new TGraph(10,m_xs,N_expected);
  //N->SetName("expected signal yield");
  grgreen->GetXaxis()->SetTitle("m_{VV} [GeV]");
  grgreen->GetYaxis()->SetTitle("number signal events");
  grgreen->GetYaxis()->SetTitleOffset(1.3);
  grgreen->SetTitle("");
  TCanvas* c_N = new TCanvas("c_N","c_N",600,400);
  gPad->SetRightMargin(0.1);
  gPad->SetLeftMargin(0.1);
  limit->SetLineColor(kBlue);
  limit->SetLineWidth(3);
  c_N->SetLogy();
  N->SetLineColor(kRed);
  N->SetLineWidth(2);
  //N->Draw("A");
  grgreen->SetMaximum(1000);
  grgreen->Draw("AF");
  gryellow->Draw("Fsame");
  limit->Draw("Csame");
  N->Draw("Lsame");
  TLegend* leg = new TLegend(0.59,0.65,0.95,0.89);
  leg->SetFillColor(kWhite);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
  leg->SetBorderSize(0);
  
  string title = "Preliminary";
  string cms = "#font[62]{CMS} #font[52]{"+string(title)+"} ";
  string lumitext = "2.6 fb^{-1}, #sqrt{s} = 13 TeV";
  string cmstext = "CMS ,2.6 fb^{-1}, #sqrt{s} = 13 TeV";
  if(decayMode.find("had")==string::npos){lumitext = "2.1 fb^{-1}, #sqrt{s} = 13 TeV";}
  string theory = "G #rightarrow WW, #Gamma = "+swidth;
  if(dependsOnKtilde)
  {
    theory = "G #rightarrow WW, #tilde{k} = "+sktilde;
  }
  if(ModelName.find("RSGrav")!=string::npos)
  {
   theory = "RS #rightarrow WW, #Gamma = "+swidth;
   if(dependsOnKtilde)
    {
      theory = "RS #rightarrow WW, #tilde{k} = "+sktilde;
    }
  }
  
  leg->AddEntry(grgreen,"Expected (95%)","f");
  leg->AddEntry(gryellow,"Expected (68%)","f");
  leg->AddEntry(limit,"observed","L");
  leg->AddEntry(N,theory.c_str(),"L");
  leg->Draw("same");
  
  TLatex CMS;
  int y = 1050;
  int x = 500;
  int x2 = 3400;
  if(decayMode.find("jjjj")!= string::npos){y=1050;x=1000;x2=3000;}
  CMS.SetTextFont(43);
  CMS.SetTextSize(18);
  CMS.DrawLatex(x,y,cms.c_str());
  CMS.DrawLatex(x2,y,lumitext.c_str());
  
  c_N->Update();
  if(dependsOnKtilde)
  {
    c_N->SaveAs(("/usr/users/dschaefer/root/results/misc/"+ModelName+"_limit_"+decayMode+"_ktilde"+swidth+".pdf").c_str());
  }
  else
  {
  c_N->SaveAs(("/usr/users/dschaefer/root/results/misc/"+ModelName+"_limit_"+decayMode+"_"+swidth+".pdf").c_str());
  }
  
  
  //===========================================================================================
  //======== my own produced samples with ktilde = 0.095 ======================================
  //===========================================================================================
  
  
  
  float* acc2 = getAcceptance(decayMode,0.095);
  float* xs_new = getTheoryCrossSection(ModelName,0.095);
  
  for(int i=0;i<10;i++)
  {
   std::cout << " acceptance int : " << acceptance[i] <<std::endl;
   std::cout << " acceptance 2   : " << acc2[i] << std::endl;
  }
  
   // TGraph* testa
   // TCanvas* test2 = new TCanvas("test2","test2",400,400);
//   obsl->Draw("AL");
//   Neve->Draw("LSAME");
  
  float* N_expected2 = getNumberOfExpectedEvents(xs_new,m_xs,acc2,ModelName,decayMode);
  TGraph* obsl = getObservedLimit(ModelName,decayMode,0.095,1);
  TGraph* Neve = new TGraph(10,m_xs,N_expected2);
  

  
  
  TGraph* pl = getExcludedPoints(ModelName,decayMode,obsl,Neve,0.095);
  pl->SetLineWidth(3);
  pl->SetLineColor(kWhite);
  //pl->SetFillStyle(3013);
  //pl->SetFillColor(kWhite);
  
  string channel = "had";
  if(decayMode.find("lvjj")!=std::string::npos)
  {
   channel = "em"; 
  }
  
  TFile* file = new TFile(("/home/dschaefer/CMSSW_7_1_5/src/HiggsAnalysis/CombinedLimit/graphs_"+channel+".root").c_str(),"READ");
  string histoname = "ExclusionLimitOnEventNumber_BulkG_WW_em_HP";
  if(channel.find("had")!=std::string::npos)
  {
   histoname =  "ExclusionLimitOnEventNumber_BulkWW_had_HP";
  }
  TH2F* obsLim = dynamic_cast<TH2F*>(file->Get(histoname.c_str()));
  TCanvas* MyC = new TCanvas("MyC","MyC",800,600);
  MyC->SetRightMargin(0.19);
//   MyC->SetLeftMargin(0.12);
//   MyC->SetTopMargin(0.08);
//   MyC->SetBottomMargin(0.15);
  MyC->SetLogz();
  obsLim->Draw("COLZ");
  //pl->Draw("f");
  pl->Draw("Same");
  
  std::map<float,float> mass_acc;
  for(int i=0;i<10;i++)
  {
   mass_acc.insert(std::pair<float, float>(m_xs[i],acc2[i]));   
  }
  TGraph* allpoints = findAllExcludedPoints(ModelName,decayMode, mass_acc,0.095);
  MyC->cd();
  allpoints->Draw("Psame");
  
  
  float massmax = 4500;
  float massmin = 800;
  int n = (massmax-massmin)/100;
  float* k = new float[n*2];
  int t=0;
  for(int i=0;i<=n;i++)
  {
    k[i] = getKtilde("RSGrav",massmin+i*100,0.3);
    std::cout << "mass max: "<< massmin+i*100 << " ktilde " << k[i]<<std::endl;
  }
  for(int i=n;i<2*n;i++)
  {
   k[i] = getKtilde("RSGrav",massmin+(i-n)*100,0.02);
   std::cout << " mass min : "<< massmin+(i-n)*100 << " ktilde " << k[i] << std::endl;
  }
  
  printWidthForKtilde("RSGrav",0.12,3600,800);
  printWidthForKtilde("RSGrav",0.2 ,2400,800);
  printWidthForKtilde("RSGrav",0.3 ,1800,800);
  printWidthForKtilde("RSGrav",0.4 ,1500,800);
  printWidthForKtilde("RSGrav",0.5 ,1100 ,800);
  printWidthForKtilde("RSGrav",0.05,4500,2000);
  printWidthForKtilde("RSGrav",0.03,4600,3200);
  
}
void makePlots( const char * model,
                const char * target, 
                const char * src, 
                const char * config,
                const char * infile) 
{

  double MAXY = 2.4;
  
  double x_Q13_SetI = sin(8.8*TMath::Pi()/180.0)*sin(8.8*TMath::Pi()/180.0);
  
  double x_Q13_SetII = sin(12.0*TMath::Pi()/180.0)*sin(12.0*TMath::Pi()/180.0);

  //Input path
  TString inpath("./root_files/RvsQ13/");
  
  TString inputfile = inpath + TString(infile);

  //Output path
  TString path("./paper02-plots/ratio/");
    
  TList * v_Variations = new TList();
  TObjString *var;

  var = new TObjString("Sin2Q13-1.8-dCP0");
  v_Variations->Add( var ); 
  var = new TObjString("Sin2Q13-1.8-dCP180");
  v_Variations->Add( var );

  if ( TString(model) != TString("StdPicture") ) {
    
    var = new TObjString("Sin2Q13-2.0-dCP0");
    v_Variations->Add( var ); 
    var = new TObjString("Sin2Q13-2.0-dCP180");
    v_Variations->Add( var );

  } else {

    var = new TObjString("Sin2Q13-2-dCP0");
    v_Variations->Add( var ); 
    var = new TObjString("Sin2Q13-2-dCP180");
    v_Variations->Add( var );  
  
  }
  
  var = new TObjString("Sin2Q13-2.2-dCP0");
  v_Variations->Add( var ); 
  var = new TObjString("Sin2Q13-2.2-dCP180");
  v_Variations->Add( var );
  
  int * linewidth = new int[6];
  int * linestyle = new int[6];
  int * linecolor = new int[6];
  
  linewidth[0] = 2;
  linewidth[1] = 3;
  linewidth[2] = 2;
  linewidth[3] = 3;
  linewidth[4] = 2;
  linewidth[5] = 3;

  linecolor[0] = 1;
  linecolor[1] = 2;
  linecolor[2] = 1;
  linecolor[3] = 2;
  linecolor[4] = 1;
  linecolor[5] = 2;

  linestyle[0] = 1;
  linestyle[1] = 1;
  linestyle[2] = 2;
  linestyle[3] = 2;
  linestyle[4] = 3;
  linestyle[5] = 3;

  TList * v_Labels = new TList();
  TObjString *label;
  
  label = new TObjString( "#alpha = 1.8" );
  v_Labels->Add( label ); 
  label = new TObjString( "#alpha = 2.0" );
  v_Labels->Add( label ); 
  label = new TObjString( "#alpha = 2.2" );
  v_Labels->Add( label ); 
  
  TFile * f1 = new TFile( inputfile.Data() );
  f1->cd();

  TList * v_Graphs = new TList();

  int max = v_Variations->GetEntries();
  
  for( int k = 0; k < max; ++k ) 
  {
    
    TString current = ((TObjString*)v_Variations->At(k))->GetString();

    TString dataPxx = TString( "Ratio_" ) 
      + TString( model )  + TString("_")
      + TString( target ) + TString("_") 
      + TString( src )    + TString("_") 
      + TString( current.Data() )
      + TString("/data");
   
    std::cout << dataPxx << std::endl;
    
 
    TTree * PxxTreeNu = (TTree*)gDirectory->Get( dataPxx.Data() );
    
    //Branches
    double xx = 0.0;
    double yy = 0.0;
    
    PxxTreeNu->SetBranchAddress("Xx",&xx);
    PxxTreeNu->SetBranchAddress("Ratio",&yy);
    
    Long64_t nentries = PxxTreeNu->GetEntries();
    
    TGraph * g1 = new TGraph();
    
    for (Long64_t i=0;i<nentries;i++) {
      PxxTreeNu->GetEntry(i);
      g1->SetPoint( i, xx, yy);
    }
    
    v_Graphs->Add( g1 );
      
  }
  
  TString cname = TString("Ratio") + TString("_") + TString(model) +  TString("_") + TString(config);
  
  TCanvas * c1 = new TCanvas( cname.Data(), "track/shower ratio", 206,141,722,575); 

  c1->SetBorderSize(2);
    
  TLegend * leg = new TLegend(0.18,0.64,0.44,0.87);
  
  leg->SetBorderSize(0);
  leg->SetTextFont(22);
  leg->SetTextSize(0.062);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);

  int labelpos = 0;
  
  for( int k = 0; k < max; ++k ) 
  {

    TGraph * gg = (TGraph*)v_Graphs->At(k);

    gg->SetMarkerStyle(25);
    gg->SetFillColor(10);

    gg->SetLineColor(linecolor[k]);
    gg->SetLineWidth(linewidth[k]);
    gg->SetLineStyle(linestyle[k]);

    gg->SetMaximum(MAXY);
    gg->SetMinimum(1.6);

    gg->GetXaxis()->SetLimits( 0.0, 0.055 );

    gg->GetXaxis()->SetTitle("sin^{2}#theta_{13}");
    gg->GetXaxis()->CenterTitle(true);
    gg->GetXaxis()->SetLabelFont(42);
    gg->GetXaxis()->SetLabelOffset(0.006);
    gg->GetXaxis()->SetLabelSize(0.06);
    gg->GetXaxis()->SetTitleSize(0.06);
    gg->GetXaxis()->SetTickLength(0.05);
    gg->GetXaxis()->SetTitleOffset(1.07);
    gg->GetXaxis()->SetTitleFont(42);
    gg->GetXaxis()->SetNdivisions(509);
    gg->GetYaxis()->SetTitle("R");
    gg->GetYaxis()->CenterTitle(true);
    gg->GetYaxis()->SetNdivisions(509);
    gg->GetYaxis()->SetLabelFont(42);
    gg->GetYaxis()->SetLabelOffset(0.007);
    gg->GetYaxis()->SetLabelSize(0.06);
    gg->GetYaxis()->SetTitleSize(0.06);
    gg->GetYaxis()->SetTitleOffset(0.93);
    gg->GetYaxis()->SetTitleFont(42);

    if ( ((k+1) % 2) == 0 )
    {
      TString alpha = ((TObjString*)v_Labels->At(labelpos))->GetString();      
      leg->AddEntry( gg, alpha.Data(),"l");
      labelpos+=1;
    }
    
    c1->cd();

    if( k == 0 )
      gg->Draw("AC");
    else
      gg->Draw("C");

    TString ThisModel;
    TString ThisConfig;
    
    if( TString(model) == TString("StdPicture") )
      ThisModel = TString("No matter effect");
    else 
    {
      ThisModel = TString(model);
      ThisModel.Insert(5," ");
    }

    ThisConfig = TString(config);
    ThisConfig.Insert(3," ");
      
    TLatex *   tex = new TLatex(0.033, (MAXY-(MAXY*0.035)), ThisModel.Data() );
    tex->SetLineWidth(2);
    tex->Draw();

    if ( TString(model) != TString("StdPicture") ) {
      tex = new TLatex(0.033, (MAXY-(MAXY*0.055)), ThisConfig.Data() );
      tex->SetLineWidth(2);
      tex->Draw();
    }
      
  
  }
  
  leg->Draw();

  
  
  double y_min = 1.60;
  double y_max = MAXY;
  
  TLine *line = new TLine(x_Q13_SetI, y_min,x_Q13_SetI, y_max);
  //line->Draw();
  line = new TLine(x_Q13_SetII, y_min,x_Q13_SetII, y_max);
  //line->Draw();

  c1->cd();
  
  std::stringstream saveAs;
  
  saveAs.str("");
  saveAs << path << model << "/pdf/" << "RvsSin2Q13_" << model << "_" << target << "_" << config << ".pdf";
  c1->SaveAs( saveAs.str().c_str() );
  
  saveAs.str("");
  saveAs << path << model << "/png/" << "RvsSin2Q13_" << model << "_" << target << "_" << config << ".png";
  c1->SaveAs( saveAs.str().c_str() );

  saveAs.str("");
  saveAs << path << model << "/eps/" << "RvsSin2Q13_" << model<< "_" <<  target << "_" << config << ".eps";
  c1->SaveAs( saveAs.str().c_str() );
  
  
}
Beispiel #6
0
// -------------------------
// -- Functions           --
// -------------------------
void makeDeadEcalEff() {
   
  gStyle->SetOptStat(0);  
  TCanvas *c1 = new TCanvas("c1","A Simple Graph with error bars",200,10,700,500);
  
  const Int_t nbins = 6;

  TString lifetime = "0.5";
  //   TString lifetime = "1";
   //   TString lifetime = "5";

   Float_t masses      [nbins] = {103, 164, 246, 328, 408, 488};  
   Float_t effOld0p5ns [nbins] = {0.884, 0.958, 0.889, 0.895, 0.897, 0.909}; 
   Float_t effDPG0p5ns [nbins] = {0.877, 0.958, 0.894, 0.884, 0.901, 0.888};  // Federico's DPG map 

   Float_t effOld1ns   [nbins] = {0.896, 0.93, 0.912, 0.944, 0.918, 0.914}; 
   Float_t effDPG1ns   [nbins] = {0.899, 0.92, 0.912, 0.926, 0.90, 0.901};  // Federico's DPG map 

   Float_t effOld5ns   [nbins] = {0.921, 0.938, 0.942, 0.92, 0.936, 0.942}; 
   Float_t effDPG5ns   [nbins] = {0.909, 0.913, 0.934, 0.911, 0.93, 0.936};  // Federico's DPG map 

   Float_t* effOld;
   Float_t* effDPG; 

   if (lifetime=="0p5") {
     effOld = effOld0p5ns;
     effDPG = effDPG0p5ns;
   }

   if (lifetime=="1") {
     effOld = effOld1ns;
     effDPG = effDPG1ns;
   }

   if (lifetime=="5") {
     effOld = effOld5ns;
     effDPG = effDPG5ns;
   }

   for (int i=0; i<nbins; i++) {
     effOld[i] = 1.0 - effOld[i];
     effDPG[i] = 1.0 - effDPG[i];
   }

   TGraph *grEffOld = new TGraph(nbins, masses, effOld);  
   TGraph *grEffDPG = new TGraph(nbins, masses, effDPG);  

   grEffOld->SetMarkerStyle(21); // 21:  square  
   grEffOld->SetMarkerSize(0.8);
   grEffOld->SetMarkerColor(kBlue);
   grEffOld->SetLineWidth(2);  
   grEffOld->SetMinimum(0);
   grEffOld->SetMaximum(0.25);
   //  grEffOld->SetTitle(";chargino mass;efficiency of dead ECAL veto"); 
   grEffOld->SetTitle(";chargino mass;1 - #epsilon"); 
   grEffOld->Draw("AP");
   //   grEffOld->Draw("P");

   grEffDPG->SetMarkerStyle(26); // 26:  hollow triangle 
   grEffDPG->SetMarkerSize(0.8);
   grEffDPG->SetMarkerColor(kRed);
   grEffDPG->SetLineWidth(2);  
   grEffDPG->Draw("P, same");

  TLine l;
  l.SetLineColor(kRed);
  l.DrawLine(2.5,1.0,6.5,1.0); 
  TLegend leg2(0.50,0.6,0.85,0.8);
  leg2.AddEntry(grEffOld, "old map ("      + lifetime + " ns)", "pl");  
  leg2.AddEntry(grEffDPG, "ECAL DPG map (" + lifetime + " ns)", "pl");  
  leg2.SetBorderSize(0);
  leg2.SetFillStyle(1001);
  leg2.SetFillColor(kWhite);
  leg2.SetBorderSize(0);
  leg2.SetTextFont(gStyle->GetTitleFont());
  leg2.Draw();


  TPaveText* pt = new TPaveText(0.50, 0.82, 0.90, 0.88, "NDC");
  pt->SetFillStyle(0);
  pt->SetBorderSize(0);
  pt->SetTextFont(gStyle->GetTitleFont());
  pt->AddText("CMS Preliminary, #sqrt{s} = 8 TeV");
  //  pt->Draw();


  c1->SetLogy(0);
  c1->Print("deadEcalEff" + lifetime + "ns.pdf");  
  c1->Clear();

  return;

} 
void makePlots( const char * model, const char * src, const char * infile , const char * option )
{
  
  //Output path
  TString path("./paper01-plots/probs/");
  
  TString dataPee  = TString( model ) + TString("_") + TString( src ) + TString("_Pee/data");
  TString dataPem  = TString( model ) + TString("_") + TString( src ) + TString("_Pem/data");
  TString dataPet  = TString( model ) + TString("_") + TString( src ) + TString("_Pet/data");
  TString dataAPee = TString( model ) + TString("_") + TString( src ) + TString("_aPee/data");
  TString dataAPem = TString( model ) + TString("_") + TString( src ) + TString("_aPem/data");
  TString dataAPet = TString( model ) + TString("_") + TString( src ) + TString("_aPet/data");
    
  TList * v_Labels = new TList();
  TObjString *label;
  label = new TObjString( "Pee" );
  v_Labels->Add( label ); 
  label = new TObjString( "Pe#mu" );
  v_Labels->Add( label ); 
  label = new TObjString( "Pe#tau" );
  v_Labels->Add( label ); 
  
  TFile * f1 = new TFile(infile);
  
  f1->cd();
  
  TTree * PeeTreeNu = (TTree*)gDirectory->Get( dataPee.Data() );
  TTree * PemTreeNu = (TTree*)gDirectory->Get( dataPem.Data() );
  TTree * PetTreeNu = (TTree*)gDirectory->Get( dataPet.Data() );
  
  TTree * PeeTreeANu = (TTree*)gDirectory->Get( dataAPee.Data() );
  TTree * PemTreeANu = (TTree*)gDirectory->Get( dataAPem.Data() );
  TTree * PetTreeANu = (TTree*)gDirectory->Get( dataAPet.Data() );
  
  //Branches
  double xx = 0.0;
  double yy = 0.0;
  
  TCanvas * c1 = new TCanvas(model, "Oscillation probabilities", 184, 60, 861, 670);
  c1->Divide(1,3);
  
  TGraph * ProbNu[3];
  ProbNu[0] = new TGraph();
  ProbNu[1] = new TGraph();
  ProbNu[2] = new TGraph();
  
  TGraph * ProbANu[3];
  ProbANu[0] = new TGraph();
  ProbANu[1] = new TGraph();
  ProbANu[2] = new TGraph();
  
  TGraph * Psum = new TGraph();
  TGraph * aPsum = new TGraph();
  
  TLegend * leg = new TLegend(0.14,0.69,0.24,0.85);
    
  PeeTreeNu->SetBranchAddress("Ex",&xx);
  PeeTreeNu->SetBranchAddress("Pb",&yy);
  
  Long64_t nentries = PeeTreeNu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PeeTreeNu->GetEntry(i);
    ProbNu[0]->SetPoint( i, xx, yy);
  }

  PeeTreeANu->SetBranchAddress("Ex",&xx);
  PeeTreeANu->SetBranchAddress("Pb",&yy);
  
  nentries = PeeTreeANu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PeeTreeANu->GetEntry(i);
    ProbANu[0]->SetPoint( i, xx, yy);
  }

  ///Pem
  
  PemTreeNu->SetBranchAddress("Ex",&xx);
  PemTreeNu->SetBranchAddress("Pb",&yy);

  nentries = PemTreeNu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PemTreeNu->GetEntry(i);
    ProbNu[1]->SetPoint( i, xx, yy);
  }
  
  PemTreeANu->SetBranchAddress("Ex",&xx);
  PemTreeANu->SetBranchAddress("Pb",&yy);
  
  nentries = PemTreeANu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PemTreeANu->GetEntry(i);
    ProbANu[1]->SetPoint( i, xx, yy);
  }

  ///Pet

  PetTreeNu->SetBranchAddress("Ex",&xx);
  PetTreeNu->SetBranchAddress("Pb",&yy);

  nentries = PetTreeNu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PetTreeNu->GetEntry(i);
    ProbNu[2]->SetPoint( i, xx, yy);
  }
  
  PetTreeANu->SetBranchAddress("Ex",&xx);
  PetTreeANu->SetBranchAddress("Pb",&yy);
  
  nentries = PetTreeANu->GetEntries();
  
  for (Long64_t i=0;i<nentries;i++) {
    PetTreeANu->GetEntry(i);
    ProbANu[2]->SetPoint( i, xx, yy);
  }

  for( int k=0; k < 3; ++k) 
  {
    
    ProbNu[k]->SetLineColor(4);
    ProbNu[k]->SetMarkerColor(4);
    ProbNu[k]->SetMarkerStyle(7);
    
    ProbNu[k]->SetFillColor(10);
    ProbNu[k]->SetMaximum(1.0);
    ProbNu[k]->SetMinimum(0.0);
    
    TString yaxis = ((TObjString*)v_Labels->At(k))->GetString();
    ProbNu[k]->GetYaxis()->SetTitle( yaxis.Data() );
    ProbNu[k]->GetXaxis()->SetTitle("E [eV]");
    ProbNu[k]->GetYaxis()->CenterTitle(true); 
    ProbNu[k]->GetXaxis()->CenterTitle(true); 
    ProbNu[k]->GetXaxis()->SetLabelOffset(0.007);
    ProbNu[k]->GetXaxis()->SetLabelSize(0.08);
    ProbNu[k]->GetXaxis()->SetTitleSize(0.07);
    ProbNu[k]->GetXaxis()->SetTitleOffset(0.9);
    ProbNu[k]->GetXaxis()->SetLabelFont(42);
    ProbNu[k]->GetYaxis()->SetLabelOffset(0.007);
    ProbNu[k]->GetYaxis()->SetLabelSize(0.08);
    ProbNu[k]->GetYaxis()->SetLabelFont(42);
    ProbNu[k]->GetYaxis()->SetTitleSize(0.09);
    ProbNu[k]->GetYaxis()->SetTitleOffset(0.45);
    ProbNu[k]->GetYaxis()->SetTitleFont(42);
    
    ProbANu[k]->SetMarkerColor(42);
    ProbANu[k]->SetMarkerStyle(23);
    ProbANu[k]->SetMarkerSize(0.3);
    
    ProbANu[k]->SetFillColor(10);
    ProbANu[k]->SetMaximum(1.0);
    ProbANu[k]->SetMinimum(0.0);
    

  }
  
  leg->AddEntry( ProbNu[0], "#nu");
  leg->AddEntry( ProbANu[0], "#bar{#nu}");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.1);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(1001);


  c1->cd(1);
  gPad->SetGridx();
  gPad->SetGridy();
  gPad->SetLogx();

  if ( std::string(model).compare("EarthB") == 0 ) 
    ProbNu[0]->GetXaxis()->SetLimits(0.98e9, 1.0e10);

  ProbNu[0]->Draw("APL");
  ProbANu[0]->Draw("PL");
  topTitle(model);
  leg->DrawClone();
  
  c1->cd(2);
  gPad->SetGridx();
  gPad->SetGridy();
  gPad->SetLogx();
  
  if ( std::string(model).compare("EarthB") == 0 ) 
    ProbNu[1]->GetXaxis()->SetLimits(0.98e9, 1.0e10);
  
  ProbNu[1]->Draw("APL");
  ProbANu[1]->Draw("PL");
  leg->DrawClone();
    
  c1->cd(3);
  gPad->SetGridx();
  gPad->SetGridy();
  gPad->SetLogx();
  
  if ( std::string(model).compare("EarthB") == 0 ) 
    ProbNu[2]->GetXaxis()->SetLimits(0.98e9, 1.0e10);
  
  ProbNu[2]->Draw("APL");
  ProbANu[2]->Draw("PL");
  leg->DrawClone();

  c1->cd();

  std::stringstream saveAs;
    
  saveAs.str("");
  saveAs << path << model << "/pdf/" << "nueosc_probs_" << model << "_" << option << ".pdf";
  c1->SaveAs( saveAs.str().c_str() );
  
  saveAs.str("");
  saveAs << path << model << "/png/" << "nueosc_probs_" << model << "_" << option << ".png";
  c1->SaveAs( saveAs.str().c_str() );

  saveAs.str("");
  saveAs << path << model << "/eps/" << "nueosc_probs_" << model << "_" << option << ".eps";
  c1->SaveAs( saveAs.str().c_str() );

  TH1D * h_Psum = new TH1D("Psum.Histo","",100, 0.99999, 1.0001);
  TH1D * h_aPsum = h_Psum->Clone("aPsum.Histo");

  for (Long64_t i=0;i<nentries;i++) {
    
    double xx = 0.0;
    double yy = 0.0;
    double p1 = 0.0;
    double p2 = 0.0;
    double p3 = 0.0;
    
    ProbNu[0]->GetPoint(i, xx, p1);
    ProbNu[1]->GetPoint(i, xx, p2);
    ProbNu[2]->GetPoint(i, xx, p3);
    
    yy = p1 + p2 + p3;
    
    if ( xx < 1.0e14 ) 
    {
      Psum->SetPoint( i, xx, yy);
      h_Psum->Fill( yy );
    }
    else 
      break;
    
  }

  for (Long64_t i=0;i<nentries;i++) {
    
    double xx = 0.0;
    double yy = 0.0;
    double p1 = 0.0;
    double p2 = 0.0;
    double p3 = 0.0;
    
    ProbANu[0]->GetPoint(i, xx, p1);
    ProbANu[1]->GetPoint(i, xx, p2);
    ProbANu[2]->GetPoint(i, xx, p3);
    
    yy = p1 + p2 + p3;
    
    if ( xx < 1.0e14 ) 
    {
      aPsum->SetPoint( i, xx, yy);
      h_aPsum->Fill( yy );
    }
    
    else 
      break;
    
  }
  
  TCanvas * c2 = new TCanvas("Sums", "Oscillation probabilities - SUMS", 184,112,394,472);
  
  c2->Divide(2,2);
  
  c2->cd(1);
  
  gPad->SetLogx();
  Psum->SetMaximum(1.1);
  Psum->SetMinimum(0.0);
  Psum->SetMarkerStyle(21);
  Psum->SetMarkerSize(0.2); 
  
  if ( std::string(model).compare("EarthB") == 0 ) 
    Psum->GetXaxis()->SetLimits(0.98e9, 1.0e10);
  
   
  Psum->Draw("APL");

  TLatex *   tex = new TLatex(1.823945e+11,0.8753448,"Nu");
  tex->SetLineWidth(2);
  tex->Draw();

  c2->Modified();
  c2->cd();
  
  //Now the histogram
  
  c2->cd(2);
  // h_Psum->GetXaxis()->SetRange(6,14);
  h_Psum->GetXaxis()->SetNdivisions(501);
  h_Psum->GetXaxis()->SetLabelFont(42);
  h_Psum->GetXaxis()->SetLabelOffset(0.007);
  h_Psum->GetXaxis()->SetLabelSize(0.05);
  h_Psum->GetXaxis()->SetTitleSize(0.06);
  h_Psum->GetXaxis()->SetTitleOffset(0.9);
  h_Psum->GetXaxis()->SetTitleFont(42);
  h_Psum->Draw("");


  h_Psum->Draw();
  
  /////

  c2->cd(3);
  
  gPad->SetLogx();
  aPsum->SetMaximum(1.1);
  aPsum->SetMinimum(0.0);
  aPsum->SetMarkerStyle(21);
  aPsum->SetMarkerSize(0.2);
  aPsum->SetMarkerColor(2);
  aPsum->GetXaxis()->SetTitle("E [eV]");
  aPsum->GetXaxis()->CenterTitle(true);
  aPsum->GetXaxis()->SetLabelFont(42);
  aPsum->GetXaxis()->SetLabelOffset(0.007);
  aPsum->GetXaxis()->SetLabelSize(0.05);
  aPsum->GetXaxis()->SetTitleSize(0.06);
  aPsum->GetXaxis()->SetTitleOffset(1.06);
  
  if ( std::string(model).compare("EarthB") == 0 ) 
    aPsum->GetXaxis()->SetLimits(0.98e9, 1.0e10);
  
  aPsum->Draw("APL");
  tex = new TLatex(1.56236e+11,0.8214771,"anti-Nu");
  tex->SetLineWidth(2);
  tex->Draw();
  
  //Now the histogram
  
  c2->cd(4);
  h_aPsum->Draw();
  
  /////

  c2->Modified();
  c2->cd();

  


  
  saveAs.str("");
  saveAs << path << model << "/png/" << "nueosc_sum_of_probs_" << model << "_" << option << ".png";
  c2->SaveAs( saveAs.str().c_str() );

}
Beispiel #8
0
TGraph* newShiftChi2Graph(const T* const dat1,
                          const Int_t    nd1,
                          const U* const dat2,
                          const Int_t    nd2,
                          const Int_t    minbin=-1,   // -1 => 0
                          const Int_t    maxbin=-1,   // -1 => nd1-1
                          const Bool_t   useSqrtErrs=kFALSE) {
   const Int_t minb = (minbin<0) ?     0 : minbin;
   const Int_t maxb = (maxbin<0) ? nd1-1 : maxbin;
   if ( (maxb<=minb) || (maxb>=nd1) || (maxb>=nd2) ) {
      Fatal("newShiftChi2Graph",
            "Invalid maxb=%d. (minb=%d, nd1=%d, nd2=%d)",
            maxb, minb, nd1, nd2);
   }
   const T* c1 = dat1;
   const U* c2 = dat2;
   Int_t pos, j(0);
   const Int_t ndh = (maxb-minb+1)/2;
   TGraphErrors* gc = new TGraphErrors;
   for (Int_t sh=1-ndh; sh<ndh; ++sh) {
      Double_t x=0, t=0, cmp=0;
      c1 = dat1+minb;
      c2 = dat2+minb-sh;

      for (Int_t i=minb; i<=maxb; ++i, ++c1, ++c2) {
         pos = c2 - dat2;
#ifdef SHIFT_INTO_WINDOW
         if (pos<nd2) {
            if (pos>=0) {
#else
         if (pos<=maxb) {
            if (pos>=minb) {
#endif
               t  = (*c1) - (*c2);
               t *= t;
               if (useSqrtErrs) {
                  t /= TMath::Abs(static_cast<Double_t>(*c2));
               }
               x += t;
               cmp += 1.0;
            }
         } else {
            break;
         }
      }
      if (cmp>1.0) {
         x /= cmp-1.0;

         gc->SetPoint(j, static_cast<Double_t>(sh), x);
         
         ++j;
      }
   }

   return gc;
}



void noAveBounceStdy(const Char_t* rtfn,
                     const Char_t* wvfn,
                     const Char_t* FPNfn,
                     const Char_t* outfn,
                     const Int_t   fitType=0,
                     const Int_t   fitOpt=0,
                     const Char_t* minner="Minuit2",
                     const Char_t* algo="Migrad",
                     const Int_t   shiftminb=-1,
                     const Int_t   shiftmaxb=-1,
                     const Bool_t  applyFilter=kTRUE) {
   // fitType:
   //   0 = fit theta phi with getShiftLL
   //   5 = fit theta phi with getShiftChi2
   //  20 = fit 3 deltaT's; use contraints for other 3
   //
   // fitOpt:
   //   0 = fit (filtered) waveforms
   //  10 = fit envelope of (filtered) waveforms
   //
   //     minner              algo
   //  Minuit /Minuit2        Migrad,Simplex,Combined,Scan  (default is Migrad)
   //  Minuit2                Fumili2
   //  Fumili
   //  GSLMultiMin            ConjugateFR, ConjugatePR, BFGS, 
   //                         BFGS2, SteepestDescent
   //  GSLMultiFit
   //  GSLSimAn
   //  Genetic

   if (mini==0) {
      mini = ROOT::Math::Factory::CreateMinimizer(minner, algo);
      mini->SetMaxFunctionCalls(1000000);
      mini->SetMaxIterations(10000);
      mini->SetTolerance(0.001);
      mini->SetPrintLevel(0);
   }

   nt = new TChain("runtree");
   nt->Add(rtfn);

   const Long64_t nents = nt->GetEntries();
   if (nents==0) {
      Error("noAveBunceStdy","No events in tree from [%s].",rtfn);
      return;
   }

   ns = new TChain("nShifts");
   ns->Add(wvfn);

   if (nents>ns->GetEntries()) {
      Error("bounceStudy","%lld entries in runtree but "
            "%lld entries in shift tree",nents,ns->GetEntries());
      return;
   }
   
   fpnf = TFile::Open(FPNfn);
   if ( (fpnf==0) || (fpnf->IsZombie()) ) {
      Error("bounceStudy","Could not open FPN file [%s]",FPNfn);
      return;
   }
   for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      gPed[ch]   = dynamic_cast<TGraphErrors*>(
         fpnf->Get(Form("gExlPed_ch%d",ch)));
      gNoise[ch] = dynamic_cast<TGraphErrors*>(
         fpnf->Get(Form("gExlRms_ch%d",ch)));
      if ( (gPed[ch]==0) || (gNoise[ch]==0) ) {
         Error("bounceStudy",
               "Couldn't get FPN/noise graphs from [%s]",FPNfn);
         return;
      }
   }

   // read from tree into...
   Float_t  pedsubs[NSnConstants::kNchans][NSnConstants::kNsamps];
   Float_t  psshift[NSnConstants::kNchans][NSnConstants::kNsamps];
   Float_t  filtered[NSnConstants::kNchans][NSnConstants::kNsamps];
   Float_t  envelope[NSnConstants::kNchans][NSnConstants::kNsamps];
   UShort_t samples[NSnConstants::kNchans][NSnConstants::kNsamps];
   UInt_t   evnum, utime, utimeus, mbchksum;
   
   nt->SetBranchAddress("mbChecksum",&mbchksum);
   nt->SetBranchAddress("EvtNum",&evnum);
   nt->SetBranchAddress("unixTime",&utime);
   nt->SetBranchAddress("unixTimeUS",&utimeus);
   for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      nt->SetBranchAddress(Form("data%02d",ch), &(samples[ch][0]));
   }

   // shift for stop tree
   Int_t nsent;
   UInt_t nsevn;
   Int_t aveShift(0), aveLen(0);
   Int_t shift[NSnConstants::kNchans];
   Int_t len[NSnConstants::kNchans];
   ns->SetBranchAddress("Ent",&nsent);
   ns->SetBranchAddress("EvtNum",&nsevn);
   for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      ns->SetBranchAddress(Form("shift%02d",ch),&(shift[ch]));
      ns->SetBranchAddress(Form("len%02d",ch),&(len[ch]));
   }
   ns->BuildIndex("EvtNum");

   // output
   TString hn;
   outf = TFile::Open(outfn,"recreate");

   if (fitType==20) {
      hn = "EvtNum:";
      for (Int_t i=1; i<NSnConstants::kNchans; ++i) {
         hn += Form("dt%d%d:",i,i-1);
      }
      hn += "chi2";
      tChanDTsFit = new TNtuple("tChanDTsFit",
                                "fit of channel dts",
                                hn.Data());
   } else {
      tThetaPhiFit = new TNtuple("tThetaPhiFit","theta phi fit tree",
                                 "EvtNum:theta:phi:chi2");
   }


   for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      for (Int_t xc=0; xc<ch; ++xc) {
         hn = Form("hFiltCorrCoefShiftVsEvt_ch%02d_ch%02d",ch,xc);
         hFiltCorrCoefShiftVsEvt[ch][xc] = new TH2F(hn.Data(),
              Form("corr coef for offset between ch%d and ch%d of filtered "
                   "wvfms vs event;event;offset (ch%d-ch%d);correlation coef",
                   ch,xc,ch,xc),
                                          nents, -0.5, nents-0.5,
                                          NSnConstants::kNsamps,
                                          1-(NSnConstants::kNsamps/2)-0.5,
                                          (NSnConstants::kNsamps/2)+0.5);
         hFiltCorrCoefShiftVsEvt[ch][xc]->SetDirectory(outf);

         hn = Form("hFiltShiftChi2VsEvt_ch%02d_ch%02d",ch,xc);
         hFiltShiftChi2VsEvt[ch][xc] = new TH2F(hn.Data(),
              Form("#chi^{2} of offset between ch%d and ch%d of filtered "
                   "wvfms vs event;event;offset (ch%d-ch%d);#chi^{2}",
                   ch,xc,ch,xc),
                                          nents, -0.5, nents-0.5,
                                          NSnConstants::kNsamps,
                                          1-(NSnConstants::kNsamps/2)-0.5,
                                          (NSnConstants::kNsamps/2)+0.5);
         hFiltShiftChi2VsEvt[ch][xc]->SetDirectory(outf);
      }
   }

   Long64_t ne(0);
   for (Long64_t ev=0; ev<nents; ++ev) {
   //for (Long64_t ev=0; ev<250; ++ev) {
      if ( (ev%500)==0 ) {
         fprintf(stderr,"Processing %lld / %lld  (%02.2f%%)            \r",
            ev, nents,
            100.*static_cast<Float_t>(ev)/static_cast<Float_t>(nents));
      }
      nt->GetEntry(ev);
      ne = ns->GetEntryNumberWithIndex(evnum);
      if (ne>-1) {
         ns->GetEntry(ne);

         // find the stop shift
         aveShift = aveLen = 0;
         for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
            aveShift += shift[ch];
            aveLen   += len[ch];
         }
         aveShift = TMath::Nint( static_cast<Float_t>(aveShift)/
                                 static_cast<Float_t>(NSnConstants::kNchans) );
         aveLen   = TMath::Nint( static_cast<Float_t>(aveLen)/
                                 static_cast<Float_t>(NSnConstants::kNchans) );
         const Int_t shiftStart = NSnConstants::kNsamps-1 - aveShift - aveLen;
         for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
            // subtract FPN
            const Double_t* pd = gPed[ch]->GetY();
            const UShort_t* sp = &(samples[ch][0]);
            Float_t*        ps = &(pedsubs[ch][0]);
            Float_t*        ph = &(psshift[ch][ shiftStart ]);
            for (Int_t sm=0; sm<NSnConstants::kNsamps;
                                  ++sm, ++pd, ++sp, ++ps, ++ph) {
               *ps = *sp - *pd;
               while ( (ph-&(psshift[ch][0])) >= NSnConstants::kNsamps) {
                  ph -= NSnConstants::kNsamps;
               }
               *ph = *ps;
            }
            
            // apply filter
            memcpy(&(filtered[ch][0]), &(psshift[ch][0]),
                   NSnConstants::kNsamps*sizeof(Float_t));
            if (applyFilter) {
               filterWaveform(&(filtered[ch][0]), NSnConstants::kNsamps);
            }
            // find envelope
            memcpy(&(envelope[ch][0]), &(filtered[ch][0]),
                   NSnConstants::kNsamps*sizeof(Float_t));
            TSnSpectral::EnvelopeReal(&(envelope[ch][0]), NSnConstants::kNsamps);

#ifdef DEBUG_SHIFTS
            TCanvas* cdbgsh = new TCanvas;
            cdbgsh->cd();
            Float_t xsm[NSnConstants::kNsamps], rsmp[NSnConstants::kNsamps];
            for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
               xsm[i] = i;
               rsmp[i] = samples[ch][i];
            }
            TGraph* gsmp = new TGraph(NSnConstants::kNsamps, xsm, rsmp);
            TGraph* gps  = new TGraph(NSnConstants::kNsamps, xsm, 
                                      &(pedsubs[ch][0]));
            TGraph* gph  = new TGraph(NSnConstants::kNsamps, xsm,
                                      &(psshift[ch][0]));
            TGraph* gfl  = new TGraph(NSnConstants::kNsamps, xsm,
                                      &(filtered[ch][0]));
            TGraph* gen  = new TGraph(NSnConstants::kNsamps, xsm,
                                      &(envelope[ch][0]));
            gsmp->SetMarkerStyle(7);
            gsmp->SetMarkerColor(kBlack);
            gsmp->SetLineColor(kBlack);
            gps->SetMarkerStyle(7);
            gps->SetMarkerColor(kRed);
            gps->SetLineColor(kRed);
            gph->SetMarkerStyle(7);
            gph->SetMarkerColor(kAzure-7);
            gph->SetLineColor(kAzure-7);
            gfl->SetMarkerStyle(7);
            gfl->SetMarkerColor(kGreen+2);
            gfl->SetLineColor(kGreen+2);
            gen->SetMarkerStyle(7);
            gen->SetMarkerColor(kViolet-1);
            gen->SetLineColor(kViolet-1);
            gsmp->SetMinimum(-1500);
            gsmp->SetMaximum(2500);
            Printf("ch%d: shift=%d, len=%d",
                   ch, shift[ch], len[ch]);
            gsmp->Draw("apc");
            gps->Draw("pc");
            gph->Draw("pc");
            gfl->Draw("pc");
            gen->Draw("pc");
            cdbgsh->WaitPrimitive();
            delete gsmp; delete gps; delete gph; delete gfl; delete gen;
            delete cdbgsh;
#endif
         }
         
         if (shiftmaxb!=shiftminb) {
            maxdt = (shiftmaxb - shiftminb) / (2.0*kSmpRate);
         } else {
            maxdt =  NSnConstants::kNsamps  / (2.0*kSmpRate);
         }
         
         const Float_t* chdat(0), * xcdat(0);
         for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
            if (fitOpt==0) {
               chdat = &(filtered[ch][0]);
            } else if (fitOpt==10) {
               chdat = &(envelope[ch][0]);
            } else {
               Fatal("noAveBounceStdy","Unknown fitOpt [%d]",fitOpt);
            }
            for (Int_t xc=0; xc<ch; ++xc) {
               if (fitOpt==0) {
                  xcdat = &(filtered[xc][0]);
               } else if (fitOpt==10) {
                  xcdat = &(envelope[xc][0]);
               } else {
                  Fatal("noAveBounceStdy","Unknown fitOpt [%d]",fitOpt);
               }
               gcor[ch][xc] = newCorrCoefGraph(chdat,
                                               xcdat,
                                               NSnConstants::kNsamps,
                                               shiftminb,
                                               shiftmaxb);
               gspl[ch][xc] = new TSpline3(Form("spl_%d_%d",ch,xc),
                                           gcor[ch][xc]);
               gchi[ch][xc] = newShiftChi2Graph(chdat,
                                                NSnConstants::kNsamps,
                                                xcdat,
                                                NSnConstants::kNsamps,
                                                shiftminb,
                                                shiftmaxb);
               gspc[ch][xc] = new TSpline3(Form("spc_%d_%d",ch,xc),
                                           gchi[ch][xc]);

#ifdef DEBUG_CORRELS
            TCanvas* cdbgcl = new TCanvas("cdbgcl","cdbgcl",800,1000);
            cdbgcl->Divide(1,3);
            cdbgcl->cd(1);
            Float_t xxsm[NSnConstants::kNsamps];
            for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
               xxsm[i] = i;
            }
            TGraph* gcfl  = new TGraph(NSnConstants::kNsamps, xxsm,
                                       &(filtered[ch][0]));
            TGraph* gxfl  = new TGraph(NSnConstants::kNsamps, xxsm,
                                       &(filtered[xc][0]));
            TGraph* gcen  = new TGraph(NSnConstants::kNsamps, xxsm,
                                       &(envelope[ch][0]));
            TGraph* gxen  = new TGraph(NSnConstants::kNsamps, xxsm,
                                       &(envelope[xc][0]));
            gcfl->SetMarkerStyle(7);
            gcfl->SetMarkerColor(kBlack);
            gcfl->SetLineColor(kBlack);
            gxfl->SetMarkerStyle(7);
            gxfl->SetMarkerColor(kRed);
            gxfl->SetLineColor(kRed);
            gcen->SetMarkerStyle(7);
            gcen->SetMarkerColor(kGray);
            gcen->SetLineColor(kGray);
            gxen->SetMarkerStyle(7);
            gxen->SetMarkerColor(kViolet-1);
            gxen->SetLineColor(kViolet-1);
            gcfl->Draw("apc");
            gxfl->Draw("pc");
            gcen->Draw("pc");
            gxen->Draw("pc");
            cdbgcl->cd(2);
            gspl[ch][xc]->SetMarkerStyle(7);
            gspl[ch][xc]->SetMarkerColor(kAzure-7);
            gspl[ch][xc]->SetLineColor(kAzure-7);
            gspl[ch][xc]->Draw("pc");
            cdbgcl->cd(3);
            gspc[ch][xc]->SetMarkerStyle(7);
            gspc[ch][xc]->SetMarkerColor(kViolet-6);
            gspc[ch][xc]->SetLineColor(kViolet-6);
            gspc[ch][xc]->Draw("pc");
            cdbgcl->cd();
            cdbgcl->Update();
            cdbgcl->WaitPrimitive();
            delete gcfl; delete gxfl; delete cdbgcl;
            delete gcen; delete gxen;
#endif

               const Int_t gn = gcor[ch][xc]->GetN();
               const Double_t* gx = gcor[ch][xc]->GetX(),
                             * gy = gcor[ch][xc]->GetY(),
                             * cx = gchi[ch][xc]->GetX(),
                             * cy = gchi[ch][xc]->GetY();
               for (Int_t k=0; k<gn; ++k, ++gx, ++gy, ++cx, ++cy) {
                  hFiltCorrCoefShiftVsEvt[ch][xc]->Fill(ev, *gx, *gy);
                  hFiltShiftChi2VsEvt[ch][xc]->Fill(ev, *cx, *cy);
               }

            }
         }
         
         if (fitType==20) {
            // fit for the best, consistent time offsets
            mini->Clear();
            ROOT::Math::Functor f(&getDeltaTsLL, NSnConstants::kNchans-1);
            mini->SetFunction(f);
            for (Int_t ch=1; ch<NSnConstants::kNchans; ++ch) {
               if (strcmp(minner,"Genetic")==0) {
                  mini->SetLimitedVariable(ch-1, 
                                           Form("dt%d%d",ch,ch-1), 0, 0.01,
                                           -maxdt, maxdt);
               } else {
                  mini->SetVariable(ch-1, Form("dt%d%d",ch,ch-1), 0, 0.01);
               }
            }
            mini->Minimize();
            const Double_t* result = mini->X();
            const Double_t* rs = result;
            Float_t* tofil = new Float_t[NSnConstants::kNchans+2];
            Float_t* tf = tofil;
            *tf++ = ev;
            for (Int_t ch=1; ch<NSnConstants::kNchans; ++ch, ++tf, ++rs) {
               *tf = *rs;
            }
            *tf = mini->MinValue();
            tChanDTsFit->Fill(tofil);
            delete[] tofil;
#ifdef DEBUG_DTS
            for (Int_t ch=1; ch<NSnConstants::kNchans; ++ch) {
               Printf("result[%d]=%g",ch-1,result[ch-1]);
            }
            TCanvas* cdbgdt = new TCanvas("cdbgdt","cdbgdt",1000,1000);
            cdbgdt->Divide(2,3);
            Float_t xxsm[NSnConstants::kNsamps];
            for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
               xxsm[i] = i;
            }

            TGraph* gorg[NSnConstants::kNchans];
            TGraph* gocp[NSnConstants::kNchans];
            TGraph* goen[NSnConstants::kNchans];
            TGraph* gshf[NSnConstants::kNchans][NSnConstants::kNchans];
            TGraph* gshe[NSnConstants::kNchans][NSnConstants::kNchans];
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               gorg[ch] = new TGraph(NSnConstants::kNsamps, xxsm,
                                     &(filtered[ch][0]));
               gocp[ch] = new TGraph(NSnConstants::kNsamps, xxsm,
                                     &(filtered[ch][0]));
               goen[ch] = new TGraph(NSnConstants::kNsamps, xxsm,
                                     &(envelope[ch][0]));
               for (Int_t xc=0; xc<ch; ++xc) {
                  Double_t dt=0;
                  for (Int_t i=(ch-xc); i>0; --i) {
                     dt += result[ch-i];
                  }
                  dt *= kSmpRate; // convert to samples
                  Printf("dt[%d][%d]=%g",ch,xc,dt);
                  gshf[ch][xc] = new TGraph(NSnConstants::kNsamps);
                  gshe[ch][xc] = new TGraph(NSnConstants::kNsamps);
                  for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
                     gshf[ch][xc]->SetPoint(i, xxsm[i]+dt, filtered[xc][i]);
                     gshe[ch][xc]->SetPoint(i, xxsm[i]+dt, envelope[xc][i]);
                  }
                  gshf[ch][xc]->SetMarkerStyle(7);
                  gshf[ch][xc]->SetLineColor(kRed);
                  gshf[ch][xc]->SetMarkerColor(kRed);
                  gshe[ch][xc]->SetMarkerStyle(7);
                  gshe[ch][xc]->SetLineColor(kViolet-1);
                  gshe[ch][xc]->SetMarkerColor(kViolet-1);
               }
               gorg[ch]->SetMarkerStyle(7);
               gorg[ch]->SetLineColor(kBlack);
               gorg[ch]->SetMarkerColor(kBlack);
               goen[ch]->SetMarkerStyle(7);
               goen[ch]->SetLineColor(kGray);
               goen[ch]->SetMarkerColor(kGray);
               gocp[ch]->SetMarkerStyle(7);
               gocp[ch]->SetLineStyle(7);
               gocp[ch]->SetLineColor(kGreen+2);
               gocp[ch]->SetMarkerColor(kGreen+2);
            }
            gStyle->SetOptStat(0);
            Int_t pp=0;
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               for (Int_t xc=0; xc<ch; ++xc) {
                  cdbgdt->cd(++pp);
                  hn = Form("hd_%d_%d",ch,xc);
                  TH2F* hd = new TH2F(hn.Data(),
                                      Form("black=ch%d, red/green=ch%d;"
                                           "sample;ADC",ch,xc),
                                      NSnConstants::kNsamps, -0.5,
                                      NSnConstants::kNsamps-0.5,
                                      200, -900, 900);
                  hd->SetBit(TH1::kCanDelete);
                  hd->Draw();
                  gorg[ch]->Draw("pc");
                  goen[ch]->Draw("pc");
                  gocp[xc]->Draw("pc");
                  gshf[ch][xc]->Draw("pc");
                  gshe[ch][xc]->Draw("pc");
               }
            }
            cdbgdt->cd();
            cdbgdt->Update();
            cdbgdt->WaitPrimitive();
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               delete gorg[ch]; delete gocp[ch]; delete goen[ch];
               for (Int_t xc=0; xc<ch; ++xc) {
                  delete gshf[ch][xc];
                  delete gshe[ch][xc];
               }
            }
            delete cdbgdt;
#endif
         } else {

            Int_t npars(2);
            Double_t (*fitFunction)(const Double_t*) = 0;
            if (fitType==0) {
               fitFunction = &getShiftLL;
            } else if (fitType==5) {
               fitFunction = &getShiftChi2;
            } else {
               Fatal("bounceStudy","Unknown fit type %d",fitType);
            }
            
            mini->Clear();
            ROOT::Math::Functor f(fitFunction, npars);
            mini->SetFunction(f);
            
            if (strcmp(minner,"Genetic")==0) {
               mini->SetLimitedVariable(0, "theta",     3, 0.01,
                                        0, TMath::Pi());
               mini->SetLimitedVariable(1, "phi"  ,   5.5, 0.01,
                                        0, TMath::TwoPi());
            } else {
               //mini->SetVariable(0, "theta",             TMath::Pi(), 0.01);
               //mini->SetVariable(1, "phi"  ,   (gRandom->Rndm()-0.5), 0.01);
               mini->SetVariable(0, "theta",     3, 0.01);
               mini->SetVariable(1, "phi"  ,   5.5, 0.01);
               //mini->SetVariable(0, "theta",     3, 0.05);
               //mini->SetVariable(1, "phi"  ,   5.5, 0.05);
            }
            mini->Minimize();
            const Double_t* result = mini->X();
            tThetaPhiFit->Fill(ev, result[0], result[1], mini->MinValue());


#ifdef DEBUG_THETAPHI
            // regularize the angles
            Double_t theta = TVector2::Phi_mpi_pi(result[0]);
            Double_t phi   = result[1];
            if (theta<0) {
               theta *= -1.0;
               phi   += TMath::Pi();
            }
            phi   = TVector2::Phi_0_2pi(phi);
            Printf("theta=%g, phi=%g (%g, %g)",
                   theta*TMath::RadToDeg(),
                   phi*TMath::RadToDeg(),
               result[0], result[1]);
            TCanvas* cdbgtp = new TCanvas("cdbgtp","cdbgtp",1000,1000);
            cdbgtp->Divide(2,3);
            Float_t xxsm[NSnConstants::kNsamps];
            for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
               xxsm[i] = i;
            }
            
            TGraph* gorg[NSnConstants::kNchans];
            TGraph* gocp[NSnConstants::kNchans];
            TGraph* gshf[NSnConstants::kNchans][NSnConstants::kNchans];
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               gorg[ch] = new TGraph(NSnConstants::kNsamps, xxsm,
                                     &(filtered[ch][0]));
               gocp[ch] = new TGraph(NSnConstants::kNsamps, xxsm,
                                     &(filtered[ch][0]));
               for (Int_t xc=0; xc<ch; ++xc) {
                  Double_t dtcor=0;
                  for (Int_t i=(ch-xc); i>0; --i) {
                     dtcor += dtCorrs[ch-i];
                  }
                  const TVector3& posCh = getStnPos(ch);
                  const TVector3& posXc = getStnPos(xc);
                  TVector3 norm;
                  norm.SetMagThetaPhi(1.0, result[0], result[1]);
                  //norm.SetMagThetaPhi(1.0, 2.95833, 5.497787);
                  const Double_t  disCh = -(posCh.Dot(norm));
                  const Double_t  disXc = -(posXc.Dot(norm));
                  // !!! check sign of delta(distance) and dtcor!
                  const Double_t  dt = kSmpRate * (
                     ( (disCh-disXc) * kNgTopFern / kC_m_ns )   // from m to ns
                     + dtcor );
                  Printf("dt[%d,%d]=%g (dis[%d]=%g, dis[%d]=%g)",
                         ch,xc,dt, ch,disCh,xc,disXc);
                  gshf[ch][xc] = new TGraph(NSnConstants::kNsamps);
                  for (Int_t i=0; i<NSnConstants::kNsamps; ++i) {
                     gshf[ch][xc]->SetPoint(i, xxsm[i]+dt, filtered[xc][i]);
                  }
                  gshf[ch][xc]->SetMarkerStyle(7);
                  gshf[ch][xc]->SetLineColor(kRed);
                  gshf[ch][xc]->SetMarkerColor(kRed);
               }
               gorg[ch]->SetMarkerStyle(7);
               gorg[ch]->SetLineColor(kBlack);
               gorg[ch]->SetMarkerColor(kBlack);
               gocp[ch]->SetMarkerStyle(7);
               gocp[ch]->SetLineStyle(7);
               gocp[ch]->SetLineColor(kGreen+2);
               gocp[ch]->SetMarkerColor(kGreen+2);
            }
            gStyle->SetOptStat(0);
            Int_t pp=0;
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               for (Int_t xc=0; xc<ch; ++xc) {
                  cdbgtp->cd(++pp);
                  hn = Form("hd_%d_%d",ch,xc);
                  TH2F* hd = new TH2F(hn.Data(),
                                      Form("black=ch%d, red/green=ch%d;"
                                           "sample;ADC",ch,xc),
                                      NSnConstants::kNsamps, -0.5,
                                      NSnConstants::kNsamps-0.5,
                                      200, -900, 900);
                  hd->SetBit(TH1::kCanDelete);
                  hd->Draw();
                  gorg[ch]->Draw("pc");
                  gocp[xc]->Draw("pc");
                  gshf[ch][xc]->Draw("pc");
               }
            }
            cdbgtp->cd();
            cdbgtp->Update();
            cdbgtp->WaitPrimitive();
            for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
               delete gorg[ch]; delete gocp[ch];
               for (Int_t xc=0; xc<ch; ++xc) {
                  delete gshf[ch][xc];
               }
            }
            delete cdbgtp;
#endif

         }

         for (Int_t ch=0; ch<NSnConstants::kNchans; ++ch) {
            for (Int_t xc=0; xc<ch; ++xc) {
               delete gspl[ch][xc];
               delete gcor[ch][xc];
               delete gchi[ch][xc];
               delete gspc[ch][xc];
            }
         }

      }
   } // event loop

   outf->Write();

}
TCanvas* plotLinearityMAT_ERUpgrade(double eta, double etmin /* GeV */, double etmax /* GeV */, int ptype, 
				 string year, string esmodel,
				 bool debug=false, bool logx=false, bool subtractAverage=false,
				 TGraph* overlay=0 ) {

  double GeV = 1000;

   gROOT->ProcessLine(".L EnergyRescalerUpgrade.cxx");
  
   egRescaler::EnergyRescalerUpgrade ers;

   ers.Init("../share/EnergyRescalerData.root",year,esmodel);

   ers.SetDebugFlag( debug );

   ers.includePresamplerContribution( false );
   ers.includeLeakageContribution( false );

   double eMin = etmin * cosh(eta) * GeV;
   double eMax = etmax * cosh(eta) * GeV;

   int nStep = 100;
   double eStep;
   if( logx )
     eStep = (log(eMax)-log(eMin))/(double)nStep;
   else
     eStep = (eMax-eMin)/(double)nStep;
   double e = eMin;

   TGraphErrors* gZee = new TGraphErrors();  // Z scale
   TGraph* gNom = new TGraph();        // nominal scale correction
   TGraph* gZeeAllUp = new TGraph();   // Zee scale uncertainty, Up
   TGraph* gZeeAllDown = new TGraph(); //                      , Down
   TGraph* gZeeUp = new TGraph();      // Zee scale uncertainty, Up
   TGraph* gZeeDown = new TGraph();    //                      , Down
   TGraph* gZeeGenUp = new TGraph();   // Zee scale uncertainty, Up
   TGraph* gZeeGenDown = new TGraph(); //                      , Down
   TGraph* gMATUp = new TGraph();      //       MAT uncertainty, Up
   TGraph* gMATDown = new TGraph();    //                      , Down
   TGraph* gPSUp = new TGraph();       //        ps uncertainty, Up
   TGraph* gPSDown = new TGraph();     //                      , Down
   TGraph* gLowUp = new TGraph();      //    low-pt uncertainty, Up
   TGraph* gLowDown = new TGraph();    //                      , Down

   int i=0;

   while( e<=eMax ) {

     double alpha          = ers.getAlphaZee(eta, egRescaler::EnergyRescalerUpgrade::Nominal);
     double alphaUp        = ers.getAlphaZee(eta, egRescaler::EnergyRescalerUpgrade::ZeeStatUp);

     double eNominal       = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::Nominal);

     double eVarZeeAllUp   = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeAllUp);
     double eVarZeeAllDown = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeAllDown);

     double eVarZeeUp      = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeMethodUp);
     double eVarZeeDown    = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeMethodDown);

     double eVarGenUp      = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeGenUp);
     double eVarGenDown    = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::ZeeGenDown);

     double eVarMATUp      = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::R12StatUp);
     double eVarMATDown    = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::R12StatDown);

     double eVarPSUp       = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::PSStatUp);
     double eVarPSDown     = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::PSStatDown);

     double eVarLowUp      = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::LowPtUp);
     double eVarLowDown    = ers.applyEnergyCorrection(eta, e, ptype, egRescaler::EnergyRescalerUpgrade::LowPtDown);

     if(i==0) {
       gZee->SetPointError(i,0,alphaUp-alpha);
       if( !subtractAverage )
	 gZee->SetPoint(i,40.*cosh(eta),alpha);
       else
	 gZee->SetPoint(i,40.*cosh(eta),0);
     }
     
     if( !subtractAverage ) {
       
       gNom->SetPoint(i, e/GeV, (e-eNominal)/eNominal); 
       
       gZeeAllUp->SetPoint(i, e/GeV, (e-eVarZeeAllUp)/eVarZeeAllUp); 
       gZeeAllDown->SetPoint(i, e/GeV, (e-eVarZeeAllDown)/eVarZeeAllDown); 
       
       gZeeUp->SetPoint(i, e/GeV, (e-eVarZeeUp)/eVarZeeUp); 
       gZeeDown->SetPoint(i, e/GeV, (e-eVarZeeDown)/eVarZeeDown); 
       
       gZeeGenUp->SetPoint(i, e/GeV, (e-eVarGenUp)/eVarGenUp); 
       gZeeGenDown->SetPoint(i, e/GeV, (e-eVarGenDown)/eVarGenDown); 
       
       gMATUp->SetPoint(i, e/GeV, (e-eVarMATUp)/eVarMATUp); 
       gMATDown->SetPoint(i, e/GeV, (e-eVarMATDown)/eVarMATDown); 
       
       gPSUp->SetPoint(i, e/GeV, (e-eVarPSUp)/eVarPSUp); 
       gPSDown->SetPoint(i, e/GeV, (e-eVarPSDown)/eVarPSDown); 
       
       gLowUp->SetPoint(i, e/GeV, (e-eVarLowUp)/eVarLowUp); 
       gLowDown->SetPoint(i, e/GeV, (e-eVarLowDown)/eVarLowDown); 
       
     } else {
       
       gNom->SetPoint(i, e/GeV, (e-eNominal)/eNominal - alpha); 
     
       gZeeAllUp->SetPoint(i, e/GeV, (e-eVarZeeAllUp)/eVarZeeAllUp - alpha); 
       gZeeAllDown->SetPoint(i, e/GeV, (e-eVarZeeAllDown)/eVarZeeAllDown - alpha); 
       
       gZeeUp->SetPoint(i, e/GeV, (e-eVarZeeUp)/eVarZeeUp - alpha); 
       gZeeDown->SetPoint(i, e/GeV, (e-eVarZeeDown)/eVarZeeDown - alpha); 
       
       gZeeGenUp->SetPoint(i, e/GeV, (e-eVarGenUp)/eVarGenUp - alpha); 
       gZeeGenDown->SetPoint(i, e/GeV, (e-eVarGenDown)/eVarGenDown - alpha); 
       
       gMATUp->SetPoint(i, e/GeV, (e-eVarMATUp)/eVarMATUp - alpha); 
       gMATDown->SetPoint(i, e/GeV, (e-eVarMATDown)/eVarMATDown - alpha); 
       
       gPSUp->SetPoint(i, e/GeV, (e-eVarPSUp)/eVarPSUp - alpha); 
       gPSDown->SetPoint(i, e/GeV, (e-eVarPSDown)/eVarPSDown - alpha); 
       
       gLowUp->SetPoint(i, e/GeV, (e-eVarLowUp)/eVarLowUp - alpha); 
       gLowDown->SetPoint(i, e/GeV, (e-eVarLowDown)/eVarLowDown - alpha); 
       
     }

     i++;

     if( logx )
       e *= exp(eStep);
     else
       e += eStep;

   }
 
   TCanvas* canvas = new TCanvas();
   if( logx )
     canvas->SetLogx();

   if( !subtractAverage ) {
     gMATUp->SetMaximum(alpha+.005);
     gMATUp->SetMinimum(alpha+-.007);
   } else {
     gMATUp->SetMaximum(.005);
     gMATUp->SetMinimum(-.007);
   }

   char grafname[99];
   if( ptype==0 )
     sprintf(grafname,"ES  Linearity (%s), #eta = %4.2f, Electrons", year.c_str(), eta);
   else if( ptype==1 )
     sprintf(grafname,"ES  Linearity (%s), #eta = %4.2f, Unconverted photons", year.c_str(), eta);
   else if( ptype==2 )
     sprintf(grafname,"ES  Linearity (%s), #eta = %4.2f, Converted photons", year.c_str(), eta);
   gMATUp->SetTitle(grafname);
   
   gMATUp->GetXaxis()->SetTitleOffset(1.2*gNom->GetXaxis()->GetTitleOffset());
   gMATUp->GetYaxis()->SetTitleOffset(1.2*gNom->GetYaxis()->GetTitleOffset());
   gMATUp->GetXaxis()->SetTitle("E [GeV]");
   gMATUp->GetYaxis()->SetTitle("#alpha(E)");
   gMATUp->SetLineWidth(2);
   gMATUp->SetLineStyle(2);
   gMATUp->SetLineColor(4);
   gMATUp->Draw("AL");

   gMATDown->SetLineWidth(2);
   gMATDown->SetLineStyle(3);
   gMATDown->SetLineColor(4);
   gMATDown->Draw("L");

   gNom->SetLineWidth(2);
   gNom->SetLineColor(4);
   gNom->Draw("L");

   gZee->SetMarkerStyle(20);
   gZee->Draw("P");

   TLegend* leg1 = new TLegend(.7,.15,.89,.3);
   leg1->SetBorderSize(0);
   leg1->SetFillColor(0);
   leg1->AddEntry(gZee,"#alpha, Z peak", "p");
   leg1->AddEntry(gNom,"PS, central", "l");
   leg1->AddEntry(gMATUp,"PS, up", "l");
   leg1->AddEntry(gMATDown,"PS, down", "l");

   leg1->Draw("same");

   // char plotname[99];
   // sprintf(plotname,"linearity_%d_%2.1f.png",ptype,eta);
   //   canvas->Print("overlay.ps");
  
   return canvas;
}
Beispiel #10
0
//------------------------------------------------------------------------
void DrawWalk()
{
  Int_t npeaks = 20;
  Int_t sigma=3.;
  Bool_t down = false;

  Int_t index[20];
  Char_t buf1[10], buf2[10];
  
  TCanvas *c1 = new TCanvas("c1", "c1",0,48,1280,951);
  gStyle->SetOptStat(0);
  c1->Divide(4,3);
  
  for (Int_t i=0; i<12; i++)
    {
      c1->cd(i+1);
      sprintf(buf1,"T0_C_%i_CFD",i+1);
      sprintf(buf2,"CFDvsQTC%i",i+1);
      cout<<buf1<<" "<<buf2<<endl;
      TH2F *qtc_cfd = (TH2F*) gFile->Get(buf2);
      TH1F *cfd = (TH1F*) gFile->Get(buf1);
      //       cfd->Draw();
      TSpectrum *s = new TSpectrum(2*npeaks,1);
      Int_t nfound = s->Search(cfd,sigma," ",0.05);
      cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;;
      if(nfound!=0){
	Float_t *xpeak = s->GetPositionX();
  	TMath::Sort(nfound, xpeak, index,down);
  	Float_t xp = xpeak[index[0]];
	Int_t xbin = cfd->GetXaxis()->FindBin(xp);
	Float_t yp = cfd->GetBinContent(xbin);
	cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[1]<<"\typeak = "<<yp<<endl;
	Float_t hmax = xp+10*sigma;
	Float_t hmin = xp-10*sigma;
	cout<<hmin<< " "<<hmax<<endl;
	//	    cfd->GetXaxis()->SetRange(hmin,hmax);
	//	    TF1 *g1 = new TF1("g1", "gaus", hmin, hmax);
	// cfd->Fit("g1","R");
	Int_t hminbin=  qtc_cfd->GetXaxis()->GetFirst();
	Int_t hmaxbin=  qtc_cfd->GetXaxis()->GetLast();
	Int_t nbins= qtc_cfd->GetXaxis()->GetNbins();
	cout<<"  qtc_cfd "<<hminbin<<" "<<hmaxbin<<" "<<nbins<<endl;
	//  qtc_cfd->Draw();
	TProfile *pr_y = qtc_cfd->ProfileX();
	Float_t maxHr=pr_y->GetBinCenter(hmaxbin);
	
	pr_y->SetMaximum(hmax);
	pr_y->SetMinimum(hmin);
	Int_t np=nbins/20;
	Double_t *xx = new Double_t[np];
	Double_t *yy = new Double_t[np];
	Int_t ng=0;
	Double_t yg=0;
	for (Int_t ip=1; ip<nbins; ip++)
	  {
	    if(ip%20 != 0 ) {
	      if (pr_y->GetBinContent(ip) !=0)
		yg +=pr_y->GetBinContent(ip);
	      //	cout<<ng<<" "<<pr_y->GetBinContent(ip)<<" "<<yg<<endl;
	      ng++;}
	    else {
	      xx[ip/20] = Float_t (pr_y->GetBinCenter(ip));
	      yy[ip/20] = yg/ng;
	      yg=0;
	      ng=0;
	     	      cout<<ip<<" "<<ip/20<<" "<< xx[ip/20]<<" "<< yy[ip/20]<<endl;
	    }
	  }
	TH2F *hr = new TH2F("hr"," ",np,0,maxHr, np, hmin, hmax);
	hr->Draw();
	TGraph *gr = new TGraph(np,xx,yy);
	gr->SetMinimum(hmin);
	gr->SetMaximum(hmax);
	gr->SetMarkerStyle(20);
	gr->Draw("P");
	//	delete [] xx;
	//	delete [] yy;
	
	// pr_y->Rebin(10);
		   //  pr_y->Draw();
	    
      }
      
    }
  

}
void EnergyDependentCorrections() {

  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(0.08,"t");
  gStyle->SetPadLeftMargin(0.15);
  //gStyle->SetPadRightMargin(0.15);
  gStyle->SetPadBottomMargin(0.15);
  gStyle->SetTitleYSize(0.05);
  gStyle->SetTitleYOffset(1.4);
  gStyle->SetTitleXSize(0.05);
  gStyle->SetTitleXOffset(1.2);
  gStyle->SetTitleSize(0.04,"Z");
  gStyle->SetTitleOffset(1.6,"Z");
  gStyle->SetLabelSize(0.04,"xyz");
  gStyle->SetLegendBorderSize(0);
  gStyle->SetFillStyle(0);

  // read in the corrections and plot their deltaA/A for each bin
  // This can be done for both theory and MC

  //Int_t octmin = year==2011?0:60;
  //Int_t octmax = year==2011?59:121;

  std::vector <Double_t> energy;
  std::vector <Double_t> UnCorr2011;
  std::vector <Double_t> TheoryCorr2011;
  std::vector <Double_t> AllCorr2011;

  std::vector <Double_t> UnCorr2012;
  std::vector <Double_t> TheoryCorr2012;
  std::vector <Double_t> AllCorr2012;

  Double_t en, val, err;
  
  std::ifstream infile(TString::Format("%s/Asymmetries/UnCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err ) {
    energy.push_back(en);
    UnCorr2011.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/DeltaTheoryOnly_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err) {
    TheoryCorr2011.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/AllCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),0,59));
  
  while (infile >> en >> val >> err) {
    AllCorr2011.push_back(val);
  }

  infile.close();
    
  infile.open(TString::Format("%s/Asymmetries/UnCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err ) {
    energy.push_back(en);
    UnCorr2012.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/DeltaTheoryOnly_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err) {
    TheoryCorr2012.push_back(val);
  }

  infile.close();

  infile.open(TString::Format("%s/Asymmetries/AllCorr_OctetAsymmetries_AnaChC_Octets_%i-%i_BinByBin.txt",getenv("ANALYSIS_RESULTS"),60,121));
  
  while (infile >> en >> val >> err) {
    AllCorr2012.push_back(val);
  }

  infile.close();


  
  
  
  

  std::vector <Double_t> en_Th;
  std::vector <Double_t> corr_Th;
  std::vector <Double_t> en_MC2011;
  std::vector <Double_t> corr_MC2011;
  std::vector <Double_t> en_MC2012;
  std::vector <Double_t> corr_MC2012;
  
  
  for (int i=2;i<80;++i) {

    if (UnCorr2011[i]!=0.) en_Th.push_back(energy[i]), corr_Th.push_back(100.*(TheoryCorr2011[i]/UnCorr2011[i]-1.));
    if (TheoryCorr2011[i]!=0.) en_MC2011.push_back(energy[i]), corr_MC2011.push_back(100.*(AllCorr2011[i]/TheoryCorr2011[i]-1.));
    if (TheoryCorr2012[i]!=0.) en_MC2012.push_back(energy[i]), corr_MC2012.push_back(100.*(AllCorr2012[i]/TheoryCorr2012[i]-1.));
  }

  

  TCanvas *c2 = new TCanvas("c2","c2",1200,800);
  c2->Divide(2,1);

  c2->cd(1);

  TGraph *gTheory = new TGraph(en_Th.size(),&en_Th[0],&corr_Th[0]);
  gTheory->SetTitle("Theory Corrections vs. Energy");
  gTheory->SetMarkerStyle(kFullCircle);
  gTheory->SetMinimum(-5.);
  gTheory->SetMaximum(0.);
  gTheory->SetLineWidth(3);
  gTheory->SetLineColor(kBlack);
  gTheory->GetYaxis()->SetTitle("#DeltaA/A (%)");
  gTheory->GetYaxis()->CenterTitle();
  gTheory->GetXaxis()->SetTitle("Energy (keV)");
  gTheory->GetXaxis()->CenterTitle();
  gTheory->Draw("AL");
  
  c2->cd(2);

  TMultiGraph *mg = new TMultiGraph();
  mg->SetTitle("MC Corrections vs. Energy");
  
  TGraph *gMC2011 = new TGraph(en_MC2011.size(),&en_MC2011[0],&corr_MC2011[0]);
  gMC2011->SetMarkerStyle(kFullCircle);
  //gMC2011->SetMinimum(-10.);
  //gMC2011->SetMaximum(6.);
  gMC2011->SetLineWidth(3);
  gMC2011->SetLineColor(kBlue);
  gMC2011->GetYaxis()->SetTitle("#DeltaA/A (%)");
  gMC2011->GetYaxis()->CenterTitle();
  gMC2011->GetXaxis()->SetTitle("Energy (keV)");
  gMC2011->GetXaxis()->CenterTitle();
  //gMC2011->Draw("AC");

  TGraph *gMC2012 = new TGraph(en_MC2012.size(),&en_MC2012[0],&corr_MC2012[0]);
  gMC2012->SetMarkerStyle(kFullCircle);
  //gMC2012->SetMinimum(-10.);
  //gMC2012->SetMaximum(6.);
  gMC2012->SetLineWidth(3);
  gMC2012->SetLineColor(kGreen);
  //gMC2012->GetYaxis()->SetTitle("#DeltaA/A (%)");
  //gMC2012->GetYaxis()->CenterTitle();
  //gMC2012->GetXaxis()->SetTitle("Energy (keV)");
  //gMC2012->GetXaxis()->CenterTitle();
  //gMC2012->Draw("AC");
  
  mg->Add(gMC2011);
  mg->Add(gMC2012);
  mg->SetMinimum(-8.);
  mg->SetMaximum(6.);
  
  mg->Draw("AC");
  mg->GetYaxis()->SetTitle("#DeltaA/A (%)");
  mg->GetYaxis()->CenterTitle();
  mg->GetXaxis()->SetTitle("Energy (keV)");
  mg->GetXaxis()->CenterTitle();
  gPad->Modified();

  TLegend *leg = new TLegend(0.55,0.75,0.85,0.85);
  leg->AddEntry(gMC2011,"2011-2012","l");
  leg->AddEntry(gMC2012,"2012-2013","l");
  leg->SetTextSize(0.05);
  leg->Draw("SAME");
}
TCanvas* plotLinearityPS_AllTypes_ERUpgrade(double eta, double etmin /* GeV */, double etmax /* GeV */, 
					    string year, string esmodel,
					    bool debug=false, bool logx=false, bool subtractAverage=false,
					    TGraph* overlay=0 ) {

  double GeV = 1000;

   gROOT->ProcessLine(".L EnergyRescalerUpgrade.cxx");
  
   egRescaler::EnergyRescalerUpgrade ers;

   ers.Init("../share/EnergyRescalerData.root",year,esmodel);

   ers.SetDebugFlag( debug );

   ers.includeMaterialContribution( false );
   ers.includeLeakageContribution( false );

   double eMin = etmin * cosh(eta) * GeV;
   double eMax = etmax * cosh(eta) * GeV;

   int nStep = 100;
   double eStep;
   if( logx )
     eStep = (log(eMax)-log(eMin))/(double)nStep;
   else
     eStep = (eMax-eMin)/(double)nStep;
   double e = eMin;

   TGraphErrors* gZee = new TGraphErrors();  // Z scale

   TGraph* gNom = new TGraph();        // nominal scale correction
   TGraph* gPSUp = new TGraph();       //        ps uncertainty, Up
   TGraph* gPSDown = new TGraph();     //                      , Down

   TGraph* gNom_UC = new TGraph();    
   TGraph* gPSUp_UC = new TGraph();   
   TGraph* gPSDown_UC = new TGraph(); 

   TGraph* gNom_CV = new TGraph();    
   TGraph* gPSUp_CV = new TGraph();   
   TGraph* gPSDown_CV = new TGraph(); 

   int i=0;

   while( e<=eMax ) {
     
     double eT = e/cosh(eta);

     double alpha          = ers.getAlphaZee(eta, egRescaler::EnergyRescalerUpgrade::Nominal);
     double alphaUp        = ers.getAlphaZee(eta, egRescaler::EnergyRescalerUpgrade::ZeeStatUp);

     double eNominal       = ers.applyEnergyCorrection(eta, e, 0, egRescaler::EnergyRescalerUpgrade::Nominal);

     double eVarPSUp       = ers.applyEnergyCorrection(eta, e, 0, egRescaler::EnergyRescalerUpgrade::B12Up);
     double eVarPSDown     = ers.applyEnergyCorrection(eta, e, 0, egRescaler::EnergyRescalerUpgrade::B12Down);

     double eNominal_UC       = ers.applyEnergyCorrection(eta, e, 1, egRescaler::EnergyRescalerUpgrade::Nominal);

     double eVarPSUp_UC       = ers.applyEnergyCorrection(eta, e, 1, egRescaler::EnergyRescalerUpgrade::B12Up);
     double eVarPSDown_UC     = ers.applyEnergyCorrection(eta, e, 1, egRescaler::EnergyRescalerUpgrade::B12Down);

     double eNominal_CV       = ers.applyEnergyCorrection(eta, e, 2, egRescaler::EnergyRescalerUpgrade::Nominal);

     double eVarPSUp_CV       = ers.applyEnergyCorrection(eta, e, 2, egRescaler::EnergyRescalerUpgrade::B12Up);
     double eVarPSDown_CV     = ers.applyEnergyCorrection(eta, e, 2, egRescaler::EnergyRescalerUpgrade::B12Down);

     if(i==0) {
       gZee->SetPointError(i,0,alphaUp-alpha);
       if( !subtractAverage )
	 gZee->SetPoint(i,40.,alpha);
       else
	 gZee->SetPoint(i,40.,0);
     }
     
     if( !subtractAverage ) {
       
       gNom->SetPoint(i, eT/GeV, (e-eNominal)/eNominal); 
       
       gPSUp->SetPoint(i, eT/GeV, (e-eVarPSUp)/eVarPSUp); 
       gPSDown->SetPoint(i, eT/GeV, (e-eVarPSDown)/eVarPSDown); 
       
       gNom_UC->SetPoint(i, eT/GeV, (e-eNominal_UC)/eNominal_UC); 
       
       gPSUp_UC->SetPoint(i, eT/GeV, (e-eVarPSUp_UC)/eVarPSUp_UC); 
       gPSDown_UC->SetPoint(i, eT/GeV, (e-eVarPSDown_UC)/eVarPSDown_UC); 
       
       gNom_CV->SetPoint(i, eT/GeV, (e-eNominal_CV)/eNominal_CV); 
       
       gPSUp_CV->SetPoint(i, eT/GeV, (e-eVarPSUp_CV)/eVarPSUp_CV); 
       gPSDown_CV->SetPoint(i, eT/GeV, (e-eVarPSDown_CV)/eVarPSDown_CV); 
       
     } else {
       
       gNom->SetPoint(i, eT/GeV, (e-eNominal)/eNominal - alpha); 
     
       gPSUp->SetPoint(i, eT/GeV, (e-eVarPSUp)/eVarPSUp - alpha); 
       gPSDown->SetPoint(i, eT/GeV, (e-eVarPSDown)/eVarPSDown - alpha); 
       
       gNom_UC->SetPoint(i, eT/GeV, (e-eNominal_UC)/eNominal_UC - alpha); 
       
       gPSUp_UC->SetPoint(i, eT/GeV, (e-eVarPSUp_UC)/eVarPSUp_UC - alpha); 
       gPSDown_UC->SetPoint(i, eT/GeV, (e-eVarPSDown_UC)/eVarPSDown_UC - alpha); 
       
       gNom_CV->SetPoint(i, eT/GeV, (e-eNominal_CV)/eNominal_CV - alpha); 
       
       gPSUp_CV->SetPoint(i, eT/GeV, (e-eVarPSUp_CV)/eVarPSUp_CV - alpha); 
       gPSDown_CV->SetPoint(i, eT/GeV, (e-eVarPSDown_CV)/eVarPSDown_CV - alpha); 
       
     }

     i++;

     if( logx )
       e *= exp(eStep);
     else
       e += eStep;

   }
 
   TCanvas* canvas = new TCanvas();
   if( logx )
     canvas->SetLogx();

   if( !subtractAverage ) {
     gPSUp->SetMaximum(alpha+.005);
     gPSUp->SetMinimum(alpha+-.007);
   } else {
     gPSUp->SetMaximum(.005);
     gPSUp->SetMinimum(-.007);
   }

   char grafname[99];
   sprintf(grafname,"Linearity (%s), PS contribution, #eta = %4.2f", year.c_str(), eta);
   gPSUp->SetTitle(grafname);

   // Electrons
   
   gPSUp->GetXaxis()->SetTitleOffset(1.2*gNom->GetXaxis()->GetTitleOffset());
   gPSUp->GetYaxis()->SetTitleOffset(1.2*gNom->GetYaxis()->GetTitleOffset());
   gPSUp->GetXaxis()->SetTitle("E_{T} [GeV]");
   gPSUp->GetYaxis()->SetTitle("#alpha(E_{T})");
   gPSUp->SetLineWidth(2);
   gPSUp->SetLineStyle(2);
   gPSUp->SetLineColor(4);
   gPSUp->Draw("AL");

   gPSDown->SetLineWidth(2);
   gPSDown->SetLineStyle(3);
   gPSDown->SetLineColor(4);
   gPSDown->Draw("L");

   gNom->SetLineWidth(2);
   gNom->SetLineColor(4);
   gNom->Draw("L");

   // Unconverted

   gPSUp_UC->SetLineWidth(2);
   gPSUp_UC->SetLineStyle(2);
   gPSUp_UC->SetLineColor(2);
   gPSUp_UC->Draw("L");

   gPSDown_UC->SetLineWidth(2);
   gPSDown_UC->SetLineStyle(3);
   gPSDown_UC->SetLineColor(2);
   gPSDown_UC->Draw("L");

   gNom_UC->SetLineWidth(2);
   gNom_UC->SetLineColor(2);
   gNom_UC->Draw("L");

   // Converted 

   gPSUp_CV->SetLineWidth(2);
   gPSUp_CV->SetLineStyle(2);
   gPSUp_CV->SetLineColor(8);
   gPSUp_CV->Draw("L");

   gPSDown_CV->SetLineWidth(2);
   gPSDown_CV->SetLineStyle(3);
   gPSDown_CV->SetLineColor(8);
   gPSDown_CV->Draw("L");

   gNom_CV->SetLineWidth(2);
   gNom_CV->SetLineColor(8);
   gNom_CV->Draw("L");

   gZee->SetMarkerStyle(20);
   gZee->Draw("P");

   TLegend* leg1 = new TLegend(.65,.15,.9,.3);
   leg1->SetBorderSize(0);
   leg1->SetFillColor(0);
    leg1->AddEntry(gZee,"#alpha, Z peak", "p");
   leg1->AddEntry(gNom,"PS, e, nom.", "l");
   leg1->AddEntry(gPSUp,"PS, e, up", "l");
   leg1->AddEntry(gPSDown,"PS, e, down", "l");

   leg1->Draw("same");

   TLegend* leg2 = new TLegend(.4,.15,.65,.3);
   leg2->SetBorderSize(0);
   leg2->SetFillColor(0);
   leg2->AddEntry(gZee," ", "");
   leg2->AddEntry(gNom_UC,"PS, #gamma (unc.), nom.", "l");
   leg2->AddEntry(gPSUp_UC,"PS, #gamma (unc.), up", "l");
   leg2->AddEntry(gPSDown_UC,"PS, #gamma (unc.), down", "l");

   leg2->Draw("same");

   TLegend* leg3 = new TLegend(.15,.15,.4,.3);
   leg3->SetBorderSize(0);
   leg3->SetFillColor(0);
   leg3->AddEntry(gZee," ", "");
   leg3->AddEntry(gNom_CV,"PS, #gamma (cnv.), nom.", "l");
   leg3->AddEntry(gPSUp_CV,"PS, #gamma (cnv.), up", "l");
   leg3->AddEntry(gPSDown_CV,"PS, #gamma (cnv.), down", "l");

   leg3->Draw("same");

   // char plotname[99];
   // sprintf(plotname,"linearity_%d_%2.1f.png",ptype,eta);
   //   canvas->Print("overlay.ps");
  
   return canvas;
}
void SinglePionEfficiencyNewVSpT::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L SinglePionEfficiencyNewVSpT.C
//      Root > SinglePionEfficiencyNewVSpT t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

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

    Long64_t nentries = fChain->GetEntriesFast();

    Long64_t nbytes = 0, nb = 0;


    // number of pt bins and intervals
    const Int_t nptbins = 17;
    const Int_t nptcuts = nptbins+1;
    //   const Double_t pt[nptcuts]={0.0, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0};
    const Double_t pt[nptcuts]= {1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0, 60.0};
    //                              0    1    2    3    4    5    6    7    8    9
    // energy ecal+hcal in different matrices
    TProfile* hprEH11x5  = new  TProfile("hprEH11x5","prEH11x5",nptbins, pt, -10., 10.);
    TProfile* hprEH11x3  = new  TProfile("hprEH11x3","prEH11x3",nptbins, pt, -10., 10.);
    TProfile* hprEH7x5   = new  TProfile("hprEH7x5","prEH7x5",nptbins, pt, -10., 10.);
    TProfile* hprEH7x3   = new  TProfile("hprEH7x3","prEH7x3",nptbins, pt, -10., 10.);
    // energy in hcal matrix
    TProfile* hprH5  = new  TProfile("hprH5","prH5",nptbins, pt, -10., 10.);
    TProfile* hprH3  = new  TProfile("hprH3","prH3",nptbins, pt, -10., 10.);

    //
    TH1F * hH5_1_2GeV    = new TH1F( "hH5_1_2GeV", "H5_1_2GeV", 40, -2., 2.);
    TH1F * hH3_1_2GeV    = new TH1F( "hH3_1_2GeV", "H3_1_2GeV", 40, -2., 2.);
    TH1F * hH5_3_4GeV    = new TH1F( "hH5_3_4GeV", "H5_3_4GeV", 40, -2., 2.);
    TH1F * hH3_3_4GeV    = new TH1F( "hH3_3_4GeV", "H3_3_4GeV", 40, -2., 2.);
    TH1F * hH5_5_10GeV   = new TH1F( "hH5_5_10GeV", "H5_5_10GeV", 40, -2., 2.);
    TH1F * hH3_5_10GeV   = new TH1F( "hH3_5_10GeV", "H3_5_10GeV", 40, -2., 2.);

    //
    TH1F * hE11_1_2GeV   = new TH1F( "hE11_1_2GeV", "E11_1_2GeV", 100, -2., 2.);
    TH1F * hE11_3_4GeV   = new TH1F( "hE11_3_4GeV", "E11_3_4GeV", 100, -2., 2.);
    TH1F * hE11_5_10GeV  = new TH1F( "hE11_5_10GeV", "E11_5_10GeV", 100, -2., 2.);

    //
    TH1F * hE11H5_1_2GeV   = new TH1F( "hE11H5_1_2GeV", "E11H5_1_2GeV", 40, -2., 2.);
    TH1F * hE11H5_3_4GeV   = new TH1F( "hE11H5_3_4GeV", "E11H5_3_4GeV", 40, -2., 2.);
    TH1F * hE11H5_5_10GeV  = new TH1F( "hE11H5_5_10GeV", "E11H5_5_10GeV", 40, -2., 2.);

    //   TH1F * hEH11x5 = new TH1F( "hEH11x5", "EH11x5", 200, -2., 2.);
    //   TH2F * hresp2 = new TH2F( "hresp2", "resp2", 200, -2., 2.,200, -2., 2.);

    // prepare for graph
    Float_t ptgr[nptbins], eptgr[nptbins];
    for(Int_t i = 0; i < nptbins; i++) {
        ptgr[i]  = 0.5*(pt[i]+pt[i+1]);
        eptgr[i] = 0.5*(pt[i+1]-pt[i]);
        cout <<" i = " << i <<" pT = " << ptgr[i] <<" err pT = " << eptgr[i] << endl;
    }

    // number of eta bins and intervals
    const Int_t netabins = 12;
    const Int_t netacuts = netabins+1;
    Float_t eta[netacuts]= {0.01, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4};
    cout <<"  Eta bins " << endl;
    // prepare eta points for graph
    Float_t etagr[netabins], eetagr[netabins];
    for(Int_t i = 0; i < netabins; i++) {
        etagr[i]  = 0.5*(eta[i]+eta[i+1]);
        eetagr[i] = 0.5*(eta[i+1]-eta[i]);
        cout <<" i = " << i <<" Eta = " << etagr[i] <<" err Eta = " << eetagr[i] << endl;
    }

    // ===> for pi- and pi+
    // N total and N reco tracks
    // efficiency and error as a function of pT
    Int_t ntrk[nptbins]     = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrkreco[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrkrecor[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Float_t trkeff[nptbins], etrkeff[nptbins];
    Double_t responceVSpt[nptbins]  = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Double_t responceVSptF[nptbins];
    Double_t eresponceVSpt[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    // N total and N reco tracks
    // efficiency and error as a function of eta
    Int_t ntrketa[netabins]     = {0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrketareco[netabins] = {0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrketarecor[netabins] = {0,0,0,0,0,0,0,0,0,0,0,0};
    Float_t trketaeff[netabins], etrketaeff[netabins];
    Double_t responceVSeta[nptbins]  = {0,0,0,0,0,0,0,0,0,0,0,0};
    Double_t responceVSetaF[nptbins];
    Double_t eresponceVSeta[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0};

    //
    Int_t Ntot = 0;
    for (Long64_t jentry=0; jentry<nentries; jentry++) {
        Long64_t ientry = LoadTree(jentry);
        if (ientry < 0) break;
        nb = fChain->GetEntry(jentry);
        nbytes += nb;
        Ntot = Ntot + 1;
        // if (Cut(ientry) < 0) continue;
        // evaluate as a function of pT
        for(Int_t i = 0; i < nptbins; i++) {
            // ==> pi+
            if(ptSim1 >= pt[i] && ptSim1 < pt[i+1]) {
                ntrk[i] = ntrk[i]+1;
                // number of reco tracks
                if(drTrk1 < 0.01 && purityTrk1 == 1) {
                    ntrkreco[i] = ntrkreco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim1));
                    Double_t eSim1 = ptSim1/sin(theta);
                    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1.0) {
                        //	    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1000) {
                        ntrkrecor[i] = ntrkrecor[i]+1;

                        Double_t e_ecal11 = e1ECAL11x11/eSim1;
                        Double_t e_ecal7  = e1ECAL7x7/eSim1;
                        Double_t e_hcal5  = e1HCAL5x5/eSim1;
                        Double_t e_hcal3  = e1HCAL3x3/eSim1;

                        Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
                        Double_t e_ecalhcal11x3 = e_ecal11 + e_hcal3;
                        Double_t e_ecalhcal7x5  = e_ecal7 + e_hcal5;
                        Double_t e_ecalhcal7x3  = e_ecal7 + e_hcal3;

                        responceVSpt[i] = responceVSpt[i] + e_ecalhcal11x5;

                        hprEH11x5->Fill(ptSim1,e_ecalhcal11x5,1.);
                        hprEH11x3->Fill(ptSim1,e_ecalhcal11x3,1.);
                        hprEH7x5->Fill(ptSim1,e_ecalhcal7x5,1.);
                        hprEH7x3->Fill(ptSim1,e_ecalhcal7x3,1.);

                        hprH5->Fill(ptSim1,e_hcal5,1.);
                        hprH3->Fill(ptSim1,e_hcal3,1.);

                        //	      if(i == nptbins-1) {
                        if(i < 5) {
                            hH5_1_2GeV->Fill(e_hcal5,1.);
                            hH3_1_2GeV->Fill(e_hcal3,1.);
                            hE11_1_2GeV->Fill(e_ecal11,1.);
                            hE11H5_1_2GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 7) {
                            hH5_3_4GeV->Fill(e_hcal5,1.);
                            hH3_3_4GeV->Fill(e_hcal3,1.);
                            hE11_3_4GeV->Fill(e_ecal11,1.);
                            hE11H5_3_4GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 9) {
                            hH5_5_10GeV->Fill(e_hcal5,1.);
                            hH3_5_10GeV->Fill(e_hcal3,1.);
                            hE11_5_10GeV->Fill(e_ecal11,1.);
                            hE11H5_5_10GeV->Fill(e_ecalhcal11x5,1.);
                        }
                    }
                }
            }
            // ==> pi-
            if(ptSim2 >= pt[i] && ptSim2 < pt[i+1]) {
                ntrk[i] = ntrk[i]+1;
                // number of reco tracks
                if(drTrk2 < 0.01 && purityTrk2 == 1) {
                    ntrkreco[i] = ntrkreco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim2));
                    Double_t eSim2 = ptSim2/sin(theta);
                    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1.0) {
                        //	    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1000.) {
                        ntrkrecor[i] = ntrkrecor[i]+1;

                        Double_t e_ecal11 = e2ECAL11x11/eSim2;
                        Double_t e_ecal7  = e2ECAL7x7/eSim2;
                        Double_t e_hcal5  = e2HCAL5x5/eSim2;
                        Double_t e_hcal3  = e2HCAL3x3/eSim2;

                        Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
                        Double_t e_ecalhcal11x3 = e_ecal11 + e_hcal3;
                        Double_t e_ecalhcal7x5  = e_ecal7 + e_hcal5;
                        Double_t e_ecalhcal7x3  = e_ecal7 + e_hcal3;

                        responceVSpt[i] = responceVSpt[i] + e_ecalhcal11x5;

                        hprEH11x5->Fill(ptSim2,e_ecalhcal11x5,1.);
                        hprEH11x3->Fill(ptSim2,e_ecalhcal11x3,1.);
                        hprEH7x5->Fill(ptSim2,e_ecalhcal7x5,1.);
                        hprEH7x3->Fill(ptSim2,e_ecalhcal7x3,1.);

                        hprH5->Fill(ptSim2,e_hcal5,1.);
                        hprH3->Fill(ptSim2,e_hcal3,1.);

                        //	      if(i == nptbins-1) {
                        if(i < 5) {
                            hH5_1_2GeV->Fill(e_hcal5,1.);
                            hH3_1_2GeV->Fill(e_hcal3,1.);
                            hE11_1_2GeV->Fill(e_ecal11,1.);
                            hE11H5_1_2GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 7) {
                            hH5_3_4GeV->Fill(e_hcal5,1.);
                            hH3_3_4GeV->Fill(e_hcal3,1.);
                            hE11_3_4GeV->Fill(e_ecal11,1.);
                            hE11H5_3_4GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 9) {
                            hH5_5_10GeV->Fill(e_hcal5,1.);
                            hH3_5_10GeV->Fill(e_hcal3,1.);
                            hE11_5_10GeV->Fill(e_ecal11,1.);
                            hE11H5_5_10GeV->Fill(e_ecalhcal11x5,1.);
                        }
                    }
                }
            }
        }
        // Nick
        // evaluate efficiency as a function on eta
        for(Int_t i = 0; i < netabins; i++) {
            // ==> pi+
            if(fabs(etaSim1) >= eta[i] && fabs(etaSim1) < eta[i+1]) {
                // number of sim tracks in pt interval
                ntrketa[i] = ntrketa[i]+1;
                // number of reco tracks
                if(drTrk1 < 0.04 && purityTrk1 >= 0.7) {
                    Double_t theta = 2.*atan(exp(-etaSim1));
                    Double_t eSim1 = ptSim1/sin(theta);
                    ntrketareco[i] = ntrketareco[i]+1;
                    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000.) {
                        ntrketarecor[i] = ntrketarecor[i]+1;
                        responceVSeta[i] = responceVSeta[i] + (e1ECAL7x7 + e1HCAL3x3)/eSim1;
                    }
                }
            }
            // ==> pi-
            if(fabs(etaSim2) >= eta[i] && fabs(etaSim2) < eta[i+1]) {
                // number of sim tracks in pt interval
                ntrketa[i] = ntrketa[i]+1;
                // number of reco tracks
                if(drTrk2 < 0.04 && purityTrk2 >= 0.7) {
                    ntrketareco[i] = ntrketareco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim2));
                    Double_t eSim2 = ptSim2/sin(theta);
                    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000.) {
                        ntrketarecor[i] = ntrketarecor[i]+1;
                        responceVSeta[i] = responceVSeta[i] + (e2ECAL7x7 + e2HCAL3x3)/eSim2;
                    }
                }
            }
        }
    }

    // calculate efficiency and full graph
    for(Int_t i = 0; i < nptbins; i++) {
        if(ntrk[i] > 0) {
            trkeff[i] = 1.*ntrkreco[i]/ntrk[i];
            etrkeff[i] = sqrt( trkeff[i]*(1.-trkeff[i])/ntrk[i] );
            //       responceVSptF[i] = responceVSpt[i]/ntrkrecor[i];
            cout <<" i = " << i
                 <<" pt interval = " << pt[i] <<" - " << pt[i+1]
                 <<" ntrkreco[i] = " << ntrkreco[i]
                 <<" ntrkrecor[i] = " << ntrkrecor[i]
                 <<" ntrk[i] = " << ntrk[i]
                 <<" eff = " << trkeff[i] << endl;
            //       	    <<" responce = " << responceVSptF[i] << endl;
        }
    }
    // calculate efficiency vs Eta and full graph
    cout <<" Efficiency vs Eta " << endl;
    for(Int_t i = 0; i < netabins; i++) {
        if(ntrketa[i] > 0) {
            trketaeff[i] = 1.*ntrketareco[i]/ntrketa[i];
            etrketaeff[i] = sqrt( trketaeff[i]*(1.-trketaeff[i])/ntrketa[i] );
            responceVSetaF[i] = responceVSeta[i]/ntrketarecor[i];
            cout <<" i = " << i
                 <<" eta interval = " << eta[i] <<" - " << eta[i+1]
                 <<" ntrketareco[i] = " << ntrketareco[i]
                 <<" ntrketa[i] = " << ntrketa[i]
                 <<" eff = " << trketaeff[i]
                 <<" responce = " << responceVSetaF[i] << endl;
        }
    }

    // create graph
    //  vs pT
    setTDRStyle(1,0);
    TCanvas* c1 = new TCanvas("X","Y",1);
    TGraph *grpt  = new TGraphErrors(nptbins,ptgr,trkeff,eptgr,etrkeff);
    TAxis* xaxis = grpt->GetXaxis();
    grpt->GetXaxis()->SetTitle("p_{T}, GeV");
    grpt->GetYaxis()->SetTitle("track finding efficiency");
    xaxis->SetLimits(0.8,50.);
    grpt->SetMarkerStyle(21);
    grpt->SetMaximum(0.9);
    grpt->SetMinimum(0.6);
    grpt->Draw("AP");
    TLatex *t = new TLatex();
    t->SetTextSize(0.042);
    //   TLegend *leg = new TLegend(0.5,0.2,0.7,0.35,NULL,"brNDC");
    //   leg->SetFillColor(10);
    //   leg->AddEntry(grpt,"#pi ^{+} and #pi ^{-}","P");
    //   leg->Draw();
    t->DrawLatex(1.,0.85,"CMSSW169, single #pi ^{+} and #pi ^{-}. |#eta ^{#pi}|< 2.5");
    c1->SaveAs("trkeff_vs_pt.gif");
    c1->SaveAs("trkeff_vs_pt.eps");

    setTDRStyle(0,0);
    //  vs Eta
    TCanvas* c2 = new TCanvas("X","Y",1);
    TGraph *greta = new TGraphErrors(netabins,etagr,trketaeff,eetagr,etrketaeff);
    TAxis* xaxis = greta->GetXaxis();
    greta->GetXaxis()->SetTitle("#eta");
    greta->GetYaxis()->SetTitle("track finding efficiency");
    xaxis->SetLimits(0.0,2.4);
    greta->SetMarkerStyle(21);
    greta->SetMaximum(1.0);
    greta->SetMinimum(0.50);
    greta->Draw("AP");
    TLatex *t = new TLatex();
    t->SetTextSize(0.042);
    //   TLegend *leg = new TLegend(0.5,0.2,0.7,0.35,NULL,"brNDC");
    //   leg->SetFillColor(10);
    //   leg->AddEntry(greta,"#pi ^{+} and #pi ^{-}","P");
    //   leg->Draw();
    t->DrawLatex(0.3,0.87,"CMSSW217, single #pi ^{+} and #pi ^{-}");
    t->DrawLatex(0.8,0.85,"1 < p^{#pi^{#pm}} < 50 GeV");
    c2->SaveAs("trkeff_vs_eta.gif");
    c2->SaveAs("trkeff_vs_eta.eps");

    cout <<" Ntot = " << Ntot << endl;

    /*
    setTDRStyle(1,0);
    //
    TCanvas* c3 = new TCanvas("X","Y",1);
    TAxis* xaxis = hEH->GetXaxis();
    hEH->GetXaxis()->SetTitle("p_{T} of #pi ^{+} and #pi ^{-}, GeV");
    hEH->GetYaxis()->SetTitle("(ECAL11x11+HCAL5x5)/E^{true}");
    //   xaxis->SetLimits(1.2,50.);
    hEH->SetMarkerStyle(21);
    hEH->SetMaximum(0.9);
    hEH->SetMinimum(0.2);
    hEH->Draw();
    c3->SaveAs("EmatrixtWithZSP11x11.5x5.gif");

    setTDRStyle(1,0);
    //
    TCanvas* c4 = new TCanvas("X","Y",1);
    TAxis* xaxis = hEmatrix->GetXaxis();
    hHmatrix->GetXaxis()->SetTitle("p_{T} of #pi ^{+} and #pi ^{-}, GeV");
    hHmatrix->GetYaxis()->SetTitle("HCAL3x3/E^{true}");
    //   xaxis->SetLimits(1.2,50.);
    hHmatrix->SetMarkerStyle(21);
    hHmatrix->SetMaximum(0.9);
    hHmatrix->SetMinimum(-0.2);
    hHmatrix->Draw();
    c4->SaveAs("HmatrixWithNoZSP3x3.gif");

    setTDRStyle(0,0);
    TCanvas* c5 = new TCanvas("X","Y",1);
    hresp2->Draw("hist");

    setTDRStyle(0,0);
    TCanvas* c6 = new TCanvas("X","Y",1);
    hhcal->Draw("hist");
    */

    TFile efile("sr_barrel.root","recreate");

    hprEH11x5->Write();
    hprEH11x3->Write();
    hprEH7x5->Write();
    hprEH7x3->Write();
    hprH5->Write();
    hprH3->Write();
    hH5_1_2GeV->Write();
    hH3_1_2GeV->Write();
    hH5_3_4GeV->Write();
    hH3_3_4GeV->Write();
    hH5_5_10GeV->Write();
    hH3_5_10GeV->Write();
    hE11_1_2GeV->Write();
    hE11_3_4GeV->Write();
    hE11_5_10GeV->Write();
    hE11H5_1_2GeV->Write();
    hE11H5_3_4GeV->Write();
    hE11H5_5_10GeV->Write();

    efile.Close();
}
void SinglePionEfficiency::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L SinglePionEfficiency.C
//      Root > SinglePionEfficiency t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

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

   Long64_t nentries = fChain->GetEntriesFast();
 
   Long64_t nbytes = 0, nb = 0;

   // number of pt bins and intervals
   const Int_t nptbins = 12;
   const Int_t nptcuts = nptbins+1;
   //                       0    1   2    3    4     5     6     7     8     9    10   11    
   Double_t pt[nptcuts]={0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0};
   // number of eta bins and intervals
   const Int_t netabins = 12;
   const Int_t netacuts = netabins+1;
   //                         0    1    2    3    4    5    6    7    8    9    10   11
   Double_t eta[netacuts]={0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4};
   cout <<"  Eta bins " << endl;

   // prepare eta points for graph
   Float_t etagr[netabins], eetagr[netabins];
   for(Int_t i = 0; i < netabins; i++) {
     etagr[i]  = 0.5*(eta[i]+eta[i+1]);
     eetagr[i] = 0.5*(eta[i+1]-eta[i]);
     cout <<" i = " << i <<" Eta = " << etagr[i] <<" err Eta = " << eetagr[i] << endl;
   } 
   // prepare for graph
   Float_t ptgr[nptbins], eptgr[nptbins];
   for(Int_t i = 0; i < nptbins; i++) {
     ptgr[i]  = 0.5*(pt[i]+pt[i+1]);
     eptgr[i] = 0.5*(pt[i+1]-pt[i]);
     cout <<" i = " << i <<" pT = " << ptgr[i] <<" err pT = " << eptgr[i] << endl;
   } 


   TH2D* hResp = new TH2D("hResp","Resp",nptbins, pt, netabins, eta);
   // histos for energy losses
   TH1F* hEnTrkNotInter[netabins];
   const char* namesEnTrkNotInter[netabins] = {"hEnTrkNotInter1",
					       "hEnTrkNotInter2",
					       "hEnTrkNotInter3",
					       "hEnTrkNotInter4",
					       "hEnTrkNotInter5",
					       "hEnTrkNotInter6",
					       "hEnTrkNotInter7",
					       "hEnTrkNotInter8",
					       "hEnTrkNotInter9",
					       "hEnTrkNotInter10",
					       "hEnTrkNotInter11",
					       "hEnTrkNotInter12"};

   const char* titleEnTrkNotInter[netabins] = {"EnTrkNotInter1",
					       "EnTrkNotInter2",
					       "EnTrkNotInter3",
					       "EnTrkNotInter4",
					       "EnTrkNotInter5",
					       "EnTrkNotInter6",
					       "EnTrkNotInter7",
					       "EnTrkNotInter8",
					       "EnTrkNotInter9",
					       "EnTrkNotInter10",
					       "EnTrkNotInter11",
					       "EnTrkNotInter12"};

   TH1F* hEnTrkInter[netabins];
   const char* namesEnTrkInter[netabins] = {"hEnTrkInter1",
					    "hEnTrkInter2",
					    "hEnTrkInter3",
					    "hEnTrkInter4",
					    "hEnTrkInter5",
					    "hEnTrkInter6",
					    "hEnTrkInter7",
					    "hEnTrkInter8",
					    "hEnTrkInter9",
					    "hEnTrkInter10",
					    "hEnTrkInter11",
					    "hEnTrkInter12"};

   const char* titleEnTrkInter[netabins] = {"EnTrkInter1",
					    "EnTrkInter2",
					    "EnTrkInter3",
					    "EnTrkInter4",
					    "EnTrkInter5",
					    "EnTrkInter6",
					    "EnTrkInter7",
					    "EnTrkInter8",
					    "EnTrkInter9",
					    "EnTrkInter10",
					    "EnTrkInter11",
					    "EnTrkInter12"};

   for(Int_t ih=0; ih < netabins; ih++) { 
     hEnTrkNotInter[ih] = new TH1F(namesEnTrkNotInter[ih], titleEnTrkNotInter[ih], 40, -1., 3.);
     hEnTrkInter[ih] = new TH1F(namesEnTrkInter[ih], titleEnTrkInter[ih], 40, -1., 3.);
   }
   //
 
   // ===> for pi- and pi+
   // N total and N reco tracks
   // find how to write output in file
   //~/scratch0/CMSSW_TEST/cmssw134gammajet/src/JetMETCorrections/GammaJet/src/GammaJetAnalysis.cc

   // total number of analized MC tracks
   Int_t ntrk[netabins][nptbins] =   {  
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of found tracks
   Int_t ntrkreco[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of lost tracks
   Int_t ntrklost[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of tracks with impact point on calo
   Int_t ntrkrecor[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // trk efficiency and error
   Float_t trkeff[netabins][nptbins], etrkeff[netabins][nptbins];
   // response in 11x11 crystals + 5x5 HCAL around IP in ECAL
   Double_t response[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // response for found tracks in cone 0.5 around MC track direction at vertex
   Double_t responseFoundTrk[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // response for lost tracks in cone 0.5 around MC track direction at vertex
   Double_t responseLostTrk[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // average response in 11x11 crystals + 5x5 HCAL around IP in ECAL
   Double_t responseF[netabins][nptbins];
   // average response for found tracks in cone 0.5 around MC track direction at vertex
   Double_t responseFoundTrkF[netabins][nptbins];
   // average response for lost tracks in cone 0.5 around MC track direction at vertex
   Double_t responseLostTrkF[netabins][nptbins];
   // ratio of responses of lost and found tracks
   Double_t leak[netabins][nptbins];

   Double_t drTrkcut = 0.01;
   Double_t purityTrkcut = 0.75;
   // 
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;
      // counting events for efficiency calculation
      for(Int_t ieta = 0; ieta < netabins; ieta++) {
	for(Int_t ipt = 0; ipt < nptbins; ipt++) {
	  // ==> pi+
	  if(fabs(etaSim1) >= eta[ieta] && fabs(etaSim1) < eta[ieta+1]) {
	    // checking leakage
	    if(ptSim1 > 10. && ptSim1 < 10000.)
	      {
		if(drTrk2 < 0.01 && purityTrk2 == 1) 
		  {
		    hEnTrkNotInter[ieta]->Fill(etCalo1/ptSim1);
		  } else {
		    hEnTrkInter[ieta]->Fill(etCalo1/ptSim1);
		  }
	      }
	    // end of checking leakage
	    if(ptSim1 >= pt[ipt] && ptSim1 < pt[ipt+1]) {
	      ntrk[ieta][ipt] = ntrk[ieta][ipt]+1;
	      // number of reco tracks
	      if(drTrk1 < drTrkcut && purityTrk1 >= purityTrkcut) { 
		ntrkreco[ieta][ipt] = ntrkreco[ieta][ipt]+1;
		// response for found tracks
		responseFoundTrk[ieta][ipt] = responseFoundTrk[ieta][ipt] + etCalo1/ptSim1;  
		//
		Double_t theta = 2.*atan(exp(-etaSim1));
		Double_t eSim1 = ptSim1/sin(theta);
		if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1000.) { 
		  ntrkrecor[ieta][ipt] = ntrkrecor[ieta][ipt]+1;
		  Double_t e_ecal11 = e1ECAL11x11/eSim1;
		  Double_t e_hcal5  = e1HCAL5x5/eSim1;
		  Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
		  response[ieta][ipt] = response[ieta][ipt] + e_ecalhcal11x5;
		}
	      } else {
		// response for lost tracks
		ntrklost[ieta][ipt] = ntrklost[ieta][ipt]+1;
		responseLostTrk[ieta][ipt] = responseLostTrk[ieta][ipt] + etCalo1/ptSim1;  
		//
	      }
	    }
	  }
	  // ==> pi-
	  if(fabs(etaSim2) >= eta[ieta] && fabs(etaSim2) < eta[ieta+1]) {
	    // checking leakage
	    if(ptSim2 > 10. && ptSim2 < 1000.)
	      {
		if(drTrk2 < 0.01 && purityTrk2 == 1) 
		  {
		    hEnTrkNotInter[ieta]->Fill(etCalo2/ptSim2);
		  } else {
		    hEnTrkInter[ieta]->Fill(etCalo2/ptSim2);
		  }
	      }
	    // end of checking leakage
	    if(ptSim2 >= pt[ipt] && ptSim2 < pt[ipt+1]) {
	      ntrk[ieta][ipt] = ntrk[ieta][ipt]+1;
	      // number of reco tracks
	      if(drTrk2 < drTrkcut && purityTrk2 >= purityTrkcut) { 
		ntrkreco[ieta][ipt] = ntrkreco[ieta][ipt]+1;
		// response for found tracks
		responseFoundTrk[ieta][ipt] = responseFoundTrk[ieta][ipt] + etCalo2/ptSim2;  
		//
		Double_t theta = 2.*atan(exp(-etaSim2));
		Double_t eSim2 = ptSim2/sin(theta);
		if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1000.) { 
		  ntrkrecor[ieta][ipt] = ntrkrecor[ieta][ipt]+1;
		  Double_t e_ecal11 = e2ECAL11x11/eSim2;
		  Double_t e_hcal5  = e2HCAL5x5/eSim2;
		  Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
		  response[ieta][ipt] = response[ieta][ipt] + e_ecalhcal11x5;
		}
	      } else {
		// response for lost tracks
		ntrklost[ieta][ipt] = ntrklost[ieta][ipt]+1;
		responseLostTrk[ieta][ipt] = responseLostTrk[ieta][ipt] + etCalo2/ptSim2;  
		//
	      }
	    }
	  }
	}
      }
   }

   // calculate efficiencfy, full graph and write output stream
   ofstream myoutput_eff("CMSSW_167_TrackNonEff.txt");
   ofstream myoutput_eff1("CMSSW_167_TrackNonEff_one.txt");
   ofstream myoutput_leak("CMSSW_167_TrackLeakage.txt");
   ofstream myoutput_leak1("CMSSW_167_TrackLeakage_one.txt");
   ofstream myoutput_resp("CMSSW_167_response.txt");

   // calculate map of leackage
   for(Int_t ieta = 0; ieta < netabins; ieta++) {
     for(Int_t ipt = 0; ipt < nptbins; ipt++) {
       
	 // found tracks
       if(ntrkreco[ieta][ipt] != 0) {
	 
	 responseFoundTrkF[ieta][ipt] = responseFoundTrk[ieta][ipt]/ntrkreco[ieta][ipt]; 
	 
       } else {
	 
	 responseFoundTrkF[ieta][ipt] = responseFoundTrkF[ieta][ipt-1];
       }
       // lost tracks
       if(ntrklost[ieta][ipt] != 0) {
	 
	 responseLostTrkF[ieta][ipt] = responseLostTrk[ieta][ipt]/ntrklost[ieta][ipt]; 
	 
       } else {
	 
	 responseLostTrkF[ieta][ipt] = responseLostTrkF[ieta][ipt-1];

       }
     }
   } 

   for(Int_t ieta = 0; ieta <= netabins; ieta++) {
     for(Int_t ipt = 0; ipt <= nptbins; ipt++) {

       if(ieta < netabins && ipt < nptbins) {

	 leak[ieta][ipt] = responseLostTrkF[ieta][ipt]/responseFoundTrkF[ieta][ipt];
	 
	 cout <<" ieta = " << ieta
	      <<" eta = " << eta[ieta]
	      <<" ipt = " << ipt
	      <<" pt = " << pt[ipt]
	      <<" ntrkreco = " << ntrkreco[ieta][ipt] 
	      <<" ntrklost = " << ntrklost[ieta][ipt] 
	      <<" responseFoundTrk = " << responseFoundTrkF[ieta][ipt] 
	      <<" responseLostTrk = " << responseLostTrkF[ieta][ipt]
	      <<" leak = " << leak[ieta][ipt] <<  endl;

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta][ipt] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;
       }
       if(ipt == nptbins && ieta < netabins) {
	 
	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta][ipt-1] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;
       }
       if(ipt < nptbins && ieta == netabins) {

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta-1][ipt] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;

       }
       if(ipt == nptbins && ieta == netabins) {

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta-1][ipt-1] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;

       }
     }
   }

   // calculate map of response and tracker efficiency

   cout <<" " << endl;
   cout <<" " << endl;
   cout <<" " << endl;

   for(Int_t ieta = 0; ieta <= netabins; ieta++) {
     for(Int_t ipt = 0; ipt <= nptbins; ipt++) {

       if(ieta < netabins && ipt < nptbins) {

	 if(ntrk[ieta][ipt] != 0 && ntrkrecor[ieta][ipt] != 0) {
	   trkeff[ieta][ipt] = 1.*ntrkreco[ieta][ipt]/ntrk[ieta][ipt];
	   etrkeff[ieta][ipt] = sqrt( trkeff[ieta][ipt]*(1.-trkeff[ieta][ipt])/ntrk[ieta][ipt] );
	   responseF[ieta][ipt] = response[ieta][ipt]/ntrkrecor[ieta][ipt];
	   
	   cout <<" ieta = " << ieta
		<<" eta = " << eta[ieta]
		<<" ipt = " << ipt
		<<" pt = " << pt[ipt]
		<<" ntrkreco = " << ntrkreco[ieta][ipt] 
		<<" ntrkrecor = " << ntrkrecor[ieta][ipt] 
		<<" ntrk = " << ntrk[ieta][ipt]
		<<" eff = " << trkeff[ieta][ipt] 
		<<" +/- " << etrkeff[ieta][ipt] 
		<<" response = " << responseF[ieta][ipt] << endl;
	   hResp->Fill(pt[ipt],eta[ieta],responseF[ieta][ipt]);
	   
	   myoutput_eff << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< trkeff[ieta][ipt] << endl;
	   
	   myoutput_resp << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << responseF[ieta][ipt] << endl;
	   
	   myoutput_eff1 << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << " 1." << endl;
	 } else {

	   trkeff[ieta][ipt] = trkeff[ieta][ipt-1];
	   responseF[ieta][ipt] = responseF[ieta][ipt-1];
	   hResp->Fill(pt[ipt],eta[ieta],responseF[ieta][ipt]);
	   myoutput_eff << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< trkeff[ieta][ipt] << endl;
	   
	   myoutput_resp << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << responseF[ieta][ipt] << endl;
	   
	   myoutput_eff1 << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << " 1." << endl;
	 }
       }

       if(ipt == nptbins && ieta < netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta][ipt-1] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta][ipt-1] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
       if(ipt < nptbins && ieta == netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta-1][ipt] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta-1][ipt] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
       if(ipt == nptbins && ieta == netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta-1][ipt-1] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta-1][ipt-1] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
     }
   }
   
   //
   // plot leakage graph
   Float_t leakage[netabins], eleakage[netabins];
   Float_t MeanNotInter[netabins], MeanErrorNotInter[netabins];
   Float_t MeanInter[netabins], MeanErrorInter[netabins];

   for(Int_t ih=0; ih < netabins; ih++) { 
     //     hEnTrkNotInter[ih]->Write();
     //     hEnTrkInter[ih]->Write();

     MeanNotInter[ih]      = hEnTrkNotInter[ih]->GetMean();
     MeanErrorNotInter[ih] = hEnTrkNotInter[ih]->GetMeanError();
     MeanInter[ih]         = hEnTrkInter[ih]->GetMean();
     MeanErrorInter[ih]    = hEnTrkInter[ih]->GetMeanError();
     leakage[ih] = MeanInter[ih]/MeanNotInter[ih];
     eleakage[ih] = leakage[ih] *
       sqrt( (MeanErrorNotInter[ih]/MeanNotInter[ih])*(MeanErrorNotInter[ih]/MeanNotInter[ih]) +
             (MeanErrorInter[ih]/MeanInter[ih])*(MeanErrorInter[ih]/MeanInter[ih]));

     cout <<" ieta = " << ih <<" MeanNotInter = " << MeanNotInter[ih] <<" +/- " << MeanErrorNotInter[ih]
	  <<" MeanInter = " << MeanInter[ih] <<" +/- " << MeanErrorInter[ih]  
	  <<" leakage = " << leakage[ih] <<" +/- " << eleakage[ih] << endl; 
   }

   TGraph *gleak = new TGraphErrors(netabins,etagr,leakage, eetagr,eleakage);
   TGraph *eMeanNotInter = new TGraphErrors(netabins,etagr,MeanNotInter, eetagr,MeanErrorNotInter);
   TGraph *eMeanInter = new TGraphErrors(netabins,etagr,MeanInter, eetagr,MeanErrorInter);
   //  vs Eta
   setTDRStyle(0,0);
   TCanvas* c3 = new TCanvas("X","Y",1);
   c3->Divide(1,2);
   c3->cd(1);
   TAxis* xaxis = eMeanNotInter->GetXaxis();
   eMeanNotInter->GetXaxis()->SetTitle("#eta");
   eMeanNotInter->GetYaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   xaxis->SetLimits(0.0,2.4);
   eMeanNotInter->SetMarkerStyle(21);
   //   eMeanNotInter->SetMaximum(0.95);
   //   eMeanNotInter->SetMinimum(0.55);
   eMeanNotInter->SetMaximum(1.);
   eMeanNotInter->SetMinimum(0.);
   eMeanNotInter->Draw("AP");
   eMeanInter->SetMarkerStyle(24);
   eMeanInter->Draw("P");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.2,0.2,0.8,0.4,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(eMeanNotInter,"recontructed tracks 2 < p_{T}^{#pi^{#pm}} < 10 GeV","P");
   leg->AddEntry(eMeanInter,"not reconstructed tracks 2 < p_{T}^{#pi^{#pm}} < 10 GeV","P");
   leg->Draw();

   c3->cd(2);
   TAxis* xaxis = gleak->GetXaxis();
   gleak->GetXaxis()->SetTitle("#eta");
   gleak->GetYaxis()->SetTitle("ratio = <E_{T for lost tracks}^{raw reco} / E_{T for found tracks}^{raw reco}>");
   xaxis->SetLimits(0.0,2.4);
   gleak->SetMarkerStyle(21);
   gleak->SetMaximum(1.0);
   //  leak->SetMinimum(0.7);
   gleak->SetMinimum(0.5);
   gleak->Draw("AP");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   //   t->DrawLatex(0.1,0.75,"<E_{T for lost tracks}^{raw reco} / E_{T for found tracks}^{raw reco}> for p_{T}^{#pi^{#pm}} >2 GeV");
   c3->SaveAs("eMean_vs_eta_pt2-10.gif");
   c3->SaveAs("eMean_vs_eta_pt2-10.eps");

   //  original distribtions
   setTDRStyle(0,0);
   gStyle->SetOptFit(0);
   TCanvas* c4 = new TCanvas("X","Y",1);
   hEnTrkNotInter[0]->GetYaxis()->SetTitle("");
   hEnTrkNotInter[0]->GetXaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   Double_t scale = 1./hEnTrkNotInter[0]->Integral();
   hEnTrkNotInter[0]->Scale(scale);
   hEnTrkNotInter[0]->SetLineWidth(4);
   hEnTrkNotInter[0]->SetMaximum(0.14);
   //   hEnTrkNotInter[0]->SetMinimum(0.55);
   // Fitting
   Int_t binMax = hEnTrkNotInter[0]->GetMaximumBin();
   TAxis* xaxis = hEnTrkNotInter[0]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[0]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkNotInter[0]->Fit("gaus","","",rFitMin,rFitMax);
   TF1 *fit = hEnTrkNotInter[0]->GetFunction("gaus"); 
   fit->SetLineWidth(4);
   fit->SetLineStyle(2);
   fit->Draw("same");
   scale = 1./hEnTrkInter[0]->Integral();
   hEnTrkInter[0]->Scale(scale);
   hEnTrkInter[0]->SetLineWidth(2);
  // Fitting
   Int_t binMax = hEnTrkInter[0]->GetMaximumBin();
   TAxis* xaxis = hEnTrkInter[0]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[0]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkInter[0]->Fit("gaus","","same",rFitMin,rFitMax);
   TF1 *fit = hEnTrkInter[0]->GetFunction("gaus"); 
   fit->SetLineWidth(2);
   fit->SetLineStyle(2);
   fit->Draw("same");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.15,0.7,0.9,0.9,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(hEnTrkNotInter[0],"recontructed tracks 2< p_{T}^{#pi^{#pm}} < 10 GeV, 0<#eta<0.2","L");
   leg->AddEntry(hEnTrkInter[0],"not reconstructed tracks 2< p_{T}^{#pi^{#pm}} < 10 GeV, 0<#eta<0.2","L");
   leg->Draw();

   c4->SaveAs("eMean_at_eta0.gif");
   c4->SaveAs("eMean_at_eta0.eps");

   //  original distribtions
   setTDRStyle(0,0);
   gStyle->SetOptFit(0);
   TCanvas* c5 = new TCanvas("X","Y",1);
   hEnTrkNotInter[9]->GetYaxis()->SetTitle("");
   hEnTrkNotInter[9]->GetXaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   Double_t scale = 1./hEnTrkNotInter[9]->Integral();
   hEnTrkNotInter[9]->Scale(scale);
   hEnTrkNotInter[9]->SetLineWidth(4);
   hEnTrkNotInter[9]->SetMaximum(0.17);
   //   hEnTrkNotInter[9]->SetMinimum(0.55);
   // Fitting
   Int_t binMax = hEnTrkNotInter[9]->GetMaximumBin();
   TAxis* xaxis = hEnTrkNotInter[9]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[9]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkNotInter[9]->Fit("gaus","","",rFitMin,rFitMax);
   TF1 *fit = hEnTrkNotInter[9]->GetFunction("gaus"); 
   fit->SetLineWidth(4);
   fit->SetLineStyle(2);
   fit->Draw("same");
   scale = 1./hEnTrkInter[9]->Integral();
   hEnTrkInter[9]->Scale(scale);
   hEnTrkInter[9]->SetLineWidth(2);
  // Fitting
   Int_t binMax = hEnTrkInter[9]->GetMaximumBin();
   TAxis* xaxis = hEnTrkInter[9]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[9]->GetRMS();
   Double_t rFitMin = binCenter - 1.2 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkInter[9]->Fit("gaus","","same",rFitMin,rFitMax);
   TF1 *fit = hEnTrkInter[9]->GetFunction("gaus"); 
   fit->SetLineWidth(2);
   fit->SetLineStyle(2);
   fit->Draw("same");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.15,0.7,0.9,0.9,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(hEnTrkNotInter[9],"recontructed tracks p_{T}^{#pi^{#pm}} > 2 GeV, 1.8<#eta<2.0","L");
   leg->AddEntry(hEnTrkInter[9],"not reconstructed tracks p_{T}^{#pi^{#pm}} > 2 GeV, 1.8<#eta<2.0","L");
   leg->Draw();

   c5->SaveAs("eMean_at_eta1.9.gif");
   c5->SaveAs("eMean_at_eta1.9.eps");

   TFile efile("response.root","recreate");
   hResp->Write();
   efile.Close();
}
Beispiel #15
0
void calc(TFile *file1, TFile *file2, const char* basename, int projnumb)
{

  TH1D *hp5_1 = (TH1D *)file1->Get(Form("%s_VMIN_SIPM1_meanHistSub_hproj_%d",basename,projnumb));
  TH1D *hp5_2 = (TH1D *)file2->Get(Form("%s_VMIN_SIPM2_meanHistSub_hproj_%d",basename,projnumb));

  if(hp5_1==NULL) {cout<<"cannot find hp5_1"<<endl; return;}
  if(hp5_2==NULL) {cout<<"cannot find hp5_2"<<endl; return;}

  int nbins = hp5_1->GetNbinsX();

  // ----------------------------------------------------------------------------
  // --- one of the preamps was broken, so we only had measurements from 1 SiPM
  // --- I made this fake data part to help in the code development while waiting
  // --- for new data with both SiPMs to be available
  // ----------------------------------------------------------------------------
  bool makefakedata = false;
  if(makefakedata)
    {
      for(int i=0; i<nbins; i++)
	{
	  hp5_2->SetBinContent(i+1,hp5_1->GetBinContent(nbins-i));
	}
    }

  double max1 = hp5_1->GetMaximum();
  double max2 = hp5_2->GetMaximum();

  hp5_1->GetXaxis()->SetTitle("Distance (cm)");
  hp5_2->GetXaxis()->SetTitle("Distance (cm)");
  hp5_1->GetYaxis()->SetTitle("Number of photoelectrons");
  hp5_2->GetYaxis()->SetTitle("Number of photoelectrons");

  if(max1>=max2)
    {
      // case 1
      hp5_1->Draw();
      hp5_2->Draw("same");
    }
  else
    {
      // case 2
      hp5_2->Draw();
      hp5_1->Draw("same");
    }

  hp5_1->SetLineColor(kBlue);
  hp5_2->SetLineColor(kRed);
  hp5_1->SetLineWidth(2);
  hp5_2->SetLineWidth(2);

  // legend coordinates may occasionally need to be relocated
  TLegend *leg = new TLegend(0.4,0.2,0.6,0.4);
  leg->AddEntry(hp5_1,"SiPM1","l");
  leg->AddEntry(hp5_2,"SiPM2","l");
  leg->SetFillStyle(0);
  leg->Draw();

  // generalize
  c1->Print(Form("Figures/ATOGETHER_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/ATOGETHER_%s_p%d.pdf",basename,projnumb));

  ofstream fout(Form("Data/Text/Asymmetry/%s_asymmetry_p%d.txt",basename,projnumb));
  TH1D *hp5_asymm = (TH1D *)hp5_1->Clone();
  double x[58];
  double y[58];
  double y1[58];
  double y2[58];
  TH1D *h1 = new TH1D("h1","",50,0,25);
  TH1D *h2 = new TH1D("h2","",50,0,25);
  for(int i=0; i<nbins; i++)
    {
      double A = hp5_1->GetBinContent(i+1);
      double B = hp5_2->GetBinContent(i+1);
      double content = (B-A)/(B+A);
      hp5_asymm->SetBinContent(i+1,content);
      hp5_asymm->SetBinError(i+1,0);
      // ---
      x[i] = hp5_1->GetBinCenter(i+1);
      y[i] = content;
      y1[i] = A;
      y2[i] = B;
      x[i] -= 2.0; // offset for off-panel part of scan, needs manual adjustment
      if(i>3&&i<54)
	{
	  // offset for off-panel, needs manual adjustment
	  h1->SetBinContent(i-3,A);
	  h2->SetBinContent(i-3,B);
	  h1->SetBinError(i-3,0);
	  h2->SetBinError(i-3,0);
	}
      // ---
      fout<<hp5_asymm->GetBinCenter(i+1)<<" "
	  <<hp5_asymm->GetBinContent(i+1)<<endl;
    }
  fout.close();

  hp5_asymm->SetMarkerColor(kBlack);
  hp5_asymm->SetMarkerStyle(kFullCircle);
  hp5_asymm->Draw("ex0p");
  hp5_asymm->GetYaxis()->SetTitle("Asymmetry of light yields");
  hp5_asymm->SetMinimum(-1);
  hp5_asymm->SetMaximum(1);
  TLine line(0.0,0.0,29.0,0.0);
  line.SetLineStyle(2);
  line.SetLineWidth(2);
  line.Draw();

  // generalize
  c1->Print(Form("Figures/ASYMMETRY_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/ASYMMETRY_%s_p%d.pdf",basename,projnumb));

  // ---

  h1->SetLineColor(kBlue);
  h2->SetLineColor(kRed);
  h1->SetLineWidth(2);
  h2->SetLineWidth(2);
  h1->SetMinimum(0);
  h2->SetMinimum(0);

  h1->GetXaxis()->SetTitle("Distance (cm)");
  h2->GetXaxis()->SetTitle("Distance (cm)");
  h1->GetYaxis()->SetTitle("Number of photoelectrons");
  h2->GetYaxis()->SetTitle("Number of photoelectrons");

  TGraph *tgy1 = new TGraph(58,x,y1);
  TGraph *tgy2 = new TGraph(58,x,y2);

  tgy1->SetLineColor(kBlue);
  tgy2->SetLineColor(kRed);
  tgy1->SetLineWidth(2);
  tgy2->SetLineWidth(2);
  tgy1->SetMinimum(0);
  tgy2->SetMinimum(0);

  tgy1->GetXaxis()->SetTitle("Distance (cm)");
  tgy2->GetXaxis()->SetTitle("Distance (cm)");
  tgy1->GetYaxis()->SetTitle("Number of photoelectrons");
  tgy2->GetYaxis()->SetTitle("Number of photoelectrons");

  double maxx = 0;
  if(max1>=max2)
    {
      // case 1
      maxx = max1;
      h1->Draw();
      h2->Draw("same");
    }
  else
    {
      // case 2
      maxx = max2;
      h2->Draw();
      h1->Draw("same");
    }

  TF1 *funx1 = new TF1("funx1","[0]+[1]*TMath::Exp(-x/[2])",0,25);
  funx1->SetLineColor(kBlue);
  funx1->SetParameter(0,5.0); // number of photoelectrons in core
  funx1->SetParameter(1,5.0); // number of photoelectrons in clad
  funx1->FixParameter(2,cld); // clad decay constant
  tgy1->Fit(funx1,"","",1,24); // need to use TGraph here, fitting h1 produces "Warning in <Fit>: Fit data is empty"
                               // I don't know why this happening, probably some dumb mistake I'm making
  TF1 *funx2 = new TF1("funx2","[0]+[1]*TMath::Exp((x-25)/[2])",0,25);
  funx2->SetLineColor(kRed);
  funx2->SetParameter(0,5.0); // number of photoelectrons in core
  funx2->SetParameter(1,5.0); // number of photoelectrons in clad
  funx2->FixParameter(2,cld); // clad decay constant
  tgy2->Fit(funx2,"","",1,24); // need to use TGraph here, fitting h2 produces "Warning in <Fit>: Fit data is empty"
                               // I don't know why this happening, probably some dumb mistake I'm making

  // tgy1->Draw("same"); // looks cool but distracting
  // tgy2->Draw("same"); // looks cool but distracting
  funx1->Draw("same");
  funx2->Draw("same");

  double numcore1 = funx1->GetParameter(0);
  double numclad1 = funx1->GetParameter(1);
  double numcore2 = funx2->GetParameter(0);
  double numclad2 = funx2->GetParameter(1);
  double Enumcore1 = funx1->GetParError(0);
  double Enumclad1 = funx1->GetParError(1);
  double Enumcore2 = funx2->GetParError(0);
  double Enumclad2 = funx2->GetParError(1);

  double fracore1 = (numcore1)/(numcore1+numclad1);
  double fracore2 = (numcore2)/(numcore2+numclad2);
  // ---
  double partB;
  partB = sqrt(Enumcore1**2+Enumclad2**2);
  double Efracore1 = fracore1*sqrt((Enumcore1/numcore1)**2+(partB/(numcore1+numclad1))**2);
  partB = sqrt(Enumcore2**2+Enumclad2**2);
  double Efracore2 = fracore2*sqrt((Enumcore2/numcore2)**2+(partB/(numcore2+numclad2))**2);

  TLatex *texAC1 = new TLatex(2,0.27*maxx,Form("f_{core} = %.3f #pm %.3f",fracore1,Efracore1));
  texAC1->SetTextColor(kBlue);
  texAC1->Draw();
  TLatex *texAC2 = new TLatex(15,0.27*maxx,Form("f_{core} = %.3f #pm %.3f",fracore2,Efracore2));
  texAC2->SetTextColor(kRed);
  texAC2->Draw();
  // ---
  TLatex *texAA1 = new TLatex(2,0.18*maxx,Form("N_{core} = %.3f #pm %.3f",numcore1,Enumcore1));
  texAA1->SetTextColor(kBlue);
  texAA1->Draw();
  TLatex *texAA2 = new TLatex(15,0.18*maxx,Form("N_{core} = %.3f #pm %.3f",numcore2,Enumcore2));
  texAA2->SetTextColor(kRed);
  texAA2->Draw();
  TLatex *texAB1 = new TLatex(2,0.1*maxx,Form("N_{clad} = %.3f #pm %.3f",numclad1,Enumclad1));
  texAB1->SetTextColor(kBlue);
  texAB1->Draw();
  TLatex *texAB2 = new TLatex(15,0.1*maxx,Form("N_{clad} = %.3f #pm %.3f",numclad2,Enumclad2));
  texAB2->SetTextColor(kRed);
  texAB2->Draw();

  // ---

  c1->Print(Form("Figures/FITATOGETHER_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/FITATOGETHER_%s_p%d.pdf",basename,projnumb));

  // ---

  // define a function to describe the data
  // this function defines and asymmetry B-A/A+B
  // it assumes the light yield has two components, core and cladding
  TF1 *fun = new TF1("fun","(([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2]))-([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2])))/(([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2]))+([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2])))",0,29);
  fun->SetParameter(0,0.5); // light fraction in fiber core
  fun->FixParameter(1,350); // decay constant in fiber core
  fun->FixParameter(2,cld); // decay constant in fiber cladding
  TF1 *fun2 = new TF1("fun2","[3]+(([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2]))-([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2])))/(([0]*TMath::Exp(-x/[1])+(1-[0])*TMath::Exp(-x/[2]))+([0]*TMath::Exp((x-25)/[1])+(1-[0])*TMath::Exp((x-25)/[2])))",0,29);
  fun2->SetParameter(0,0.5); // light fraction in fiber core
  fun2->FixParameter(1,350); // decay constant in fiber core
  fun2->FixParameter(2,cld); // decay constant in fiber cladding
  fun2->SetParameter(3,0.01);

  TGraph *tg = new TGraph(58,x,y);
  tg->SetMarkerStyle(kFullCircle);
  tg->Draw("ap");
  tg->GetYaxis()->SetTitle("Asymmetry of light yields");
  tg->GetXaxis()->SetTitle("Distance (cm)");
  tg->GetXaxis()->SetLimits(0,25);
  double scale = 0.4;
  tg->SetMinimum(-1*scale);
  tg->SetMaximum(1*scale);
  tg->Fit("fun2","","",0,25);
  TLine line2(0.0,0.0,25.0,0.0);
  line2.SetLineStyle(2);
  line2.SetLineWidth(2);
  line2.Draw();

  // get the fit parameters
  double frac = fun2->GetParameter(0);
  double core = fun2->GetParameter(1);
  double clad = fun2->GetParameter(2);
  double Efrac = fun2->GetParError(0);
  double off = fun2->GetParameter(3);
  double Eoff = fun2->GetParError(3);

  // use the fit parameters to put text boxes with fit information on the plt
  TLatex *tex1 = new TLatex(15,-0.30*scale,Form("f_{core} = %.3f #pm %.3f",frac,Efrac));
  tex1->SetTextColor(kGreen+2);
  tex1->Draw();
  TLatex *tex2 = new TLatex(15,-0.45*scale,Form("#lambda_{core} = %.1f (FIXED)",core));
  tex2->SetTextColor(kBlack);
  tex2->Draw();
  TLatex *tex3 = new TLatex(15,-0.60*scale,Form("#lambda_{clad} = %.1f (FIXED)",clad));
  tex3->SetTextColor(kBlack);
  tex3->Draw();
  TLatex *texX = new TLatex(15,-0.75*scale,Form("offset = %.3f #pm %.3f",off,Eoff));
  texX->SetTextColor(kGreen+2);
  texX->Draw();

  // generalize
  c1->Print(Form("Figures/FITASYMMETRY_%s_p%d.png",basename,projnumb));
  c1->Print(Form("Figures/FITASYMMETRY_%s_p%d.pdf",basename,projnumb));

  // ---
  frac1[projnumb] = fracore1;
  frac2[projnumb] = fracore2;
  fracAv[projnumb] = (fracore1+fracore2)/2.0;
  fracAs[projnumb] = frac;

  delete h1;
  delete h2;

}
double thetaOpt2(double *par){

  int upperAntNums[NUM_PHI]={8,0,9,1,10,2,11,3,12,4,13,5,14,6,15,7};
  int lowerAntNums[NUM_PHI]={16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  int lowerAntFromUpper[NUM_PHI]={17,19,21,23,25,27,29,31,16,18,20,22,24,26,28,30};
  int nadirAntNums[NUM_PHI]={32,-1,33,-1,34,-1,35,-1,36,-1,37,-1,38,-1,39,-1};
  int bottomFromNadir[8]={16,18,20,22,24,26,28,30};

  Double_t deltaR[40]={0};  
  Double_t deltaZ[40]={0};  
  Double_t deltaPhi[40]={0};  
  Double_t deltaHeading[1]={0};
  double  deltaTArrayMod[40]={0};
 
 int count3 = 0;


//   for(int i = 0; i<32;i++){
//     deltaR[i]=par[i];   
//     deltaZ[i]=par[i+32];
//     deltaPhi[i]=par[i+64];

//     cout << i << "  " <<0 << " " << deltaR[i] << " " << deltaPhi[i] << " " << deltaZ[i] << endl;

//   }

  for(int i = 7; i<8;i++){
    deltaR[7]=par[0];   
    deltaZ[7]=par[1];
    deltaPhi[7]=par[2];

    cout << i << "  " <<0 << " " << deltaR[i] << " " << deltaPhi[i] << " " << deltaZ[i] << endl;

  }


  // for(int i = 0; i<16;i++){
  //  deltaPhi[i]=deltaPhi[i] + par[16]; 
  //  deltaPhi[i+16]=deltaPhi[i+16] + par[17];     
  // }

  double theReturn = 0;
  double sumMean = 0;
  double sumMean2 = 0;
  int count8 = 0;
  double sumGrads = 0;

  TMultiGraph *myMG = new TMultiGraph;
  TMultiGraph *myMG3 = new TMultiGraph;
  TMultiGraph *myMG2 = new TMultiGraph;;

  AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
  char eventName[FILENAME_MAX];
  char headerName[FILENAME_MAX];
  char hkName[FILENAME_MAX];
  char gpsName[FILENAME_MAX];
  char corrName[FILENAME_MAX];
  char outName[FILENAME_MAX];
  char baseDir[FILENAME_MAX];
  char *corTreeDir = "../../../Outfiles";
  double dummyArray[40][1] ={{0}}; 
  TGraph *tempAntGraph;

  vector<vector<double> > phiAngle;
  vector<vector<double> > deltaTVec;
  vector<vector<int> > firstAntVec;
  vector<vector<int> > secondAntVec;

  vector<vector<double> > phiAngleArray2;
  vector<vector<double> > deltaTArray2;

  vector<double> temp;
  vector<int> temp2;
  temp.push_back(0);
  temp2.push_back(0);

  double deltaTArrayLoop[6000] ={0};
  double phiAngleArrayLoop[6000] = {0};


  int leftOpt, rightOpt;


  double meanPhi[40] = {0}; 
  meanPhi[0] =22.5-12.5;
  meanPhi[1] =67.5-12.5;
  meanPhi[2] =112.5-12.5;
  meanPhi[3] =157.5-12.5;
  meanPhi[4] =202.5-12.5;
  meanPhi[5] =247.5-12.5;
  meanPhi[6] =292.5-12.5;
  meanPhi[7] =337.5-12.5;
  meanPhi[8] =45-12.5;
  meanPhi[9] =90-12.5;
  meanPhi[10] =135-12.5;
  meanPhi[11] =180-12.5;
  meanPhi[12] =225-12.5;
  meanPhi[13] =270-12.5;
  meanPhi[14] =315-12.5;
  meanPhi[15] =360-12.5;

  meanPhi[16] = 22.5-12.5;
  meanPhi[17] = 45-12.5;
  meanPhi[18] = 67.5-12.5;
  meanPhi[19] = 90-12.5;
  meanPhi[20] = 112.5-12.5;
  meanPhi[21] = 135-12.5;
  meanPhi[22] = 157.5-12.5;
  meanPhi[23] = 180-12.5;
  meanPhi[24] = 202.5-12.5;
  meanPhi[25] = 225-12.5;
  meanPhi[26] = 247.5-12.5;
  meanPhi[27] = 270-12.5;
  meanPhi[28] = 292.5-12.5;
  meanPhi[29] = 315-12.5;
  meanPhi[30] = 337.5-12.5;
  meanPhi[31] = 360-12.5;


  meanPhi[32] = 22.5-12.5;
  meanPhi[33] = 67.5-12.5;
  meanPhi[34] = 112.5-12.5;
  meanPhi[35] = 157.5-12.5;
  meanPhi[36] = 202.5-12.5;
  meanPhi[37] = 247.5-12.5;
  meanPhi[38] = 292.5-12.5;
  meanPhi[39] = 337.5-12.5;

  for(int i =0; i < 40; i++){
    phiAngleArray2.push_back(temp);
    deltaTArray2.push_back(temp);

  }

  for(int loop = 1; loop <4; loop++){
    int run = 16+loop;
    //int run = 18;

    canSurf->cd(loop+1);

    phiAngle.clear();
    deltaTVec.clear();
    firstAntVec.clear();
    secondAntVec.clear();

    for(int i = 0; i < 40; i++){
      phiAngle.push_back(temp);
      deltaTVec.push_back(temp);
      firstAntVec.push_back(temp2);
      secondAntVec.push_back(temp2);
    }

    //sprintf(baseDir,"http://www.hep.ucl.ac.uk/uhen/anita/private/monitor2/runs/fromLoki/");
    sprintf(baseDir,"/Users/simonbevan/Desktop/");
    sprintf(eventName,"%s/run%d/eventFile%d.root",baseDir,run,run);
    sprintf(headerName,"%s/run%d/headFile%d.root",baseDir,run,run);
    sprintf(gpsName,"%s/run%d/gpsFile%d.root",baseDir,run,run);
    sprintf(corrName,"%s/corRun%d.root",corTreeDir,run);

   
    RawAnitaEvent *event = 0;
    PrettyAnitaHk *hk = 0;
   
    RawAnitaHeader *header =0;
    Adu5Pat *pat =0;
    CorrelationSummary *corSum =0;
   
  
    TFile *fpHead = TFile::Open(headerName);
    TTree *headTree = (TTree*) fpHead->Get("headTree");
    headTree->SetBranchAddress("header",&header);
    headTree->BuildIndex("eventNumber");
   
    TFile *fpGps = TFile::Open(gpsName);
    TTree *adu5PatTree = (TTree*) fpGps->Get("adu5PatTree");
    adu5PatTree->BuildIndex("realTime");
    adu5PatTree->SetBranchAddress("pat",&pat);
   
    Int_t labChip;
    TFile *fpCor = new TFile(corrName);
    TTree *corTree = (TTree*) fpCor->Get("corTree");
    corTree->SetBranchAddress("cor",&corSum);
    corTree->SetBranchAddress("labChip",&labChip);

    Long64_t numEntries=corTree->GetEntries();
    int counter=0;

    Long64_t entry=0;
    UInt_t eventNumber, triggerTime, triggerTimeNs;
    Int_t firstAnt,secondAnt,maxAnt,corInd;
    Double_t deltaT,deltaTExpected;
    Double_t phiWave, phiMaxAnt;
    Double_t corPeak, corRMS;
    Double_t balloonLat, balloonLon, balloonAlt;
    Double_t heading,pitch,roll;
  

    Double_t thetaWave;

    for(entry=0;entry<numEntries;entry++) {

      corTree->GetEntry(entry);
      Long64_t headEntry=headTree->GetEntryNumberWithIndex(corSum->eventNumber);
      if(headEntry<0) 
	continue;
      headTree->GetEntry(headEntry);
     
      if( (header->triggerTimeNs>0.5e6) || (header->triggerTimeNs<0.2e6) )  
	continue; 

      triggerTimeNs=header->triggerTimeNs;
      triggerTime=header->triggerTime;
      eventNumber=header->eventNumber;
  

      Long64_t bestEntry = adu5PatTree->GetEntryNumberWithBestIndex(header->triggerTime);
      if(bestEntry>-1) 
	adu5PatTree->GetEntry(bestEntry);
      else 
	continue;
      
      balloonLat=pat->latitude;
      balloonLon=pat->longitude;
      balloonAlt=pat->altitude;
      heading=pat->heading;
      pat->pitch=0.64;
      pat->roll=0.14;

      pitch=pat->pitch;
      roll=pat->roll;

      UsefulAdu5Pat usefulPat(pat);
      
      for(corInd=0;corInd<19;corInd++) {
	
	firstAnt=corSum->firstAnt[corInd];
	secondAnt=corSum->secondAnt[corInd];

	//replace taylor dome
	
	usefulPat.fSourceLongitude=0;
	//	deltaTExpected=usefulPat.getDeltaTTaylor(corSum->firstAnt[corInd],corSum->secondAnt[corInd]);
	deltaTExpected=usefulPat.getDeltaTTaylorOpt(corSum->firstAnt[corInd],corSum->secondAnt[corInd],deltaR,deltaZ,deltaPhi);
	
	deltaT=corSum->maxCorTimes[corInd];
	maxAnt=corSum->centreAntenna;
	phiWave=usefulPat.getPhiWave()*TMath::RadToDeg();
	phiMaxAnt=fGeomTool->getAntPhiPositionRelToAftFore(corSum->centreAntenna)*TMath::RadToDeg();
	corPeak=corSum->maxCorVals[corInd];
	corRMS=corSum->rmsCorVals[corInd];

	if((deltaT - deltaTExpected)*(deltaT - deltaTExpected) < 1 && (corPeak/corRMS)>8 ){
	  phiAngle[0].push_back(phiWave);
	  deltaTVec[0].push_back(deltaT - deltaTExpected + deltaTArrayMod[firstAnt] - deltaTArrayMod[secondAnt]);
	  firstAntVec[0].push_back(firstAnt);
	  secondAntVec[0].push_back(secondAnt);  
	}
      }

      counter++; 
    
    }

 

    double deltaTArray[40][3000] = {{0}};
    double phiAngleArray[40][3000]= {{0}};

    double deltaTArrayCut[40][3000]= {{0}};
    double phiAngleArrayCut[40][3000]= {{0}};
    int whichCut[40][3000] = {{0}};

    int middleAnt; 
    int leftAnt,rightAnt;

    int countArray[40] = {0};





    //fill arrays
    //for(int ants = par[0]; ants < par[0]+1; ants++){
    for(int ants = 0; ants < 32; ants++){

      double lower  = meanPhi[ants] - 20;
      double upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //  	double upper = 360;


	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower;
	       upper= upper;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }




      int count = 0;
      int count2 = 0;
       count3 = 0;
      double sumPhi = 0;
      bool true1 = false;
      bool true2 = false;

      if(ants <32){
	fGeomTool->getThetaPartners(ants,leftAnt,rightAnt); 
      }else{
	leftAnt = ants;
	rightAnt = ants +1;
	if(ants == 39){
	  leftAnt = ants;
	  rightAnt = 32;
	}
      }    

      for(int events = 1; events < phiAngle[0].size(); events++){
	int firstAntTemp = (int)firstAntVec[0][events];
	int secondAntTemp = (int)secondAntVec[0][events];
	int rightTemp = int(rightAnt);

	int aboveTemp = 0;

	if(ants <16){
	  aboveTemp = lowerAntFromUpper[ants];
	}else{
	  aboveTemp = upperAntNums[ants-16];
	}
  
	if(firstAntTemp < 32){
      
 	  if( ((firstAntTemp == ants) &&  (secondAntTemp == rightTemp))){
	    //if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){
	    if((phiAngle[0][events] > lower ) && (phiAngle[0][events]< upper)){
 	    deltaTArray[ants][count] = deltaTVec[0][events];
 	    phiAngleArray[ants][count] = phiAngle[0][events];
 	    whichCut[ants][count] = 1; 

	    count++;
	     }


	  } else if(((firstAntTemp == ants) &&  (secondAntTemp == aboveTemp))){
// 	    //if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){

      double lower  = meanPhi[ants] - 20;
      double upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //  	double upper = 360;


	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower - 45;
	       upper= upper - 45;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }



	    //    if((phiAngleArray[ants][events] > lower ) && (phiAngleArray[ants][events]< upper)){
	  if((phiAngle[0][events] > lower ) && (phiAngle[0][events]< upper)){
	    deltaTArray[ants][count] = deltaTVec[0][events];
	      phiAngleArray[ants][count] = phiAngle[0][events];
	      whichCut[ants][count] = 0; 

	      count++;   
	      }
	  }
 
	}else{
      
	  rightTemp = firstAntTemp+1;
	  if(rightTemp>39){
	    rightTemp = 32;
	  }
      
	  if(firstAntTemp == ants){
	
	  }
      
	  if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){
		
	    deltaTArray[ants][count] = deltaTVec[0][events];
	    phiAngleArray[ants][count] = phiAngle[0][events];
	whichCut[ants][count] = 3; 
	    count++;
	  }
	}
    
    
      }
      countArray[ants] = count;
      
  
    }
    
    
    //make cuts
    for(int ants = 0; ants < 32; ants++){
   
       count3 = 0;
      if(ants <32){
	fGeomTool->getThetaPartners(ants,leftAnt,rightAnt); 
      }else{
	leftAnt = ants -1;
	rightAnt = ants +1;
	if(ants == 39){
	  leftAnt = ants - 1;
	  rightAnt = 32;
	}
      }    

      double sumPhi = 0;
    double   lower  = meanPhi[ants] - 20;
    double   upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //   	double upper = 360;


 

	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower;
	       upper= upper;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }


      for(int events = 0; events < countArray[ants]; events++){
	  
 
// 	if(whichCut[ants][events]==1){
//      lower  = meanPhi[ants] - 20;
//       upper = meanPhi[ants] + 20;
// 		if(lower < 0){
// 	  lower = 0;
// 	  upper = 20;
// 	}

// 	if(upper > 360){
// 	  lower = 330;
// 	  upper = 360;
// 	}



// 	}

//	if((phiAngleArray[ants][events] > lower ) && (phiAngleArray[ants][events]< upper)){
	  phiAngleArrayCut[ants][count3] = phiAngleArray[ants][events];
	  deltaTArrayCut[ants][count3] = deltaTArray[ants][events];
	    
	  	  count3++;
	      
		  //		  	}

      }
	
      for(int events = 0; events < count3-1; events++){
	phiAngleArray2[ants].push_back(phiAngleArrayCut[ants][events]);
	deltaTArray2[ants].push_back(deltaTArrayCut[ants][events]);
      }

	
    }
    
    delete event;
    delete hk; 
    delete header;
    delete pat;
    delete corSum;

    delete fpHead;
    delete fpGps ;
    delete fpCor;

  }

  sumMean = 0;
  sumMean2 = 0;
  sumGrads = 0;
  for(int ants = 0; ants < 32; ants++){
    count8 = 0;
    for(int events = 1; events < phiAngleArray2[ants].size(); events++){

      if( deltaTArrayLoop[count8]<1){      
	deltaTArrayLoop[count8] = deltaTArray2[ants][events];
	phiAngleArrayLoop[count8] = phiAngleArray2[ants][events];
	count8++;
      }
      
    }
    
    if(count8==0){
      tempAntGraph  = new TGraph(1, dummyArray[ants], dummyArray[ants]);
    }else{
      
      tempAntGraph  = new TGraph(count8-1,  phiAngleArrayLoop, deltaTArrayLoop);
      
      if(ants == 7){  
	
	canSurf->cd(1);
	
	tempAntGraph->SetMinimum(-0.5);
	tempAntGraph->SetMaximum(0.5);
	tempAntGraph->Draw("ap");    

	tempAntGraph->SetMarkerStyle(1);
	tempAntGraph->GetXaxis()->SetLimits(0,360);
    
	sumMean = sumMean + tempAntGraph->GetMean(2)*tempAntGraph->GetMean(2);

	if(ants == 8 || ants == 16 || ants == 12 || ants == 24){
	  tempAntGraph->SetMarkerColor(8);
	}

	if(ants == 3 || ants == 7 || ants == 23 || ants == 31){
	  tempAntGraph->SetMarkerColor(1);
	}
    
	if(ants == 9 || ants == 13 || ants == 18 || ants == 26){
	  tempAntGraph->SetMarkerColor(2);
	}
    
    
	if(ants == 10 || ants == 14 || ants == 20 || ants == 28){
	  tempAntGraph->SetMarkerColor(3);
	}
    
	if(ants == 11 || ants == 15 || ants == 22 || ants == 30){
	  tempAntGraph->SetMarkerColor(4);
	}
    
	if(ants == 0 || ants == 4 || ants == 17 || ants == 25){
	  tempAntGraph->SetMarkerColor(5);
	}


	if(ants == 2 || ants == 6 || ants == 21 || ants == 29){
	  tempAntGraph->SetMarkerColor(6);
	}

	if(ants == 1 || ants == 5 || ants == 19 || ants == 27){
	  tempAntGraph->SetMarkerColor(7);
	}
    
	tempAntGraph->GetXaxis()->SetTitle("phi (degrees)");
	tempAntGraph->GetYaxis()->SetTitle("actual - expected time");
	myMG2->Add(tempAntGraph);
	myMG2->Draw("p");
	
 	vector<double> myFit = leastSquares(phiAngleArrayLoop, deltaTArrayLoop, count8-1);
	double slope = myFit[0];
	double intercept = myFit[1];
	
	double tempX[2] = {slope*(meanPhi[ants]-20)+intercept,slope*(meanPhi[ants]+20)+intercept};
	double tempY[2] = {(meanPhi[ants]-20),(meanPhi[ants]+20)};
	sumGrads = sumGrads + myFit[0]*myFit[0]*10000;
      
      }
    } 
    

  }
  
  cout << " " << endl;
  cout << sumMean << "  " << sumGrads <<endl;
  canSurf->Update();
  cout << "  " << endl;  

  theReturn = sumMean+sumGrads;

  return theReturn;
   
}
void L1PrescalesSimulator::run(int nevs) {

	cout << "Start..." << endl;

	lumiSectTimeNs_ = 23.31;

	l_ = new TLegend(0.6, 0.7, 0.85, 0.9);

	Hbits_ = new TH1D("Hbits","",192,0.,192.);
	Hbits2_ = new TH1D("Hbits2","",192,0.,192.);

	gStyle->SetOptTitle(kFALSE);
	Hbits_->SetTitle("");
	Hbits_->GetXaxis()->SetTitle("Bit");
	Hbits2_->SetTitle("");
	Hbits2_->GetXaxis()->SetTitle("Bit");

	// clear buffers
	lumiSec2Lumi_.clear();
	lumiSec2rate_.clear();
	lumiSec2ratePrescaled_.clear();
	rateVecs_.clear();
	bit2prescale_.clear();
	bxMultiplicatorVec_.clear();
	lumiVec_.ResizeTo(0);
	bitMaskVec_.clear();

	cout << "Open config file: " << tb_.getMacroDir()
			<< "conf/PrescalesSimulator.conf" << endl;

	tb_.readConfigFile(tb_.getMacroDir() + "conf/PrescalesSimulator.conf",
			parameterMap_);

	// fill parameters
	numberOfBunches_ = toolbox::convertFromString<int>(parameterMap_["nOfBunches"]);
	commonPrescale_ = toolbox::convertFromString<int>(parameterMap_["commonPrescale"]);
	xMin_ = toolbox::convertFromString<float>(parameterMap_["xMin"]);
	xMax_ = toolbox::convertFromString<float>(parameterMap_["xMax"]);
	xFitMin_ = toolbox::convertFromString<float>(parameterMap_["xFitMin"]);
	xFitMax_ = toolbox::convertFromString<float>(parameterMap_["xFitMax"]);
	yMax_ = toolbox::convertFromString<int>(parameterMap_["yMax"]);

	int tmp = 1;

	std::map<string, string>::iterator itr;

	do {
		ostringstream oss;

		oss << tmp;

		itr = parameterMap_.find(oss.str());

		if (itr != parameterMap_.end())

			bxMultiplicatorVec_.push_back(toolbox::convertFromString<float>(itr->second));

		tmp++;

	} while (itr != parameterMap_.end());

	tmp = 1;

	tb_.readConfigFile(tb_.getMacroDir() + "conf/bitmasks.dat", parameterMap_);

	cout << "Bit masks: " << endl;

	do {
		ostringstream oss;

		oss << "m" << tmp;

		itr = parameterMap_.find(oss.str());

		if (itr != parameterMap_.end()) {
			cout << (itr->second) << endl;

			bitMaskVec_.push_back(toolbox::convertFromString<ULong64_t>(itr->second, 16));

		}

		tmp++;

	} while (itr != parameterMap_.end());

	// original luminosity and prescaled luminosity + bx multiplicator
	nOfPlots_ = 2 + bxMultiplicatorVec_.size();

	if (nevs) {

		hreset();

		getPrescales();

		getLuminosities();

		loop(bit2prescale_);

	}


	TCanvas* c2 = new TCanvas("c2", "", 900, 700);

	c2->GetEvent();

	Hbits_->Draw();
	Hbits2_->SetLineColor(2);
	Hbits2_->Draw("same");

	// draw the graphs  	

	TCanvas* c1 = new TCanvas("c1", "", 900, 700);
	c1->SetGrid(1, 1);

	TGraph* g = new TGraph(lumiVec_, rateVecs_[0]);

	g->GetXaxis()->SetLimits(xMin_, xMax_);

	g->GetXaxis()->SetTitle("Luminosity per bunch [10^{30} Hz/cm^{2}]");
	g->GetYaxis()->SetTitle("Rate [Hz]");

	g->Fit("pol2", "", "", xFitMin_, xFitMax_);

	g->SetMaximum(yMax_);

	g->Draw("A*");

	gStyle->SetOptTitle(kFALSE);
	g->SetTitle();

	ostringstream buf, buf2;
	buf << numberOfBunches_ << " (original rate)";
	buf2 << numberOfBunches_ << "b";

	l_->AddEntry(g, tb_.toCStr(buf), "l");

	TGraph* g2 = new TGraph(lumiVec_, rateVecs_[1]);

	g2->SetMarkerStyle(21);
	g2->SetLineColor(2);

	g2->Fit("pol2", "", "", xFitMin_, xFitMax_);

	TF1* fitFkt = g2->GetFunction("pol2");
	fitFkt->SetLineColor(2);

	l_->AddEntry(g2, tb_.toCStr(buf2), "l");

	g2->Draw("*");

	addGraphsForSimulatedNOfBx();

	l_->Draw();


}
int main(int argc, char *argv[])
{
    FILE *fp;
    RawDataPacket r;
    //char *filename;
    unsigned char buf[1024*1024];
    int n;

    //if (argc != 2) {
    //    usage();
    //    exit(1);
    //}

    //filename = argv[1];
    //fp = fopen(filename, "r");
    //if (fp == NULL) {
        //err(1, "fopen for %s", filename);
    //}
    
    fp = stdin;

    TApplication theApp("name", &argc, argv);
    TCanvas *c1 = new TCanvas("c1", "C1", 800, 600);
    int n_points = 1024;
    int x[n_points];
    int y[n_points];
    //TGraph *graph = new TGraph(n_points);
    TGraph *graph = new TGraph();
    TText *text = new TText();
    text->SetTextSize(0.05);
    text->SetTextColor(kBlack);
    text->SetNDC(1);

    for ( ; ; ) {
        n = fread(buf, 1, RawDataPacket::HEADER_SIZE, fp);
        if (n == 0) {
            if (feof(fp)) {
                break;;
            }
            else if (ferror(fp)) {
                exit(0);
            }
        }
        else if (n != RawDataPacket::HEADER_SIZE) {
            errx(1, "partial read %d bytes.  Should be %d bytes", n, RawDataPacket::HEADER_SIZE);
        }
        r.set_buf(buf, n);
        if (! r.is_raw_data_packet()) {
            cout << "Not a RawDataPacket" << endl;
            exit(1);
        }
        int data_length   = r.get_data_length();
        cout << "data_length:   " << data_length   << endl;
        n = fread(&buf[RawDataPacket::HEADER_SIZE], 1, data_length, fp);
        if (n == 0) {
            if (feof(fp)) {
                break;;
            }
            else if (ferror(fp)) {
                exit(0);
            }
        }
        else if (n != data_length) {
            errx(1, "partial read %d bytes.  Should be %d bytes", n, data_length);
        }
            
        int window_size   = r.get_window_size();
        int trigger_count = r.get_trigger_count();
        //int n_ch          = r.get_num_of_ch();
        
        //cout << "window_size:   " << window_size   << endl;
        //cout << "trigger_count: " << trigger_count << endl;
        
        //for (int ch = 0; ch < n_ch; ch ++) {
        //    for (int w = 0; w < window_size; w++) {
        //        unsigned short data = r.get_data_at(ch, w);
        //        cout << "trg: "     << trigger_count;
        //        cout << " ch: "      << ch;
        //        cout << " window: " << w;
        //        cout << " data: "   << data;
        //        cout << endl;
        //    }
        //}
        int ch = 0;
        for (int w = 0; w < window_size; w++) {
            x[w] = w;
            y[w] = r.get_data_at(ch, w);
            graph->SetPoint(w, x[w], y[w]);
        }
        graph->SetTitle(Form("Channel: %d", ch));
        graph->SetMinimum(0.0);
        graph->SetMaximum(4096.0);
        graph->Draw("al*");
        text -> DrawText(0.7, 0.92, Form("Trigger: %d", trigger_count));
        c1->Update();
        r.reset_buf();
        usleep(500000);
    }

    return 0;
}