Exemple #1
0
void RebinProfile(){

	f = new TFile("../../../rootfiles/MC/EPOS_PbPb_Ntrk_0.root");

	TH2D* h2;
	h2 = (TH2D*)f->Get("demo/scatterHist_effcorr");



	TCanvas* C = new TCanvas("fitscatterplot","EPOS Hydjet Scatterplot",1800,1200);

	C->Divide(3,2);
	C->cd(1);

	double newbins[8] = {-0.3,-0.075,-0.045,-0.015,0.015,0.045,0.075,0.3};
	//double newbins[6] = {-0.3,-0.045,-0.015,0.015,0.045,0.3};
	TH2D* hnew = new TH2D("rebin","rebin",7,newbins,1000,-0.3,0.3); 

	TAxis *xaxis = h2->GetXaxis();
	TAxis *yaxis = h2->GetYaxis();
	for (int k=1; k<=yaxis->GetNbins();k++) {
		for (int l=1; l<=xaxis->GetNbins();l++) {
			hnew->Fill(xaxis->GetBinCenter(l),yaxis->GetBinCenter(k),h2->GetBinContent(l,k));
		}
	}

	TProfile *prof = hnew->ProfileX();

	TF1* fit1 = new TF1("Linear fitting case 1", "[0]+x*[1]", -0.2, 0.2);
	fit1->SetLineColor(kBlue);
	fit1->SetLineStyle(1);
	fit1->SetLineWidth(3);
	prof->Fit(fit1,"RN0");

	TLatex* text2 = makeLatex(Form("slope : %.3f #pm %.3f",fit1->GetParameter(1),fit1->GetParError(1)),0.55,0.25) ;
	prof->Draw();

	text2->Draw("same");
	fit1->Draw("same");


	


/*
	for (Int_t i=0;i<2;i++) {
		for (Int_t j=0;j<3;j++) {


			h = (TH2D*)f->Get("demo/scatterHist_noeffcorr");
			h -> new TH2D(" ");


			corrTable[oc]->SetBinContent(eta+1, pt+1, c);

			

			double c1 = testload.getWeight(ptbins[pt], etabins[eta], ocbin[oc], "eff");
			double c2 = testload.getWeight(ptbins[pt], etabins[eta], ocbin[oc], "fak");
			double c = c1/(1-c2);

			if( oc == 0 && eta == 15 && pt == 20 ) cout << "1: " << c << endl;
			if( oc == 4 && eta == 15 && pt == 20 ) cout << "4: " << c << endl;
				//cout << "corr factor: " << c << endl; 
			corrTable[oc]->SetBinContent(eta+1, pt+1, c);


			c = c1/(1-c2);
			c2 = c3/(1-c1);
			c4 = c2/(1-c3);
			c5 = c6/(1-c7);

*/
		}
Exemple #2
0
void calibrateEM()
{

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

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

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

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

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

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

  TF1 *fitter = new TF1("fitf","[0]*x", 0,10);
  fitter->SetParameter(0,1.0);
  fitter->SetParNames("calibration factor");
  //FIXME: Fit the histogram to get the calibration factor
  hcounts->Fit("fitf");
}
Exemple #3
0
void canvas_write()
{
   //just in case this script is executed multiple times
   delete gROOT->GetListOfFiles()->FindObject("hsimple.root");
   delete gROOT->GetListOfCanvases()->FindObject("c1");

   gBenchmark->Start("ntuple1");
   //
   // Connect ROOT histogram/ntuple demonstration file
   // generated by example hsimple.C.
   TFile *f1 = new TFile("hsimple.root");
   //
   // Create a canvas, with 4 pads
   //
   TCanvas *c1 = new TCanvas("c1","The Ntuple canvas",200,10,700,780);
   TPad *pad1 = new TPad("pad1","This is pad1",0.02,0.52,0.48,0.98,21);
   TPad *pad2 = new TPad("pad2","This is pad2",0.52,0.52,0.98,0.98,21);
   TPad *pad3 = new TPad("pad3","This is pad3",0.02,0.02,0.48,0.48,21);
   TPad *pad4 = new TPad("pad4","This is pad4",0.52,0.02,0.98,0.48,1);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();
   pad4->Draw();
   //
   // Change default style for the statistics box
   gStyle->SetStatW(0.30);
   gStyle->SetStatH(0.20);
   gStyle->SetStatColor(42);
   //
   // Display a function of one ntuple column imposing a condition
   // on another column.
   pad1->cd();
   pad1->SetGrid();
   pad1->SetLogy();
   pad1->GetFrame()->SetFillColor(15);
   TNtuple *ntuple = (TNtuple*)f1->Get("ntuple");
   ntuple->SetLineColor(1);
   ntuple->SetFillStyle(1001);
   ntuple->SetFillColor(45);
   ntuple->Draw("3*px+2","px**2+py**2>1");
   ntuple->SetFillColor(38);
   ntuple->Draw("2*px+2","pz>2","same");
   ntuple->SetFillColor(5);
   ntuple->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same");
   pad1->RedrawAxis();
   //
   // Display the profile of two columns
   // The profile histogram produced is saved in the current directory with
   // the name hprofs
   pad2->cd();
   pad2->SetGrid();
   pad2->GetFrame()->SetFillColor(32);
   ntuple->Draw("pz:px>>hprofs","","goffprofs");
   TProfile *hprofs = (TProfile*)gDirectory->Get("hprofs");
   hprofs->SetMarkerColor(5);
   hprofs->SetMarkerSize(0.7);
   hprofs->SetMarkerStyle(21);
   hprofs->Fit("pol2");
   // Get pointer to fitted function and modify its attributes
   TF1 *fpol2 = hprofs->GetFunction("pol2");
   fpol2->SetLineWidth(4);
   fpol2->SetLineColor(2);
   //
   // Display a scatter plot of two columns with a selection.
   // Superimpose the result of another cut with a different marker color
   pad3->cd();
   pad3->GetFrame()->SetFillColor(38);
   pad3->GetFrame()->SetBorderSize(8);
   ntuple->SetMarkerColor(1);
   ntuple->Draw("py:px","pz>1");
   ntuple->SetMarkerColor(2);
   ntuple->Draw("py:px","pz<1","same");
   //
   // Display a 3-D scatter plot of 3 columns. Superimpose a different selection.
   pad4->cd();
   ntuple->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)");
   ntuple->SetMarkerColor(4);
   ntuple->Draw("pz:py:px","pz<6 && pz>4","same");
   ntuple->SetMarkerColor(5);
   ntuple->Draw("pz:py:px","pz<4 && pz>3","same");
   TPaveText *l4 = new TPaveText(-0.9,0.5,0.9,0.95);
   l4->SetFillColor(42);
   l4->SetTextAlign(12);
   l4->AddText("You can interactively rotate this view in 2 ways:");
   l4->AddText("  - With the RotateCube in clicking in this pad");
   l4->AddText("  - Selecting View with x3d in the View menu");
   l4->Draw();
   //
   c1->cd();
   c1->Update();
   gStyle->SetStatColor(19);
   gBenchmark->Show("ntuple1");

   TSQLFile* fsql1 = new TSQLFile(dbname, "recreate", username, userpass);
   if (fsql1->IsZombie()) { delete fsql1; return; }

//  changing TSQLFile configuration, you may improve speed
//  of reading or writing object to/from sql database

//   fsql1->SetUseSuffixes(kFALSE);
//   fsql1->SetArrayLimit(1000);
//   fsql1->SetUseIndexes(1);
//   fsql1->SetTablesType("ISAM");
//   fsql1->SetUseTransactions(kFALSE);


   //  Unncomment this line to see all SQL commands in log file
   //  fsql1->StartLogFile("canvas.log");

   gBenchmark->Start("writeSQL");
   c1->Write("Canvas");
   gBenchmark->Show("writeSQL");
   delete fsql1;
}
//This macro is used to study (and calibrate) the radial dependence of the light signal. Tracks that originate at the center of the TPC are brighter than those on the side and this needs to be accounted for in energy reconstruction.
//The neutron calibration is very useful for this purpose as the tracks are quite short, which makes the radial position of the track well defined.
void DCTPCTree::Loop()
{

TStopwatch timer;
  gROOT->SetStyle("Plain");
  gStyle->SetEndErrorSize(3);
  gStyle->SetPalette(1,0);
  gStyle->SetLineWidth(2);
  gStyle->SetHistLineWidth(2);
//   gStyle->SetOptStat(kFALSE);
  gStyle->SetOptFit(kTRUE);
  TH1::AddDirectory(false);
  
  TFile *outtree = new TFile("$LittleDCTPC_neutron_calibration_input");
  TTree *dctreepc = (TTree*)outtree->Get("dctpc_eventinfo");
  DCTPCTree aStep(dctreepc);
  
  TH2D *hist_radialE=new TH2D("","",30,0,150,30,0,2.0);
  TH2D *hist_energy=new TH2D("E", "E", 100, 0, 1000, 100, 0, 1000);

double rstart=0.;
double rend=0.;

  Long64_t nentries = dctreepc->GetEntries();
  cout << "Number of Entries: " << nentries << endl;
 
  for (int event = 0; event<nentries; event++)
    {
      aStep.GetEntry(event); 
      
      if(event%10000==0)
	  cout<<((double)event/(double)nentries)*100.<<"%"<<endl;	

double rr=(pow(aStep.Track_x_pix,2)+pow(aStep.Track_y_pix,2))*pow(MMPERPIXEL/10.,2);

 //these cuts are meant to isolate short, fully contained tracks not originating from the rings. We want short tracks so that the radial position is well defined.
     if (aStep.BurnIn==0 && 
     aStep.Edge==0  && 
     (aStep.Etrack_kev-aStep.Etrig_kev)<50. && 
     aStep.Track_range_pix<80. )	
	{
	
     //this cut removes the events that are associated with a very small waveform, probably due to noise
	 if(abs((aStep.Etrig_kev)-(aStep.Etrack_kev))>1000. && (aStep.Etrig_kev)<2000.)
	 continue;

	 hist_radialE->Fill(rr,(aStep.Etrack_kev)/(aStep.Etrig_kev));	 	
	 hist_energy->Fill(aStep.Etrack_kev,aStep.Etrig_kev);	
	 	  
	 }
    
     }
 
new TCanvas;
hist_radialE->Draw("COLZ");  
  
TProfile *prof = hist_radialE->ProfileX();
new TCanvas;
prof->Draw();  


//perform a simple fit that can be used for calibrating energy as a function of radius  
TF1 *f1 = new TF1("f1","[0]/([1] +x)^[2]",0,500);
prof->Fit("f1");
  
cout<<"Param 0: "<<f1->GetParameter(0)<<endl;
cout<<"Param 1: "<<f1->GetParameter(1)<<endl;
cout<<"Param 2: "<<f1->GetParameter(2)<<endl;

//this is the original fit used in the DCTPC NIM paper. It is interesting to compare the two fits. 
TF1 *f2 = new TF1("f2","1./(pow(1+ x/(16.123*16.123),3.5857/2 ))",0,500);
f2->SetLineColor(2);
f2->Draw("SAME");

new TCanvas; 
f2->Draw();
f1->Draw("SAME");

new TCanvas;
hist_energy->Draw("COLZ");
  
}
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

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

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

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

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

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

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

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

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

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

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

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

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

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

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

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

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

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

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

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

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

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

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

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


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

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

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

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

      }
    }
  }
  else{
    telC = NULL;
  }

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

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

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

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

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

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

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


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

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

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

    neventsGR++;

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

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

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

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

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

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

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


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

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

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

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

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

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

  h->SetStats(0);

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

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


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

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

  h->Draw();
  
  new TCanvas;

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

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

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

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

  return nsecGR*1./86400;
  
}
void ClusterWidthAnalysisTreeMaker::FitProfiles(std::map<ULong64_t , std::vector<TProfile*> > &ProfVsAngle, string output_file){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Slope;
  double errSlope;
  double Origin;
  double errOrigin;
  double Chi2;
  int index;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Slope",&Slope,"Slope/D");
  tree->Branch("errSlope",&errSlope,"errSlope/D");
  tree->Branch("Origin",&Origin,"Origin/D");
  tree->Branch("errOrigin",&errOrigin,"errOrigin/D");
  tree->Branch("Chi2",&Chi2,"Chi2/D");


  //TCanvas* c1 = new TCanvas();
  TH1F* hChi2 = new TH1F("hChi2", "hChi2", 100, 0, 100);
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TProfile*> >::iterator iter = ProfVsAngle.begin(); iter != ProfVsAngle.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_prof_%u",iter->first,i);
 	  	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TProfile*  Prof = iter->second[i];
	  
	  if(!Prof) 
       { std::cout<<" Profile "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      //if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  /*if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}*/
 
	  
	  detid = iter->first;

	  bool rmfit=false;
	  
	  TF1* pol = new TF1("pol", "pol1", -3, 3);
	  pol->SetRange(-1,0);
	  Prof->Fit("pol", "qr");
	  double chi2 = pol->GetChisquare()/pol->GetNDF();
	  hChi2->Fill(chi2);
	  if(chi2>10) rmfit=true;
	  

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Prof->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Slope = pol->GetParameter(1);
	  errSlope = pol->GetParError(1);
	  Origin = pol->GetParameter(0);
	  errOrigin = pol->GetParError(0);
	  Chi2 = chi2;
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  //hNhits->Write();

  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
Exemple #7
0
void AnalysisBase::findBeamRegionAndAlign(int iPass){

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

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

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

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

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

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

      double x_trk0 = x_trk;

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

        double x_dut = getDUTHitPosition(j);

        x_trk = x_trk0;

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

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

  //hnn->Draw();

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

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

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

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

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

  //return;
  

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

}
int recoil_analysis(TString inputz, TString rootoutput, char* psoutput, int binz) {

  ifstream inputResp(inputz);
  ifstream inputSET(inputz);
  TFile* ROOTout = new TFile(rootoutput, "update");

  int theBin = -1;
  theBin = binz;


 int ptnbins = 46;
 double ptbins[] = {0.0, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0, 9.0, 
		   10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 
		    30.0, 33.0, 36.0, 39.0, 42.0, 45.0, 49.0, 55.0, 70.0, 100.0, 500.0};


  // Defines the variables  
  RooRealVar resp("resp", "u_{T}/q_{T}", 0., 30.);
  RooRealVar ZBset("ZBset", "ZB SET", 0., 40.);//was 20
  RooRealVar dphi_norm("dphi_norm", "#Delta#phi / #pi", -1., 1.);
  RooRealVar lumi("lumi", "lumi", 0., 20.);
  RooRealVar zphi("zphi", "Z #phi", 0., 2*TMath::Pi());
  RooRealVar set_ut("set_ut", "SET - u_{T}", 0., 100.);
  RooRealVar ut("ut", "u_{T}", 0., 200.); //was 200
 
  double resp_bdr[] = {20., 15., 15., 10.,10.,10., 5., 5.,5., 5.,5.,5.,3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5};
  double dphi_bdr[] = { 1.,  1.,  1., 1., 1., 1., 1., 1., 1., 1.,  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., .5, .5, .5, .5, .5, .5, .5, .5, .3, .3, .3, .3,.3,.3,.3,.3, .2, .2, .2, .2, .2, .2, .1, .1};


 int ptnbinszphi = 16;
 double ptbinszphi[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 15.0, 20.0, 30., 500.0};


 int ptnbinsset = 15;
 double ptbinsset[] = {0.0, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30., 40.0, 50.0, 70.0, 500.0};
 double set_ut_bdr[]= {20., 30., 40., 40., 50., 50., 60., 60., 60., 60., 70.,70.,70., 70., 90.};
 double ut_bdr[]=    {10., 10., 15., 15.,15., 20., 20., 25., 30., 40.,40., 60.,60.,90., 200.}; //250

  // Import the recoil (response x delta phi) from dump file 
  RooDataSet** RecoilRespData;
  RooDataSet** SETData;

  cout<<"importing data response"<<endl;
  if (theBin == -1 || theBin == -3) RecoilRespData = importRecoilRespData(inputResp, resp, ZBset, dphi_norm, lumi, zphi, ptnbins, ptbins);

  if (theBin == -2) SETData = importSETData(inputSET, set_ut, ut, ptnbinsset, ptbinsset);
  if (theBin == -4) RecoilRespData = importRecoilRespData(inputResp, resp, ZBset, dphi_norm, lumi, zphi, ptnbinszphi, ptbinszphi);
  
  inputResp.close();
  inputSET.close();
  
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0000);
  gStyle->SetPalette(1,0);
  TCanvas* c1 = new TCanvas("c1","c1");
  c1->Print(TString::Format("%s[", psoutput));



   for (int i=0; i<ptnbins; i++) {
     //this is dphi and response in bins of true phi
    if (i!=theBin && theBin != -1) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist0(0);
    TH2D* genHist1(0);
    TH2D* genHist2(0);
    TH2D* genHist3(0);
    TH2D* genHist4(0);
    TH2D* genHist5(0);

    //slightly different binning than 0-1, etc on 0 to 2pi scale to be more even on the sides (2 larger bins, rather than one)
    RooDataSet* RecoilRespData_phi0 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=0.&&zphi<1.");
    RooDataSet* RecoilRespData_phi1 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=1.&&zphi<2.");
    RooDataSet* RecoilRespData_phi2 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=2.&&zphi<3.");
    RooDataSet* RecoilRespData_phi3 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=3.&&zphi<4.");
    RooDataSet* RecoilRespData_phi4 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=4.&&zphi<5.");
    RooDataSet* RecoilRespData_phi5 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=5.");

    RecoilRespData_phi0->printMultiline(cout, 1);
    RecoilRespData_phi1->printMultiline(cout, 1);
    RecoilRespData_phi2->printMultiline(cout, 1);
    RecoilRespData_phi3->printMultiline(cout, 1);
    RecoilRespData_phi4->printMultiline(cout, 1);
    RecoilRespData_phi5->printMultiline(cout, 1);


    cout<<"RESP bin start HIST "<<i<<endl;
    genHist0 = (TH2D*) RecoilRespData_phi0->createHistogram(TString::Format("recoil_resp_hist_truephi0_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist1 = (TH2D*) RecoilRespData_phi1->createHistogram(TString::Format("recoil_resp_hist_truephi1_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist2 = (TH2D*) RecoilRespData_phi2->createHistogram(TString::Format("recoil_resp_hist_truephi2_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist3 = (TH2D*) RecoilRespData_phi3->createHistogram(TString::Format("recoil_resp_hist_truephi3_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist4 = (TH2D*) RecoilRespData_phi4->createHistogram(TString::Format("recoil_resp_hist_truephi4_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist5 = (TH2D*) RecoilRespData_phi5->createHistogram(TString::Format("recoil_resp_hist_truephi5_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
      
  
    cout<<"RESP bin start Write "<<i<<endl;
 
     genHist0->Smooth(1);
    genHist0->SetName(TString::Format("recoil_resp_hist_truephi0_bin_%d", i));
    genHist0->SetTitle(TString::Format("recoil_resp_hist_truephi0_bin_%d", i));      
    double integral0 = genHist0->Integral();
    genHist0->Scale(1/integral0);

     genHist1->Smooth(1);
    genHist1->SetName(TString::Format("recoil_resp_hist_truephi1_bin_%d", i));
    genHist1->SetTitle(TString::Format("recoil_resp_hist_truephi1_bin_%d", i));      
    double integral1 = genHist1->Integral();
    genHist1->Scale(1/integral1);

     genHist2->Smooth(1);
    genHist2->SetName(TString::Format("recoil_resp_hist_truephi2_bin_%d", i));
    genHist2->SetTitle(TString::Format("recoil_resp_hist_truephi2_bin_%d", i));      
    double integral2 = genHist2->Integral();
    genHist2->Scale(1/integral2);

     genHist3->Smooth(1);
    genHist3->SetName(TString::Format("recoil_resp_hist_truephi3_bin_%d", i));
    genHist3->SetTitle(TString::Format("recoil_resp_hist_truephi3_bin_%d", i));      
    double integral3 = genHist3->Integral();
    genHist3->Scale(1/integral3);

     genHist4->Smooth(1);
    genHist4->SetName(TString::Format("recoil_resp_hist_truephi4_bin_%d", i));
    genHist4->SetTitle(TString::Format("recoil_resp_hist_truephi4_bin_%d", i));      
    double integral4 = genHist4->Integral();
    genHist4->Scale(1/integral4);

     genHist5->Smooth(1);
    genHist5->SetName(TString::Format("recoil_resp_hist_truephi5_bin_%d", i));
    genHist5->SetTitle(TString::Format("recoil_resp_hist_truephi5_bin_%d", i));      
    double integral5 = genHist5->Integral();
    genHist5->Scale(1/integral5);



    ROOTout->cd();
    genHist0->Write(TString::Format("recoil_resp_hist_truephi0_bin_%d", i),TObject::kOverwrite);
    genHist0->Draw("colz");      
    c1->Print(psoutput);

    genHist1->Write(TString::Format("recoil_resp_hist_truephi1_bin_%d", i),TObject::kOverwrite);
    genHist1->Draw("colz");      
    c1->Print(psoutput);

    genHist2->Write(TString::Format("recoil_resp_hist_truephi2_bin_%d", i),TObject::kOverwrite);
    genHist2->Draw("colz");      
    c1->Print(psoutput);

    genHist3->Write(TString::Format("recoil_resp_hist_truephi3_bin_%d", i),TObject::kOverwrite);
    genHist3->Draw("colz");      
    c1->Print(psoutput);

    genHist4->Write(TString::Format("recoil_resp_hist_truephi4_bin_%d", i),TObject::kOverwrite);
    genHist4->Draw("colz");      
    c1->Print(psoutput);

    genHist5->Write(TString::Format("recoil_resp_hist_truephi5_bin_%d", i),TObject::kOverwrite);
    genHist5->Draw("colz");      
    c1->Print(psoutput);
  }

   for (int i=0; i<ptnbins; i++) {
     //this is zbset and response, in bins of luminosity
     if (i!=theBin && theBin != -3) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist0(0);
    TH2D* genHist1(0);
    TH2D* genHist2(0);
    TH2D* genHist3(0);
    TH2D* genHist4(0);
    TH2D* genHist5(0);
    RooDataSet* RecoilRespData_lumi0 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=0.&&lumi<2.");
    RooDataSet* RecoilRespData_lumi1 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=2.&&lumi<3.");
    RooDataSet* RecoilRespData_lumi2 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=3.&&lumi<4.");
    RooDataSet* RecoilRespData_lumi3 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=4.&&lumi<5.");
    RooDataSet* RecoilRespData_lumi4 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=5.&&lumi<6.");
    RooDataSet* RecoilRespData_lumi5 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=6.");

    RecoilRespData_lumi0->printMultiline(cout, 1);
    RecoilRespData_lumi1->printMultiline(cout, 1);
    RecoilRespData_lumi2->printMultiline(cout, 1);
    RecoilRespData_lumi3->printMultiline(cout, 1);
    RecoilRespData_lumi4->printMultiline(cout, 1);
    RecoilRespData_lumi5->printMultiline(cout, 1);


    cout<<"RESP bin start HIST "<<i<<endl;
    genHist0 = (TH2D*) RecoilRespData_lumi0->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist1 = (TH2D*) RecoilRespData_lumi1->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist2 = (TH2D*) RecoilRespData_lumi2->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist3 = (TH2D*) RecoilRespData_lumi3->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist4 = (TH2D*) RecoilRespData_lumi4->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist5 = (TH2D*) RecoilRespData_lumi5->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20
    
   
    cout<<"RESP bin start Write "<<i<<endl;

     genHist0->Smooth(1);
    genHist0->SetName(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i));
    genHist0->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i));      
    double integral0 = genHist0->Integral();
    genHist0->Scale(1/integral0);

    genHist1->Smooth(1);
    genHist1->SetName(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i));
    genHist1->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i));      
    double integral1 = genHist1->Integral();
    genHist1->Scale(1/integral1);

    genHist2->Smooth(1);
    genHist2->SetName(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i));
    genHist2->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i));      
    double integral2 = genHist2->Integral();
    genHist2->Scale(1/integral2);

    genHist3->Smooth(1);
    genHist3->SetName(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i));
    genHist3->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i));      
    double integral3 = genHist3->Integral();
    genHist3->Scale(1/integral3);

     genHist4->Smooth(1);
    genHist4->SetName(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i));
    genHist4->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i));      
    double integral4 = genHist4->Integral();
    genHist4->Scale(1/integral4);

     genHist5->Smooth(1);
    genHist5->SetName(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i));
    genHist5->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i));      
    double integral5 = genHist5->Integral();
    genHist5->Scale(1/integral5);

    ROOTout->cd();
    genHist0->Write(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i),TObject::kOverwrite);
    genHist0->Draw("colz");      
    c1->Print(psoutput);

    genHist1->Write(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i),TObject::kOverwrite);
    genHist1->Draw("colz");      
    c1->Print(psoutput);

    genHist2->Write(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i),TObject::kOverwrite);
    genHist2->Draw("colz");      
    c1->Print(psoutput);

    genHist3->Write(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i),TObject::kOverwrite);
    genHist3->Draw("colz");      
    c1->Print(psoutput);

    genHist4->Write(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i),TObject::kOverwrite);
    genHist4->Draw("colz");      
    c1->Print(psoutput);

    genHist5->Write(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i),TObject::kOverwrite);
    genHist5->Draw("colz");      
    c1->Print(psoutput);

  }
   std::vector <double>  parmMean;
   std::vector <double>  parmA;
   std::vector <double>  parmB;
   std::vector <double>  parmC;
   std::vector <double>  parmD;
   
   parmMean.clear();
   parmA.clear();
   parmB.clear();
   parmC.clear();
   parmD.clear();

  for (int i=0; i<ptnbinszphi; i++) {
     //this is zbset and response, in bins of luminosity
     if (i!=theBin && theBin != -4) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist(0);
  
    double twopi = 2*TMath::Pi();
    cout<<"RESP bin start HIST "<<i<<endl;
    genHist = (TH2D*) RecoilRespData[i]->createHistogram(TString::Format("recoil_resp_zphi_hist_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							    YVar(zphi, Binning(64, 0., twopi)));//was 40 0 20    
  
   
    cout<<"RESP bin start Write "<<i<<endl;
   
    genHist->SetName(TString::Format("recoil_resp_zphi_hist_bin_%d", i));
    genHist->SetTitle(TString::Format("recoil_resp_zphi_hist_bin_%d", i));      
    TProfile *myhisty = genHist->ProfileY();

    ROOTout->cd();
    myhisty->Write(TString::Format("recoil_resp_zphi_hist_bin_%d", i),TObject::kOverwrite);
    TF1 *pol3 = new TF1("pol3", "pol3");
    myhisty->Fit("pol3");
    double stats[7];
    myhisty->GetStats(stats); 
    parmMean.push_back(myhisty->GetMean(2));
    parmA.push_back(pol3->GetParameter(0));
    parmB.push_back(pol3->GetParameter(1));
    parmC.push_back(pol3->GetParameter(2));
    parmD.push_back(pol3->GetParameter(3));

    myhisty->Draw();  
    c1->Print(psoutput); 
  }

  if (theBin == -4){
    
      cout<<"HardRecoil_zphiresp_Mean:       ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmMean[i]<<" ";
    }
    cout<<parmMean[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterA: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmA[i]<<" ";
    }
    cout<<parmA[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterB: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmB[i]<<" ";
    }
    cout<<parmB[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterC: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmC[i]<<" ";
    }
    cout<<parmC[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterD: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmD[i]<<" ";
    }
    cout<<parmD[ptnbinszphi-1]<<endl;;
  }



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

    if (theBin != -2) continue;      
    if (SETData[i]->numEntries() < 5) continue;
    cout<<"SET bin "<<i<<endl;
    SETData[i]->printMultiline(cout, 1);
    TH2D* genHist(0);
  
    cout<<"SET bin start HIST "<<i<<endl;
    genHist = (TH2D*) SETData[i]->createHistogram(TString::Format("set_ut_kde_bin_%d", i).Data(), 
						  set_ut, Binning(500, 0., set_ut_bdr[i]),
						  YVar(ut, Binning(500, 0., ut_bdr[i]))); 
    genHist->Smooth(1);
    genHist->SetName(TString::Format("set_ut_hist_bin_%d", i));
    genHist->SetTitle(TString::Format("set_ut_hist_bin_%d", i));      
    double integral = genHist->Integral();
    genHist->Scale(1/integral);
    ROOTout->cd();
    genHist->Write(TString::Format("set_ut_hist_bin_%d", i),TObject::kOverwrite);
    genHist->Draw("colz");      
    c1->Print(psoutput);
    
  }

  c1->Print(TString::Format("%s]", psoutput));

  ROOTout->Close();

  return(0);
}
void ntuple1() {
   //Small tree analysis script
   // To see the output of this macro, click begin_html <a href="gif/ntuple1.gif">here</a> end_html
   //Author:: Rene Brun
   
   //just in case this script is executed multiple times
   delete gROOT->GetListOfFiles()->FindObject("hsimple.root");
   delete gROOT->GetListOfCanvases()->FindObject("c1");

   gBenchmark->Start("ntuple1");
   //
   // Connect ROOT histogram/ntuple demonstration file
   // generated by example $ROOTSYS/tutorials/hsimple.C.
   TFile *f1 = TFile::Open("hsimple.root");
   if (!f1) return;
   //
   // Create a canvas, with 4 pads
   //
   TCanvas *c1 = new TCanvas("c1","The Ntuple canvas",200,10,700,780);
   TPad *pad1 = new TPad("pad1","This is pad1",0.02,0.52,0.48,0.98,21);
   TPad *pad2 = new TPad("pad2","This is pad2",0.52,0.52,0.98,0.98,21);
   TPad *pad3 = new TPad("pad3","This is pad3",0.02,0.02,0.48,0.48,21);
   TPad *pad4 = new TPad("pad4","This is pad4",0.52,0.02,0.98,0.48,1);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();
   pad4->Draw();
   //
   // Change default style for the statistics box
   gStyle->SetStatW(0.30);
   gStyle->SetStatH(0.20);
   gStyle->SetStatColor(42);
   //
   // Display a function of one ntuple column imposing a condition
   // on another column.
   pad1->cd();
   pad1->SetGrid();
   pad1->SetLogy();
   pad1->GetFrame()->SetFillColor(15);
   TNtuple *ntuple = (TNtuple*)f1->Get("ntuple");
   ntuple->SetLineColor(1);
   ntuple->SetFillStyle(1001);
   ntuple->SetFillColor(45);
   ntuple->Draw("3*px+2","px**2+py**2>1");
   ntuple->SetFillColor(38);
   ntuple->Draw("2*px+2","pz>2","same");
   ntuple->SetFillColor(5);
   ntuple->Draw("1.3*px+2","(px^2+py^2>4) && py>0","same");
   pad1->RedrawAxis();
   //
   // Display the profile of two columns
   // The profile histogram produced is saved in the current directory with
   // the name hprofs
   pad2->cd();
   pad2->SetGrid();
   pad2->GetFrame()->SetFillColor(32);
   ntuple->Draw("pz:px>>hprofs","","goffprofs");
   TProfile *hprofs = (TProfile*)gDirectory->Get("hprofs");
   hprofs->SetMarkerColor(5);
   hprofs->SetMarkerSize(0.7);
   hprofs->SetMarkerStyle(21);
   hprofs->Fit("pol2");
   // Get pointer to fitted function and modify its attributes
   TF1 *fpol2 = hprofs->GetFunction("pol2");
   fpol2->SetLineWidth(4);
   fpol2->SetLineColor(2);
   //
   // Display a scatter plot of two columns with a selection.
   // Superimpose the result of another cut with a different marker color
   pad3->cd();
   pad3->GetFrame()->SetFillColor(38);
   pad3->GetFrame()->SetBorderSize(8);
   ntuple->SetMarkerColor(1);
   ntuple->Draw("py:px","pz>1");
   ntuple->SetMarkerColor(2);
   ntuple->Draw("py:px","pz<1","same");
   //
   // Display a 3-D scatter plot of 3 columns. Superimpose a different selection.
   pad4->cd();
   ntuple->Draw("pz:py:px","(pz<10 && pz>6)+(pz<4 && pz>3)");
   ntuple->SetMarkerColor(4);
   ntuple->Draw("pz:py:px","pz<6 && pz>4","same");
   ntuple->SetMarkerColor(5);
   ntuple->Draw("pz:py:px","pz<4 && pz>3","same");
   TPaveText *l4 = new TPaveText(-0.9,0.5,0.9,0.95);
   l4->SetFillColor(42);
   l4->SetTextAlign(12);
   l4->AddText("You can interactively rotate this view in 2 ways:");
   l4->AddText("  - With the RotateCube in clicking in this pad");
   l4->AddText("  - Selecting View with x3d in the View menu");
   l4->Draw();
   //
   c1->cd();
   c1->Update();
   gStyle->SetStatColor(19);
   gBenchmark->Show("ntuple1");
}
void plotPhotonType(char* var="(ecalRecHitSumEtConeDR04+hcalTowerSumEtConeDR04):genCalIsoDR04")
{
  
  TCut allCut = simpleCut + hardScatterCut;
   
  TProfile *hTemplate;
  TProfile *htmp= new TProfile("htmp","",100,0,20);
  htmp->SetXTitle("genCalIso [GeV]");
  htmp->SetYTitle("recCalIso [GeV]");

  hTemplate= getPlot(htmp,var,allCut,"MPA_PhotonJetPt15_31X.root","Analysis");
  hTemplate->SetName("hTemplate");
  hTemplate->Draw();
  gStyle->SetOptFit(11111);
  hTemplate->Fit("pol1","","");
  TF1* f1 = hTemplate->GetFunction("pol1");

  float p0 = f1->GetParameter(0);
  float p1 = f1->GetParameter(1);

  char tempName[1000];
  sprintf(tempName,
 	  "((ecalRecHitSumEtConeDR04+hcalTowerSumEtConeDR04)-genCalIsoDR04*%f):((ecalRecHitSumEtConeDR04+hcalTowerSumEtConeDR04)-genCalIsoDR04*(%f))",p1,-1.0/p1);
  cout << tempName << endl;

  TProfile *hTemplate_decompos;
  const int nbin=50;
  const float min = 0.0;
  const float max = 10.0;
  TProfile *htmp2= new TProfile("htmp2","",nbin,min,max);
  hTemplate_decompos= getPlot(htmp2,tempName,allCut,"MPA_PhotonJetPt15_31X.root","Analysis");
  hTemplate_decompos->SetName("hTemplate_decompos");
  hTemplate_decompos->Draw();  
  hTemplate_decompos->SetYTitle(Form("recCalIso-genCalIso*%.2f",p1));
  hTemplate_decompos->SetXTitle(Form("recCalIso+genCalIso*%.2f",1.0/p1));
  gStyle->SetOptFit(11111);
//   hTemplate_decompos->Fit("pol1");
  
  
  TCanvas* c1 = new TCanvas("c1","",500,1000);
  c1->Divide(1,2);
  c1->cd(1);
  hTemplate->Draw("");
  c1->cd(2);
  hTemplate_decompos->SetErrorOption("S");
  hTemplate_decompos->Draw("");
  c1->Print("bestGenCalIsoDR04.eps");
  c1->Print("bestGenCalIsoDR04.gif");
 
  TCanvas* c2 = new TCanvas("c2","",500,1000);
  c2->Divide(1,2);
  c2->cd(1);
  TH1F* hMean = new TH1F("hMean","",nbin,min,max);
  hMean->SetXTitle(Form("recCalIso+genCalIso*%.2f",1.0/p1));
  hMean->SetTitleSize(0.06,"Y");
  hMean->SetTitleOffset(1.2,"Y");
  hMean->SetYTitle(Form("Mean of recCalIso-genCalIso*%.2f",p1));
  for(int i=1; i <= nbin; i++)
    hMean->SetBinContent(i,hTemplate_decompos->GetBinContent(i));
  hMean->Draw();
  c2->cd(2);
  TH1F* hRMS = new TH1F("hRMS","",nbin,min,max);
  hRMS->SetXTitle(Form("recCalIso+genCalIso*%.2f",1.0/p1));
  hRMS->SetTitleSize(0.06,"Y");
  hRMS->SetTitleOffset(1.2,"Y");
  hRMS->SetYTitle(Form("RMS of recCalIso-genCalIso*%.2f",p1));
  for(int i=1; i <= nbin; i++)
    hRMS->SetBinContent(i,hTemplate_decompos->GetBinError(i));
  hRMS->Draw();
  c2->Print("bestGenCalIsoDR04_sup.eps");
  c2->Print("bestGenCalIsoDR04_sup.gif");


  int bestDeComposXBin = 11;
  
  float bestDeComposX = hMean->GetBinCenter(bestDeComposXBin);
  float bestDeComposY = hMean->GetBinContent(bestDeComposXBin);

  cout << "bestDeComposX = " << bestDeComposX << endl;
  cout << "bestDeComposY = " << bestDeComposY << endl;
  float bestGenIso = (bestDeComposX - bestDeComposY)/((1.0)/p1 + p1);
  float bestRecIso =  bestDeComposX - (1.0/p1) * bestGenIso;

  cout << "bestGenIso = " << bestGenIso << endl;
  cout << "bestRecIso = " << bestRecIso << endl;


}
void draw_clouds_profiles()
{
    //        gROOT->ProcessLine(".L ../utils.C");
    //        gROOT->ProcessLine(".L AliLRCFit.cxx");
    TFile *f[8];

    //    f[0] = new TFile( "output_classesByV0M_LHC10h.root" );
    //    f[0] = new TFile( "output_classesByV0M_LHC10h_c10_5_1.root" );
        f[0] = new TFile( "output_classesByV0M_LHC10h_c10_5_25_1_05.root" );
//    f[0] = new TFile( "output_classesByV0M_LHC11h_FemtoPlus_c10_5_CUT_OUTLIERS.root" );

//    f[0] = new TFile( "output_classesByV0M_LHC15o_fieldMM_c10_5_CUT_OUTLIERS.root" );
//    f[0] = new TFile( "output_classesByV0M_LHC15o_fieldPP_c10_5_CUT_OUTLIERS.root" );

//    const int nCW = 2; //nCentrWidths
//    const double cWidths[nCW] = { 10, 5 }; //width of the centrality bins
//    const double cStep[nCW] = { 5, 2.5 }; //centrality bins step
//    const int nCentrBins[nCW] = { 17, 35 }; //n centrality bins

    //    const int nCW = 3; //nCentrWidths
    //    const double cWidths[nCW] = { 10, 5, 1.0 }; //width of the centrality bins
    //    const double cStep[nCW] = { 5, 2.5, 1.0 }; //centrality bins step
    //    const int nCentrBins[nCW] = { 17, 35, 90 }; //n centrality bins

    //    const int nCW = 4; //nCentrWidths
    //    const double cWidths[nCW] = { 10, 5, 1.0, 0.5 }; //width of the centrality bins
    //    const double cStep[nCW] = { 5, 2.5, 1.0, 1.0 }; //centrality bins step
    //    const int nCentrBins[nCW] = { 17, 35, 90, 90 }; //n centrality bins

        const int nCW = 5; //nCentrWidths
        const double cWidths[nCW] = { 10, 5, 2.5, 1.0, 0.5 }; //width of the centrality bins
        const double cStep[nCW] = { 5, 2.5,  2.5, 1.0, 1.0 }; //centrality bins step
        const int nCentrBins[nCW] = { 17, 35, 36,  90, 90 }; //n centrality bins


    TH2D *hist2D;//[200][3];
    TProfile *profile;//[200][3];
    int cW = 2;
    int etaW = 1;
    int phiW = 0;

    const int kCorrType = 1; //0-NN, 1-PtPt, 2-PtN

    TCanvas *canv_tmp_for_fit = new TCanvas("canv_tmp_for_fit","canv_tmp_for_fit",50,50,300,300 );
    TCanvas *canv_2D_clouds = new TCanvas("canv_2D_clouds","canv_2D_clouds",150,250,1400,600 );
    tuneCanvas(canv_2D_clouds);
    canv_2D_clouds->Divide(2,1);

    gStyle->SetOptStat( kFALSE );

    TGraph *grFromFit2D = new TGraph;

    bool firstDraw = true;
    //    for ( int cBin = 0; cBin < nCentrBins[cW]; cBin++ )
    for ( int cBin = nCentrBins[cW]-1; cBin >= 0; cBin-- )
    {
                if (cBin%2!=0)
                    continue;

        //        cout << "cBin=" << cBin << endl;

        float cBinMin = cStep[cW] * cBin;
        float cBinMax = cWidths[cW] + cStep[cW] * cBin;

        // ##### pad 1 - clouds
        tunePad( canv_2D_clouds->cd(1) );
        if ( kCorrType == 0 )
        {
            hist2D = (TH2D*)f[0]->Get( Form("hist2D_NN_c%.1f-%.1f_etaW_%d_phiW_%d", cBinMin, cBinMax, etaW, phiW) );
            hist2D->SetTitle( "");
            hist2D->GetXaxis()->SetTitle( "N_{ch} Forward");
            hist2D->GetYaxis()->SetTitle( "N_{ch} Backward");
            hist2D->GetXaxis()->SetRangeUser(0,650);
            hist2D->GetYaxis()->SetRangeUser(0,650);
        }
        else if ( kCorrType == 1 )
        {
            hist2D = (TH2D*)f[0]->Get( Form("hist2D_PtPt_c%.1f-%.1f_etaW_%d_phiW_%d", cBinMin, cBinMax, etaW, phiW) );
            hist2D->SetTitle( "");
            hist2D->GetXaxis()->SetTitle( "#LTp_{T}#GT Forward");
            hist2D->GetYaxis()->SetTitle( "#LTp_{T}#GT Backward");
        }     hist2D->SetMarkerColor(kOrange-9+cBin);
        tuneHist2D_onPad(hist2D);
        hist2D->GetXaxis()->CenterTitle();
        hist2D->GetYaxis()->CenterTitle();

        //        removeBinsWithFewEntries(hist2D);

        hist2D->DrawCopy( firstDraw ? "" : "same" );

        // ##### pad 2 - profiles
        tunePad( canv_2D_clouds->cd(2) );
        profile = hist2D->ProfileX();    //(TProfile*)f[0]->Get( Form("hist2D_c%.1f-%.1f_etaW_%d_phiW_%d_pfx", cBinMin, cBinMax, etaW, phiW) );
        if ( kCorrType == 0 )
        {
            profile->SetTitle( "");
            profile->GetYaxis()->SetTitle( "#LTN_{ch}#GT Backward");
            profile->GetXaxis()->SetRangeUser(0,650);
            profile->GetYaxis()->SetRangeUser(0,650);
        }
        else if ( kCorrType == 1 )
        {
            profile->SetTitle( "");
            profile->GetYaxis()->SetTitle( "#LT#LTp_{T}#GT#GT Backward");
        }
        profile->SetLineColor(kOrange-9+cBin);
        profile->SetMarkerStyle(7);
        tuneProfile_onPad( profile );
        profile->GetYaxis()->CenterTitle();

        deleteProfileEmptyBinErrors(profile);


        canv_tmp_for_fit->cd();
        profile->Fit("pol1","Q");//,"",0.25,1.2);//,"N");
        canv_2D_clouds->cd(2);

        TF1 *fit = profile->GetFunction("pol1");
        Double_t p0 = fit->GetParameter(0);
        Double_t p1 = fit->GetParameter(1);
        grFromFit2D->SetPoint(grFromFit2D->GetN(), (cBinMax+cBinMin)/2, p1);

        double meanX = hist2D->ProjectionX()->GetMean();
        double rmsX = hist2D->ProjectionX()->GetRMS();
        fit->SetRange( meanX-3*rmsX, meanX+3*rmsX );
        fit->SetLineColorAlpha( kRed, 0.6 );

        fit->Draw("same");

        profile->DrawCopy( firstDraw ? "" : "same" );



        firstDraw = false;
    }

    TGraphErrors *grByFormula; /*[cW][etaW]*/
    if ( kCorrType == 0 )
    {
        grByFormula = (TGraphErrors*)f[0]->Get( Form( "grNN_c%d_eta%d", cW, etaW ) );
    }
    else if ( kCorrType == 1 )
    {
        grByFormula = (TGraphErrors*)f[0]->Get( Form( "grPtPt_c%d_eta%d", cW, etaW ) );
    }



    TCanvas *canv_GrCoeff = new TCanvas("canv_GrCoeff","canv_GrCoeff",20,150,900,700 );
    grByFormula->Draw("APL");

    grFromFit2D->SetLineColor(kRed);
    grFromFit2D->DrawClone("PL");



    return;

    TGraphErrors *gr[10][10];
    for ( int cW = 0; cW < 2; cW++ )
        for ( int etaW = 0; etaW < 3; etaW++ )
            gr[cW][etaW] = (TGraphErrors*)f[0]->Get( Form( "grPtPt_c%d_eta%d", cW, etaW ) );



    drawGraph( gr[1][0], 24, kBlack, "APL" );
    drawGraph( gr[0][0], 20, kBlack, "PL" );

    //    drawGraph( gr[1][1], 24, kBlue, "PL" );
    //    drawGraph( gr[0][1], 20, kBlue, "PL" );

    //    drawGraph( gr[1][2], 24, kGreen, "PL" );
    //    drawGraph( gr[0][2], 20, kGreen, "PL" );

    ////    drawGraph( gr[6], 24, kRed, "PL" );
    //    drawGraph( gr[7], 20, kRed, "PL" );



    f[1] = new TFile( "output_histos_graphs_LHC15o_fieldMM.root" );
    TGraphErrors *grMM[10][10];
    for ( int cW = 0; cW < 2; cW++ )
        for ( int etaW = 0; etaW < 3; etaW++ )
            grMM[cW][etaW] = (TGraphErrors*)f[1]->Get( Form( "grPtPt_c%d_eta%d", cW, etaW ) );

    drawGraph( grMM[1][0], 24, kGreen, "PL" );
    drawGraph( grMM[0][0], 20, kGreen, "PL" );

    //    drawGraph( grMM[1][1], 24, kRed, "PL" );
    //    drawGraph( grMM[0][1], 20, kRed, "PL" );

    //    drawGraph( grMM[1][2], 24, kGreen, "PL" );
    //    drawGraph( grMM[0][2], 20, kGreen, "PL" );




    //    gROOT->ProcessLine( ".q");
}
//This macro is used to study (and calibrate) the radial dependence of the light signal. Tracks that originate at the center of the TPC are brighter than those on the side and this needs to be accounted for in energy reconstruction.
void DCTPCTree::Loop()
{

TStopwatch timer;
  gROOT->SetStyle("Plain");
  gStyle->SetEndErrorSize(3);
  gStyle->SetPalette(1,0);
  gStyle->SetLineWidth(2);
  gStyle->SetHistLineWidth(2);
  gStyle->SetOptStat(kFALSE);
  gStyle->SetOptFit(kTRUE);
  TH1::AddDirectory(false);
  
  TFile *outtree = new TFile("$BigDCTPC_calibration_input");
  TTree *dctreepc = (TTree*)outtree->Get("dctpc_eventinfo");
  DCTPCTree aStep(dctreepc);
  
  TH2D *hist_radialE=new TH2D("","",30,0,600,30,0,2.);
  TH2D *hist_energy=new TH2D("E", "E", 100, 0, 1000, 100, 0, 1000);
  TH2D *hist_energy2=new TH2D("E", "E", 100, 0, 1000, 100, 0, 1000);
  
double recalibmesh = 1.;
double recalibCCD = 1.;
double recalibanode = 1.;
double rstart=0.;
double rend=0.;

  Long64_t nentries = dctreepc->GetEntries();
  cout << "Number of Entries: " << nentries << endl;
 
  for (int event = 0; event<nentries; event++)
    {
      aStep.GetEntry(event); 
      
      if(event%10000==0)
	  cout<<((double)event/(double)nentries)*100.<<"%"<<endl;	

double rr=(pow(aStep.Track_x_pix,2)+pow(aStep.Track_y_pix,2))*pow(MMPERPIXEL/10.,2);

 //these cuts are meant to isolate short, fully contained tracks not originating from the rings. We want short tracks so that the radial position is well defined.
     if (
     aStep.Edge==0  && 
     aStep.Ntrig <=2 &&
TMath::Abs((aStep.Etrig_kev-aStep.Etrack_kev)/(aStep.Etrig_kev+aStep.Etrack_kev))<0.4 &&
TMath::Abs((aStep.Etrig_kev-aStep.Emesh_kev)/(aStep.Etrig_kev+aStep.Emesh_kev))<0.1 &&
     aStep.Track_range_pix<80.
     )	
	{
 

	 hist_radialE->Fill(rr,(aStep.Etrack_kev)/(aStep.Etrig_kev));
hist_energy->Fill(aStep.Etrack_kev,aStep.Etrig_kev);  
hist_energy2->Fill(aStep.Etrig_kev,aStep.Emesh_kev);
	 
	 }
    
     }
 
new TCanvas;
hist_radialE->SetXTitle("radius (pixels)");
hist_radialE->SetYTitle("E_{CCD}/E_{anode}");
hist_radialE->Draw("COLZ");  
  
TProfile *prof = hist_radialE->ProfileX();
new TCanvas;

prof->SetYTitle("E_{CCD}/E_{anode}");
prof->Draw();  


//perform a simple fit that can be used for calibrating energy as a function fo radius  
TF1 *f1 = new TF1("f1","[0]/([1] +x)^[2]",0,440);
prof->Fit("f1","R");
  
cout<<"Param 0: "<<f1->GetParameter(0)<<endl;
cout<<"Param 1: "<<f1->GetParameter(1)<<endl;
cout<<"Param 2: "<<f1->GetParameter(2)<<endl;

//6.23665/pow(141.035+r,0.360402);

TF1 *f2 = new TF1("f2","7.56874/(146.405+x)^0.388667",0,440); 
  
f2->Draw("SAME");
new TCanvas;
hist_energy->Draw("COLZ"); 

new TCanvas;
hist_energy2->Draw("COLZ");   
  
}
// Do the extraction of the actual constants
void ExtractTimeOffsetsAndCEff(int run = 2931, TString filename = "hd_root.root") {

    // Open our input and output file
    thisFile = TFile::Open(filename);
    TFile *outputFile = TFile::Open("BCALTimeOffsetAndCEff_Results.root", "RECREATE");
    outputFile->mkdir("Fits");
    outputFile->mkdir("ResultOverview");

    // Check to make sure it is open
    if (thisFile == 0) {
        cout << "Unable to open file " << fileName.Data() << "...Exiting" << endl;
        return;
    }

    // We need to have the value of C_effective used for the position determination to get the time offsets
    double C_eff = 16.75; // cm/ns

    // Since we are updating existing constants we will need their current values. We can pipe them in from the CCDB...
    // We need a place to store them...
    double tdc_offsets[1152];
    double adc_offsets[1536];

    //Pipe the current constants into this macro
    //NOTE: This dumps the "LATEST" values. If you need something else, modify this script.
    char command[100];
    sprintf(command, "ccdb dump /BCAL/TDC_offsets:%i:default", run);
    FILE* locInputFile = gSystem->OpenPipe(command, "r");
    if(locInputFile == NULL)
        return 0;
    //get the first (comment) line
    char buff[1024];
    if(fgets(buff, sizeof(buff), locInputFile) == NULL)
        return 0;
    //get the remaining lines
    double time;
    int counter = 0;
    while(fgets(buff, sizeof(buff), locInputFile) != NULL) {
        istringstream locConstantsStream(buff);
        locConstantsStream >> time;
        cout << "TDC Time Offset = " << time << endl;
        tdc_offsets[counter] = time;
        counter++;
    }
    if (counter != 1152) cout << "Wrong number of TDC entries (" << counter << " != 1152)?" << endl;
    //Close the pipe
    gSystem->ClosePipe(locInputFile);

    sprintf(command, "ccdb dump /BCAL/ADC_timing_offsets:%i:default", run);
    locInputFile = gSystem->OpenPipe(command, "r");
    if(locInputFile == NULL)
        return 0;
    //get the first (comment) line
    char buff[1024];
    if(fgets(buff, sizeof(buff), locInputFile) == NULL)
        return 0;
    //get the remaining lines
    counter = 0;
    while(fgets(buff, sizeof(buff), locInputFile) != NULL) {
        istringstream locConstantsStream(buff);
        locConstantsStream >> time;
        cout << "ADC Time Offset = " << time << endl;
        adc_offsets[counter] = time;
        counter++;
    }
    if (counter != 1536) cout << "Wrong number of ADC entries (" << counter << " != 1536)?" << endl;
    //Close the pipe
    gSystem->ClosePipe(locInputFile);

    // This stream will be for outputting the results in a format suitable for the CCDB
    // Will wait to open until needed
    ofstream adcOffsetFile, tdcOffsetFile;
    adcOffsetFile.open("ADCOffsetsBCAL.txt");
    tdcOffsetFile.open("TDCOffsetsBCAL.txt");

    // Declaration of the fit funtion
    TF1 *f1 = new TF1("f1", "[0]+[1]*x", -200, 200);
    f1->SetParLimits(0, -20.0, 20.0);
    f1->SetParLimits(1, 0.85, 1.15);
    outputFile->cd("ResultOverview");
    // Make some histograms to get the distributions of the fit parameters
    TH1I *h1_c0 = new TH1I("h1_c0", "Distribution of parameter c_{0}", 100, -15, 15);
    TH1I *h1_c1 = new TH1I("h1_c1", "Distribution of parameter c_{1}", 100, 0.85, 1.15);
    TH1F *h1_c0_all = new TH1F ("h1_c0_all", "Value of c0; CCDB Index; c0 [cm]", 768, 0.5, 768.5);
    TH1F *h1_c1_all = new TH1F ("h1_c1_all", "Value of c1; CCDB Index; c1 [cm]", 768, 0.5, 768.5);
    TH2I *h2_c0_c1 = new TH2I("h2_c0_c1", "c_{1} Vs. c_{0}; c_{0}; c_{1}", 100, -15, 15, 100, 0.85, 1.15);

    // Fit the global offset histogram to get the per channel global offset
    double globalOffset[768];
    TH1D * selectedBCALOffset = new TH1D("selectedBCALOffset", "Selected Global BCAL Offset; CCDB Index; Offset [ns]", 768, 0.5, 768 + 0.5);
    TH1I * BCALOffsetDistribution = new TH1I("BCALOffsetDistribution", "Global BCAL Offset; Global Offset [ns]; Entries", 100, -10, 10);

    thisHist = Get2DHistogram("BCAL_Global_Offsets", "Target Time", "Target Time Minus RF Time Vs. Cell Number");
    if(thisHist != NULL) {
        int nBinsX = thisHist->GetNbinsX();
        int nBinsY = thisHist->GetNbinsY();
        for (int i = 1 ; i <= nBinsX; i++) {
            TH1D *projY = thisHist->ProjectionY("temp", i, i);
            // Scan over the histogram
            float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX();
            float timeWindow = 0.5; //ns (Full Width)
            int binWindow = int(timeWindow / nsPerBin);
            double maxEntries = 0;
            double maxMean = 0;
            for (int j = 1 ; j <= projY->GetNbinsX(); j++) {
                int minBin = j;
                int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX();
                double sum = 0, nEntries = 0;
                for (int bin = minBin; bin <= maxBin; bin++) {
                    sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin);
                    nEntries += projY->GetBinContent(bin);
                    if (bin == maxBin) {
                        if (nEntries > maxEntries) {
                            maxMean = sum / nEntries;
                            maxEntries = nEntries;
                        }
                    }
                }
            }
            globalOffset[i-1] = maxMean;
            selectedBCALOffset->SetBinContent(i, maxMean);
            BCALOffsetDistribution->Fill(maxMean);
        }
    }

    outputFile->cd("Fits");
    // Now we want to loop through all available module/layer/sector and try to make a fit of each one
    for (unsigned int iModule = 1; iModule <=48; iModule++) {
        for (unsigned int iLayer = 1; iLayer <= 4; iLayer++) { // Only 3 layers with TDCs
            for (unsigned int iSector = 1; iSector <= 4; iSector++) {
                int the_cell = (iModule - 1) * 16 + (iLayer - 1) * 4 + iSector;
                int the_tdc_cell = (iModule - 1) * 12 + (iLayer - 1) * 4 + iSector; // One less layer of TDCs
                // Format the string to lookup the histogram by name
                char name[200];
                sprintf(name, "Module %.2i Layer %.2i Sector %.2i", iModule, iLayer, iSector);

                // These histograms are created on the fly in the plugin, so there is a chance that they do not exist, in which case the pointer will be NULL

                TH2I *h_offsets   = Get2DHistogram ("BCAL_TDC_Offsets", "Z Position", name);

                // Use FitSlicesY routine to extract the mean of each x bin
                TObjArray ySlices;

                if (h_offsets != NULL) {
                    h_offsets->RebinX(5);
                    TProfile *profile = h_offsets->ProfileX();
                    f1->SetParameters(0, 1); // Just out initial guess
                    TFitResultPtr fr = profile->Fit(f1, "SQR");
                    Int_t fitStatus = fr;
                    if (fitStatus == 0) {
                        double c0 = fr->Parameter(0);
                        double c0_err = fr->ParError(0);
                        double c1 = fr->Parameter(1);
                        double c1_err = fr->ParError(1);
                        if (c0 == 10.0 || c0 == -10.0 || c1 == 0.9 || c1 == 1.1) {
                            cout << "WARNING: Parameter hit limit " << name << endl;
                        }
                        h1_c0->Fill(c0);
                        h1_c1->Fill(c1);
                        h2_c0_c1->Fill(c0,c1);
                        h1_c0_all->SetBinContent(the_cell, c0);
                        h1_c0_all->SetBinError(the_cell, c0_err);
                        h1_c1_all->SetBinContent(the_cell, c1);
                        h1_c1_all->SetBinError(the_cell, c1_err);
                        adcOffsetFile << adc_offsets[(the_cell - 1) * 2] + 0.5 * c0 / C_eff + globalOffset[the_cell] << endl;
                        adcOffsetFile << adc_offsets[ the_cell*2 - 1] - 0.5 * c0 / C_eff + globalOffset[the_cell] << endl;
                        if (iLayer != 4) {
                            tdcOffsetFile << tdc_offsets[(the_tdc_cell - 1) * 2] + 0.5 * c0 / C_eff + globalOffset[the_cell] << endl;
                            tdcOffsetFile << tdc_offsets[the_tdc_cell*2 - 1] - 0.5 * c0 / C_eff + globalOffset[the_cell] << endl;
                        }
                    }
                    else {
                        cout << "WARNING: Fit Status "<< fitStatus << " for Upstream " << name << endl;
                        adcOffsetFile << adc_offsets[(the_cell - 1) * 2] + globalOffset[the_cell] << endl;
                        adcOffsetFile << adc_offsets[the_cell*2 - 1] + globalOffset[the_cell] << endl;
                        if (iLayer != 4) {
                            tdcOffsetFile << tdc_offsets[(the_tdc_cell - 1) * 2] + globalOffset[the_cell] << endl;
                            tdcOffsetFile << tdc_offsets[the_tdc_cell*2 - 1] + globalOffset[the_cell] << endl;
                        }
                    }
                }
                else {
                    adcOffsetFile << adc_offsets[ (the_cell-1) * 2] + globalOffset[the_cell] << endl;
                    adcOffsetFile << adc_offsets[  the_cell*2  - 1] + globalOffset[the_cell] << endl;
                    if (iLayer != 4) {
                        tdcOffsetFile << tdc_offsets[(the_tdc_cell -1) * 2] + globalOffset[the_cell] << endl;
                        tdcOffsetFile << tdc_offsets[ the_tdc_cell*2 - 1] + globalOffset[the_cell] << endl;
                    }
                }
            }
        }
    }
    adcOffsetFile.close();
    tdcOffsetFile.close();
    outputFile->Write();
    thisFile->Close();
    return;
}
Exemple #14
0
//______________________________________________________________________________
void Ifit2()
{
  file = new TFile("run41800dETIFWC1.root");
  Bool_t IsFWC1 = kTRUE;

  TMinuit *minuit = new TMinuit(3);
  minuit->SetFCN(fcn);
  Double_t arglist[10];
  Int_t ierflg;      
     
  //ToF peak position from MC
  Double_t ToFFWC1Theta[6] =
    {
      2.088228e+01,2.092216e+01,2.112093e+01,2.149825e+01,2.212018e+01,2.297665e+01
    };
  
  Double_t ToFFWC2Theta[6] =
   {
     1.976750e+01,1.988218e+01,2.025691e+01,2.078644e+01,2.158632e+01,2.263857e+01
   };
  
  Double_t ToFFWCTheta[6];
  for(Int_t i = 0; i<6; i++){
    if(IsFWC1)  ToFFWCTheta[i] = ToFFWC1Theta[i];
   else ToFFWCTheta[i] = ToFFWC2Theta[i];
  }

  //  Int_t nbin = 3;

  TH2D* hdEToF[6][24];
  TF1*  fFit[6][24];
 
  for(Int_t el = 1; el<25; el++){
    Double_t vstart[3]; 
    for(Int_t bin = 1; bin<7; bin++){
       
      hdEToF[bin-1][el-1] = (TH2D*)file->Get(Form("hToFFWCdEFWC_bin%02d_ifwc%02d",bin,el));
      hdE = hdEToF[bin-1][el-1];

      //err x and y
      //So here I fit x coordinate of THE point
      //Then I calculate where I would like to cut the whole thing off
      TF1* g1 = new TF1("g1","gaus",15.,28.);  
      Double_t maxt = ToFFWCTheta[bin-1];
      hdE->ProjectionX("hproj1")->Fit("g1", "IQ", "", maxt-2.5, maxt+2.5);
      merrx = g1->GetParameter(2);
      cutx = maxt+3*merrx;
      

      //Same for y.
      TF1* g2 = new TF1("g2","gaus",0.,4000.);
      Int_t BinDown = hdE->GetXaxis()->FindBin(maxt-2.5);
      Int_t BinUp = hdE->GetXaxis()->FindBin(maxt+2.5);
      Double_t maxy = hdE->ProjectionY()->GetMaximumBin();
      Double_t maxdE = hdE->GetYaxis()->GetBinCenter(maxy);
      hdE->ProjectionY("hproj2",BinDown,BinUp)->Fit("g2", "I", "", maxdE-500., maxdE+500);
      merry = g2->GetParameter(2);
      cuty = maxdE+5*merry;
      
      cout<<"err: "<<merrx<<" "<<merry<<endl;
      cout<<"cut: "<<cutx<<" "<<cuty<<endl;
      //Ranges of fitting 
      nbinsx = hdE->GetXaxis()->FindBin(38.);     
      nbinx0 = hdE->GetXaxis()->FindBin(maxt+4*merrx);

      //I set range of fitting in y
      Int_t up = hdE->GetYaxis()->GetNbins();
      nbinsy = up;            
      Int_t nentr = hdE->GetEntries();
      for(Int_t i=0; i<nbinsy; i++){
			if(i<maxy) continue;
			if(hdE->ProjectionX("hproj",i+1,i+1)->GetEntries()<0.0005*nentr){
	  			nbinsy = i+1; 
	}
      }
      
      cout<<"x range: "<<maxt+4*merrx<<" - "<<38.<<endl;
      cout<<"Y range: "<<hdE->GetYaxis()->GetBinCenter(nbinsy)<<endl;
     
      //3Hen peak position
      ym = maxdE;
      xm =  hdE->GetXaxis()->GetBinCenter(hdE->ProjectionX()->GetMaximumBin());
      cout<<" xm, ym: "<<xm<<" "<<ym<<endl;

      //Fit to profile - start parameters
      TF1* g0 = new TF1("g0","pol2",15.,38.);
      TProfile* pp;
      pp = hdE->ProfileX();
      pp->Fit("g0","IQ","0",maxt-5*merrx,/*hdE->GetXaxis()->GetBinCenter(nbinsx)*/38.);   
      
      //initialize TMinuit with a maximum of 3 params
      ierflg = 0;
      arglist[0] = 1;
      minuit->mnexcm("SET ERR", arglist ,1,ierflg);
      
      // Set starting values and step sizes for parameters
      if(bin<5){
		vstart[0] = g0->GetParameter(2);
		vstart[1] = g0->GetParameter(1);
	//	vstart[2] = g0->GetParameter(0);
      }

      Double_t step[3] = {0.01 , 1. , 10.};
      minuit->mnparm(0, "a", vstart[0], step[0], 0,0,ierflg);
      minuit->mnparm(1, "b", vstart[1], step[1], 0,0,ierflg);
      // minuit->mnparm(2, "c", vstart[2], step[2], 0,0,ierflg);
      
      // Now ready for minimization step
      arglist[0] = 1500;
      arglist[1] = 1;
      minuit->mnexcm("MIGRAD", arglist ,2,ierflg);
      
      // Print results
      Double_t amin,edm,errdef;
      Int_t nvpar,nparx,icstat;
      minuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      //gMinuit->mnprin(3,amin);
      
      // get parameters
      
      double pval[2],perr[2],plo[2],phi[2];
      
      TString para0,para1,para2;
      
      int istat;
      
      minuit->mnpout(0,para0,pval[0],perr[0],plo[0],phi[0],istat);
      minuit->mnpout(1,para1,pval[1],perr[1],plo[1],phi[1],istat);
      //minuit->mnpout(2,para2,pval[2],perr[2],plo[2],phi[2],istat);
      
      fFit[bin-1][el-1] = new TF1(Form("fFit_bin%02d_el%02d",bin,el), "pol2", 0., 40.); 
      fFit[bin-1][el-1]->FixParameter(2, pval[0]);
      fFit[bin-1][el-1]->FixParameter(1, pval[1]);
      fFit[bin-1][el-1]->FixParameter(0, ym - pval[0]*xm*xm - pval[1]*xm);
    }
  }

  TCanvas* cc[6];
  for(Int_t el=0; el<6; el++){
    cc[el] = new TCanvas(Form("c_el%02d",el),Form("c_el%02d",el),1350,950);
    cc[el]->Divide(4,6);

    for(Int_t bin = 0; bin<24; bin++){  
      cc[el]->cd(bin+1);
      hdEToF[el][bin]->Draw("colz");
      fFit[el][bin]->Draw("same");
    }  
  }

}