Example #1
0
//------------------------------------------------------------------------
void fitSlices(TH2* hCorr, TF1* func){

   int nBins = hCorr->GetNbinsX();

   TH1D* hMean = new TH1D(Form("%s_1",hCorr->GetName()),"",nBins,hCorr->GetXaxis()->GetXmin(),hCorr->GetXaxis()->GetXmax());
   TH1D* hSigma = new TH1D(Form("%s_2",hCorr->GetName()),"",nBins,hCorr->GetXaxis()->GetXmin(),hCorr->GetXaxis()->GetXmax());

   for(int i = 1; i < nBins+1; i++){
      int bin = nBins - i;
      TH1D* h = hCorr->ProjectionY(Form("%s_bin%d",hCorr->GetName(),bin),i,i);

      func->SetParameter(0,h->GetMaximum());
      func->SetParameter(1,h->GetMean());
      func->SetParameter(2,h->GetRMS());

      h->Fit(func,"Q");

      /*hMean->SetBinContent(i,func->GetParameter(1));
      hMean->SetBinError(i,func->GetParError(1));
      hSigma->SetBinContent(i,func->GetParameter(2));
      hSigma->SetBinError(i,func->GetParError(2));*/

      hMean->SetBinContent(i,h->GetMean());
      hMean->SetBinError(i,func->GetParError(1)); //errors are not use later for the actual table
      hSigma->SetBinContent(i,h->GetRMS());
      hSigma->SetBinError(i,func->GetParError(2));

   }
}
Example #2
0
int main(int argc, char* argv[]){

	double initP = atof(argv[1]);
	
	//let should add script to run all models, then individual rms can be extracted from the rms file

// Path to Histograms  	
TFile *f = new TFile("../../EventOutputs/ResultHistos_Minimalist.root");
TFile *f_2 = new TFile("../../EventOutputs/ResultHistos_Minimalist2.root");
	//grab the pi0 energy sum from the result histos file
	//histogram of the minimalist energy sum
	//TH1D * minRMS = (TH1D*)f->Get("hESumConstrained");
	//histogram of the elimination method and minimization fit Energy vaules
	//TH1D * elimRMS = (TH1D*)f->Get("hEfitSum");
	//measured value of pi0 energy
	//TH1D * measRMS = (TH1D*)f->Get("hESum");


	//pull the RMS from the histograms
	//double 	min = minRMS->GetRMS();
	//double elim = elimRMS->GetRMS();
	//double meas = measRMS->GetRMS();

//        double myrms = (TH1D*)f->Get("hEfitSum")->GetRMS();


	//get the minimimalist stuff
	TH1D * minRMS = (TH1D*)f->Get("hmass_min");
	TH1D * measRMS = (TH1D*)f_2->Get("hmass_m");
	TH1D * min2RMS = (TH1D*)f_2->Get("hmass_min2");

	double min = minRMS->GetRMS();
	double meas = measRMS->GetRMS();
	double min2 = min2RMS->GetRMS();
	//append the RMS to a text file
	
	std::ofstream f1;
	std::ofstream f2;
	std::ofstream f3;
	f1.open("RMSmin.txt", std::ofstream::out | std::ofstream::app);
	f2.open("RMSmin2.txt", std::ofstream::out | std::ofstream::app);
	
	f3.open("RMSmeas.txt", std::ofstream::out | std::ofstream::app);

	f1<<std::setprecision(9);
	f2<<std::setprecision(9);
	f3<<std::setprecision(9);
	//f1<<meas<<" "<<min<<" "<<elim<<" "<<initP<<std::endl;
	f1<<meas<<" "<<min<<" "<<initP<<std::endl;
	f2<<meas<<" "<<min2<<" "<<initP<<std::endl;
	f3<<meas<<" "<<initP<<std::endl;

	f1.close();
	f2.close();
	f3.close();
	
	return 0;


}
Example #3
0
void fitSlices(TH2* hCorr, TF1* func){

   int nBins = hCorr->GetNbinsX();

   TH1D* hMean = new TH1D(Form("%s_1",hCorr->GetName()),"",nBins,hCorr->GetXaxis()->GetXmin(),hCorr->GetXaxis()->GetXmax());
   TH1D* hSigma = new TH1D(Form("%s_2",hCorr->GetName()),"",nBins,hCorr->GetXaxis()->GetXmin(),hCorr->GetXaxis()->GetXmax());

   for(int i = 1; i < nBins+1; ++i){
      int bin = nBins - i;
      TH1D* h = hCorr->ProjectionY(Form("%s_bin%d",hCorr->GetName(),bin),i,i);

      func->SetParameter(0,h->GetMaximum());
      func->SetParameter(1,h->GetMean());
      func->SetParameter(2,h->GetRMS());

      if(useFits) h->Fit(func);

      hMean->SetBinContent(i,func->GetParameter(1));
      hMean->SetBinError(i,func->GetParError(1));
      hSigma->SetBinContent(i,func->GetParameter(2));
      hSigma->SetBinError(i,func->GetParError(2));
      
      if(onlySaveTable){
	 h->Delete();
      }
   }
}
Example #4
0
TH1D * smartGausProfileXSQRTN (TH2F * strip, double width){
 TProfile * stripProfile = strip->ProfileX () ;
 
 // (from FitSlices of TH2.h)
 
 double xmin = stripProfile->GetXaxis ()->GetXmin () ;
 double xmax = stripProfile->GetXaxis ()->GetXmax () ;
 int profileBins = stripProfile->GetNbinsX () ;
 
 std::string name = strip->GetName () ;
 name += "_smartGaus_X" ; 
 TH1D * prof = new TH1D(name.c_str (),strip->GetTitle (),profileBins,xmin,xmax) ;
 
 int cut = 0 ; // minimum number of entries per fitted bin
 int nbins = strip->GetXaxis ()->GetNbins () ;
 int binmin = 1 ;
 int ngroup = 1 ; // bins per step
 int binmax = nbins ;
 
 // loop over the strip bins
 for (int bin=binmin ; bin<=binmax ; bin += ngroup) 
 {
  TH1D *hpy = strip->ProjectionY ("_temp",bin,bin+ngroup-1,"e") ;
  if (hpy == 0) continue ;
  int nentries = Int_t (hpy->GetEntries ()) ;
  if (nentries == 0 || nentries < cut) {delete hpy ; continue ;} 
  
  Int_t biny = bin + ngroup/2 ;
  
  TF1 * gaussian = new TF1 ("gaussian","gaus", hpy->GetMean () - width * hpy->GetRMS (), hpy->GetMean () + width * hpy->GetRMS ()) ; 
  gaussian->SetParameter (1,hpy->GetMean ()) ;
  gaussian->SetParameter (2,hpy->GetRMS ()) ;
  hpy->Fit ("gaussian","RQL") ;           
  
  //       hpy->GetXaxis ()->SetRangeUser ( hpy->GetMean () - width * hpy->GetRMS (), hpy->GetMean () + width * hpy->GetRMS ()) ;         
  prof->Fill (strip->GetXaxis ()->GetBinCenter (biny), gaussian->GetParameter (1)) ;       
  prof->SetBinError (biny,gaussian->GetParameter (2) / sqrt(hpy->GetEntries())) ;
//   prof->SetBinError (biny,gaussian->GetParError (1)) ;
  
  delete gaussian ;
  delete hpy ;
 } // loop over the bins
 
 delete stripProfile ;
 return prof ;
}
Example #5
0
void testResult(){
  
  std::ifstream ifs0("simGain.txt");
  std::ifstream ifs1("CalibrationN.txt");
  if( !ifs0.is_open() ){return;}
  if( !ifs1.is_open() ){return;}

  TH1D* hisGain = new TH1D("test","",200,0,2);
  TH1D* hisInit = new TH1D("test1","",200,0,2);
  double cal0;
  double cal1;
  double calfactor0[2716]={0};
  double calfactor1[2716]={0};
  
  Int_t  N;
  Int_t ID;
  while( !ifs0.eof() ){
    ifs0 >> ID >> cal0;
    calfactor0[ID] = cal0;
    std::cout<< ID << std::endl;
  }

  while( !ifs1.eof() ){
    ifs1 >> ID >> cal1 >> N;
    std::cout<< ID << std::endl;
    calfactor1[ID] = cal1;
  }
  
  for( int i = 0; i< 2716; i++){
    if(calfactor0[i] ==0 || calfactor1[i] ==0){
      continue;
    }
    hisGain->Fill(calfactor0[i]/calfactor1[i]);
    hisInit->Fill(calfactor0[i]);
  }
  hisGain->Draw();
  hisInit->SetLineColor(2);
  hisInit->Draw("same");

  std::cout<< hisGain->GetRMS()/hisGain->GetMean() << "\t"
	   << hisInit->GetRMS()/hisInit->GetMean() << std::endl;
}
void GaussianProfile::getTruncatedMeanRMS(TH1* hist, float& mean, float& mean_error, float& rms, float& rms_error) {
  int nBins = hist->GetNbinsX();
  double xMin = hist->GetXaxis()->GetXmin();
  double xMax = hist->GetXaxis()->GetXmax();
  //double binWidth = (xMax - xMin) / (double) nBins; //WARNING: this works only if bins are of the same size
  double integral = hist->Integral();

  int maxBin = 0;
  TF1* gaussian = new TF1("gaussian", "gaus");
  fitProjection(hist, gaussian, 1.5, "RQN");
  //maxBin = (int) ceil((gaussian->GetParameter(1) - xMin) / binWidth);
  maxBin = hist->FindBin(gaussian->GetParameter(1));
  delete gaussian;

  TH1D* newHisto = new TH1D("newHisto", "", nBins, xMin, xMax);
  newHisto->SetBinContent(maxBin, hist->GetBinContent(maxBin));
  newHisto->SetBinError(maxBin, hist->GetBinError(maxBin));
  int iBin = maxBin;
  int delta_iBin = 1;
  int sign  = 1;

  while (newHisto->Integral() < 0.99 * integral) {
    iBin += sign * delta_iBin;

    newHisto->SetBinContent(iBin, hist->GetBinContent(iBin));
    newHisto->SetBinError(iBin, hist->GetBinError(iBin));

    delta_iBin += 1;
    sign *= -1;
  }

  rms = newHisto->GetRMS();
  rms_error = newHisto->GetRMSError();

  while (newHisto->Integral() < 0.99 * integral) {
    iBin += sign * delta_iBin;

    newHisto->SetBinContent(iBin, hist->GetBinContent(iBin));
    newHisto->SetBinError(iBin, hist->GetBinError(iBin));

    delta_iBin += 1;
    sign *= -1;
  }

  mean = newHisto->GetMean();
  mean_error = newHisto->GetMeanError();

  delete newHisto;
}
Example #7
0
//_____________________________________________________________________________
TH1D *SetRMS(TH2D *h2, const TString s)
{
  TH1D *h = h2->ProjectionX(s.Data()); h->Reset();
  for (Int_t kx=1; kx<=h2->GetNbinsX(); kx++) {
    TH1D *hTmp = h2->ProjectionY(Form("hTmp_%d",kx), kx, kx);

    if (hTmp->Integral()<=0.)
      h->SetBinContent(kx, 0.);
    else
      h->SetBinContent(kx, hTmp->GetRMS());

      cout << h->GetBinContent(kx) << endl;
    delete hTmp; hTmp = 0;
  }

  return h;
}
Example #8
0
	double FitConfidence::choleskyUncertainty( double xx, double * fCov, TF1 * f, int nSamples ){
		int nP = f->GetNpar();
		INFO( FitConfidence::classname(), "Num Params : " << nP  );
		
		double *fCovSqrt = new double[ nP * nP ];
		calcCholesky( nP, fCov, fCovSqrt );

		double yerr = 0;

		TH1D *hDistributionAtX = new TH1D("hDistributionAtX","",200,f->Eval(xx) - .2,f->Eval(xx) + .2);
		
		for (int n = 0; n < nSamples; n++ ) {
			double val = randomSqrtCov(xx,f,nP,fCovSqrt);
			hDistributionAtX->Fill( val );
		}
		yerr = hDistributionAtX->GetRMS();
		hDistributionAtX->Delete();

		return yerr;

	}
Example #9
0
void chipHistos(const char *filenames = "/export/data1/dambach/hardware/ntpls/gradeA/*.root")
{

  Init();      // do not forget to load the Utilities.C

  TH1D *gainH = new TH1D("gainH", "RMS(gain)/Mean(gain)", 100, 0., 0.2);
  TH1D *pedH = new TH1D("pedH", "RMS(pedestal)", 100, 0., 100.);
  TH1D *noiseH = new TH1D("noiseH", "RMS(trimmed threshold)", 100, 0., 8.);
  TH1D *tthrH = new TH1D("tthrH", "Mean (trimmed threshold)", 100, 50., 70.);
  
  TH1D *gainDist = new TH1D("gainDist", "gainR/gainM", 100, 0., 10.);
  TH1D *pedDist = new TH1D("pedDist", "pedR", 100, -1000., 1000.);
  
  TChain *c = new TChain("mod");
  c->Add(filenames);
  
  float ped[16][4160], gain[16][4160];
  int defects[16][4160];
  c->SetBranchAddress("ped", ped); 
  c->SetBranchAddress("gain", gain);
  c->SetBranchAddress("defects", defects);
  
  int nb(0), nbytes(0);
  
  for (int i = 0; i < c->GetEntries(); ++i)
    {
      nb = c->GetEntry(i);   nbytes += nb;
      
      
      for(int chipId = 0; chipId < 16; chipId++)
	{
	  gainDist->Reset();
	  pedDist->Reset();
	  
	  int allPix = 4160; 
	  for (int p = 0; p < allPix; p++)
	    {
	      if(defects[chipId][p] == 0)
		{
		  gainDist->Fill(gain[chipId][p]);
		  pedDist->Fill(ped[chipId][p]);	      
		}
	    }
	  double gainRMS = gainDist->GetRMS();
	  double pedRMS = pedDist->GetRMS();
	  double gainMean = gainDist->GetMean();
	  double pedMean = pedDist->GetMean();
	  
	  if (gainMean != 0) gainH->Fill(gainRMS/gainMean);
	  pedH->Fill(pedRMS);
	}
    }
  
  canvas->Clear();
  canvas->Divide(2,2);
  
  canvas->cd(1);
  InitPad("log");
  gainH->GetXaxis()->SetTitle("DAC units");
  gainH->GetYaxis()->SetTitle("# pixels");
  gainH->GetXaxis()->SetTitleSize(0.055);
  gainH->GetYaxis()->SetTitleSize(0.055);
  gainH->Draw();
  
  canvas->cd(2);
  InitPad("log");
  pedH->GetXaxis()->SetTitle("DAC units");
  pedH->GetYaxis()->SetTitle("# pixels");
  pedH->GetXaxis()->SetTitleSize(0.055);
  pedH->GetYaxis()->SetTitleSize(0.055);
  pedH->Draw();

  canvas->cd(3);
  InitPad("log");
  noiseH->GetXaxis()->SetTitle("DAC units");
  noiseH->GetYaxis()->SetTitle("# pixels");
  noiseH->GetXaxis()->SetTitleSize(0.055);
  noiseH->GetYaxis()->SetTitleSize(0.055);
  c->Draw("tthrR>>noiseH");

  canvas->cd(4);
  InitPad("log");
  tthrH->SetMinimum(0.5);
  tthrH->GetXaxis()->SetTitle("DAC units");
  tthrH->GetYaxis()->SetTitle("# pixels");
  tthrH->GetXaxis()->SetTitleSize(0.055);
  tthrH->GetYaxis()->SetTitleSize(0.055);
  c->Draw("tthrM>>tthrH");

}
void writeSignalHistosForModel(std::vector<TH1D *>& vsd,
			       const TString& sigmodel,
			       TFile *allHistFile)
{
  for (int ichan=0; ichan<NUMCHAN; ichan++) {
    TH1D * sdh = vsd[ichan];

    // Find limit window from gaussian fit to signal peak.
    //
    double wid  = sdh->GetRMS();
    double mean = sdh->GetMean();

    //TCanvas *c1 = new TCanvas(s,s,300,300);
    TFitResultPtr r = sdh->Fit("gaus","QNS","",mean-2.5*wid,mean+2.5*wid);

    cout<<" mean= "<<mean<<", RMS= "<<wid<<", Fit sigma= "<<r->Parameter(2)<<endl;
    //cout<<r->Parameter(0)<<" "<<r->Parameter(1)<<" "<<r->Parameter(2)<<endl;

    TAxis *xax = sdh->GetXaxis();

#if 0
    int lobin = xax->FindFixBin(r->Parameter(1)-2*r->Parameter(2));
    int hibin = xax->FindFixBin(r->Parameter(1)+2*r->Parameter(2));
    sd.sumwinmin = xax->GetBinLowEdge(lobin);
    sd.sumwinmax = xax->GetBinUpEdge(hibin);
#elif 0
    int lobin = xax->FindFixBin(140);   sd.sumwinmin=140; // 1 bin  left,
    int hibin = xax->FindFixBin(170)-1; sd.sumwinmax=170; // 2 bins right
#else
    int lobin = xax->FindFixBin(sumwinmin);
    int hibin = xax->FindFixBin(sumwinmax)-1;
#endif
    int nbins = hibin-lobin+1;

    // for variable binning - all histos must have the same binning per channel
    TVectorD xbins   = TVectorD(sdh->GetNbinsX(),sdh->GetXaxis()->GetXbins()->GetArray());
    TVectorD xwindow = xbins.GetSub(lobin-1,hibin);

    xax->SetRange(lobin,hibin);

    // Copy contents to window-restricted signal histogram
    // and write to output file.
    //
    TString name = Form("Signal%s_%s",sigmodel.Data(),channames[ichan]);
    printf("Booking TH1D(%s,%s,%d,xwindowarray)\n",
	   name.Data(),sdh->GetTitle(),nbins);
    TH1D *signm = new TH1D(name.Data(),
			   sdh->GetTitle(),
			   nbins,
			   xwindow.GetMatrixArray());

    // make copies of the histograms that are restricted to the
    // bin range lobin-hibin
    //
    for (int ibin=lobin; ibin<=hibin; ibin++) 
      signm->SetBinContent((ibin-lobin+1),
			   sdh->GetBinContent(ibin)
			   *sdh->GetBinWidth(ibin)
			   );

    if (!sigmodel.CompareTo("wh"))
      signm->Scale(whsigscaleto);
    else
      signm->Scale(sigscaleto);

    allHistFile->WriteTObject(signm);

  } // channel loop
}                                                     // writeSignalHistosForModel
Example #11
0
void chipSummary(const char *dirName, int chipId, int TrimVcal)
{
	if (f && f->IsOpen()) f->Close();
	//	if (f1 && f1->IsOpen()) f1->Close();
	if (g && g->IsOpen()) g->Close();

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

	gStyle->SetStatFont(132);
	gStyle->SetTextFont(132);
	gStyle->SetLabelFont(132, "X");
	gStyle->SetLabelFont(132, "Y");
	gStyle->SetLabelSize(0.08, "X");
	gStyle->SetLabelSize(0.08, "Y");
	gStyle->SetNdivisions(6, "X");
	gStyle->SetNdivisions(8, "Y");
	gStyle->SetTitleFont(132);

	gROOT->ForceStyle();

	tl = new TLatex;
	tl->SetNDC(kTRUE);
	tl->SetTextSize(0.09);

	ts = new TLatex;
	ts->SetNDC(kTRUE);
	ts->SetTextSize(0.08);

	line = new TLine;
	line->SetLineColor(kRed);
	line->SetLineStyle(kSolid);
	
	box = new TBox;
	box->SetFillColor(kRed);
	box->SetFillStyle(3002);

	f = new TFile(Form("%s/%s", dirName, fileName), "READ");
	
	//		if (strcmp(fileName, adFileName) == 0) f1 = f;
	// 	else f1 = new TFile(Form("%s/%s", dirName, adFileName), "READ");
	
	sprintf(trimFileName,"Trim%i.root",TrimVcal);
	if (strcmp(fileName, trimFileName) == 0) g = f;
	else g = new TFile(Form("%s/%s", dirName, trimFileName), "READ");
 
	//sprintf(fname, "%s/../../criteria.dat", dirName);
	sprintf(fname, "criteria.dat", dirName);
	if ( !readCriteria(fname) ) { 
	  
	  printf("\nchipSummary> ----> COULD NOT READ GRADING CRITERIA !!!");
	  printf("chipSummary> ----> Aborting execution of chipgSummaryPage.C ... \n\n", fileName, dirName);  
	  break;
	}

	TH1D *h1;
	TH2D *h2;

	c1 = new TCanvas("c1", "", 800, 800);
	c1->Clear();
	c1->Divide(4,4, 0.01, 0.04);

  //	shrinkPad(0.1, 0.1, 0.1, 0.3);


        TString noslash(dirName);
        noslash.ReplaceAll("/", " ");
        noslash.ReplaceAll(".. ", "");
	
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 1
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Dead pixels
	TH2D *hpm = new TH2D("hpm", "", 80, 0., 80., 52, 0., 52.);

	int nDeadPixel(0);
	int nMaskDefect(0);
	int nNoisyPixel(0);
	int nRootFileProblems(0);

	c1->cd(1);
	h2 = (TH2D*)f->Get(Form("PixelMap_C%i", chipId));
        if (h2) {
	  for (int icol = 0; icol < 52; ++icol)
	  {
		for (int irow = 0; irow < 80; ++irow)
		{
		        hpm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));

			if (h2->GetBinContent(icol+1, irow+1)  == 0)
			{
				++nDeadPixel;
			}
			if (h2->GetBinContent(icol+1, irow+1)  > 10)
			{
				++nNoisyPixel;
			}
			if (h2->GetBinContent(icol+1, irow+1)  < 0)
			{
				++nMaskDefect;
			}
		}
	  }
	  h2->SetTitle("");
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Pixel Map");
	}

	else { ++nRootFileProblems; }

	// -- sCurve width and noise level
	TH1D *hw = new TH1D("hw", "", 100, 0., 600.);
	TH1D *hd = new TH1D("hd", "", 100, 0., 600.);  // Noise in unbonded pixel (not displayed)
	TH2D *ht = new TH2D("ht", "", 52, 0., 52., 80, 0., 80.);
	TH1D *htmp;

	float mN(0.), sN(0.), nN(0.), nN_entries(0.);
	int over(0), under(0);

	double htmax(255.), htmin(0.);
	
	float thr, sig;
	int a,b;
	FILE *inputFile;
	char string[200];
	sprintf(string, "%s/SCurve_C0%i.dat", dirName, TrimVcal);
	inputFile = fopen(string, "r");

	double minThrDiff(-5.);
	double maxThrDiff(5.);
	h2 = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
	if (!inputFile)
	{
		printf("chipSummary> !!!!!!!!!  ----> SCurve: Could not open file %s to read fit results\n", string);
	}
	else
	{
	  for (int i = 0; i < 2; i++) fgets(string, 200, inputFile);

		for (int icol = 0; icol < 52; ++icol)
		{
			for (int irow = 0; irow < 80; ++irow)
			{
				fscanf(inputFile, "%e %e %s %2i %2i", &thr, &sig, string, &a, &b);  //comment
//  				printf("chipSummary> sig %e thr %e\n", sig, thr);
				hw->Fill(sig);
				thr = thr / 65;

				ht->SetBinContent(icol+1, irow+1, thr); 
			
				if ( h2 ) {
				  if( h2->GetBinContent(icol+1, irow+1)  > minThrDiff)
				  {
				    hd->Fill(sig);
				  }
				}
			}
		}
		c1->cd(2);
		hw->Draw();
		tl->DrawLatex(0.1, 0.92, "S-Curve widths: Noise (e^{-})");
		

		/*		c1->cd(15);
		hd->SetLineColor(kRed);
		hd->Draw();
		tl->DrawLatex(0.1, 0.92, "S-Curve widths of dead bumps");
		if ( hd->GetEntries() > 0 ) {
		  ts->DrawLatex(0.55, 0.82, Form("entries: %4.0f", hd->GetEntries()));
		  ts->DrawLatex(0.55, 0.74, Form("#mu:%4.2f", hd->GetMean()));
		  ts->DrawLatex(0.55, 0.66, Form("#sigma: %4.2f", hd->GetRMS()));
		}
		*/

		mN =  hw->GetMean();
		sN =  hw->GetRMS();
		nN =  hw->Integral(hw->GetXaxis()->GetFirst(), hw->GetXaxis()->GetLast());
		nN_entries =  hw->GetEntries();

		under = hw->GetBinContent(0);
		over  = hw->GetBinContent(hw->GetNbinsX()+1);


		ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nN));
		ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mN));
		ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sN));
			
		if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
		if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));

		c1->cd(3);
		if ( ht->GetMaximum() < htmax ) { 
		  htmax = ht->GetMaximum();
		}
		if ( ht->GetMinimum() > htmin ) {
		  htmin = ht->GetMinimum();
		}
		ht->GetZaxis()->SetRangeUser(htmin,htmax);
		ht->Draw("colz");
		tl->DrawLatex(0.1, 0.92, "Vcal Threshold from SCurve");
	}

	// -- Noise level map
	c1->cd(4);
        gPad->SetLogy(1);
 	gStyle->SetOptStat(1);
	
	float mV(0.), sV(0.), nV(0.), nV_entries(0.);
	over = 0.; under = 0.;

	if (!g->IsZombie())
	{
	      h1 = (TH1D*)g->Get(Form("VcalThresholdMap_C%iDistribution;7", chipId));
              if (h1) {
		h1->SetTitle("");
		h1->SetAxisRange(0., 100.);
		h1->Draw();

		mV = h1->GetMean();
		sV = h1->GetRMS();
		nV = h1->Integral(h1->GetXaxis()->GetFirst(), h1->GetXaxis()->GetLast());
		nV_entries = h1->GetEntries();

		under = h1->GetBinContent(0);
		over  = h1->GetBinContent(h1->GetNbinsX()+1);
              }
              else {

	        ++nRootFileProblems;
		mV = 0.;
		sV = 0.;
               
              }

	      ts->DrawLatex(0.15, 0.82, Form("N: %4.0f", nV));
	      ts->DrawLatex(0.15, 0.74, Form("#mu: %4.1f", mV));
	      ts->DrawLatex(0.15, 0.66, Form("#sigma: %4.1f", sV));
	      
	      if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	      if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	}

	tl->DrawLatex(0.1, 0.92, "Vcal Threshold Trimmed");
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 2
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Bump Map
	TH2D *hbm = new TH2D("hbm", "", 80, 0., 80., 52, 0., 52.);

	int nDeadBumps(0);

	c1->cd(5);
	gStyle->SetOptStat(0);
	h2 = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
        if (h2) {

	  for (int icol = 0; icol < 52; ++icol)
	  {
		for (int irow = 0; irow < 80; ++irow)
		{
		        hbm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));

			if ( h2->GetBinContent(icol+1, irow+1)  >= minThrDiff )
			{
			   cout << Form("chipSummary> dead %3d %3d: %7.5f", icol, irow, h2->GetBinContent(icol, irow)) << endl;
				++nDeadBumps;
			}
		}
	  }

	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(minThrDiff, maxThrDiff);
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding Problems");
	}

	else { ++nRootFileProblems; }

	// -- Bump Map
	c1->cd(6);  
	gPad->SetLogy(1);
	//gStyle->SetOptStat(1);
	h1 = (TH1D*)f->Get(Form("vcals_xtalk_C%iDistribution", chipId));
        if (h1) {
  	  h1->SetTitle("");
	  h1->SetAxisRange(-50., 50.); //DOES NOT WORK!!!???
	  h1->Draw();
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding");
	}
	
	else { ++nRootFileProblems; }
	
	// -- Trim bits
	int trimbitbins(3);
	int nDeadTrimbits(0);
	c1->cd(7); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f->Get(Form("TrimBit14_C%i", chipId));
	if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(0., 60.);
	  h1->SetMinimum(0.5);
	  h1->Draw("");
	  tl->DrawLatex(0.1, 0.92, "Trim Bit Test");
	  for (int i = 1; i <= trimbitbins; ++i) nDeadTrimbits += h1->GetBinContent(i);
	}

	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit13_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kRed);
	  h1->Draw("same");
	  for (int i = 1; i <= trimbitbins; ++i) nDeadTrimbits += h1->GetBinContent(i);
	}

	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit11_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kBlue);
	  h1->Draw("same");
	  for (int i = 1; i <= trimbitbins; ++i) nDeadTrimbits += h1->GetBinContent(i);
	}

	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit7_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kGreen);
	  h1->Draw("same");
	  for (int i = 1; i <= trimbitbins; ++i) nDeadTrimbits += h1->GetBinContent(i);
	}
	
	else { ++nRootFileProblems; }
	
	// -- For numerics and titels see at end


	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 3
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Address decoding
	TH2D *ham = new TH2D("ham", "", 80, 0., 80., 52, 0., 52.);

	int nAddressProblems(0);
	
	c1->cd(9);
	gStyle->SetOptStat(0);
	h2 = (TH2D*)f->Get(Form("AddressDecoding_C%i", chipId));
        if (h2) {
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      ham->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));

	      if (h2 && h2->GetBinContent(icol+1, irow+1) < 1) {
	        cout << Form("chipSummary> address problem %3d %3d: %7.5f", icol, irow, h2->GetBinContent(icol, irow))
		     << endl;
	        ++nAddressProblems;
	      }
	    }
	  }
	  h2->SetTitle("");
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Address decoding");
	}

	else { ++nRootFileProblems; }

	// -- Address levels
	c1->cd(10); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f->Get(Form("AddressLevels_C%i", chipId));
        if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(-1200., 1000.);
	  h1->Draw();
	  tl->DrawLatex(0.1, 0.92, "Address Levels");
	}

	else { ++nRootFileProblems; }
		
	// -- PHCalibration (Gain & Pedesdtal)

	TH1D *hg = new TH1D("hg", "", 250, -1., 5.5);
	TH2D *hgm = new TH2D("hgm", "", 52, 0., 52., 80, 0., 80.);
	TH1D *hp1 = new TH1D("hp", "", 100,0,5);	
	TH1D *hp = new TH1D("hp", "", 900, -600., 600.);
	hp->StatOverflows(kTRUE);
	TH1D *rp = new TH1D("rp", "", 900, -600., 600.);
	rp->StatOverflows(kFALSE);

	TH1D *htmp;
	
	float mG(0.), sG(0.), nG(0.), nG_entries(0.);
	float mP(0.), sP(0.), nP(0.), nP_entries(0.); 
	over = 0.; under = 0.;

	float par0, par1, par2, par3, par4, par5; // Parameters of Vcal vs. Pulse Height Fit
	float ped, gain;
	int a,b;
	
	int mPbin(0), xlow(-100), xup(255), extra(0);       // for restricted RMS
	double integral(0.);


	FILE *inputFile;
	char string[200];  
	sprintf(string, "%s/phCalibrationFitTan_C0%i.dat", dirName, TrimVcal);
	inputFile = fopen(string, "r");

	if (!inputFile)
	{
		printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	}
	else
	{
		for (int i = 0; i < 2; i++) fgets(string, 200, inputFile);

		for (int icol = 0; icol < 52; ++icol)
		{
			for (int irow = 0; irow < 80; ++irow)
			{
			  //	fscanf(inputFile, "%e %e %e %e %e %e %s %2i %2i", &par0, &par1, &par2, &par3, &par4, &par5, string, &a, &b);
			  fscanf(inputFile, "%e %e %e %e %s %2i %2i", &par0, &par1, &par2, &par3, string, &a, &b);

				if (par2 != 0.)  // dead pixels have par2 == 0.
				{
				  // ped = -par3/par2;
					gain = 1./par2;
					//	ped = par3;
					ped=par3+par2*(tanh(-par1));
					hp->Fill(ped);
					hg->Fill(gain);
					hp1->Fill(par1);
					//	cout <<gain<<" " << ped<<endl;
					hgm->SetBinContent(icol + 1, irow + 1, gain);
				}
			}
		}

		mG =  hg->GetMean();
		sG =  hg->GetRMS();
		nG =  hg->Integral(hg->GetXaxis()->GetFirst(), hg->GetXaxis()->GetLast());
		nG_entries = hg->GetEntries();

		under = hg->GetBinContent(0);
		over  = hg->GetBinContent(hp->GetNbinsX()+1);
		
		c1->cd(11);

		//	hg->Draw();
		tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");
		
		if ( hg->GetMean() > 1.75 ) {
		  ts->DrawLatex(0.15, 0.82, Form("N: %4.0f", nG));
		  ts->DrawLatex(0.15, 0.74, Form("#mu: %4.2f", mG));
		  ts->DrawLatex(0.15, 0.66, Form("#sigma: %4.2f", sG));

		  if ( under ) ts->DrawLatex(0.15, 0.82, Form("<= %i", under));			               
		  if ( over  ) ts->DrawLatex(0.75, 0.82, Form("%i =>", over ));
		}
		else {
		  ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nG));
		  ts->DrawLatex(0.65, 0.74, Form("#mu: %4.2f", mG));
		  ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.2f", sG));
	
		  if ( under ) ts->DrawLatex(0.15, 0.82, Form("<= %i", under));			               
		  if ( over  ) ts->DrawLatex(0.75, 0.82, Form("%i =>", over ));
		}


		mP =  hp->GetMean();
		sP =  hp->GetRMS();
		nP =  hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());
		nP_entries = hp->GetEntries();

		if ( nP > 0 ) {

		  // -- restricted RMS
		  integral = 0.;
		  mPbin = -1000; xlow = -1000; xup = 1000;
		  over = 0.; under = 0.;
		  
		  mPbin = hp->GetXaxis()->FindBin(mP);
				  
		  for (int i = 0; integral <  pedDistr; i++) { 
		    
		    xlow = mPbin-i;
		    xup =  mPbin+i;
		    integral = hp->Integral(xlow, xup)/nP;
		    
		  }
		  
		  extra = xup - xlow;
		}
		else {

		  xlow = -300; xup = 600; extra = 0;
		  over = 0.; under = 0.;
		}

		  
		hp->GetXaxis()->SetRange(xlow - extra, xup + extra);

		nP    = hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());
		under = hp->GetBinContent(0);
		over  = hp->GetBinContent(hp->GetNbinsX()+1);


		c1->cd(15);

		//	hgm->Draw("colz");
		hp1->Draw();
		tl->DrawLatex(0.1, 0.92, "PH Calibration: P1");






		
		c1->cd(12);

		hp->DrawCopy();

		rp->Add(hp);
		rp->GetXaxis()->SetRange(xlow, xup);

       		mP =  rp->GetMean();
		sP =  rp->GetRMS();

		// box->DrawBox( rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xup), 1.05*rp->GetMaximum());
		rp->SetFillColor(kRed);
		rp->SetFillStyle(3002);
		rp->Draw("same");
		line->DrawLine(rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xlow), 0.6*rp->GetMaximum());
		line->DrawLine(rp->GetBinCenter(xup),  0, rp->GetBinCenter(xup),  0.6*rp->GetMaximum());
	 
		tl->DrawLatex(0.1, 0.92, "PH Calibration: Pedestal (DAC)");
		
		if ( hp->GetMean() < 126. ) {

		  ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nP));
		  ts->SetTextColor(kRed);
		  ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mP));
		  ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sP));
		  ts->SetTextColor(kBlack);

		  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
		  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
				
		}
		else {

		  ts->DrawLatex(0.16, 0.82, Form("N: %4.0f", nP));
		  ts->SetTextColor(kRed);
		  ts->DrawLatex(0.16, 0.74, Form("#mu: %4.1f", mP));
		  ts->DrawLatex(0.16, 0.66, Form("#sigma: %4.1f", sP));
		  ts->SetTextColor(kBlack);

		  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
		  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
		}


		
	}
	
	

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Numerics and Titles
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Compute the final verdict on this chip  //?? FIXME (below is pure randomness)
	char finalVerdict(0);
	if (nDeadTrimbits > 40) finalVerdict += 1;
	if (nDeadPixel > 40) finalVerdict += 10;
	if (nNoisyPixel > 40) finalVerdict += 10;
	if (nAddressProblems > 40) finalVerdict += 10;
	if (nDeadBumps > 40) finalVerdict += 100;


	// -- Defects
	c1->cd(8);
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	double y = 0.92;
	y -= 0.11;
	tl->DrawLatex(0.1, y, "Summary");
	tl->DrawLatex(0.7, y, Form("%d", finalVerdict));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Dead Pixels: "));
	tl->DrawLatex(0.7, y, Form("%4d", nDeadPixel));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Noisy Pixels: "));
	tl->DrawLatex(0.7, y, Form("%4d", nNoisyPixel));
	
	y -= 0.10;
	tl->DrawLatex(0.1, y, "Mask defects: ");
	tl->DrawLatex(0.7, y, Form("%4d", nMaskDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Bumps: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadBumps));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Trimbits: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadTrimbits));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Address Probl: ");
	tl->DrawLatex(0.7, y, Form("%4d", nAddressProblems));

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 4
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	TH2D *htm = new TH2D("htm", "", 80, 0., 80., 52, 0., 52.);

	c1->cd(13);
	
	gStyle->SetOptStat(0);
	h2 = (TH2D*)g->Get(Form("TrimMap_C%i;8", chipId));

        if (h2) {
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      htm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));
	    }
	  }
  	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(0., 16.);
	  h2->Draw("colz");
	}

	else { ++nRootFileProblems; }

	tl->DrawLatex(0.1, 0.92, "Trim Bits");


	FILE *tCalFile;
	sprintf(string, "%s/../T-calibration/TemperatureCalibration_C%i.dat", dirName, chipId);
	tCalFile = fopen(string, "r");
	char tCalDir[200];
	sprintf(tCalDir, "%s/../T-calibration", dirName);

	if ( tCalFile ) {
	
	  analyse(tCalDir, chipId);
	}
	else {

	  c1->cd(14);
	  TGraph *graph = (TGraph*)f->Get(Form("TempCalibration_C%i", chipId));
	  if ( graph ) { graph->Draw("A*"); }
	  else { ++nRootFileProblems; }
	  tl->DrawLatex(0.1, 0.92, "Temperature calibration");
	}


	// -- Operation Parameters
	c1->cd(16);
	
	y = 0.92;
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Op. Parameters"));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);

	y -= 0.11;
	int vana(-1.);
        vana = dac_findParameter(dirName, "Vana", chipId);
	tl->DrawLatex(0.1, y, "VANA: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3i DAC", vana));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int caldel(-1.);
        caldel = dac_findParameter(dirName, "CalDel", chipId);
	tl->DrawLatex(0.1, y, "CALDEL: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", caldel));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vthrcomp(-1.);
        vthrcomp = dac_findParameter(dirName, "VthrComp", chipId);
	tl->DrawLatex(0.1, y, "VTHR: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vthrcomp));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vtrim(-1.);
        vtrim = dac_findParameter(dirName, "Vtrim", chipId);
	tl->DrawLatex(0.1, y, "VTRIM: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vtrim));
	else tl->DrawLatex(0.7, y, "N/A");
	
	y -= 0.10;
	int ibias(-1.);
        ibias = dac_findParameter(dirName, "Ibias_DAC", chipId);
	tl->DrawLatex(0.1, y, "IBIAS_DAC: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", ibias));
	else tl->DrawLatex(0.7, y, "N/A");
       
	y -= 0.10;
	int voffset(-1.);
        voffset = dac_findParameter(dirName, "VoffsetOp", chipId);
	tl->DrawLatex(0.1, y, "VOFFSETOP: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", voffset));
	else tl->DrawLatex(0.7, y, "N/A");

	// -- Page title
	c1->cd(0);
	tl->SetTextSize(0.025);
	tl->SetTextFont(22);
	tl->DrawLatex(0.02, 0.97, Form("%s (Trim%i)", noslash.Data(),TrimVcal));

	TDatime date;
	tl->SetTextSize(0.02);
	tl->DrawLatex(0.75, 0.97, Form("%s", date.AsString()));

	c1->SaveAs(Form("%s/chipSummary_C%i_%i.ps", dirName, chipId,TrimVcal));
	c1->SaveAs(Form("%s/C%i_%i.gif", dirName, chipId,TrimVcal));
	

	// -- Dump into logfile
	ofstream OUT(Form("%s/summary_C%i_%i.txt", dirName, chipId,TrimVcal));
	OUT << "nDeadPixel: "         << nDeadPixel << endl;
	OUT << "nNoisyPixel: "        << nNoisyPixel << endl;
	OUT << "nDeadTrimbits: "      << nDeadTrimbits << endl;
	OUT << "nDeadBumps: "         << nDeadBumps << endl;
	OUT << "nMaskDefect: "        << nMaskDefect << endl;
	OUT << "nAddressProblems: "   << nAddressProblems << endl;
        OUT << "nRootFileProblems: "  << nRootFileProblems << endl;
	OUT << "SCurve "              << nN_entries << " " << mN << " " << sN << endl;
	OUT << "Threshold "           << nV_entries << " " << mV  << " " << sV << endl;
	OUT << "Gain "                << nG_entries << " " << mG << " " << sG << endl;
	OUT << "Pedestal "            << nP_entries << " " << mP << " " << sP << endl;
	OUT.close();
	
}
Example #12
0
void plotXY(char* fname){

  // input: root file from GBL

  gStyle->SetOptStat(0);
  Double_t w = 1.2; // number of RMS for gaussian fit
  TString filename = fname;
  TCanvas *cTop = new TCanvas("cTop","Residuals in lab frame, TOP", 800, 1000);
  TCanvas *cBot = new TCanvas("cBot","Residuals in lab frame, BOTTOM",800, 1000);
  cTop->SetFillColor(kBlue-10); cTop->SetFillStyle(3001);
  cBot->SetFillColor(kMagenta-10); cBot->SetFillStyle(3001);
  Double_t halfWid = 38.34/2.;
  Double_t halfLen = 98.33/2.;
  TBox *module = new TBox(-halfLen, -halfWid, halfLen, halfWid);
  module->SetLineColor(kMagenta);
  module->SetFillStyle(0);

  Int_t ic=0;
  TFile *f = new TFile(filename.Data());
  // extract string 
  Int_t idx2 = filename.Index("/");
  Int_t idx1 = filename.Index("_");
  TString outn = filename(idx1+1,idx2-(idx1+1));
  TString outname ="predXY_"; outname += outn.Data(); outname += ".txt";
  TString topName ="predXY_"; topName += outn.Data(); topName += "_topO.gif";
  TString botName ="predXY_"; botName += outn.Data(); botName += "_botO.gif";
  //  ofstream outf(outname.Data());
  // top
  Int_t nrow = 13;
  Double_t space = 0.007;
  Double_t space1 = 0.03;
  Double_t y2 = 1./13*nrow-space1;
  Double_t y1 = 1./13*(--nrow)-space1;
  TPad *tp1 = new TPad("tp1","tp1",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp2 = new TPad("tp2","tp2",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *tp3 = new TPad("tp3","tp3",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp4 = new TPad("tp4","tp4",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *tp5 = new TPad("tp5","tp5",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp6 = new TPad("tp6","tp6",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  Double_t off = 0.12;
  off = 0.165;
  y1 -= space1; y2 -= space1;
  space1 *= 2;
  TPad *tp7 = new TPad("tp7","tp7",0.+off,y1,0.33+off,y2);
  TPad *tp8 = new TPad("tp8","tp8",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp9 = new TPad("tp9","tp9",0.+off,y1,0.33+off,y2);
  TPad *tp10 = new TPad("tp10","tp10",0.66-off,y1,1.-off,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *tp11 = new TPad("tp11","tp11",0.+off,y1,0.33+off,y2);
  TPad *tp12 = new TPad("tp12","tp12",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp13 = new TPad("tp13","tp13",0.+off,y1,0.33+off,y2);
  TPad *tp14 = new TPad("tp14","tp14",0.66-off,y1,1.-off,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *tp15 = new TPad("tp15","tp15",0.+off,y1,0.33+off,y2);
  TPad *tp16 = new TPad("tp16","tp16",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *tp17 = new TPad("tp17","tp17",0.+off,y1,0.33+off,y2);
  TPad *tp18 = new TPad("tp18","tp18",0.66-off,y1,1.-off,y2);
  cout << " TOP " << endl;

  cTop->cd();
  tp1->Draw();
  tp2->Draw();
  tp3->Draw();
  tp4->Draw();
  tp5->Draw();
  tp6->Draw();
  tp7->Draw();
  tp8->Draw();
  tp9->Draw();
  tp10->Draw();
  tp11->Draw();
  tp12->Draw();
  tp13->Draw();
  tp14->Draw();
  tp15->Draw();
  tp16->Draw();
  tp17->Draw();
  tp18->Draw();

  ic = 2;
  Int_t ipad=0;
  for(Int_t i=1; i<4; i++){
    TString hisname = "h_xy_module_L"; hisname  += i;
    hisname += "t_halfmodule_axial_sensor0";
    TString layer = "L"; layer+=i; layer+= "TA"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    TH1D *his = (TH1D*)his2->ProjectionY();
    ipad++;
    TString pd = "tp"; pd+=ipad;
    TPad *pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    Double_t low = his->GetMean()-w*his->GetRMS();
    Double_t up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up);
    his2->Draw("colz");
    module->Draw("same");
    TF1 *fit = his->GetFunction("gaus");
    // cout << "sensor " << i << " axial mean :  " << his->GetMean()*1000. << " - RMS : " << his->GetRMS()*1000. << " (um) " << " " << his->GetEntries() << endl;
    // cout << "sensor " << i << " axial mu :  " << fit->GetParameter(1)*1000. << " - sigma : " << fit->GetParameter(2)*1000. << " (um) " << endl;
    // outf << layer.Data() << " " << fit->GetParameter(1)*1000. << " " << fit->GetParameter(2)*1000. << " " << his->GetEntries() << endl;

    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "t_halfmodule_stereo_sensor0";
    layer = "L"; layer+=i; layer+= "TS"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    his = (TH1D*)his2->ProjectionY();
    ipad++;
    pd = "tp"; pd+=ipad;
    pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
  }
  //  ic = 19;
  for(Int_t i=4; i<7; i++){
    TString hisname = "h_xy_module_L"; hisname  += i;
    TString hisname2 = hisname;
    hisname += "t_halfmodule_axial_hole_sensor0";
    hisname2 += "t_halfmodule_axial_slot_sensor0";
    TH2D *hisOther = (TH2D*) f->Get(hisname2.Data());
    Double_t norma2 = hisOther->GetMaximum();
    TString layer = "L"; layer+=i; layer+= "TAHo"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    TH1D *his = (TH1D*)his2->ProjectionY();     
    Double_t norma1 = his2->GetMaximum();
    Double_t normamax = TMath::Max(norma1,norma2);
    his2->SetMaximum(normamax);
    ipad++;
    TString pd = "tp"; pd+=ipad;
    TPad *pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    Double_t low = his->GetMean()-w*his->GetRMS();
    Double_t up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    TF1 *fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname2 = hisname;
    hisname += "t_halfmodule_stereo_hole_sensor0";
    hisname2 += "t_halfmodule_stereo_slot_sensor0";
    TH2D *hisOther = (TH2D*) f->Get(hisname2.Data());
    norma2 = hisOther->GetMaximum();
    TString layer = "L"; layer+=i; layer+= "TAHo"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    TH1D *his = (TH1D*)his2->ProjectionY();     
    norma1 = his2->GetMaximum();
    normamax2 = TMath::Max(norma1,norma2);
    his2->SetMaximum(normamax2);
    layer = "L"; layer+=i; layer+= "TSHo"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    his = (TH1D*)his2->ProjectionY();
    ipad++; ipad++;
    pd = "tp"; pd+=ipad;
    pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "t_halfmodule_axial_slot_sensor0";
    layer = "L"; layer+=i; layer+= "TASl";
    his2 = (TH2D*) f->Get(hisname.Data());
    his2->SetMaximum(normamax);
    his = (TH1D*)his2->ProjectionY();     
    ipad--;
    pd = "tp"; pd+=ipad;
    pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "t_halfmodule_stereo_slot_sensor0";
    layer = "L"; layer+=i; layer+= "TSSl"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    his2->SetMaximum(normamax2);
    his = (TH1D*)his2->ProjectionY();     
    ipad++; ipad++;
    pd = "tp"; pd+=ipad;
    pad = (TPad*) cTop->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
  }
  cout << endl;
  cout << "------------------------" << endl;
  cout << endl;
  cout << " BOTTOM " << endl;
  nrow = 13;
  space = 0.007;
  space1 = 0.03;
  y2 = 1./13*nrow-space1;
  y1 = 1./13*(--nrow)-space1;
  TPad *bp1 = new TPad("bp1","bp1",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp2 = new TPad("bp2","bp2",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *bp3 = new TPad("bp3","bp3",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp4 = new TPad("bp4","bp4",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *bp5 = new TPad("bp5","bp5",0.33,y1,0.66,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp6 = new TPad("bp6","bp6",0.33,y1,0.66,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  off = 0.165;
  y1 -= space1; y2 -= space1;
  space1 *= 2;
  TPad *bp7 = new TPad("bp7","bp7",0.+off,y1,0.33+off,y2);
  TPad *bp8 = new TPad("bp8","bp8",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp9 = new TPad("bp9","bp9",0.+off,y1,0.33+off,y2);
  TPad *bp10 = new TPad("bp10","bp10",0.66-off,y1,1.-off,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *bp11 = new TPad("bp11","bp11",0.+off,y1,0.33+off,y2);
  TPad *bp12 = new TPad("bp12","bp12",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp13 = new TPad("bp13","bp13",0.+off,y1,0.33+off,y2);
  TPad *bp14 = new TPad("bp14","bp14",0.66-off,y1,1.-off,y2);
  y2 = y1-space; y1 = 1./13.*(--nrow)-space1;
  TPad *bp15 = new TPad("bp15","bp15",0.+off,y1,0.33+off,y2);
  TPad *bp16 = new TPad("bp16","bp16",0.66-off,y1,1.-off,y2);
  y2 = y1; y1 = 1./13.*(--nrow)-space1;
  TPad *bp17 = new TPad("bp17","bp17",0.+off,y1,0.33+off,y2);
  TPad *bp18 = new TPad("bp18","bp18",0.66-off,y1,1.-off,y2);

  cBot->cd();
  bp1->Draw();
  bp2->Draw();
  bp3->Draw();
  bp4->Draw();
  bp5->Draw();
  bp6->Draw();
  bp7->Draw();
  bp8->Draw();
  bp9->Draw();
  bp10->Draw();
  bp11->Draw();
  bp12->Draw();
  bp13->Draw();
  bp14->Draw();
  bp15->Draw();
  bp16->Draw();
  bp17->Draw();
  bp18->Draw();

  cBot->cd();
  bp1->Draw();
  bp2->Draw();
  bp3->Draw();
  bp4->Draw();
  bp5->Draw();
  bp6->Draw();
  bp7->Draw();
  bp8->Draw();
  bp9->Draw();
  bp10->Draw();
  bp11->Draw();
  bp12->Draw();
  bp13->Draw();
  bp14->Draw();
  bp15->Draw();
  bp16->Draw();
  bp17->Draw();
  bp18->Draw();

  ic=0;
  ipad = 0;
  for(Int_t i=1; i<4; i++){
    TString hisname = "h_xy_module_L"; hisname  += i;
    TString hisname2 = hisname;
    hisname += "b_halfmodule_stereo_sensor0";
    hisname2 += "b_halfmodule_axial_sensor0";
    TH2D *hisOther = (TH2D*) f->Get(hisname2.Data());
    Double_t norma2 = hisOther->GetMaximum();
    TString layer = "L"; layer+=i; layer+= "BS"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    Double_t norma1 = his2->GetMaximum();
    Double_t normamax = TMath::Max(norma1,norma2);
    //    his2->SetMaximum(normamax);
    TH1D *his = (TH1D*)his2->ProjectionY();     
    if(layer.Contains("1")){his->SetFillColor(kRed);}
    else if(layer.Contains("2")){his->SetFillColor(kOrange);}
    else if(layer.Contains("3")){his->SetFillColor(kYellow);}
    else if(layer.Contains("4")){his->SetFillColor(kGreen);}
    else if(layer.Contains("5")){his->SetFillColor(kCyan);}
    else if(layer.Contains("6")){his->SetFillColor(kBlue);}
    if(layer.Contains("A")){his->SetFillStyle(3007);}
    else if(layer.Contains("S")){his->SetFillStyle(3004);}
    //    cBot->cd(++ic);
    ipad++;
    TString pd = "bp"; pd+=ipad;
    TPad *pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    Double_t low = his->GetMean()-w*his->GetRMS();
    Double_t up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    TF1 *fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "b_halfmodule_axial_sensor0";
    layer = "L"; layer+=i; layer+= "BA"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    //   his2->SetMaximum(normamax);
    his = (TH1D*)his2->ProjectionY();     
    ipad++;
    pd = "bp"; pd+=ipad;
    pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
  }
  for(Int_t i=4; i<7; i++){
    TString hisname = "h_xy_module_L"; hisname  += i;
    TString hisname2 = hisname;
    hisname += "b_halfmodule_stereo_hole_sensor0";
    hisname2 += "b_halfmodule_stereo_slot_sensor0";
    TH2D *hisOther = (TH2D*) f->Get(hisname2.Data());
    Double_t norma2 = hisOther->GetMaximum();
    TString layer = "L"; layer+=i; layer+= "BSHo"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    TH1D *his = (TH1D*)his2->ProjectionY();     
    Double_t norma1 = his2->GetMaximum();
    Double_t normamax1 = TMath::Max(norma1,norma2);
    his2->SetMaximum(normamax1);
    ipad++; 
    TString pd = "bp"; pd+=ipad;
    TPad *pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    Double_t low = his->GetMean()-w*his->GetRMS();
    Double_t up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    TF1 *fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    TString hisname2 = hisname;
    hisname += "b_halfmodule_axial_hole_sensor0";
    hisname2 += "b_halfmodule_axial_slot_sensor0";
    TH2D *hisOther = (TH2D*) f->Get(hisname2.Data());
    Double_t norma2 = hisOther->GetMaximum();
    TString layer = "L"; layer+=i; layer+= "BAHo"; 
    TH2D *his2 = (TH2D*) f->Get(hisname.Data());
    TH1D *his = (TH1D*)his2->ProjectionY();     
    Double_t norma1 = his2->GetMaximum();
    Double_t normamax2 = TMath::Max(norma1,norma2);
    his2->SetMaximum(normamax2);
    ipad++; ipad++;
    pd = "bp"; pd+=ipad;
    pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "b_halfmodule_stereo_slot_sensor0";
    layer = "L"; layer+=i; layer+= "BSSl"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    his2->SetMaximum(normamax1);
    his = (TH1D*)his2->ProjectionY();     
    ipad--;
    pd = "bp"; pd+=ipad;
    pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
    hisname = "h_xy_module_L"; hisname  += i;
    hisname += "b_halfmodule_axial_slot_sensor0";
    layer = "L"; layer+=i; layer+= "BASl"; 
    his2 = (TH2D*) f->Get(hisname.Data());
    his2->SetMaximum(normamax2);
    his = (TH1D*)his2->ProjectionY();     
    ipad++; ipad++;
    pd = "bp"; pd+=ipad;
    pad = (TPad*) cBot->GetListOfPrimitives()->FindObject(pd.Data());
    pad->cd();
    low = his->GetMean()-w*his->GetRMS();
    up = his->GetMean()+w*his->GetRMS();    
    his->Fit("gaus","Q0","",low,up); his2->Draw("colz");
    module->Draw("same");
    fit = his->GetFunction("gaus");
  }

  //  outf.close();
  cTop->SaveAs(topName.Data());
  cBot->SaveAs(botName.Data());

}
Example #13
0
// ============================================================================
/// finalize the algorithm
// ============================================================================
StatusCode Aida2Root::finalize()
{

  always() << "Get the native ROOT representation of histograms!" << endmsg ;

  {  // loop over all 1D-histograms
    for ( List::const_iterator ipath = m_1Ds.begin() ;
          m_1Ds.end() != ipath ; ++ipath )
    {
      /// retrieve the historam by full path:
      AIDA::IHistogram1D* aida = 0 ;
      StatusCode sc = histoSvc()->retrieveObject( *ipath , aida ) ;
      if ( sc.isFailure() || 0 == aida )
      { return Error ( "Unable to retrieve 1D-histogram '" + (*ipath) + "'"  ) ; }
      /// convert it to ROOT
      TH1D* root = Gaudi::Utils::Aida2ROOT::aida2root ( aida ) ;
      if ( 0 == root )
      { return Error ( "Unable to convert to ROOT the 1D-histogram '"+(*ipath)+"'") ; }
      /// use the native printout from ROOT
      info() << "The native ROOT printout for 1D-histogram '" << (*ipath) << "':" << endmsg ;
      root->Print() ;

      info () << " |  Compare       | AIDA/HistoStats |     ROOT/TH1    |      Delta      | "  << endmsg ;
      const std::string format = " | %1$-14.14s | %2$ 15.8g | %3$- 15.8g | %4$= 15.8g | "  ;
      info () << print
        ( Gaudi::Utils::HistoStats::mean        ( aida ) ,
          root->GetMean      ()    , "'mean'"        , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::meanErr     ( aida ) ,
          root->GetMeanError ()    , "'meanErr'"     , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::rms         ( aida ) ,
          root->GetRMS       ()    , "'rms'"         , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::rmsErr      ( aida ) ,
          root->GetRMSError  ()    , "'rmsErr'"      , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::skewness    ( aida ) ,
          root->GetSkewness ()     , "'skewness'"    , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::skewnessErr ( aida ) ,
          root->GetSkewness ( 11 ) , "'skewnessErr'" , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::kurtosis  ( aida ) ,
          root->GetKurtosis ()     , "'kurtosis'"    , format  ) << endmsg ;
      info () << print
        ( Gaudi::Utils::HistoStats::kurtosisErr ( aida ) ,
          root->GetKurtosis ( 11 ) , "'kurtosisErr'" , format  ) << endmsg ;
    }
  }

  { // loop over all 2D-histograms
    for ( List::const_iterator ipath = m_2Ds.begin() ;
          m_2Ds.end() != ipath ; ++ipath )
    {
      /// retrieve the historam by full path:
      AIDA::IHistogram2D* aida = 0 ;
      StatusCode sc = histoSvc()->retrieveObject( *ipath , aida ) ;
      if ( sc.isFailure() || 0 == aida )
      { return Error ( "Unable to retrieve 2D-histogram '" + (*ipath) + "'"  ) ; }
      /// convert it to ROOT
      TH2D* root = Gaudi::Utils::Aida2ROOT::aida2root ( aida ) ;
      if ( 0 == root )
      { return Error ( "Unable to convert to ROOT the 2D-histogram '"+(*ipath)+"'") ; }
      /// use the native printout from ROOT
      info() << "The native ROOT printout for 2D-histogram '" << (*ipath) << "':" << endmsg ;
      root->Print() ;
    }
  }

  { // loop over all 3D-histograms
    for ( List::const_iterator ipath = m_3Ds.begin() ;
          m_3Ds.end() != ipath ; ++ipath )
    {
      /// retrieve the historam by full path:
      AIDA::IHistogram3D* aida = 0 ;
      StatusCode sc = histoSvc()->retrieveObject( *ipath , aida ) ;
      if ( sc.isFailure() || 0 == aida )
      { return Error ( "Unable to retrieve 3D-histogram '" + (*ipath) + "'"  ) ; }
      /// convert it to ROOT
	TH3D* root = Gaudi::Utils::Aida2ROOT::aida2root ( aida ) ;
      if ( 0 == root )
      { return Error ( "Unable to convert to ROOT the 3D-histogram '"+(*ipath)+"'") ; }
      /// use the native printout from ROOT
      info() << "The native ROOT printout for 3D-histogram '" << (*ipath) << "':" << endmsg ;
      root->Print() ;
    }
  }


  { // loop over all 1D-profiles
    for ( List::const_iterator ipath = m_1Ps.begin() ;
          m_1Ps.end() != ipath ; ++ipath )
    {
      /// retrieve the historam by full path:
      AIDA::IProfile1D* aida = 0 ;
      StatusCode sc = histoSvc()->retrieveObject( *ipath , aida ) ;
      if ( sc.isFailure() || 0 == aida )
      { return Error ( "Unable to retrieve 1D-profile '" + (*ipath) + "'"  ) ; }
      /// convert it to ROOT
	TProfile* root = Gaudi::Utils::Aida2ROOT::aida2root ( aida ) ;
      if ( 0 == root )
      { return Error ( "Unable to convert to ROOT the 1D-profile '"+(*ipath)+"'") ; }
      /// use the native printout from ROOT
      info() << "The native ROOT printout for 1D-profile '" << (*ipath) << "':" << endmsg ;
      root->Print() ;
    }
  }


  { // loop over all 2D-profiles
    for ( List::const_iterator ipath = m_2Ps.begin() ;
          m_2Ps.end() != ipath ; ++ipath )
    {
      /// retrieve the historam by full path:
      AIDA::IProfile2D* aida = 0 ;
      StatusCode sc = histoSvc()->retrieveObject( *ipath , aida ) ;
      if ( sc.isFailure() || 0 == aida )
      { Error ( "Unable to retrieve 2D-profile '" + (*ipath) + "'"  ) ; }
      /// convert it to ROOT
	TProfile2D* root = Gaudi::Utils::Aida2ROOT::aida2root ( aida ) ;
      if ( 0 == root )
      { Error ( "Unable to convert to ROOT the 2D-profile '"+(*ipath)+"'") ; }
      /// use the native printout from ROOT
      info() << "The native ROOT printout for 2D-profile '" << (*ipath) << "':" << endmsg ;
      root->Print() ;
    }
  }

  return GaudiHistoAlg::finalize() ;
}
Example #14
0
int logWeightingScanAll(){//main
  SetTdrStyle();

  //TString plotDir = "../PLOTS/gitV00-02-12/version12/gamma/200um/";
  TString plotDir = "/afs/cern.ch/work/a/amagnan/PFCalEEAna/PLOTS/gitV00-02-12/version12/gamma/200um/";

  bool useFit = true;

  //const unsigned nPu = 2;
  //unsigned pu[nPu] = {0,140};
  const unsigned nPu = 1;//2;
  unsigned pu[nPu] = {0};//,140};

  const unsigned nScans = 50;
  const double wStart = 1.;
  const double wStep = (6.-wStart)/nScans;

  const unsigned neta = 4;//7;
  const unsigned npt = 3;//13;

  const unsigned nLayers = 30;

  unsigned eta[neta] = {17,21,25,29};
  //unsigned pt[npt] = {20,30,40,50,60,70,80,90,100,125,150,175,200};
  unsigned pt[npt] = {20,50,100};

  //TF1 *cauchy = new TF1("cauchy","1/(TMath::Pi()*[2]*(1+pow((x-[0])/[2],2)))",-15,15);
  //cauchy->SetParameters(0,0,2.5);


  double wxminall[nPu][nLayers][neta];
  double wyminall[nPu][nLayers][neta];
  double etaval[neta];
       
  const unsigned nCanvas = 5;  
  TCanvas *mycx[nCanvas];
  TCanvas *mycy[nCanvas];
  for (unsigned iC(0);iC<nCanvas;++iC){
    std::ostringstream lName;
    lName << "mycx" << iC;
    mycx[iC] = new TCanvas(lName.str().c_str(),lName.str().c_str(),1500,1000);
    mycx[iC]->Divide(3,2);
    lName.str("");
    lName << "mycy" << iC;
    mycy[iC] = new TCanvas(lName.str().c_str(),lName.str().c_str(),1500,1000);
    mycy[iC]->Divide(3,2);
  }
  
  TCanvas *mycW = new TCanvas("mycW","mycW",1500,1000);
  TCanvas *mycFit = new TCanvas("mycFit","mycFit",1);

  for (unsigned ieta(0); ieta<neta;++ieta){
    etaval[ieta] = eta[ieta]/10.;
    bool savePoint = (eta[ieta] == 17);// &&  pt[ipt]==50);
    std::ostringstream pteta;
    pteta << "eta" << eta[ieta];// << "_et" << pt[ipt];
      
    TFile *fin[nPu];
      
    TFile *fout = 0;
    if (savePoint) {
      fout = TFile::Open(("PLOTS/LogWeightingStudy_"+pteta.str()+".root").c_str(),"RECREATE");
      fout->mkdir("scan");
      fout->mkdir("scan/xpos");
      fout->mkdir("scan/ypos");
      for (unsigned iS(0); iS<nScans;++iS){
	std::ostringstream lName;
	lName << "scan/xpos/scan_" << wStart+iS*wStep;
	fout->mkdir(lName.str().c_str());
	lName.str("");
	lName << "scan/ypos/scan_" << wStart+iS*wStep;
	fout->mkdir(lName.str().c_str());
      }
	
      fout->cd();
    }
    TH1F *p_xt;
    TH1F *p_yt; 
    TH1F *p_intercalibSigmaSquare[nPu];
    TH1F *p_chi2ndf; 
    if (savePoint) {
      p_xt = new TH1F("p_xt",";x truth (mm)",100,-5,5); 
      p_yt = new TH1F("p_yt",";y truth (mm)",100,-5,5);//200,1170,1370); 
	
      p_intercalibSigmaSquare[0] = new TH1F("p_intercalibSigmaSquare_0",";#sigma_{E}^{2} (2% intercalib) (GeV^2)",3000,0,30000);
      p_intercalibSigmaSquare[1] = new TH1F("p_intercalibSigmaSquare_140",";#sigma_{E}^{2} (2% intercalib) (GeV^2)",3000,0,30000);
      p_chi2ndf = new TH1F("p_chi2ndf",";#chi^{2}/N",100,0,20);
    }
      
    TH1F *p_posx[nPu][nLayers][nScans];
    TH1F *p_posy[nPu][nLayers][nScans];
      
    TH1F *p_wx[nPu][nLayers][3];
    TH1F *p_wy[nPu][nLayers][3];
      
    TH2F *p_Exy[nPu][nLayers];
    TH2F *p_deltavsreco_x[nPu][nLayers];
    TH2F *p_deltavsreco_y[nPu][nLayers];
    TH2F *p_recovstruth_x[nPu][nLayers];
    TH2F *p_recovstruth_y[nPu][nLayers];
      
    if (savePoint){
      mycFit->Print("PLOTS/fits_x.pdf[");
      mycFit->Print("PLOTS/fits_y.pdf[");
    }
      
    gStyle->SetOptStat("eMRuo");
      
    TGraphErrors *grX[nPu][nLayers];
    TGraphErrors *grY[nPu][nLayers];
    TGraphErrors *grXrms[nPu][nLayers];
    TGraphErrors *grYrms[nPu][nLayers];
      
    double resxmin[nPu][nLayers];
    double resymin[nPu][nLayers];
    double lay[nLayers];
    double wxmin[nPu][nLayers];
    double wymin[nPu][nLayers];

    for (unsigned ipu(0); ipu<nPu; ++ipu){//loop on pu


      std::vector<std::vector<double> > Exy;
      std::vector<double> init;
      init.resize(25,0);
      Exy.resize(nLayers,init);
      std::vector<double> truthPosX;
      truthPosX.resize(nLayers,0);
      std::vector<double> truthPosY;
      truthPosY.resize(nLayers,0);
	  
	  
      std::ostringstream label;
      label << "pu" << pu[ipu];
      if (savePoint){
	fout->mkdir(label.str().c_str());
	fout->cd(label.str().c_str());
      }

      for (unsigned iL(0);iL<nLayers;++iL){
	lay[iL] = iL;
	resxmin[ipu][iL] = 100;
	wxmin[ipu][iL] = 10;
	resymin[ipu][iL] = 100;
	wymin[ipu][iL] = 10;
	label.str("");   
	label << "pu" << pu[ipu];
	if (savePoint) fout->cd(label.str().c_str());
	label.str("");   
	label << "grX_pu" << pu[ipu] << "_" << iL;
	grX[ipu][iL] = new TGraphErrors();
	grX[ipu][iL]->SetName(label.str().c_str());
	label.str("");   
	label << "grY_pu" << pu[ipu] << "_" << iL;
	grY[ipu][iL] = new TGraphErrors();
	grY[ipu][iL]->SetName(label.str().c_str());
	label.str("");   
	label << "grXrms_pu" << pu[ipu] << "_" << iL;
	grXrms[ipu][iL] = new TGraphErrors();
	grXrms[ipu][iL]->SetName(label.str().c_str());
	label.str("");   
	label << "grYrms_pu" << pu[ipu] << "_" << iL;
	grYrms[ipu][iL] = new TGraphErrors();
	grYrms[ipu][iL]->SetName(label.str().c_str());
	if (savePoint) {
	  label.str("");   
	  label << "Exy_pu"<< pu[ipu] << "_" << iL;
	  p_Exy[ipu][iL] = new TH2F(label.str().c_str(),";x idx;y idx; E (mips)",
				    5,0,5,5,0,5);
	}
	label.str("");   
	label << "deltavsreco_x_pu"<< pu[ipu] << "_" << iL;
	p_deltavsreco_x[ipu][iL] = new TH2F(label.str().c_str(),";x reco (mm);x_{reco}-x_{truth} (mm);",
					    30,-15,15,100,-10,10);
	label.str("");
	label << "deltavsreco_y_pu"<< pu[ipu] << "_" << iL;
	p_deltavsreco_y[ipu][iL] = new TH2F(label.str().c_str(),";y reco (mm);y_{reco}-y_{truth} (mm);",
					    30,-15,15,100,-10,10);
	if (savePoint) {
	  label.str("");   
	  label << "recovstruth_x_pu"<< pu[ipu] << "_" << iL;
	  p_recovstruth_x[ipu][iL] = new TH2F(label.str().c_str(),";x_{truth} (mm);x reco (mm)",
					      30,-15,15,30,-15,15);
	  label.str("");
	  label << "recovstruth_y_pu"<< pu[ipu] << "_" << iL;
	  p_recovstruth_y[ipu][iL] = new TH2F(label.str().c_str(),";y_{truth} (mm);y reco (mm)",
					      30,-15,15,//200,1170,1370,
					      30,-15,15
					      ); 
	    
	}


	if (savePoint) {
	  if (savePoint) {
	    label.str("");   
	    label << "pu" << pu[ipu];
	    fout->cd(label.str().c_str());
	  }
	  for (unsigned i(0);i<5;++i){
	    label.str("");     
	    label << "wx_pu" << pu[ipu] << "_" << iL << "_" << i;
	    p_wx[ipu][iL][i] = new TH1F(label.str().c_str(),
					";wx;events",
					100,-10,0);
	    label.str("");     
	    label << "wy_pu" << pu[ipu] << "_" << iL << "_" << i;
	    p_wy[ipu][iL][i] = new TH1F(label.str().c_str(),
					";wy;events",
					100,-10,0);
	  }
	}
	for (unsigned iS(0); iS<nScans;++iS){
	  label.str("");
	  label << "scan/xpos/scan_" << wStart+iS*wStep;
	  if (savePoint) fout->cd(label.str().c_str());
	  label.str("");
	  label << "posx_pu" << pu[ipu] << "_" << iL << "_" << iS;
	  p_posx[ipu][iL][iS] = new TH1F(label.str().c_str(),
					 ";x-x_{truth} (mm);events",
					 100,-10,10);
	  label.str("");
	  label << "scan/ypos/scan_" << wStart+iS*wStep;
	  if (savePoint) fout->cd(label.str().c_str());
	  label.str("");
	  label << "posy_pu" << pu[ipu] << "_" << iL << "_" << iS;
	  p_posy[ipu][iL][iS] = new TH1F(label.str().c_str(),
					 ";y-y_{truth} (mm);events",
					 100,-10,10);
	}
      }//loop on layers
	  
      for (unsigned ipt(0); ipt<npt;++ipt){
	
	std::ostringstream linputStr;
	linputStr << plotDir << "/" << "eta" << eta[ieta] << "_et" << pt[ipt] << "_pu" << pu[ipu] ;
	//linputStr << "_logweight";
	linputStr << ".root";
	fin[ipu] = TFile::Open(linputStr.str().c_str());
	if (!fin[ipu]) {
	  std::cout << " -- Error, input file " << linputStr.str() << " cannot be opened. Skipping..." << std::endl;
	  continue;
	}
	else std::cout << " -- File " << linputStr.str() << " successfully opened." << std::endl;
	    
	TTree *tree = (TTree*)gDirectory->Get("EcellsSR2");
	if (!tree) {
	  std::cout << " Tree not found! " << std::endl;
	  continue;
	  //return 1;
	}

	for (unsigned iL(0);iL<nLayers;++iL){
	  label.str("");     
	  label << "TruthPosX_" << iL;
	  tree->SetBranchAddress(label.str().c_str(),&truthPosX[iL]);
	  label.str("");     
	  label << "TruthPosY_" << iL;
	  tree->SetBranchAddress(label.str().c_str(),&truthPosY[iL]);
	      
	  for (unsigned iy(0);iy<5;++iy){
	    for (unsigned ix(0);ix<5;++ix){
	      unsigned idx = 5*iy+ix;
	      label.str("");     
	      label << "E_" << iL << "_" << idx;
	      tree->SetBranchAddress(label.str().c_str(),&Exy[iL][idx]);
	    }
	  }
	}//loop on layers
	
	unsigned nEvts = tree->GetEntries();
	for (unsigned ievt(0); ievt<nEvts; ++ievt){//loop on entries
	      
	  if (ievt%50 == 0) std::cout << "... Processing entry: " << ievt << std::endl;
	      
	  tree->GetEntry(ievt);
	      
	  double Etotsq = 0;
	      
	  for (unsigned iL(0);iL<nLayers;++iL){
	    double Etot = 0;
	    double Ex[5] = {0,0,0,0,0};
	    double Ey[5] = {0,0,0,0,0};
	    for (unsigned idx(0);idx<25;++idx){
	      if (iL>22) Etot += Exy[iL][idx];
	      else if ((idx>5 && idx<9)||
		       (idx>10 && idx<14)||
		       (idx>15 && idx<19)) Etot += Exy[iL][idx];
	    }
	    Etotsq += pow(calibratedE(Etot*absWeight(iL,eta[ieta]/10.),eta[ieta]/10.),2);

	    if (iL>22){
	      Ex[0] = Exy[iL][0]+Exy[iL][5]+Exy[iL][10]+Exy[iL][15]+Exy[iL][20];
	      Ex[1] = Exy[iL][1]+Exy[iL][6]+Exy[iL][11]+Exy[iL][16]+Exy[iL][21];
	      Ex[2] = Exy[iL][2]+Exy[iL][7]+Exy[iL][12]+Exy[iL][17]+Exy[iL][22];
	      Ex[3] = Exy[iL][3]+Exy[iL][8]+Exy[iL][13]+Exy[iL][18]+Exy[iL][23];
	      Ex[4] = Exy[iL][4]+Exy[iL][9]+Exy[iL][14]+Exy[iL][19]+Exy[iL][24];
	      Ey[0] = Exy[iL][0]+Exy[iL][1]+Exy[iL][2]+Exy[iL][3]+Exy[iL][4];
	      Ey[1] = Exy[iL][5]+Exy[iL][6]+Exy[iL][7]+Exy[iL][8]+Exy[iL][9];
	      Ey[2] = Exy[iL][10]+Exy[iL][11]+Exy[iL][12]+Exy[iL][13]+Exy[iL][14];
	      Ey[3] = Exy[iL][15]+Exy[iL][16]+Exy[iL][17]+Exy[iL][18]+Exy[iL][19];
	      Ey[4] = Exy[iL][20]+Exy[iL][21]+Exy[iL][22]+Exy[iL][23]+Exy[iL][24];
	    }
	    else {
	      Ex[0] = Exy[iL][6]+Exy[iL][11]+Exy[iL][16];
	      Ex[1] = Exy[iL][7]+Exy[iL][12]+Exy[iL][17];
	      Ex[2] = Exy[iL][8]+Exy[iL][13]+Exy[iL][18];
	      Ey[0] = Exy[iL][6]+Exy[iL][7]+Exy[iL][8];
	      Ey[1] = Exy[iL][11]+Exy[iL][12]+Exy[iL][13];
	      Ey[2] = Exy[iL][16]+Exy[iL][17]+Exy[iL][18];
	    }
	    
	    double simplex = 0;
	    double simpley = 0;
	    if (Etot!=0) {
	      if (iL>22) {
		simplex = 10*(2*Ex[4]+Ex[3]-Ex[1]-2*Ex[0])/Etot;
		simpley = 10*(2*Ey[4]+Ey[3]-Ey[1]-2*Ey[0])/Etot;
	      }
	      else {
		simplex = 10*(Ex[2]-Ex[0])/Etot;
		simpley = 10*(Ey[2]-Ey[0])/Etot;
	      }
	    }
		
	    double xt = truthPosX[iL];
	    unsigned cellCenter = static_cast<unsigned>((truthPosY[iL]+5)/10.)*10;
	    double yt = 0;
	    //if (cellCenter>truthPosY[iL]) yt = cellCenter-truthPosY[iL];
	    yt=truthPosY[iL]-cellCenter;
	    p_deltavsreco_x[ipu][iL]->Fill(simplex,simplex-xt);
	    p_deltavsreco_y[ipu][iL]->Fill(simpley,simpley-yt);
	    if (savePoint) {
	      p_xt->Fill(xt);
	      p_yt->Fill(yt);
	      p_recovstruth_x[ipu][iL]->Fill(xt,simplex);
	      p_recovstruth_y[ipu][iL]->Fill(yt,simpley);
	
	      for (unsigned idx(0);idx<9;++idx){
		p_Exy[ipu][iL]->Fill(idx%5,idx/5,Exy[iL][idx]/Etot);
	      }
	    }
	    double wx[6][nScans];
	    double wy[6][nScans];
	  
	    for (unsigned i(0);i<6;++i){
	      for (unsigned iS(0); iS<nScans;++iS){
		wx[i][iS] = 0;
		wy[i][iS] = 0;
	      }
	    }
	    for (unsigned i(0);i<5;++i){
	      if (savePoint) p_wx[ipu][iL][i]->Fill(log(Ex[i]/Etot));
	      if (savePoint) p_wy[ipu][iL][i]->Fill(log(Ey[i]/Etot));
	      for (unsigned iS(0); iS<nScans;++iS){
		double w0 = wStart+iS*wStep;
		wx[i][iS] = std::max(0.,log(Ex[i]/Etot)+w0);
		wy[i][iS] = std::max(0.,log(Ey[i]/Etot)+w0);
		// if (log(Ex[i]/Etot)+w0<0)
		//   std::cout << " - iL= " << iL << " i=" << i << " w0=" << w0 
		// 		<< " logEx=" << log(Ex[i]/Etot)
		// 		<< " wx " << wx[i][iS] 
		// 		<< std::endl;
		// if (log(Ey[i]/Etot)+w0<0) 
		//   std::cout << " - iL= " << iL << " i=" << i << " w0=" << w0 
		// 		<< " logEy=" << log(Ey[i]/Etot)
		// 		<< " wy " << wy[i][iS] 
		// 		<< std::endl;
		wx[5][iS] += wx[i][iS];
		wy[5][iS] += wy[i][iS];
	      }
	    }
	    for (unsigned iS(0); iS<nScans;++iS){
	      double x = 0;//10*(wx[2][iS]-wx[0][iS])/wx[3][iS];
	      if (wx[5][iS]!=0) {
		if (iL>22) x = 10*(2*wx[4][iS]+wx[3][iS]-wx[1][iS]-2*wx[0][iS])/wx[5][iS];
		else x = 10*(wx[2][iS]-wx[0][iS])/wx[5][iS];
	      }
	      double y = 0;//10*(wy[2][iS]-wy[0][iS])/wy[3][iS];
	      if (wy[5][iS]!=0) {
		if (iL>22) y = 10*(2*wy[4][iS]+wy[3][iS]-wy[1][iS]-2*wy[0][iS])/wy[5][iS];
		else y = 10*(wy[2][iS]-wy[0][iS])/wy[5][iS];
	      }

	      //if (fabs(y-yt)>5) std::cout << " --- iL=" << iL << " iS=" << iS 
	      //<< " x=" << x << " xt=" << xt 
	      //<< " y=" << y << " yt=" << yt 
	      //<< std::endl;
	      p_posx[ipu][iL][iS]->Fill(x-xt);
	      p_posy[ipu][iL][iS]->Fill(y-yt);
	    }

	  }//loop on layers
	  if (savePoint) p_intercalibSigmaSquare[ipu]->Fill(Etotsq);
	}//loop on entries
    
      }//loop on pt

      //fill first point with linear weighting
      TLatex lat;
      char buf[500];

      for (unsigned iL(0);iL<nLayers;++iL){
	mycFit->cd();
	TH1D *projy = p_deltavsreco_x[ipu][iL]->ProjectionY();
	projy->Draw();
	projy->Fit("gaus","0+Q");
	TF1 *fitx = projy->GetFunction("gaus");
	fitx->SetLineColor(6);
	fitx->Draw("same");
	sprintf(buf,"Layer %d, linear weighting, pu=%d",iL,pu[ipu]);
	lat.DrawLatexNDC(0.1,0.96,buf);
	
	grX[ipu][iL]->SetPoint(0,0.5,fitx->GetParameter(2));
	grX[ipu][iL]->SetPointError(0,0,fitx->GetParError(2));
	grXrms[ipu][iL]->SetPoint(0,0.5,projy->GetRMS());
	grXrms[ipu][iL]->SetPointError(0,0,projy->GetRMSError());
	mycFit->Update();
	if (savePoint) mycFit->Print("PLOTS/fits_x.pdf");
	
	mycFit->cd();
	projy = p_deltavsreco_y[ipu][iL]->ProjectionY();
	projy->Draw();
	projy->Fit("gaus","0+Q");
	TF1 *fity = projy->GetFunction("gaus");
	fitx->SetLineColor(6);
	fitx->Draw("same");
	sprintf(buf,"Layer %d, linear weighting, pu=%d",iL,pu[ipu]);
	lat.DrawLatexNDC(0.1,0.96,buf);
	
	grY[ipu][iL]->SetPoint(0,0.5,fity->GetParameter(2));
	grY[ipu][iL]->SetPointError(0,0,fity->GetParError(2));
	grYrms[ipu][iL]->SetPoint(0,0.5,projy->GetRMS());
	grYrms[ipu][iL]->SetPointError(0,0,projy->GetRMSError());
	mycFit->Update();
	if (savePoint) mycFit->Print("PLOTS/fits_y.pdf");
      }

      //fit vs w0, get w0min
      for (unsigned iL(0);iL<nLayers;++iL){
	for (unsigned iS(0); iS<nScans;++iS){
	  mycFit->cd();
	  p_posx[ipu][iL][iS]->Draw();
	  double w0 = wStart+iS*wStep;
	  //myGaus->SetParameters();
	  p_posx[ipu][iL][iS]->Fit("gaus","0+Q","",-2.,2.);
	  TF1 *fitx = p_posx[ipu][iL][iS]->GetFunction("gaus");
	  fitx->SetLineColor(6);
	  fitx->Draw("same");
	  sprintf(buf,"Layer %d, w0=%3.1f, pu=%d",iL,w0,pu[ipu]);
	  lat.DrawLatexNDC(0.1,0.96,buf);

	  mycFit->Update();
	  if (savePoint) mycFit->Print("PLOTS/fits_x.pdf");

	  mycFit->cd();
	  p_posy[ipu][iL][iS]->Draw();
	  p_posy[ipu][iL][iS]->Fit("gaus","0+Q","",-2.,2.);
	  TF1 *fity = p_posy[ipu][iL][iS]->GetFunction("gaus");
	  fity->SetLineColor(6);
	  fity->Draw("same");
	  sprintf(buf,"Layer %d, w0=%3.1f, pu=%d",iL,w0,pu[ipu]);
	  lat.DrawLatexNDC(0.1,0.96,buf);
	  mycFit->Update();
	  if (savePoint) mycFit->Print("PLOTS/fits_y.pdf");
	  //grX[ipu][iL]->SetPoint(iS,w0,p_posx[ipu][iL][iS]->GetRMS());
	  //grX[ipu][iL]->SetPointError(iS,0,p_posx[ipu][iL][iS]->GetRMSError());
	  //grY[ipu][iL]->SetPoint(iS,w0,p_posy[ipu][iL][iS]->GetRMS());
	  //grY[ipu][iL]->SetPointError(iS,0,p_posy[ipu][iL][iS]->GetRMSError());
	  double xval = useFit? fitx->GetParameter(2) : p_posx[ipu][iL][iS]->GetRMS();
	  if (savePoint) p_chi2ndf->Fill(fitx->GetChisquare()/fitx->GetNDF());
	
	  grX[ipu][iL]->SetPoint(iS+1,w0,fitx->GetParameter(2));
	  grX[ipu][iL]->SetPointError(iS+1,0,fitx->GetParError(2));
	  grXrms[ipu][iL]->SetPoint(iS+1,w0,p_posx[ipu][iL][iS]->GetRMS());
	  grXrms[ipu][iL]->SetPointError(iS+1,0,p_posx[ipu][iL][iS]->GetRMSError());
	  if (xval < resxmin[ipu][iL]){
	    resxmin[ipu][iL] = xval;
	    wxminall[ipu][iL][ieta] = w0;
	    wxmin[ipu][iL] = w0;
	  }
	  double yval = useFit? fity->GetParameter(2) : p_posy[ipu][iL][iS]->GetRMS();
	  if (savePoint) p_chi2ndf->Fill(fity->GetChisquare()/fity->GetNDF());
	  grY[ipu][iL]->SetPoint(iS+1,w0,fity->GetParameter(2));
	  grY[ipu][iL]->SetPointError(iS+1,0,fity->GetParError(2));
	  grYrms[ipu][iL]->SetPoint(iS+1,w0,p_posy[ipu][iL][iS]->GetRMS());
	  grYrms[ipu][iL]->SetPointError(iS+1,0,p_posy[ipu][iL][iS]->GetRMSError());
	
	  if (yval < resymin[ipu][iL]){
	    resymin[ipu][iL] = yval;
	    wyminall[ipu][iL][ieta] = w0;
	    wymin[ipu][iL] = w0;
	  }
	}
	grX[ipu][iL]->SetTitle(";W0; #sigma(x-xt) (mm)");
	grY[ipu][iL]->SetTitle(";W0; #sigma(y-yt) (mm)");
	grX[ipu][iL]->SetLineColor(ipu+1);
	grX[ipu][iL]->SetMarkerColor(ipu+1);
	grX[ipu][iL]->SetMarkerStyle(ipu+21);
	grY[ipu][iL]->SetLineColor(ipu+1);
	grY[ipu][iL]->SetMarkerColor(ipu+1);
	grY[ipu][iL]->SetMarkerStyle(ipu+21);

	grXrms[ipu][iL]->SetLineColor(ipu+3);
	grXrms[ipu][iL]->SetMarkerColor(ipu+3);
	grXrms[ipu][iL]->SetMarkerStyle(ipu+23);
	grYrms[ipu][iL]->SetLineColor(ipu+3);
	grYrms[ipu][iL]->SetMarkerColor(ipu+3);
	grYrms[ipu][iL]->SetMarkerStyle(ipu+23);

	mycx[iL/6]->cd(iL%6+1);
	grX[ipu][iL]->Draw(ipu==0?"APL":"PLsame");
	grXrms[ipu][iL]->Draw("PLsame");
	//gStyle->SetStatX(0.4);
	//gStyle->SetStatY(1.0);
	//p_Exy[ipu][iL]->Draw("colztext");
	sprintf(buf,"Layer %d",iL);
	lat.DrawLatexNDC(0.4,0.85,buf);
	mycy[iL/6]->cd(iL%6+1);
	grY[ipu][iL]->Draw(ipu==0?"APL":"PLsame");
	grYrms[ipu][iL]->Draw("PLsame");
	lat.DrawLatexNDC(0.4,0.85,buf);

      }//loop on layers

      //return 1;
    }//loop on pu

    if (savePoint) {
      mycFit->Print("PLOTS/fits_x.pdf]");
      mycFit->Print("PLOTS/fits_y.pdf]");
    }

    return 1;

    TLegend *leg = new TLegend(0.6,0.6,0.94,0.94);
    leg->SetFillColor(0);
    if (grX[0][10]) leg->AddEntry(grX[0][10],"fit pu=0","P");
    if (grXrms[0][10]) leg->AddEntry(grXrms[0][10],"RMS pu=0","P");
    if (grX[1][10]) leg->AddEntry(grX[1][10],"fit pu=140","P");
    if (grXrms[1][10]) leg->AddEntry(grXrms[1][10],"RMS pu=140","P");
    for (unsigned iC(0);iC<nCanvas;++iC){
      mycx[iC]->cd(1);
      leg->Draw("same");
      mycx[iC]->Update();
      std::ostringstream lsave;
      lsave << "PLOTS/logWeighted_x_" << 6*iC << "_" << 6*iC+5 << "_" << pteta.str() ;
      lsave << ".pdf";
      mycx[iC]->Print(lsave.str().c_str());
      mycx[iC]->Update();
	
      mycy[iC]->cd(1);
      leg->Draw("same");
      lsave.str("");
      lsave << "PLOTS/logWeighted_y_" << 6*iC << "_" << 6*iC+5 << "_" << pteta.str();
      lsave << ".pdf";
      mycy[iC]->Print(lsave.str().c_str());
    }
      
    //plot w0min vs layer
    TGraph *grW[4] = {0,0,0,0};
    for (unsigned ipu(0); ipu<nPu; ++ipu){//loop on pu
      std::cout << " --Processing pu " << pu[ipu] << std::endl;
	
      grW[2*ipu] = new TGraph(nLayers,lay,wxmin[ipu]);
      grW[2*ipu+1] = new TGraph(nLayers,lay,wymin[ipu]);
      for (unsigned iL(0);iL<nLayers;++iL){
	std::cout << " if (layer==" << iL 
		  << ") return " << (wxmin[ipu][iL]+wymin[ipu][iL])/2. <<";"
	  //		<< " minimum x= " << grX[ipu][iL]->GetYaxis()->GetXmin()
	  //		<< " minimum y= " << grY[ipu][iL]->GetYaxis()->GetXmin()
		  << std::endl;
      }
      mycW->cd();
      grW[2*ipu]->SetTitle(";layer;W0");
      grW[2*ipu]->SetMaximum(6);
      grW[2*ipu]->SetMinimum(0);
      grW[2*ipu]->SetLineColor(2*ipu+1);
      grW[2*ipu]->SetMarkerColor(2*ipu+1);
      grW[2*ipu]->SetMarkerStyle(20+2*ipu+1);
      grW[2*ipu+1]->SetLineColor(2*ipu+2);
      grW[2*ipu+1]->SetMarkerColor(2*ipu+2);
      grW[2*ipu+1]->SetMarkerStyle(20+2*ipu+2);
      if (ipu==0) {
	grW[2*ipu]->Draw("APL");
	grW[2*ipu+1]->Draw("PLsame");
      }
      else {
	grW[2*ipu]->Draw("PLsame");
	grW[2*ipu+1]->Draw("PLsame");
      }
    }
    std::ostringstream lsave;
    lsave << "PLOTS/w0minvsLayers_" << pteta.str();
    if (useFit) lsave << "_fit";
    else lsave << "_rms";
    lsave << ".pdf";
    mycW->Update();
    mycW->Print(lsave.str().c_str());

    if (savePoint) fout->Write();
    else {
      for (unsigned i(0);i<4;++i){
	if (grW[i]) grW[i]->Delete();
      }
      for (unsigned ipu(0); ipu<nPu; ++ipu){//loop on pu
	for (unsigned iL(0); iL<nLayers;++iL){//loop on layers
	  grX[ipu][iL]->Delete();
	  grXrms[ipu][iL]->Delete();
	  grY[ipu][iL]->Delete();
	  grYrms[ipu][iL]->Delete();
	  p_deltavsreco_x[ipu][iL]->Delete();
	  p_deltavsreco_y[ipu][iL]->Delete();
	  for (unsigned iS(0); iS<nScans;++iS){
	    p_posx[ipu][iL][iS]->Delete();
	    p_posy[ipu][iL][iS]->Delete();
	  }
	}
      }
    }

    std::cout << " -- eta point finished successfully" << std::endl;

  }//loop on eta

  //plot w0min vs pt for all eta
  TGraph *grW[4] = {0,0,0,0};
  mycW->Clear();
  for (unsigned iL(0); iL<nLayers;++iL){//loop on layers
    for (unsigned ipu(0); ipu<nPu; ++ipu){//loop on pu
      std::cout << " --Processing pu " << pu[ipu] << std::endl;
      grW[2*ipu] = new TGraph(neta,etaval,wxminall[ipu][iL]);
      grW[2*ipu+1] = new TGraph(neta,etaval,wyminall[ipu][iL]);
      mycW->cd();//ieta+1);
      grW[2*ipu]->SetTitle(";#eta;W0");
      grW[2*ipu]->SetMaximum(6);
      grW[2*ipu]->SetMinimum(0);
      grW[2*ipu]->SetLineColor(2*ipu+1);
      grW[2*ipu]->SetMarkerColor(2*ipu+1);
      grW[2*ipu]->SetMarkerStyle(20+2*ipu+1);
      grW[2*ipu+1]->SetLineColor(2*ipu+2);
      grW[2*ipu+1]->SetMarkerColor(2*ipu+2);
      grW[2*ipu+1]->SetMarkerStyle(20+2*ipu+2);
      if (ipu==0) {
	grW[2*ipu]->Draw("APL");
	grW[2*ipu+1]->Draw("PLsame");
      }
      else {
	grW[2*ipu]->Draw("PLsame");
	grW[2*ipu+1]->Draw("PLsame");
      }
    }//loop on pu
    std::ostringstream lsave;
    lsave << "PLOTS/w0minvseta_layer" << iL;
    if (useFit) lsave << "_fit";
    else lsave << "_rms";
    lsave << ".pdf";
    
    char buf[500];
    TLatex lat;
    sprintf(buf,"Layer %d",iL);
    lat.DrawLatexNDC(0.1,0.96,buf);
    
    mycW->Update();
    mycW->Print(lsave.str().c_str());
  }//loop on layers
  
  
  return 0;
}//main
Example #15
0
void fitTools::getTruncatedMeanAndRMS(TH1D* h1_projection, Float_t& mean, Float_t& mean_err, Float_t& rms, Float_t& rms_err, Double_t percentIntegral_MEAN, Double_t percentIntegral_RMS) {
//TCanvas* getTruncatedMeanAndRMS(TH1D* h1_projection, Float_t& mean, Float_t& mean_err, Float_t& rms, Float_t& rms_err, Double_t percentIntegral_MEAN=0.9, Double_t percentIntegral_RMS=0.68) {

   bool useMode = false;


   if( percentIntegral_MEAN<0. || percentIntegral_MEAN>1. ) {
     std::cout << "WARNING! percentIntegral_MEAN is " << percentIntegral_MEAN << "!! Setting it to 90%." << std::endl;
     percentIntegral_MEAN = 0.9;
   }

   if( percentIntegral_RMS<0. || percentIntegral_RMS>1. ) {
     std::cout << "WARNING! percentIntegral_RMS is " << percentIntegral_RMS << "!! Setting it to 68%." << std::endl;
     percentIntegral_RMS = 0.68;
   }

   Int_t nBins = h1_projection->GetNbinsX();
   Double_t xMin = h1_projection->GetXaxis()->GetXmin();
   Double_t xMax = h1_projection->GetXaxis()->GetXmax();
   Double_t binWidth = (xMax-xMin)/(Double_t)nBins; //WARNING: this works only if bins are of the same size
   Double_t integral = h1_projection->Integral();
//  std::cout << "xmax: " << xMax << "\txMin: " << xMin << std::endl;
  
   //first: find maximum
//  std::cout << "N: " << gaussian->GetParameter(0) << "\tmu: " << gaussian->GetParameter(1) << "\tsigma: " << gaussian->GetParameter(2) << std::endl;
   Int_t maxBin;
   if( useMode ) {
     maxBin = h1_projection->GetMaximumBin();
   } else {
     TF1* gaussian = new TF1("gaussian", "gaus");
     gaussian->SetLineColor(kGreen);
     fitProjection(h1_projection, gaussian, 1.5, "RQN");
     maxBin = (Int_t)ceil((gaussian->GetParameter(1)-xMin)/binWidth);
     delete gaussian;
   }

//  std::cout << "maxBin: " << maxBin << "\tbin center: " << h1_projection->GetXaxis()->GetBinCenter(maxBin) << "\t gauss mu: " << gaussian->GetParameter(1) << std::endl;
   TH1D* newHisto = new TH1D("newHisto", "", nBins, xMin, xMax);
   newHisto->SetBinContent( maxBin, h1_projection->GetBinContent(maxBin) );
   newHisto->SetBinError( maxBin, h1_projection->GetBinError(maxBin) );
   Int_t iBin = maxBin;
   Int_t delta_iBin = 1;
   Int_t sign  = 1;
//  std::cout << "iBin: " << iBin << "\tint: " << newHisto->Integral()/integral << std::endl;

   while( newHisto->Integral() < percentIntegral_RMS*integral ) {

     iBin += sign*delta_iBin; 
     
//  std::cout << "iBin: " << iBin << "\tint: " << newHisto->Integral()/integral << std::endl;
     newHisto->SetBinContent( iBin, h1_projection->GetBinContent(iBin) );
     newHisto->SetBinError( iBin, h1_projection->GetBinError(iBin) );

     delta_iBin += 1;
     sign *= -1;

   }

//  std::cout << "done with rms." << std::endl;
//    TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);
//    c1->cd();
//    h1_projection->Draw();
//    newHisto->SetFillColor(kRed);
//    newHisto->DrawClone("HISTO same");

   rms = newHisto->GetRMS();
   rms_err = newHisto->GetRMSError();

//std::cout << "rms: " << rms << std::endl;
   while( newHisto->Integral() < percentIntegral_MEAN*integral ) {
//  std::cout << "iBin: " << iBin << "\tint: " << newHisto->Integral()/integral << std::endl;

     iBin += sign*delta_iBin; 
     
     newHisto->SetBinContent( iBin, h1_projection->GetBinContent(iBin) );
     newHisto->SetBinError( iBin, h1_projection->GetBinError(iBin) );

     delta_iBin += 1;
     sign *= -1;

   }

//    newHisto->SetFillStyle(3004);
//    newHisto->SetFillColor(kBlue);
//    newHisto->DrawClone("HISTO same");

   mean = newHisto->GetMean();
   mean_err = newHisto->GetMeanError();

   delete newHisto;

//    return c1;
}
Example #16
0
	TGraphErrors *FitConfidence::choleskyBands( TFitResultPtr fitResult, TF1 * f, int nSamples, int nPoints, Reporter* rp,  double x1, double x2 ){

		int nP = f->GetNpar();
		// INFO( FitConfidence::classname(), "Num Params : " << nP  );
		TMatrixDSym cov = fitResult->GetCovarianceMatrix();
		double *covArray = new double[ nP * nP ]; // number of parameters x number of parameters
		covArray = cov.GetMatrixArray();

		// for ( int i = 0; i < 9; i++ ){
		// 	INFO( FitConfidence::classname(), "[" << i << "] = " << covArray[ i ] );
		// }

		double *fCov = new double[ nP * nP ];
		fCov = cov.GetMatrixArray();
		double *fCovSqrt = new double[ nP * nP ];
		calcCholesky( nP, fCov, fCovSqrt );

		// for ( int i = 0; i < 9; i++ ){
		// 	INFO( FitConfidence::classname(), "[" << i << "] = " << fCovSqrt[ i ] );
		// }

		

		// calculate instead
		if ( -1.0 == x1  && -1.0 == x2 )
			f->GetRange( x1, x2 );

		double step = ( x2 - x1 ) / (double) nPoints;

		double x[ nPoints + 1 ];
		double y[ nPoints + 1 ];
		// double yup[ nPoints + 1 ];
		// double ydown[ nPoints + 1 ];
		double yerr[ nPoints + 1 ];
		vector<double> samples;

		int i = 0;
		for (double xx = x1; xx < x2; xx+= step) {
			x[i] = xx;
			TH1D *hDistributionAtX = new TH1D("hDistributionAtX","",200,f->Eval(x[i]) - .2,f->Eval(x[i]) + .2);
			for (int n = 0; n < nSamples; n++ ) {
				double val = randomSqrtCov(x[i],f,nP,fCovSqrt);
				hDistributionAtX->Fill( val );
				samples.push_back( val );
			}
			//hDistributionAtX->DrawCopy();

			y[i] 		= f->Eval(x[i]);
			yerr[i] 	= hDistributionAtX->GetRMS();
			
			// cross check - should always give the same result
			// but very innefficient
			//yerr[i] = choleskyUncertainty( xx, fitResult, f, nSamples );

			// rp.savePage();
			hDistributionAtX->Delete();
			i++;
		} 

		TGraphErrors * g = new TGraphErrors( i - 1, x, y, 0, yerr );

		return g;
	}
Example #17
0
void runlsbpvrw(TString name = "ge1bLoose") {

  TFile* fin = TFile::Open("../pvrw.root","READ");
  if(fin->IsZombie()) cout << "Problem opening input file!" << endl;
  
  TH1D* hPVphysics = (TH1D*)fin->Get("hPVphysics_"+name);
  TH1D* hPVprescalePass = (TH1D*)fin->Get("hPVprescalePass_"+name);
  TH1D* hPVprescaleFail = (TH1D*)fin->Get("hPVprescaleFail_"+name);
  
  TH1D* tPVphysics = (TH1D*)hPVphysics->Clone("tPVphysics");
  TH1D* tPVprescalePass = (TH1D*)hPVprescalePass->Clone("tPVprescalePass");
  TH1D* tPVprescaleFail = (TH1D*)hPVprescaleFail->Clone("tPVprescaleFail");
  tPVphysics->Reset();
  tPVprescalePass->Reset();
  tPVprescaleFail->Reset();
  
  TH1D* hPFresults = new TH1D("hPFresults", "hPFresults", 500, 0.0, 0.3);


  //toy loop
  for(int i=0; i<1000; i++) {
    
    //make toy inputs
    for(int n=1; n<=hPVphysics->GetNbinsX(); n++) {
      //tPVphysics->SetBinContent(n,r->Gaus(hPVphysics->GetBinContent(n), hPVphysics->GetBinError(n)));
      //tPVprescalePass->SetBinContent(n,r->Gaus(hPVprescalePass->GetBinContent(n),hPVprescalePass->GetBinError(n)));
      //tPVprescaleFail->SetBinContent(n,r->Gaus(hPVprescaleFail->GetBinContent(n),hPVprescaleFail->GetBinError(n)));

      tPVphysics->SetBinContent(n,r->Poisson(hPVphysics->GetBinContent(n)));
      tPVprescalePass->SetBinContent(n,r->Poisson(hPVprescalePass->GetBinContent(n)));
      tPVprescaleFail->SetBinContent(n,r->Poisson(hPVprescaleFail->GetBinContent(n)));
    }

    
    //do cross check (no toy)
    if(i==0) {
      TH1D* hPVprescale = (TH1D*)hPVprescalePass->Clone("hPVprescale");
      hPVprescale->Reset();
      hPVprescale->Add(hPVprescalePass,hPVprescaleFail);

      TH1D* hPVprescale_RW = (TH1D*)hPVphysics->Clone("hPVprescale_RW");
      hPVprescale_RW->Scale(hPVprescale->Integral()/hPVphysics->Integral());
      TH1D* hPV_W = (TH1D*)hPVphysics->Clone("hPV_W");
      hPV_W->Reset();
      hPV_W->Divide(hPVprescale_RW,hPVprescale); 
      
      //weighted LSB pass and fail mdp
      TH1D* hPVprescalePass_RW = (TH1D*)hPVprescalePass->Clone("hPVprescalePass_RW");
      TH1D* hPVprescaleFail_RW = (TH1D*)hPVprescaleFail->Clone("hPVprescaleFail_RW");
      hPVprescalePass_RW->Multiply(hPV_W);
      hPVprescaleFail_RW->Multiply(hPV_W);
    
      cout << name << " PFratio: " << hPVprescalePass_RW->Integral()/hPVprescaleFail_RW->Integral() << endl;
    }


    //now find PFratio for this toy
    TH1D* tPVprescale = (TH1D*)tPVprescalePass->Clone("tPVprescale");
    tPVprescale->Reset();
    tPVprescale->Add(tPVprescalePass,tPVprescaleFail);
    
    TH1D* tPVprescale_RW = (TH1D*)tPVphysics->Clone("tPVprescale_RW");
    tPVprescale_RW->Scale(tPVprescale->Integral()/tPVphysics->Integral());
    TH1D* tPV_W = (TH1D*)tPVphysics->Clone("tPV_W");
    tPV_W->Reset();
    tPV_W->Divide(tPVprescale_RW,tPVprescale); 
    
    //weighted LSB pass and fail mdp
    TH1D* tPVprescalePass_RW = (TH1D*)tPVprescalePass->Clone("tPVprescalePass_RW");
    TH1D* tPVprescaleFail_RW = (TH1D*)tPVprescaleFail->Clone("tPVprescaleFail_RW");
    tPVprescalePass_RW->Multiply(tPV_W);
    tPVprescaleFail_RW->Multiply(tPV_W);
    
    double tPFratio = tPVprescalePass_RW->Integral()/tPVprescaleFail_RW->Integral();
      
    hPFresults->Fill(tPFratio);

  }//end of toy loop
  
  cout << name << " result: " << hPFresults->GetMean() << " +- " << hPFresults->GetRMS() << endl;

  TCanvas* c1 = new TCanvas("c1", "c1", 640, 480);
  c1->cd();
  hPFresults->Draw();  
  c1->SaveAs("lsbpvrw_"+name+".png");

  fin->Close();
}
void balanceMetVsAj(TString infname,
                    TString insrc, TString metType = "",bool drawLegend = false,
                    bool drawSys = true
                    )
{
   // ===========================================================
   // Get Input
   // ===========================================================
   TFile *inf = new TFile(infname);
   
   // ===========================================================
   // Analysis Setup
   // ===========================================================
   Int_t plotLayer=10; // 0 only >0.5, 1 >0.5 and highpt, 10 ~ all
   
   cout << infname << " " << insrc << endl;
   
   TH1D *ppos[nptrange+1];
   TH1D *pneg[nptrange+1];
   TH1D *pe[nptrange+1];

   // =================================
   // Get Weighted Mean for each Aj bin
   // =================================
   // Book histograms
   for (int i=0;i<nptrange+1;i++) {
      pe[i]=new TH1D(Form("p%d",i),"",nAjBin,AjBins);
   }
   
   TTree * tm = (TTree*)inf->Get("t"+insrc);
   // Find cone boundary
   int coneidr=0;
   for (int idr=0; idr<ndrbin; ++idr) {
      if (drbins[idr]>=0.8)  {
         coneidr=idr;
         break;
      }
   }
   
   // Get Values
   for (int a=0; a<nAjBin; ++a) {
      float sum=0, sumerr=0;
      for (int i=0;i<nptrange+1;i++) {
//          hname = Form("%s_merge%d_%s",insrc.Data(),i,metType.Data());
         TString hname = "hMpt"+insrc;
         if (i<nptrange) hname+=Form("_pt%d",i);
         else hname+=Form("_ptall");
//          TH2D * hMptAj = (TH2D*)inf->Get(hname);
//          cout << hname << " " << hMptAj << endl;
//          TH1D * hMpt = hMptAj->ProjectionY(hname+Form("_a%d",a),a+1,a+1);
         hname+=Form("_a%d",a);
         TString cut = Form("Aj>=%.3f&&Aj<%.3f",AjBins[a],AjBins[a+1]);
         TH1D * hMpt = new TH1D(hname,cut,1600,-800,800);
         // Define Observable: limited dR
         TString var;
         int idrbeg,idrend;
         if (metType=="InCone") {
            idrbeg=0; idrend=coneidr;
         } else {
            idrbeg=coneidr; idrend=ndrbin;
         }
         if (i<nptrange) {
            var  = Form("xptdr[%d][%d]",i,idrbeg);
            for (int idr=idrbeg+1; idr<idrend; ++idr) {
               var+= Form("+xptdr[%d][%d]",i,idr);
            }
         } else {
            var = Form("Sum$(xptdr[][%d])",idrbeg);
            for (int idr=idrbeg+1; idr<idrend; ++idr) {
               var+= Form("+Sum$(xptdr[][%d])",idr);
            }
         }
         // Now make histograms
         if (a==0) cout << metType << ": " << var << endl;
         tm->Project(hname,var,cut);
         float mpt = hMpt->GetMean();
         float mpterr = hMpt->GetRMS()/sqrt(hMpt->GetEntries());
         if (doResCorr) {
            if (i==nptrange) {
               mpt-=(pe[nptrange-4]->GetBinContent(a+1)*0.2);
               mpt-=(pe[nptrange-3]->GetBinContent(a+1)*0.2);
               mpt-=(pe[nptrange-2]->GetBinContent(a+1)*0.2);
               mpt-=(pe[nptrange-1]->GetBinContent(a+1)*0.2);
            } else if (i>=nptrange-4) {
               mpt*=0.8;
            }
         }
         pe[i]->SetBinContent(a+1,mpt);
         pe[i]->SetBinError(a+1,mpterr);
//          cout << hMpt->GetName() << ": " << hMpt->GetEntries() << " mean: " << pe[i]->GetBinContent(a+1) << " err: " << pe[i]->GetBinError(a+1) << endl;
         if (i<nptrange) {
            sum+=mpt;
            sumerr+=pow(mpterr,2);
         }
      }      
      cout << "Aj " << a << " pt sum: " << sum << endl;
   }
   
   StackHistograms(nptrange,pe,ppos,pneg,nAjBin);
   
   TH1D *pall=pe[nptrange];
   
   pall->SetXTitle("A_{J}");
   pall->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)");
   pall->GetXaxis()->CenterTitle();
   pall->GetYaxis()->CenterTitle();
   pall->GetXaxis()->SetLabelSize(22);
   pall->GetXaxis()->SetLabelFont(43);
   pall->GetXaxis()->SetTitleSize(24);
   pall->GetXaxis()->SetTitleFont(43);
   pall->GetYaxis()->SetLabelSize(22);
   pall->GetYaxis()->SetLabelFont(43);
   pall->GetYaxis()->SetTitleSize(24);
   pall->GetYaxis()->SetTitleFont(43);
   pall->GetXaxis()->SetTitleOffset(1.8);
   pall->GetYaxis()->SetTitleOffset(2.4);
   pall->SetNdivisions(505);
   pall->SetAxisRange(-59.9,59.9,"Y");
   pall->SetMarkerSize(1);
   pall->SetMarkerColor(kBlack);
   pall->SetMarkerStyle(kFullCircle);
   pall->Draw("E");
   float addSys = 0;
   if ( drawSys==1)   addSys=0; // No sys error at this moment
   
   // ====================
   // Finally Draw
   // ====================
   for (int i=0;i<nptrange;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nptrange-1) continue;
      ppos[i]->SetLineWidth(1);
      ppos[i]->SetFillStyle(1001);
      ppos[i]->Draw("hist same");
      pneg[i]->SetLineWidth(1);
      pneg[i]->SetFillStyle(1001);
      pneg[i]->Draw("hist same");
//      PrintHistogram(ppos[i]);
//      PrintHistogram(pneg[i]);
   }
   
   // ====================
   // Draw Statistical Error bars
   // ====================
   for (int i=0;i<nptrange;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nptrange-1) continue;
      if ( i==0 )       drawErrorShift(ppos[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(ppos[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(ppos[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(ppos[i],0.016,addSys);
      if ( i==0 )       drawErrorShift(pneg[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(pneg[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(pneg[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(pneg[i],0.016,addSys);
   }
   pall->Draw("E same");
//   PrintHistogram(pall);
   
   // ====================
   // Draw Systematic Errors
   // ====================
   if (drawSys == 1) {
      for(int i = 0; i < nAjBin; ++i){
         double x = pall->GetBinCenter(i+1);
         double y = pall->GetBinContent(i+1);
         // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics
         double errReco = -pe[nptrange-1]->GetBinContent(i+1)*0.2;
         double errBck = 3.0; // compare HYDJET+SIG to SIG
         double err = sqrt(errReco*errReco+errBck*errBck);
         DrawTick(y,err,err,x,1,0.02,1);
      }
   }
   
   // ====================
   // Draw Legend
   // ====================
   TLegend *leg = new TLegend(0.10,0.68,0.70,0.96);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(63);
   leg->SetTextSize(16);
   leg->AddEntry(pall,Form("> %.1f GeV/c",ptranges[0]),"p");
   for (int i=0;i<nptrange;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nptrange-1) continue;
      if (i!=nptrange-1){
         leg->AddEntry(ppos[i],Form("%.1f - %.1f GeV/c",ptranges[i],ptranges[i+1]),"f");
      } else {
         leg->AddEntry(ppos[i],Form("> %.1f GeV/c",ptranges[i]),"f");
      }
   }
   
   if (drawLegend) leg->Draw();
   
   TLine * l0 = new TLine(0,0,0.5,0);
   l0->SetLineStyle(2);
   l0->Draw();
   
   
   TLine * l1 = new TLine(0.0001,-10,0.0001,10);
   l1->Draw();
}
int main(int argc, char* argv[]) {

  std::string outputDir = "AK4Jets_Plot";                 
  mkdir(outputDir.c_str(), 0777); 

  TString dataFileName_DoubleMu;
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_DoubleMu.root");
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_DoubleMu.root");
  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_DoubleMu.root");
  TFile* dataFile_DoubleMu = TFile::Open(dataFileName_DoubleMu);
  if (dataFile_DoubleMu) {
    std::cout << "Opened data file '" << dataFileName_DoubleMu << "'." << std::endl;
  }
  TString dataFileName_HT450;
  //  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_HT450.root");
  //  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_HT450.root");
  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_WideEtaBin_HT450.root");
  TFile* dataFile_HT450 = TFile::Open(dataFileName_HT450);
  if (dataFile_HT450) {
    std::cout << "Opened data file '" << dataFileName_HT450 << "'." << std::endl;
  }

  TH1D *pT_AK4JetHLT = (TH1D*)dataFile_HT450->Get("AK4_pT_JetHLT");

  gErrorIgnoreLevel = kWarning;

  TF1* lineup1      = new TF1("lineup1", " 0.01", 0, 3000);
  TF1* linedown1 = new TF1("linedown1", "-0.01", 0, 3000);
  lineup1->SetLineColor(kBlack);                                                                                                                                        
  lineup1->SetLineStyle(2);                                                                                                                                             
  linedown1->SetLineColor(kBlack);                                                                                                                                      
  linedown1->SetLineStyle(2);

  TF1* lineup2      = new TF1("lineup2", " 0.02", 0, 3000);
  TF1* linedown2 = new TF1("linedown2", "-0.02", 0, 3000);
  lineup2->SetLineColor(kBlack);                                                                                                                                        
  lineup2->SetLineStyle(2);                                                                                                                                             
  linedown2->SetLineColor(kBlack);                                                                                                                                      
  linedown2->SetLineStyle(2);


  // procedura
  // prendo gli istogramma 1D del bias
  // per ogni bin di pT e eta
  // li fitto con una cristal ball
  // poi grafico il picco in funzione del pT in ogni bin di eta
  // fitto con una funzione logaritmica
  // mi creo l'istogramma 2D (eta,pT) con correzione sull'asse z

  //////////////////////// pTBias 1D
  EtaBinning mEtaBinning;
  size_t etaBinningSize = mEtaBinning.size();
  PtBinning mPtBinning;
  size_t pTBinningSize = mPtBinning.size();

  cout<< etaBinningSize << endl;

  for (size_t ii = 0; ii < etaBinningSize; ii++) {
    // for (size_t ii = 0; ii < 1; ii++) {
    for (size_t jj = 0; jj < pTBinningSize; jj++) {
      // for (size_t jj = 8; jj < 9; jj++) {
      
      std::string etaName = mEtaBinning.getBinName(ii);
      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      
      std::string HistoName = TString::Format("AK4_pTBias_%s_pT_%i_%i", etaName.c_str(), (int) ptBins.first, (int) ptBins.second ).Data();

      cout<< "("<<ii << ";"<< jj<<")" << endl;
      cout<< HistoName.c_str() << endl;


      TH1D *h;

      double sigma;
      double sigma2;
      
      if( jj < 2){ // pT<300
	sigma = 3;
	sigma2 = 4;
	h = (TH1D*)dataFile_DoubleMu->Get( HistoName.c_str() );
	cout << " Lo prendo dal DoubleMu" << endl;
      }else if( jj<8 ){
	sigma = 4; // 4
	sigma2 = 5; //5
	h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }else{
	sigma = 4;
	sigma2 = 4; //3
	h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
	cout << " Lo prendo dal HT450" << endl;
      }
      
      if( jj > 8) continue; // >8 prima
      if( ii==3 && jj > 6) continue; // ultimo fit in endcap non funziona
      if(!h) continue;
      int Nentries = h->GetEntries();
      if(Nentries<100) continue; //200

      h->Rebin(2);

      double hN = h->GetMaximum();
      double hMean = h->GetMean();
      double hRMS = h->GetRMS();

      /*
	TF1 *expon = new TF1("expon", "[0] + [1]*exp(-[2]*x)", 0.1, 0.4);
	h -> Fit(expon, "R");
      */
      
      /*
      TF1 *crystal = new TF1("crystal", CrystalBall, hMean-2*hRMS , hMean+1*hRMS, 5);
      crystal->SetParameters(hN, hMean, hRMS, 1.0, 2.0);
      crystal->SetParNames("N", "Mean", "sigma","#alpha","n");
      crystal->SetParLimits(0, hN-0.05*hN, hN+0.05*hN);
      h -> Fit(crystal, "R");
      */

      /*
	TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, hMean-3*hRMS , hMean+4*hRMS, 7);
	doublecrystal->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
	doublecrystal->SetParameters(hN, 0.01, 0.03, 1.2, 30., 15, 40.);
	doublecrystal->SetParLimits(1, 0.005, 0.015);
	doublecrystal->SetParLimits(2, 0.015, 0.035);
	doublecrystal->SetParLimits(3, 0 , 1.4);
	doublecrystal->SetParLimits(4, 1, 10);
	doublecrystal->SetParLimits(5, 0, 10);
	doublecrystal->SetParLimits(6, 0, 15);
	h -> Fit(doublecrystal, "R");
      */

      /*
      // secondo giro
      TF1 *doublecrystal2 = new TF1("doublecrystal2", doubleCrystalBall, doublecrystal->GetParameter(1)-2* doublecrystal->GetParameter(2),doublecrystal->GetParameter(1)+1*doublecrystal->GetParameter(2), 7);      
      doublecrystal2->SetLineColor(kBlue);
      doublecrystal2->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      doublecrystal2->SetParameters(doublecrystal->GetParameter(0), doublecrystal->GetParameter(1), doublecrystal->GetParameter(2),  doublecrystal->GetParameter(3),  doublecrystal->GetParameter(4),  doublecrystal->GetParameter(5), doublecrystal->GetParameter(6));  
      h -> Fit(doublecrystal2, "+R");

      // terzo giro
      TF1 *doublecrystal3 = new TF1("doublecrystal3", doubleCrystalBall, doublecrystal2->GetParameter(1)-2* doublecrystal2->GetParameter(2),doublecrystal2->GetParameter(1)+1*doublecrystal2->GetParameter(2), 7);      
      doublecrystal3->SetLineColor(kGreen);
      doublecrystal3->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      doublecrystal3->SetParameters(doublecrystal2->GetParameter(0), doublecrystal2->GetParameter(1), doublecrystal2->GetParameter(2),  doublecrystal2->GetParameter(3),  doublecrystal2->GetParameter(4),  doublecrystal2->GetParameter(5), doublecrystal2->GetParameter(6));  
      h -> Fit(doublecrystal3, "+R");
      */      
      /*
      // provo a fittare solo la coda --> non viene manco cosi
      TF1 *Function = new TF1("Function", "[0]*(  (pow([4]/fabs([3]),[4])*exp(-0.5*[3]*[3])) / pow( ([4]/fabs([3])- fabs([3]) - (x - [1])/[2]),[4]))", 0.03 , 0.4);
      Function->SetParNames("N", "Mean", "sigma","aR","nR");
      Function->SetParameters(hN, hMean, hRMS, 1 , 3.);
      Function->SetParLimits(0, hN-0.05*hN, hN+0.05*hN);
      h -> Fit(Function, "R");
      */

      TF1 *ExponentialGauss = new TF1("ExponentialGauss", ExpGaussExp, hMean-sigma*hRMS , hMean+sigma*hRMS, 5);
      ExponentialGauss->SetParNames("N", "Mean", "sigma","kL","kR");
      ExponentialGauss->SetParameters(hN, hMean, hRMS, 1., 1.);
      ExponentialGauss->SetParLimits(0, hN-0.2*hN, hN+0.2*hN); // se non funziona rimettilo
      if( jj>= 8 ) ExponentialGauss->SetParLimits(2, 0.005, 0.025);
      // if( jj>= 9 ) ExponentialGauss->SetParLimits(1, -0.01, 0.01);
      // ExponentialGauss->FixParameter(0, hN);
      h -> Fit(ExponentialGauss, "R");

      // secondo giro
      TF1 *ExponentialGauss2 = new TF1("ExponentialGauss2", ExpGaussExp, ExponentialGauss->GetParameter(1)-sigma2*ExponentialGauss->GetParameter(2) , ExponentialGauss->GetParameter(1)+sigma2*ExponentialGauss->GetParameter(2), 5);
      ExponentialGauss2 -> SetParNames("N", "Mean", "sigma","kL","kR");
      ExponentialGauss2 -> SetParameters( ExponentialGauss->GetParameter(0), ExponentialGauss->GetParameter(1), ExponentialGauss->GetParameter(2), ExponentialGauss->GetParameter(3), ExponentialGauss->GetParameter(4));
      h -> Fit(ExponentialGauss2, "R");

      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      //      gPad->SetLogy();
      // h -> SetStats(0);
      gStyle->SetOptFit(1111);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      h -> GetXaxis()->SetRangeUser(-0.4, 0.4);
      h  -> Draw();
      c1 -> SaveAs( Form("AK4Jets_Plot/%s.png", HistoName.c_str() ) );
      c1 -> Destructor();

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

      //      int pTMin = ptBins.first;
      //      int pTMax = ptBins.second;
      //      double pTMean= (pTMin + pTMax) /2. ;
           
      pT_AK4JetHLT ->GetXaxis()->SetRangeUser(ptBins.first, ptBins.second);                                                                                                
      double pTMean = pT_AK4JetHLT->GetMean();                                                                                                                             
      std::cout<< "Bin " << ptBins.first<< "-"<<ptBins.second<<" -> Mean  "<< pTMean << std::endl;

      double pTBias     = ExponentialGauss2 -> GetParameter(1);
      double pTBiasErr = ExponentialGauss2 -> GetParError(1);

      cout<< "ii = "<< ii <<endl;
      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;

      std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%s", etaName.c_str()).Data();
      cout<< TGraphName.c_str() << endl;
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, pTBiasErr);

    }
  }

  cout << endl;
  cout<< "Fitto i TGraph" << endl;
  
  for(int ii = 0; ii < etaBinningSize ; ii++){ 
    // for(int ii = 0; ii < 1 ; ii++){ 

    std::string etaName = mEtaBinning.getBinName(ii);
      
    std::string TGraphName = TString::Format("AK4_pTBias_vs_pT_etabin_%s", etaName.c_str()).Data();
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    cout<< TGraphName.c_str() << endl;
    
    // TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)*log(x)) + [1]*(log(x)*log(x)) + [2]*log(x) + [3]", 65, 700);
    // TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*(log(x)) + [2]", 60, 700);
    // TF1* functionFit = new TF1( "functionFit", "[0]*log(x) + [1]", 65, 700);

    TF1* functionFit = new TF1("functionFit"," ([0]/2)*( [3] + TMath::Erf( (x-[1])/[2]) )", 0, 1000);
    //    TF1* functionFit = new TF1("functionFit"," [0]*(TMath::Erf( (x-[1])/[2])) ", 0, 1000);
    functionFit -> SetParameters(0.02, 100, 200, -0.01);
    functionFit -> SetParLimits(0, 0.005, 0.05); //0.04
    functionFit -> SetParLimits(1, 150, 300);
    functionFit -> SetParLimits(2, 100, 350); //125

    if(ii==3){
      functionFit -> SetParLimits(0, 0.005, 0.03); //0.04
      functionFit -> SetParLimits(1, 150, 300);
      functionFit -> SetParLimits(2, 20, 350); //125
    }
 
   // functionFit -> SetParLimits(3, 0, 10000);
    

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    //    gPad -> SetLogx();
    gStyle->SetOptFit(0);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    nh_h->second->SetMaximum(0.05);
    nh_h->second->SetMinimum(-0.05);
    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    lineup1 -> Draw("same");
    linedown1 -> Draw("same");
    lineup2 -> Draw("same");
    linedown2 -> Draw("same");
    c1 -> SaveAs( Form("AK4Jets_Plot/%s.png", TGraphName.c_str() ) );
    c1 -> Destructor();
   
    double Par0       =  functionFit->GetParameter(0);
    double Par1       =  functionFit->GetParameter(1);
    double Par2       =  functionFit->GetParameter(2);                                                                                                              
    double Par3       =  functionFit->GetParameter(3); 
    double NDF       =  functionFit->GetNDF();
    double Chisquare      =  functionFit->GetChisquare();
    cout<< "Par 0 = " << Par0 << endl;
    cout<< "Par 1 = " << Par1 << endl;
    cout<< "Par 2 = " << Par2 << endl;
    cout<< "Par 3 = " << Par3 << endl;                                                                                                                                                                 
    cout<< "Chisquare / NDF = " << Chisquare<<"/"<<NDF << endl;

    for(int jj=0; jj < binnum; jj++){
      
      int pTMin = pTMeanArray[jj];
      int pTMax = pTMeanArray[jj+1];
      double pTMean= (pTMin + pTMax) /2. ;
      cout<<"pT Mean = " << pTMean <<endl;

      //      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean) + Par2;
      //double pTBiasFit = Par0*(log(pTMean)*log(pTMean)*log(pTMean)) + Par1*log(pTMean)*log(pTMean) + Par2*log(pTMean) + Par3;

      //    functionFit  = ([0]/2)   *( [3]  + TMath::Erf( (x-[1])/[2]) )", 0, 1000);
      double pTBiasFit = (Par0/2)*( Par3 + TMath::Erf( (pTMean -Par1)/Par2));
      cout<<"pT Bias from fit = " << pTBiasFit <<endl;

      Histo_Corrections->SetBinContent(ii+1, jj+1, pTBiasFit);
   
    }

  } 


    TCanvas *c2 = new TCanvas("c2", "c2", 900, 800);
    Histo_Corrections->SetStats(0);
    gStyle->SetPalette(55);
    Histo_Corrections->SetContour(100);
    Histo_Corrections->Draw("colz");
    c2->SetRightMargin(0.13);
    c2->SaveAs("AK4Jets_Plot/Corrections.png");

    TFile* outputFile= new TFile("AK4JetsCorrections_JEC_HLT_v7.root","RECREATE");
    outputFile->cd();
    Histo_Corrections -> Write();
    outputFile->Close();

 
  return 0;
}
Example #20
0
void chipSummary(const char *dirName, int chipId)
{
        directory = TString(dirName);
	
	if (f && f->IsOpen()) f->Close();
	if (f1 && f1->IsOpen()) f1->Close();
	if (g && g->IsOpen()) g->Close();

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

	gStyle->SetStatFont(132);
	gStyle->SetTextFont(132);
	gStyle->SetLabelFont(132, "X");
	gStyle->SetLabelFont(132, "Y");
	gStyle->SetLabelSize(0.08, "X");
	gStyle->SetLabelSize(0.08, "Y");
	gStyle->SetNdivisions(6, "X");
	gStyle->SetNdivisions(8, "Y");
	gStyle->SetTitleFont(132);

	gROOT->ForceStyle();

	tl = new TLatex;
	tl->SetNDC(kTRUE);
	tl->SetTextSize(0.09);

	ts = new TLatex;
	ts->SetNDC(kTRUE);
	ts->SetTextSize(0.08);

	line = new TLine;
	line->SetLineColor(kRed);
	line->SetLineStyle(kSolid);
	
	box = new TBox;
	box->SetFillColor(kRed);
	box->SetFillStyle(3002);

	f = new TFile(Form("%s/%s", dirName, fileName), "READ");
	
	if (strcmp(fileName, adFileName) == 0) f1 = f;
	else f1 = new TFile(Form("%s/%s", dirName, adFileName), "READ");
	
	if (strcmp(fileName, trimFileName) == 0) g = f;
	else g = new TFile(Form("%s/%s", dirName, trimFileName), "READ");
 
	sprintf(fname, "%s/../../macros/criteria-full.dat", dirName);
	if ( !readCriteria(fname) ) { 
	  
	  printf("\nchipSummary> ----> COULD NOT READ GRADING CRITERIA !!!");
	  printf("chipSummary> ----> Aborting execution of chipgSummaryPage.C ... \n\n", fileName, dirName);  
	  break;
	}

	TH1D *h1;
	TH2D *h2;

	c1 = new TCanvas("c1", "", 800, 800);
	c1->Clear();
	c1->Divide(4,4, 0.01, 0.04);

  //	shrinkPad(0.1, 0.1, 0.1, 0.3);

	FILE *sCurveFile, *phLinearFile, *phTanhFile;

        TString noslash(dirName);
        noslash.ReplaceAll("/", " ");
        noslash.ReplaceAll(".. ", "");
	
	char string[200];
	int pixel_alive;

	int nDeadPixel(0);
	int nIneffPixel(0);
	int nMaskDefect(0);
	int nNoisy1Pixel(0);
	int nDeadBumps(0);
	int nDeadTrimbits(0);
	int nAddressProblems(0);

	int nNoisy2Pixel(0);
	int nThrDefect(0);
	int nGainDefect(0);
	int nPedDefect(0);
	int nPar1Defect(0);

	int nRootFileProblems(0);

	int nDoubleFunctCounts(0);
	int nDoublePerfCounts(0);
	int nDoubleCounts(0);
	int nDoubleTrims(0);
	int nDoublePHs(0);

        int vcal = dac_findParameter(dirName, "Vcal", chipId);
	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 1
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Dead pixels
	c1->cd(1);

	TH2D *hpm;
	hpm = (TH2D*)f->Get(Form("PixelMap_C%i", chipId));

        if (hpm) {

	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {      
	      
	      hpm->SetTitle("");
	      hpm->Draw("colz");
	      tl->DrawLatex(0.1, 0.92, "Pixel Map");
	    }
	  }

	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- sCurve width and noise level
	TH1D *hw = new TH1D("hw", "", 100, 0., 600.);
	TH1D *hd = new TH1D("hd", "", 100, 0., 600.);  // Noise in unbonded pixel (not displayed)
	TH2D *ht = new TH2D("ht", "", 52, 0., 52., 80, 0., 80.);
	TH1D *htmp;

	float mN(0.), sN(0.), nN(0.), nN_entries(0.);
	int over(0), under(0);

	double htmax(255.), htmin(0.);
	
	float thr, sig;
	int a,b;

	double minThrDiff(-5.);
	double maxThrDiff(5.);

	h2 = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	if (!sCurveFile) {

	  printf("chipSummary> !!!!!!!!!  ----> SCurve: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(sCurveFile, "%e %e %s %2i %2i", &thr, &sig, string, &a, &b);
	      //  				printf("chipSummary> sig %e thr %e\n", sig, thr);
	      
	      hw->Fill(sig);
	      thr = thr / 65.;
	      
	      ht->SetBinContent(icol+1, irow+1, thr); 
	      
	      if ( h2 ) {
		if( h2->GetBinContent(icol+1, irow+1)  >= minThrDiff) {
		  
		  hd->Fill(sig);
		}
	      }
	    }
	  }
	  
	  fclose(sCurveFile);

	  c1->cd(2);
	  hw->Draw();
	  tl->DrawLatex(0.1, 0.92, "S-Curve widths: Noise (e^{-})");
	  
	  
	  /*		c1->cd(15);
			hd->SetLineColor(kRed);
			hd->Draw();
			tl->DrawLatex(0.1, 0.92, "S-Curve widths of dead bumps");
			if ( hd->GetEntries() > 0 ) {
			ts->DrawLatex(0.55, 0.82, Form("entries: %4.0f", hd->GetEntries()));
			ts->DrawLatex(0.55, 0.74, Form("#mu:%4.2f", hd->GetMean()));
			ts->DrawLatex(0.55, 0.66, Form("#sigma: %4.2f", hd->GetRMS()));
			}
	  */
	  
	  mN =  hw->GetMean();
	  sN =  hw->GetRMS();
	  nN =  hw->Integral(hw->GetXaxis()->GetFirst(), hw->GetXaxis()->GetLast());
	  nN_entries =  hw->GetEntries();
	  
	  under = hw->GetBinContent(0);
	  over  = hw->GetBinContent(hw->GetNbinsX()+1);
	  
	  
	  ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nN));
	  ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mN));
	  ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sN));
	  
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(3);
	  if ( ht->GetMaximum() < htmax ) { 
	    htmax = ht->GetMaximum();
	  }
	  if ( ht->GetMinimum() > htmin ) {
	    htmin = ht->GetMinimum();
	  }
	  ht->GetZaxis()->SetRangeUser(htmin,htmax);
	  ht->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Vcal Threshold Untrimmed");
	  
	}
	
	// -- Noise level map
	c1->cd(4);
        gPad->SetLogy(1);
 	gStyle->SetOptStat(1);

	float mV(0.), sV(0.), nV(0.), nV_entries(0.);
	over = 0.; under = 0.;

	if (!g->IsZombie())
	{
	      h1 = (TH1D*)g->Get(Form("VcalThresholdMap_C%iDistribution;7", chipId));
              if (h1) {
		h1->SetTitle("");
		h1->SetAxisRange(0., 100.);
		h1->Draw();

		mV = h1->GetMean();
		sV = h1->GetRMS();
		nV = h1->Integral(h1->GetXaxis()->GetFirst(), h1->GetXaxis()->GetLast());
		nV_entries = h1->GetEntries();

		under = h1->GetBinContent(0);
		over  = h1->GetBinContent(h1->GetNbinsX()+1);
              }
              else {

	        ++nRootFileProblems;
		mV = 0.;
		sV = 0.;
               
              }

	      ts->DrawLatex(0.15, 0.82, Form("N: %4.0f", nV));
	      ts->DrawLatex(0.15, 0.74, Form("#mu: %4.1f", mV));
	      ts->DrawLatex(0.15, 0.66, Form("#sigma: %4.1f", sV));
	      
	      if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	      if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	}

	tl->DrawLatex(0.1, 0.92, "Vcal Threshold Trimmed");

	
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 2
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Bump Map
	TH2D *hbm;

	c1->cd(5);
	gStyle->SetOptStat(0);
	hbm = (TH2D*)f->Get(Form("vcals_xtalk_C%i", chipId));
        
        if (hbm) {

	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(minThrDiff, maxThrDiff);
	  h2->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding Problems");
	}

	else { ++nRootFileProblems; }

	// -- Bump Map
	c1->cd(6);  
	gPad->SetLogy(1);
	//gStyle->SetOptStat(1);
	h1 = (TH1D*)f->Get(Form("vcals_xtalk_C%iDistribution", chipId));

        if (h1) {
  	  h1->SetTitle("");
	  h1->GetXaxis()->SetRangeUser(-50., 50.);
	  h1->GetYaxis()->SetRangeUser(0.5, 5.0*h1->GetMaximum());
	  h1->DrawCopy();
	  tl->DrawLatex(0.1, 0.92, "Bump Bonding");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}
	
	// -- Trim bits
	int trimbitbins(3);
	c1->cd(7); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f->Get(Form("TrimBit14_C%i", chipId));
	if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(0., 60.);
	  h1->SetMinimum(0.5);
	  h1->Draw("");
	  tl->DrawLatex(0.1, 0.92, "Trim Bit Test");          
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit13_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kRed);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit11_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kBlue);
	  h1->Draw("same");
	}
	else { ++nRootFileProblems; }

	h1 = (TH1D*)f->Get(Form("TrimBit7_C%i", chipId));
	if (h1) {
	  h1->SetLineColor(kGreen);
	  h1->Draw("same");
	}	
	else { ++nRootFileProblems; }
	
	// -- For numerics and titels see at end


	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 3
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Address decoding	
	// --------------------

	TH2D *ham;
	ham = (TH2D*)f1->Get(Form("AddressDecoding_C%i", chipId));

	c1->cd(9);
	gStyle->SetOptStat(0);
        if (ham) {

	  ham->SetTitle("");
	  ham->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "Address decoding");
	}

	else { ++nRootFileProblems; }

	// -- Address levels

	c1->cd(10); 
	gPad->SetLogy(1);
	h1 = (TH1D*)f1->Get(Form("AddressLevels_C%i", chipId));
        if (h1) {
	  h1->SetTitle("");
	  h1->SetAxisRange(-1500., 1500.);
	  h1->Draw();
	  tl->DrawLatex(0.1, 0.92, "Address Levels");
	
	} else { 
	  
	  ++nRootFileProblems; 
	}


	// -- PHCalibration: Linear Fit (Gain & Pedesdtal)
	// -----------------------------------------------

	TH1D *hg = new TH1D("hg", "", 300, -2.0, 5.5);
	TH2D *hgm = new TH2D("hgm", "", 52, 0., 52., 80, 0., 80.);
	
	TH1D *hp = new TH1D("hp", "", 900, -300., 600.);
	hp->StatOverflows(kTRUE);

	TH1D *rp = new TH1D("rp", "", 900, -300., 600.);
	rp->StatOverflows(kFALSE);

	TH1D *htmp;

	float par0, par1, par2, par3, par4, par5; // Parameters of Vcal vs. Pulse Height Fit

	float mG(0.), sG(0.), nG(0.), nG_entries(0.);
	float mP(0.), sP(0.), nP(0.), nP_entries(0.); 
	over = 0.; under = 0.;

	float ped, gain;
	int a,b;
	
	int mPbin(0), xlow(-100), xup(255), extra(0);       // for restricted RMS
	float pedMin(0), pedMax(1000);
	double integral(0.);

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");

	if (!phLinearFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
		
	  for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	  
	  for (int icol = 0; icol < 52; ++icol)	{
	    for (int irow = 0; irow < 80; ++irow) {
	      fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		     &par0, &par1, &par2, &par3, &par4, &par5, string, &a, &b);
	      
	      if (par2 != 0.)  {  // dead pixels have par2 == 0.
		
		gain = 1./par2;
		ped = par3;
		hp->Fill(ped);
		hg->Fill(gain);
		hgm->SetBinContent(icol + 1, irow + 1, gain);
	      }
	    }
	  }
	  
	  fclose(phLinearFile);
	  

	  // -- Gain

	  c1->cd(11);

	  mG =  hg->GetMean();
	  sG =  hg->GetRMS();
	  nG =  hg->Integral(hg->GetXaxis()->GetFirst(), hg->GetXaxis()->GetLast());
	  nG_entries = hg->GetEntries();
	  
	  under = hg->GetBinContent(0);
	  over  = hg->GetBinContent(hp->GetNbinsX()+1);
	  	  
	  gPad->SetLogy(1);
	  hg->GetYaxis()->SetRangeUser(0.5, 5.0*hg->GetMaximum());
	  hg->Draw();
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");
	  
	  if ( hg->GetMean() > 1.75 ) {

	    ts->DrawLatex(0.15, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.15, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.15, 0.64, Form("#sigma: %4.2f", sG));

	  } else {

	    ts->DrawLatex(0.65, 0.80, Form("N: %4.0f", nG));
	    ts->DrawLatex(0.65, 0.72, Form("#mu: %4.2f", mG));
	    ts->DrawLatex(0.65, 0.64, Form("#sigma: %4.2f", sG));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  
	  c1->cd(15);

	  hgm->Draw("colz");
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Gain (ADC/DAC)");

	  // -- Pedestal

	  c1->cd(12);

	  mP =  hp->GetMean();
	  sP =  hp->GetRMS();
	  nP =  hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());
	  nP_entries = hp->GetEntries();
	  
	  if ( nP > 0 ) {
	    
	    // -- restricted RMS
	    integral = 0.;
	    mPbin = -1000; xlow = -1000; xup = 1000;
	    over = 0.; under = 0.;
	    
	    mPbin = hp->GetXaxis()->FindBin(mP);
	    
	    for (int i = 0; integral <  pedDistr; i++) { 
		    
	      xlow = mPbin-i;
	      xup =  mPbin+i;
	      integral = hp->Integral(xlow, xup)/nP;
		    
	    }
		  
	    extra = xup - xlow;
	  }
	  else {

	    xlow = -300; xup = 600; extra = 0;
	    over = 0.; under = 0.;
	  }

  	  under = hp->Integral(0, xlow - extra);
  	  over  = hp->Integral(xup + 1.5*extra, hp->GetNbinsX());
		  
	  hp->GetXaxis()->SetRange(xlow - extra, xup + 1.5*extra);

	  nP    = hp->Integral(hp->GetXaxis()->GetFirst(), hp->GetXaxis()->GetLast());

	  pedMin = hp->GetBinCenter(xlow-extra);
	  pedMax = hp->GetBinCenter(xup+1.5*extra);


	  cout<< " ========> Ped min  " << pedMin << " Ped max " << pedMax 
	      << ", over: " << over << " under: " << under << endl;		

	  hp->DrawCopy();

	  rp->Add(hp);
	  rp->GetXaxis()->SetRange(xlow, xup);

	  mP =  rp->GetMean();
	  sP =  rp->GetRMS();

	  // box->DrawBox( rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xup), 1.05*rp->GetMaximum());
	  rp->SetFillColor(kRed);
	  rp->SetFillStyle(3002);
	  rp->Draw("same");
	  line->DrawLine(rp->GetBinCenter(xlow), 0, rp->GetBinCenter(xlow), 0.6*rp->GetMaximum());
	  line->DrawLine(rp->GetBinCenter(xup),  0, rp->GetBinCenter(xup),  0.6*rp->GetMaximum());
	 
	  tl->DrawLatex(0.1, 0.92, "PH Calibration: Pedestal (DAC)");
		
	  if ( hp->GetMean() < 126. ) {

	    ts->DrawLatex(0.65, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.65, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.65, 0.66, Form("#sigma: %4.1f", sP));
				
	  } else {

	    ts->DrawLatex(0.16, 0.82, Form("N: %4.0f", nP));
	    ts->SetTextColor(kRed);
	    ts->DrawLatex(0.16, 0.74, Form("#mu: %4.1f", mP));
	    ts->DrawLatex(0.16, 0.66, Form("#sigma: %4.1f", sP));
	  }

	  if ( under ) ts->DrawLatex(0.15, 0.55, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.55, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	  

		
	}

	
	// -- PHCalibration: Tanh Fit (Parameter1)
	// ----------------------------------------
	
	c1->cd(11);

	over = 0.; under = 0.;

	float nPar1(0.), nPar1_entries(0.), mPar1(0.), sPar1(0.);
	
        TH1D *hPar1 = new TH1D("par1", "", 350, -1., 6.);

	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (!phTanhFile) {
	  
	  printf("chipSummary> !!!!!!!!!  ----> phCal: Could not open file %s to read fit results\n", string);
	
	} else {
	  
	  for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);
	  
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", &par0, &par1, &par2, &par3, string, &a, &b);		
	      hPar1->Fill(par1);
	    }
	  }
	  
	  fclose(phTanhFile);	


	  // -- Parameter 1

	  hPar1->SetLineColor(kBlue);
	  hPar1->Draw("same");
	  
	  mPar1 =  hPar1->GetMean();
	  sPar1 =  hPar1->GetRMS();
	  nPar1 =  hPar1->Integral(hPar1->GetXaxis()->GetFirst(), hPar1->GetXaxis()->GetLast());	
	  nPar1_entries = hPar1->GetEntries();
	  
	  under = hPar1->GetBinContent(0);
	  over  = hPar1->GetBinContent(hPar1->GetNbinsX()+1);
	  
	  ts->SetTextColor(kBlue);
	  
	  if ( hg->GetMean() > 1.75 ) {
	  
	    ts->DrawLatex(0.15, 0.40, "Par1:");
	    ts->DrawLatex(0.15, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.15, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.15, 0.14, Form("#sigma: %4.2f", sPar1));
	  
	  } else {

	    ts->DrawLatex(0.65, 0.40, "Par1:");
	    ts->DrawLatex(0.65, 0.30, Form("N: %4.0f", nPar1));
	    ts->DrawLatex(0.65, 0.22, Form("#mu: %4.2f", mPar1));
	    ts->DrawLatex(0.65, 0.14, Form("#sigma: %4.2f", sPar1));
	  }
	  
	    
	  if ( under ) ts->DrawLatex(0.15, 0.48, Form("<= %i", under));			               
	  if ( over  ) ts->DrawLatex(0.75, 0.48, Form("%i =>", over ));
	  ts->SetTextColor(kBlack);
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Row 4
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	
	// Trim Bits
	// ----------

	TH2D *htm = new TH2D("htm", "", 80, 0., 80., 52, 0., 52.);

	c1->cd(13);
	
	gStyle->SetOptStat(0);
	h2 = (TH2D*)f->Get(Form("TrimMap_C%i;8", chipId));

        if (h2) {
	  for (int icol = 0; icol < 52; ++icol) {
	    for (int irow = 0; irow < 80; ++irow) {
	      
	      htm->SetBinContent(irow+1, icol+1, h2->GetBinContent(icol+1, irow+1));
	    }
	  }
  	  h2->SetTitle("");
	  h2->GetZaxis()->SetRangeUser(0., 16.);
	  h2->Draw("colz");
	}

	else { ++nRootFileProblems; }

	tl->DrawLatex(0.1, 0.92, "Trim Bits");


	FILE *tCalFile;
	sprintf(string, "%s/../T-calibration/TemperatureCalibration_C%i.dat", dirName, chipId);
	tCalFile = fopen(string, "r");
	char tCalDir[200];
	sprintf(tCalDir, "%s/../T-calibration", dirName);

	if ( tCalFile ) {
	
	  analyse(tCalDir, chipId);
	}
	else {

	  c1->cd(14);
	  TGraph *graph = (TGraph*)f->Get(Form("TempCalibration_C%i", chipId));
	  if ( graph ) { graph->Draw("A*"); }
	  else { ++nRootFileProblems; }
	  tl->DrawLatex(0.1, 0.92, "Temperature calibration");
	}



	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// -- Count defects and double counting
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	float fl0, fl1, fl2, fl3, fl4, fl5, tmp;
	int   i1, i2;
	char hname[200];

//  	TH2D *get = 0, *hget = 0, *htb0 = 0, *htb1 = 0, *htb2 = 0, *htb3 = 0, *htb4 = 0;

//  	for (int i = 1; i < 6; ++i) {
	  
//  	  get = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i));

//  	  if (get) {
//  	    hget = (TH2D*)get->Clone();
//  	    hget->SetName(Form("TB0C%i", i));

//  	    if (i == 1) htb0 = hget;
//  	    if (i == 2) htb1 = hget;
//  	    if (i == 3) htb2 = hget;
//  	    if (i == 4) htb3 = hget;
//  	    if (i == 5) htb4 = hget;

//  	  }
//  	}


 	TH2D *htb[5];
 	for (int i = 0; i < 5; ++i) {

 	  htb[i] = (TH2D*)f->Get(Form("CalThresholdMap_C%i;%i", chipId, i+1));
	  htb[i]->SetName(Form("tbC%i%i", chipId, i+1));
 	}

	TH2D *htthr = 0;
 	htthr = (TH2D*)f->Get(Form("VcalThresholdMap_C%d;8", chipId));

	sprintf(string, "%s/SCurve_C%i.dat", dirName, chipId);
	sCurveFile = fopen(string, "r");

	sprintf(string, "%s/phCalibrationFit_C%i.dat", dirName, chipId);
	phLinearFile = fopen(string, "r");
	
	sprintf(string, "%s/phCalibrationFitTan_C%i.dat", dirName, chipId);
	phTanhFile = fopen(string, "r");
	
	if (sCurveFile)   for (int i = 0; i < 2; i++) fgets(string, 200, sCurveFile);
	if (phLinearFile) for (int i = 0; i < 2; i++) fgets(string, 200, phLinearFile);
	if (phTanhFile)   for (int i = 0; i < 2; i++) fgets(string, 200, phTanhFile);

	int px_counted    = 0;
	int px_funct_counted    = 0;
	int px_perf_counted    = 0;
	int trim_counted    = 0;
	int ph_counted    = 0;
	float tb_diff = 0;
	float tb, tb0;
	    
	for (int icol = 0; icol < 52; ++icol) {
	  for (int irow = 0; irow < 80; ++irow) {
	    
	    pixel_alive   = 1;
	    px_funct_counted = 0;
	    px_perf_counted = 0;
	    px_counted = 0;

	    trim_counted = 0;
	    ph_counted = 0;
	    
	    // -- Pixel alive
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  == 0)  { 
	      
	      pixel_alive = 0; 
	      
	      ++nDeadPixel;   
	      cout << Form("chipSummary> dead pixel %3d %3d: %7.5f", 
			   icol, irow, hpm->GetBinContent(icol+1, irow+1)) << endl;
	    }

	    if (hpm && hpm->GetBinContent(icol+1,irow+1)  > 10) { ++nNoisy1Pixel; px_counted = 1; px_funct_counted = 1;}
	    if (hpm && hpm->GetBinContent(icol+1, irow+1)  < 0) { ++nMaskDefect;  px_counted = 1; px_funct_counted = 1;}

	    if (hpm && (hpm->GetBinContent(icol+1, irow+1) < 10) 
		  && (hpm->GetBinContent(icol+1, irow+1) > 0) ) { ++nIneffPixel;  px_counted = 1; px_funct_counted = 1;}
	    
	    
	    // -- Bump bonding
	    if ( pixel_alive && hbm ) {
	      if ( hbm->GetBinContent(icol+1, irow+1)  >= minThrDiff ) {

		if ( px_counted )      nDoubleCounts++;
		px_counted = 1;

		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;
		
		++nDeadBumps;	
		
		cout << Form("chipSummary> bump defect %3d %3d: %7.5f", 
			     icol, irow, hbm->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    
	    // -- Trim bits 1 - 4
	    if ( pixel_alive && htb[0] ) {

	      tb0 = htb[0]->GetBinContent(icol+1, irow+1);
	      
	      for ( int i = 1; i <= 4; i++ ) {

		if ( htb[i] ) {
		  
		  tb = htb[i]->GetBinContent(icol+1, irow+1);

		  tb_diff = TMath::Abs(tb-tb0);

		  if (tb_diff  <= 2) {
		    
		    if ( px_counted ) nDoubleCounts++;
		    px_counted = 1;
		    
		    if ( px_funct_counted ) nDoubleFunctCounts++;
		    px_funct_counted = 1;
		    
		    if ( trim_counted ) nDoubleTrims++;
		    trim_counted = 1;
		    
		    ++nDeadTrimbits;
		    
		    cout << Form("chipSummary> trim bit defect %3d %3d: %4.2f", icol, irow, tb_diff) << endl;
		  }
		}
	      }
	    }

	    // -- Address decoding
	    if (pixel_alive && ham) {

	      if( ham->GetBinContent(icol+1, irow+1) < 1 ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_funct_counted ) nDoubleFunctCounts++;
		px_funct_counted = 1;

		++nAddressProblems;

		cout << Form("chipSummary> address problem %3d %3d: %7.5f", 
			     icol, irow, ham->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }
	    
	    // -- Threshold
	    if (pixel_alive && htthr) {

	      if ( TMath::Abs(htthr->GetBinContent(icol+1, irow+1) - vcalTrim) > tthrTol ) {

		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		++nThrDefect;

		cout << Form("chipSummary> threshold problem %3d %3d: %7.5f", 
			     icol, irow, htthr->GetBinContent(icol+1, irow+1)) << endl;
	      }
	    }

	    // -- Noise
	    fscanf(sCurveFile, "%e %e %s %2i %2i", &fl1, &fl2, string, &i1, &i2);

	    if (pixel_alive) {
	      if ( (fl2 < noiseMin) 
		   || (fl2 > noiseMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;
		
		++nNoisy2Pixel; 

		cout << Form("chipSummary> noise defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, fl2, i1, i2) << endl;
	      } 
	    }
	    
	    // -- Gain & Pedestal
	    fscanf(phLinearFile, "%e %e %e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, &fl4, &fl5, string, &i1, &i2);

	    if (pixel_alive) {
	      
	      if (fl2 != 0) gain = 1./fl2;
	      ped = fl3;

	      if ( (gain < gainMin) || (gain > gainMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;
		    
		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nGainDefect;

		cout << Form("chipSummary> gain defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, gain, i1, i2) << endl;
	      }

	      if ( (ped < pedMin) 
		   || (ped > pedMax) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPedDefect;

		cout << Form("chipSummary> pedestal defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, ped, i1, i2) << endl;
	      }
		
	      
	    }
	    

	    // -- Par1
	    fscanf(phTanhFile, "%e %e %e %e %s %2i %2i", 
		   &fl0, &fl1, &fl2, &fl3, string, &i1, &i2);
	    
	    if (pixel_alive && phTanhFile) {
	      
	      if ( (fl1 < par1Min) 
		   || (fl1 > par1Max) ) {
		
		if ( px_counted ) nDoubleCounts++;
		px_counted = 1;

		if ( px_perf_counted ) nDoublePerfCounts++;
		px_perf_counted = 1;

		if ( ph_counted ) nDoublePHs++;
		ph_counted = 1;

		++nPar1Defect;

		cout << Form("chipSummary> par1 defect %3d %3d: %7.5f (%2i %2i)", 
			     icol, irow, par1, i1, i2) << endl;
	      }
	    }
	    
	  }
	}
			
	fclose(sCurveFile); 
	fclose(phLinearFile);
	fclose(phTanhFile);
	      

	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	// Numerics and Titles
	// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

	// -- Compute the final verdict on this chip  //?? FIXME (below is pure randomness)
	float finalVerdict(0);
	if (nDeadTrimbits > 0)    finalVerdict += 1;
	if (nDeadPixel > 0)       finalVerdict += 10;
	if (nNoisy1Pixel > 0)     finalVerdict += 10;
	if (nAddressProblems > 0) finalVerdict += 10;
	if (nDeadBumps > 0)       finalVerdict += 100;
	if (nNoisy2Pixel > 0)     finalVerdict += 1000;
	if (nThrDefect > 0)       finalVerdict += 10000;
	if (nGainDefect > 0)      finalVerdict += 100000;
	if (nPedDefect > 0)       finalVerdict += 100000;
	if (nPar1Defect > 0)      finalVerdict += 100000;

	// -- Defects
	c1->cd(8);
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	double y = 0.98;

	y -= 0.11;
	tl->DrawLatex(0.1, y, "Summary");
// 	tl->DrawLatex(0.6, y, Form("%06d", finalVerdict));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Dead Pixels: "));
	tl->DrawLatex(0.7, y, Form("%4d", nDeadPixel));

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Noisy Pixels 1: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nNoisy1Pixel));
	
	y -= 0.10;
	tl->DrawLatex(0.1, y, "Mask defects: ");
	tl->DrawLatex(0.7, y, Form("%4d", nMaskDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Bumps: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadBumps));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Dead Trimbits: ");
	tl->DrawLatex(0.7, y, Form("%4d", nDeadTrimbits));

	y -= 0.10;
	tl->DrawLatex(0.1, y, "Address Probl: ");
	tl->DrawLatex(0.7, y, Form("%4d", nAddressProblems));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Noisy Pixels 2: "));
	tl->DrawLatex(0.7, y, Form("%4d", nNoisy2Pixel));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("Trim Probl.: "));
	tl->DrawLatex(0.7, y, Form("%4d", nThrDefect));

	y -= 0.10;
	tl->DrawLatex(0.1, y, Form("PH defects: "));
	tl->DrawLatex(0.5, y, Form("%4d/", nGainDefect));

	tl->SetTextColor(kRed);
	tl->DrawLatex(0.6, y, Form("%4d/",nPedDefect));
	tl->SetTextColor(kBlack);

	tl->SetTextColor(kBlue);
	tl->DrawLatex(0.7, y, Form("%4d",nPar1Defect));
	tl->SetTextColor(kBlack);

// 	y -= 0.10;
// 	tl->DrawLatex(0.1, y, Form("Par1 defect: "));
// 	tl->DrawLatex(0.7, y, Form("%4d", nPar1Defect));


	// -- Operation Parameters
	c1->cd(16);
	
	y = 0.92;
	tl->SetTextSize(0.10);
	tl->SetTextFont(22);
	y -= 0.11;
	tl->DrawLatex(0.1, y, Form("Op. Parameters"));

	tl->SetTextFont(132);
	tl->SetTextSize(0.09);

	y -= 0.11;
	int vana(-1.);
        vana = dac_findParameter(dirName, "Vana", chipId);
	tl->DrawLatex(0.1, y, "VANA: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3i DAC", vana));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int caldel(-1.);
        caldel = dac_findParameter(dirName, "CalDel", chipId);
	tl->DrawLatex(0.1, y, "CALDEL: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", caldel));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vthrcomp(-1.);
        vthrcomp = dac_findParameter(dirName, "VthrComp", chipId);
	tl->DrawLatex(0.1, y, "VTHR: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vthrcomp));
	else tl->DrawLatex(0.7, y, "N/A");

	y -= 0.10;
	int vtrim(-1.);
        vtrim = dac_findParameter(dirName, "Vtrim", chipId);
	tl->DrawLatex(0.1, y, "VTRIM: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", vtrim));
	else tl->DrawLatex(0.7, y, "N/A");
	
	y -= 0.10;
	int ibias(-1.);
        ibias = dac_findParameter(dirName, "Ibias_DAC", chipId);
	tl->DrawLatex(0.1, y, "IBIAS_DAC: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", ibias));
	else tl->DrawLatex(0.7, y, "N/A");
       
	y -= 0.10;
	int voffset(-1.);
        voffset = dac_findParameter(dirName, "VoffsetOp", chipId);
	tl->DrawLatex(0.1, y, "VOFFSETOP: ");
	if (vana >= 0.) tl->DrawLatex(0.6, y, Form("%3d DAC", voffset));
	else tl->DrawLatex(0.7, y, "N/A");

	// -- Page title
	c1->cd(0);
	tl->SetTextSize(0.04);
	tl->SetTextFont(22);
	tl->DrawLatex(0.02, 0.97, Form("%s (C%i)", noslash.Data(), chipId));

	TDatime date;
	tl->SetTextSize(0.02);
	tl->DrawLatex(0.75, 0.97, Form("%s", date.AsString()));

	c1->SaveAs(Form("%s/chipSummary_C%i.ps", dirName, chipId));
	c1->SaveAs(Form("%s/C%i.png", dirName, chipId));
		

	// -- Dump into logfile
	ofstream OUT(Form("%s/summary_C%i.txt", dirName, chipId));
	OUT << "nDeadPixel: "         << nDeadPixel << endl;
	OUT << "nNoisy1Pixel: "       << nNoisy1Pixel << endl;
	OUT << "nDeadTrimbits: "      << nDeadTrimbits << endl;
	OUT << "nDeadBumps: "         << nDeadBumps << endl;
	OUT << "nMaskDefect: "        << nMaskDefect << endl;
	OUT << "nAddressProblems: "   << nAddressProblems << endl;
	OUT << "nNoisy2Pixel: "       << nNoisy2Pixel << endl;
	OUT << "nTThrDefect: "        << nThrDefect << endl;
	OUT << "nGainDefect: "        << nGainDefect << endl;
	OUT << "nPedDefect: "         << nPedDefect << endl;
	OUT << "nParDefect: "         << nPar1Defect << endl;
	OUT << "nDoubleCounts: "      << nDoubleCounts << endl;
	OUT << "nDoubleFunctCounts: " << nDoubleFunctCounts << endl;
	OUT << "nDoublePerfCounts: "  << nDoublePerfCounts << endl;
	OUT << "nDoubleTrims: "       << nDoubleTrims << endl;
	OUT << "nDoublePHs: "         << nDoublePHs << endl;
        OUT << "nRootFileProblems: "  << nRootFileProblems << endl;
	OUT << "SCurve "              << nN_entries    << " " << mN << " " << sN << endl;
	OUT << "Threshold "           << nV_entries    << " " << mV  << " " << sV << endl;
	OUT << "Gain "                << nG_entries    << " " << mG << " " << sG << endl;
	OUT << "Pedestal "            << nP_entries    << " " << mP << " " << sP << endl;
	OUT << "Parameter1 "          << nPar1_entries << " " << mPar1 << " " << sPar1 << endl;
	OUT.close();
	
}
int main(int argc, char* argv[]) {

  std::string outputDir = "WideJets_Plot";                 
  mkdir(outputDir.c_str(), 0777); 

  //  TString dataFileName_DoubleMu;
  //  dataFileName_DoubleMu = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_DoubleMu.root");
  // TFile* dataFile_DoubleMu = TFile::Open(dataFileName_DoubleMu);
  // if (dataFile_DoubleMu) {
  //  std::cout << "Opened data file '" << dataFileName_DoubleMu << "'." << std::endl;
  // }

  TString dataFileName_HT450;
  dataFileName_HT450 = TString::Format("../../output/HLTReco_Comparison/rootFile_JEC_HLT_v7_RecoLowerCuts10GeV_HT450.root");
  TFile* dataFile_HT450 = TFile::Open(dataFileName_HT450);
  if (dataFile_HT450) {
    std::cout << "Opened data file '" << dataFileName_HT450 << "'." << std::endl;
  }

  TH1D *pT_WideJetHLT = (TH1D*)dataFile_HT450->Get("pT_WideJetHLT");

  if( !pT_WideJetHLT) cout<<"Not found" <<endl;

  gErrorIgnoreLevel = kWarning;

  // procedura
  // prendo gli istogramma 1D del bias
  // per ogni bin di pT e eta
  // li fitto con una cristal ball
  // poi grafico il picco in funzione del pT in ogni bin di eta
  // fitto con una funzione logaritmica
  // mi creo l'istogramma 2D (eta,pT) con correzione sull'asse z

  //////////////////////// pTBias 1D
  EtaBinning mEtaBinning;
  size_t etaBinningSize = mEtaBinning.size();
  PtBinning mPtBinning;
  size_t pTBinningSize = mPtBinning.size();

  cout<< etaBinningSize << endl;

  for (size_t ii = 0; ii < etaBinningSize; ii++) { 
    // for (size_t ii = 9; ii < 10; ii++) {
    for (size_t jj = 0; jj < pTBinningSize; jj++) {

      cout<< "ii = "<< ii <<endl;
      cout<< "jj = "<< jj <<endl;

      if(jj < 2) continue; // pT<300
      if(jj > 7) continue; // pT>900

      std::string etaName = mEtaBinning.getBinName(ii);
      std::pair<float, float> ptBins = mPtBinning.getBinValue(jj);	       
      
      std::string HistoName = TString::Format("pTBias_%s_pT_%i_%i", etaName.c_str(), (int) ptBins.first, (int) ptBins.second ).Data();
      
      cout<< HistoName.c_str() << endl;
      
      TH1D *h;
      h = (TH1D*)dataFile_HT450->Get( HistoName.c_str() );
            
      double hN = h->GetMaximum();
      double hMean = h->GetMean();
      double hRMS = h->GetRMS();

      //histo->GetMean() - sigma * histo->GetRMS(), histo->GetMean() + sigma * histo->GetRMS() 

      //      TF1 *crystal = new TF1("crystal", CrystalBall, hMean-1*hRMS , hMean+1*hRMS, 5);
      TF1 *crystal = new TF1("crystal", CrystalBall, -0.1, 0.15, 5);
      //      TF1 *crystal = new TF1("crystal", CrystalBall, -0.05, 0.1, 5);
      crystal->SetParameters(hN, hMean, hRMS, 1.0, 2.0);
      crystal->SetParNames("N", "Mean", "sigma","#alpha","n");
      
      //      TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, hMean-1*hRMS , hMean+1*hRMS, 7);
      TF1 *doublecrystal = new TF1("doublecrystal", doubleCrystalBall, -0.2 , 0.2, 7);
      doublecrystal->SetParameters(hN, hMean, hRMS, 3, 3, 3, 3);
      doublecrystal->SetParNames("N", "Mean", "sigma","#alphaR","nR","#alphaL", "nL");
      
      TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
      h -> SetMarkerStyle(20);
      h -> SetMarkerSize(1.5);
      h -> GetXaxis()->SetRangeUser(-0.4, 0.4);
      // h -> Fit(crystal, "R");
      h -> Fit(doublecrystal, "R");
      h -> Draw();
      c1 -> SaveAs( Form("WideJets_Plot/%s.png", HistoName.c_str() ) );
      c1-> Destructor();

      /////////////////////////////////////////////////
      
      pT_WideJetHLT ->GetXaxis()->SetRangeUser(ptBins.first, ptBins.second);
      double pTMean = pT_WideJetHLT->GetMean();
      std::cout<< "Bin " << ptBins.first<< "-"<<ptBins.second<<" -> Mean  "<< pTMean << std::endl; 
      
      double pTBias = doublecrystal->GetParameter(1);
      double pTBiasErr = doublecrystal->GetParError(1);
      
      cout<< "pT mean = "<< pTMean <<endl;
      cout<< "pT Bias = "<< pTBias <<endl;
      cout<< "sigma(pT Bias) = "<< pTBiasErr <<endl;

      std::string TGraphName = TString::Format("pTBias_vs_pT_etabin_%i", ii).Data();
      cout<< TGraphName.c_str() << endl;
      CreateAndFillUserTGraph(TGraphName.c_str(), jj, pTMean, pTBias, 0, pTBiasErr);
      
    }
  }
  

  for(int ii = 0; ii < etaBinningSize ; ii++){ 
   
    std::string TGraphName = TString::Format("pTBias_vs_pT_etabin_%i", ii).Data();
    cout<< TGraphName.c_str() << endl;
    map<std::string , TGraphErrors*>::iterator nh_h = userTGraphs_.find( TGraphName );
    if( nh_h == userTGraphs_.end()) continue;

    TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)*log(x)) + [1]*(log(x)*log(x)) + [2]*log(x) + [3]", 300, 1000);
    //TF1* functionFit = new TF1( "functionFit", "[0]*(log(x)*log(x)) + [1]*log(x) + [2]", 300, 1000);

    TCanvas *c1 = new TCanvas("c1", "c1", 800, 800);
    nh_h->second->SetMarkerStyle(20);
    nh_h->second->SetMarkerSize(1.5);
    nh_h->second->GetXaxis()->SetRangeUser(300, 1000);
    nh_h->second->SetMaximum(0.1);
    nh_h->second->SetMinimum(-0.1);
    nh_h->second->Fit(functionFit, "R");
    nh_h->second->Draw("ZAP");
    c1 -> SaveAs( Form("WideJets_Plot/%s.png", TGraphName.c_str() ) );
    c1 -> Destructor();

    double Par0       =  functionFit->GetParameter(0);
    double Par1       =  functionFit->GetParameter(1);
    double Par2       =  functionFit->GetParameter(2);                                                                                                              
    double Par3       =  functionFit->GetParameter(3); 
    double NDF       =  functionFit->GetNDF();
    double Chisquare      =  functionFit->GetChisquare();
    cout<< "Par 0 = " << Par0 << endl;
    cout<< "Par 1 = " << Par1 << endl;
    cout<< "Par 2 = " << Par2 << endl;
    cout<< "Par 3 = " << Par3 << endl;                                                                                                                                                                 
    cout<< "Chisquare / NDF = " << Chisquare<<"/"<<NDF << endl;

    for(int jj=0; jj < binnum; jj++){
      
      int pTMin = pTMeanArray[jj];
      int pTMax = pTMeanArray[jj+1];
      double pTMean= (pTMin + pTMax) /2. ;
      cout<<"pT Mean = " << pTMean <<endl;

      //      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)) + Par1*log(pTMean) + Par2;
      double pTBiasFit = Par0*(log(pTMean)*log(pTMean)*log(pTMean)) + Par1*log(pTMean)*log(pTMean) + Par2*log(pTMean) + Par3;
      cout<<"pT Bias from fit = " << pTBiasFit <<endl;

      Histo_Corrections->SetBinContent(ii+1, jj+1, pTBiasFit);
    }
  } 

    TCanvas *c2 = new TCanvas("c2", "c2", 900, 800);
    Histo_Corrections->SetStats(0);
    gStyle->SetPalette(55);
    Histo_Corrections->SetContour(100);
    Histo_Corrections->Draw("colz");
    c2->SetRightMargin(0.13);
    c2->SaveAs("WideJets_Plot/Corrections.png");

    TFile* outputFile= new TFile("WideJetsCorrections_JEC_HLT_v7.root","RECREATE");
    outputFile->cd();
    Histo_Corrections -> Write();
    outputFile->Close();

   
  return 0;
}
void composeTrackAnalysisbyAssociator(string FileListName, int FileNumber) {

    if(debug) cout << FileListName << endl;
    string theFileName;
    ifstream composeFileList;
    composeFileList.open(FileListName.c_str());

    string OutputPlotNamepreFix = FileListName + "_";
    string OutputPlotNameFix = ".png";

    unsigned int EventNumber;
    unsigned int trackingParticleMatch;
    double recTrackPurity;
    double recTrackrefMomentum;
    double recTrackrefPhi;
    double recTrackrefEta;
    double recTrackinnerMomentum;
    double recTrackinnerPhi;
    double recTrackinnerEta;
    unsigned int recTrackinnerValid;
    double recTrackouterMomentum;
    double recTrackouterPhi;
    double recTrackouterEta;
    unsigned int recTrackouterValid;
    double simTrackinnerMomentum;
    double simTrackinnerPhi;
    double simTrackinnerEta;
    unsigned int simTrackinnerMatch;
    double simTrackouterMomentum;
    double simTrackouterPhi;
    double simTrackouterEta;
    unsigned int simTrackouterMatch;
    double recTrackinnerMomentumofTSOS;
    double recTrackinnerPhiofTSOS;
    double recTrackinnerEtaofTSOS;
    unsigned int recTrackinnerValidofTSOS;
    double recTrackouterMomentumofTSOS;
    double recTrackouterPhiofTSOS;
    double recTrackouterEtaofTSOS;
    unsigned int recTrackouterValidofTSOS;
    double recTrackimpactMomentumofTSOS;
    double recTrackimpactPhiofTSOS;
    double recTrackimpactEtaofTSOS;
    unsigned int recTrackimpactValidofTSOS;
    int recTrackCharge;
    double simTrackMomentumPt;
    double simTrackPhi;
    double simTrackEta;
    int simTrackCharge;

    TObjArray* myEfficiencyHist = new TObjArray();
    TObjArray* myParticleHist = new TObjArray();
    TObjArray* mySTAHist = new TObjArray();
    TObjArray* myChargeCheckHist = new TObjArray();
    TObjArray* myDeltaPtHist = new TObjArray();
    TObjArray* myDeltaPhiHist = new TObjArray();
    TObjArray* myDeltaEtaHist = new TObjArray();
    vector<string> TypeName;
    TypeName.clear();

    for(int Index = 0; Index < FileNumber; Index++) {
        getline(composeFileList, theFileName);
        TypeName.push_back(theFileName);
        string fullFileName = "data/"+ theFileName + ".root";
        if(debug) cout << theFileName << endl;
        TFile* RootFile = TFile::Open(fullFileName.c_str());

        TTree* T1 = (TTree*)RootFile->Get("ExTree");
        T1->SetBranchAddress("EventNumber", &EventNumber);
        T1->SetBranchAddress("trackingParticleMatch", &trackingParticleMatch);
        T1->SetBranchAddress("recTrackPurity", &recTrackPurity);
        T1->SetBranchAddress("recTrackrefMomentum", &recTrackrefMomentum);
        T1->SetBranchAddress("recTrackrefPhi", &recTrackrefPhi);
        T1->SetBranchAddress("recTrackrefEta", &recTrackrefEta);
        T1->SetBranchAddress("recTrackinnerMomentum", &recTrackinnerMomentum);
        T1->SetBranchAddress("recTrackinnerPhi", &recTrackinnerPhi);
        T1->SetBranchAddress("recTrackinnerEta", &recTrackinnerEta);
        T1->SetBranchAddress("recTrackinnerValid", &recTrackinnerValid);
        T1->SetBranchAddress("recTrackouterMomentum", &recTrackouterMomentum);
        T1->SetBranchAddress("recTrackouterPhi", &recTrackouterPhi);
        T1->SetBranchAddress("recTrackouterEta", &recTrackouterEta);
        T1->SetBranchAddress("recTrackouterValid", &recTrackouterValid);
        T1->SetBranchAddress("simTrackinnerMomentum", &simTrackinnerMomentum);
        T1->SetBranchAddress("simTrackinnerPhi", &simTrackinnerPhi);
        T1->SetBranchAddress("simTrackinnerEta", &simTrackinnerEta);
        T1->SetBranchAddress("simTrackinnerMatch", &simTrackinnerMatch);
        T1->SetBranchAddress("simTrackouterMomentum", &simTrackouterMomentum);
        T1->SetBranchAddress("simTrackouterPhi", &simTrackouterPhi);
        T1->SetBranchAddress("simTrackouterEta", &simTrackouterEta);
        T1->SetBranchAddress("simTrackouterMatch", &simTrackouterMatch);
        T1->SetBranchAddress("recTrackinnerMomentumofTSOS", &recTrackinnerMomentumofTSOS);
        T1->SetBranchAddress("recTrackinnerPhiofTSOS", &recTrackinnerPhiofTSOS);
        T1->SetBranchAddress("recTrackinnerEtaofTSOS", &recTrackinnerEtaofTSOS);
        T1->SetBranchAddress("recTrackinnerValidofTSOS", &recTrackinnerValidofTSOS);
        T1->SetBranchAddress("recTrackouterMomentumofTSOS", &recTrackouterMomentumofTSOS);
        T1->SetBranchAddress("recTrackouterPhiofTSOS", &recTrackouterPhiofTSOS);
        T1->SetBranchAddress("recTrackouterEtaofTSOS", &recTrackouterEtaofTSOS);
        T1->SetBranchAddress("recTrackouterValidofTSOS", &recTrackouterValidofTSOS);
        T1->SetBranchAddress("recTrackimpactMomentumofTSOS", &recTrackimpactMomentumofTSOS);
        T1->SetBranchAddress("recTrackimpactPhiofTSOS", &recTrackimpactPhiofTSOS);
        T1->SetBranchAddress("recTrackimpactEtaofTSOS", &recTrackimpactEtaofTSOS);
        T1->SetBranchAddress("recTrackimpactValidofTSOS", &recTrackimpactValidofTSOS);
        T1->SetBranchAddress("recTrackCharge", &recTrackCharge);
        T1->SetBranchAddress("simTrackMomentumPt", &simTrackMomentumPt);
        T1->SetBranchAddress("simTrackPhi", &simTrackPhi);
        T1->SetBranchAddress("simTrackEta", &simTrackEta);
        T1->SetBranchAddress("simTrackCharge", &simTrackCharge);

        string TempHistName;
        TempHistName = theFileName + "_Efficiency2simPt";
        TH1D* Efficiency2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_Particle2simPt";
        TH1D* Particle2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_STA2simPt";
        TH1D* STA2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_InverseChargeRato2simPt";
        TH1D* InverseChargeRato2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_DeltaPt2simPt";
        TH1D* DeltaPt2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_DeltaPhi2simPt";
        TH1D* DeltaPhi2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_DeltaEta2simPt";
        TH1D* DeltaEta2simPtHist = new TH1D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale);
        TempHistName = theFileName + "_MaxPurity2simPt";
        TH2D* MaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 6, 0., 1.2);
        TempHistName = theFileName + "_Multiplicity2simPt";
        TH2D* Multiplicity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 10, 0., 10.);
        TempHistName = theFileName + "_ChargeCheck2simPt";
        TH2D* ChargeCheck2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 5, -2.5, 2.5);
        TempHistName = theFileName + "_simTrackMomentumPtmaxPurity2simPt";
        TH2D* simTrackMomentumPtmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, (int)5*PtScale, 0, PtScale);
        TempHistName = theFileName + "_simTrackPhimaxPurity2simPt";
        TH2D* simTrackPhimaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 314, -PI, PI);
        TempHistName = theFileName + "_simTrackEtamaxPurity2simPt";
        TH2D* simTrackEtamaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 400, -2.0, 2.0);
        TempHistName = theFileName + "_recTrackimpactMomentumofTSOSmaxPurity2simPt";
        TH2D* recTrackimpactMomentumofTSOSmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, (int)5*PtScale, 0, PtScale);
        TempHistName = theFileName + "_recTrackimpactPhiofTSOSmaxPurity2simPt";
        TH2D* recTrackimpactPhiofTSOSmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 314, -PI, PI);
        TempHistName = theFileName + "_recTrackimpactEtaofTSOSmaxPurity2simPt";
        TH2D* recTrackimpactEtaofTSOSmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 600, -3.0, 3.0);
        TempHistName = theFileName + "_recTrackimpactValidofTSOSmaxPurity2simPt";
        TH2D* recTrackimpactValidofTSOSmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(), (int)(PtScale/2), 0, PtScale, 2, 0., 2.);
        TempHistName = theFileName + "_DeltaPtmaxPurity2simPt";
        TH2D* DeltaPtmaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(),  (int)(PtScale/2), 0, PtScale, (int)5*PtScale, -1.*PtScale, PtScale);
        TempHistName = theFileName + "_DeltaPhimaxPurity2simPt";
        TH2D* DeltaPhimaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(),  (int)(PtScale/2), 0, PtScale, 314, -PI, PI);
        TempHistName = theFileName + "_DeltaEtamaxPurity2simPt";
        TH2D* DeltaEtamaxPurity2simPtHist = new TH2D(TempHistName.c_str(), TempHistName.c_str(),  (int)(PtScale/2), 0, PtScale, 400, -2.0, 2.0);

        unsigned int trackingParticleMatch_temp;
        unsigned int efficiency_temp;
        double recTrackPurity_temp;
        double recTrackrefMomentum_temp;
        double recTrackrefPhi_temp;
        double recTrackrefEta_temp;
        double recTrackinnerMomentum_temp;
        double recTrackinnerPhi_temp;
        double recTrackinnerEta_temp;
        unsigned int recTrackinnerValid_temp;
        double recTrackouterMomentum_temp;
        double recTrackouterPhi_temp;
        double recTrackouterEta_temp;
        unsigned int recTrackouterValid_temp;
        double simTrackinnerMomentum_temp;
        double simTrackinnerPhi_temp;
        double simTrackinnerEta_temp;
        unsigned int simTrackinnerMatch_temp;
        double simTrackouterMomentum_temp;
        double simTrackouterPhi_temp;
        double simTrackouterEta_temp;
        unsigned int simTrackouterMatch_temp;
        double recTrackinnerMomentumofTSOS_temp;
        double recTrackinnerPhiofTSOS_temp;
        double recTrackinnerEtaofTSOS_temp;
        unsigned int recTrackinnerValidofTSOS_temp;
        double recTrackouterMomentumofTSOS_temp;
        double recTrackouterPhiofTSOS_temp;
        double recTrackouterEtaofTSOS_temp;
        unsigned int recTrackouterValidofTSOS_temp;
        double recTrackimpactMomentumofTSOS_temp;
        double recTrackimpactPhiofTSOS_temp;
        double recTrackimpactEtaofTSOS_temp;
        unsigned int recTrackimpactValidofTSOS_temp;
        int recTrackCharge_temp;
        double simTrackMomentumPt_temp;
        double simTrackPhi_temp;
        double simTrackEta_temp;
        int simTrackCharge_temp;

        int Nentries = T1->GetEntries(); 
        for(int i = 0; i < Nentries; i++) { 
            T1->GetEntry(i);
            if(trackingParticleMatch == 0) {
                MaxPurity2simPtHist->Fill(simTrackMomentumPt, 0);
                Multiplicity2simPtHist->Fill(simTrackMomentumPt, 0);
                int tempParticleBinNumber = Particle2simPtHist->FindBin(simTrackMomentumPt);
                double tempParticleBinValue = Particle2simPtHist->GetBinContent(tempParticleBinNumber);
                tempParticleBinValue += 1.;
                Particle2simPtHist->SetBinContent(tempParticleBinNumber, tempParticleBinValue);
            }
            else {
                efficiency_temp = 1;
                trackingParticleMatch_temp = trackingParticleMatch;
                recTrackPurity_temp = recTrackPurity;
                recTrackrefMomentum_temp = recTrackrefMomentum;
                recTrackrefPhi_temp = recTrackrefPhi;
                recTrackrefEta_temp = recTrackrefEta;
                recTrackinnerMomentum_temp = recTrackinnerMomentum;
                recTrackinnerPhi_temp = recTrackinnerPhi;
                recTrackinnerEta_temp = recTrackinnerEta;
                recTrackinnerValid_temp = recTrackinnerValid;
                recTrackouterMomentum_temp = recTrackouterMomentum;
                recTrackouterPhi_temp = recTrackouterPhi;
                recTrackouterEta_temp = recTrackouterEta;
                recTrackouterValid_temp = recTrackouterValid;
                simTrackinnerMomentum_temp = simTrackinnerMomentum;
                simTrackinnerPhi_temp = simTrackinnerPhi;
                simTrackinnerEta_temp = simTrackinnerEta;
                simTrackinnerMatch_temp = simTrackinnerMatch;
                simTrackouterMomentum_temp = simTrackouterMomentum;
                simTrackouterPhi_temp = simTrackouterPhi;
                simTrackouterEta_temp = simTrackouterEta;
                simTrackouterMatch_temp = simTrackouterMatch;
                recTrackinnerMomentumofTSOS_temp = recTrackinnerMomentumofTSOS;
                recTrackinnerPhiofTSOS_temp = recTrackinnerPhiofTSOS;
                recTrackinnerEtaofTSOS_temp = recTrackinnerEtaofTSOS;
                recTrackinnerValidofTSOS_temp = recTrackinnerValidofTSOS;
                recTrackouterMomentumofTSOS_temp = recTrackouterMomentumofTSOS;
                recTrackouterPhiofTSOS_temp = recTrackouterPhiofTSOS;
                recTrackouterEtaofTSOS_temp = recTrackouterEtaofTSOS;
                recTrackouterValidofTSOS_temp = recTrackouterValidofTSOS;
                recTrackimpactMomentumofTSOS_temp = recTrackimpactMomentumofTSOS;
                recTrackimpactPhiofTSOS_temp = recTrackimpactPhiofTSOS;
                recTrackimpactEtaofTSOS_temp = recTrackimpactEtaofTSOS;
                recTrackimpactValidofTSOS_temp = recTrackimpactValidofTSOS;
                recTrackCharge_temp = recTrackCharge;
                simTrackMomentumPt_temp = simTrackMomentumPt;
                simTrackPhi_temp = simTrackPhi;
                simTrackEta_temp = simTrackEta;
                simTrackCharge_temp = simTrackCharge;

                bool nextStep = true;
                while(nextStep) {
                    i++;
                    T1->GetEntry(i);
                    if(trackingParticleMatch <= trackingParticleMatch_temp)
                        nextStep = false;
                    else
                        trackingParticleMatch_temp = trackingParticleMatch;
                    if(nextStep == true && recTrackPurity_temp < recTrackPurity) {
                        if(debug) cout << "step another match, trackingParticleMatch_temp: " << trackingParticleMatch_temp << endl;
                        //trackingParticleMatch_temp = trackingParticleMatch;
                        recTrackPurity_temp = recTrackPurity;
                        recTrackrefMomentum_temp = recTrackrefMomentum;
                        recTrackrefPhi_temp = recTrackrefPhi;
                        recTrackrefEta_temp = recTrackrefEta;
                        recTrackinnerMomentum_temp = recTrackinnerMomentum;
                        recTrackinnerPhi_temp = recTrackinnerPhi;
                        recTrackinnerEta_temp = recTrackinnerEta;
                        recTrackinnerValid_temp = recTrackinnerValid;
                        recTrackouterMomentum_temp = recTrackouterMomentum;
                        recTrackouterPhi_temp = recTrackouterPhi;
                        recTrackouterEta_temp = recTrackouterEta;
                        recTrackouterValid_temp = recTrackouterValid;
                        simTrackinnerMomentum_temp = simTrackinnerMomentum;
                        simTrackinnerPhi_temp = simTrackinnerPhi;
                        simTrackinnerEta_temp = simTrackinnerEta;
                        simTrackinnerMatch_temp = simTrackinnerMatch;
                        simTrackouterMomentum_temp = simTrackouterMomentum;
                        simTrackouterPhi_temp = simTrackouterPhi;
                        simTrackouterEta_temp = simTrackouterEta;
                        simTrackouterMatch_temp = simTrackouterMatch;
                        recTrackinnerMomentumofTSOS_temp = recTrackinnerMomentumofTSOS;
                        recTrackinnerPhiofTSOS_temp = recTrackinnerPhiofTSOS;
                        recTrackinnerEtaofTSOS_temp = recTrackinnerEtaofTSOS;
                        recTrackinnerValidofTSOS_temp = recTrackinnerValidofTSOS;
                        recTrackouterMomentumofTSOS_temp = recTrackouterMomentumofTSOS;
                        recTrackouterPhiofTSOS_temp = recTrackouterPhiofTSOS;
                        recTrackouterEtaofTSOS_temp = recTrackouterEtaofTSOS;
                        recTrackouterValidofTSOS_temp = recTrackouterValidofTSOS;
                        recTrackimpactMomentumofTSOS_temp = recTrackimpactMomentumofTSOS;
                        recTrackimpactPhiofTSOS_temp = recTrackimpactPhiofTSOS;
                        recTrackimpactEtaofTSOS_temp = recTrackimpactEtaofTSOS;
                        recTrackimpactValidofTSOS_temp = recTrackimpactValidofTSOS;
                        recTrackCharge_temp = recTrackCharge;
                        simTrackMomentumPt_temp = simTrackMomentumPt;
                        simTrackPhi_temp = simTrackPhi;
                        simTrackEta_temp = simTrackEta;
                        simTrackCharge_temp = simTrackCharge;
                    }
                }
                i--;
                //if(debug) cout << "Filling Multiplicity " << trackingParticleMatch_temp << endl;
                MaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackPurity_temp);
                Multiplicity2simPtHist->Fill(simTrackMomentumPt_temp, trackingParticleMatch_temp);
                ChargeCheck2simPtHist->Fill(simTrackMomentumPt_temp, simTrackCharge_temp*recTrackCharge_temp);
                simTrackMomentumPtmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, simTrackMomentumPt_temp);
                simTrackPhimaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, simTrackPhi_temp);
                simTrackEtamaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, simTrackEta_temp);
                recTrackimpactMomentumofTSOSmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactMomentumofTSOS_temp);
                recTrackimpactPhiofTSOSmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactPhiofTSOS_temp);
                recTrackimpactEtaofTSOSmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactEtaofTSOS_temp);
                recTrackimpactValidofTSOSmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactValidofTSOS_temp);
                DeltaPtmaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, (recTrackimpactMomentumofTSOS_temp-simTrackMomentumPt_temp)/simTrackMomentumPt_temp);
                DeltaPhimaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactPhiofTSOS_temp-simTrackPhi_temp);
                DeltaEtamaxPurity2simPtHist->Fill(simTrackMomentumPt_temp, recTrackimpactEtaofTSOS_temp-simTrackEta_temp);


                int tempParticleBinNumber = STA2simPtHist->FindBin(simTrackMomentumPt_temp);
                double tempParticleBinValue = Particle2simPtHist->GetBinContent(tempParticleBinNumber);
                tempParticleBinValue += 1.;
                Particle2simPtHist->SetBinContent(tempParticleBinNumber, tempParticleBinValue);
                double tempSTABinValue = STA2simPtHist->GetBinContent(tempParticleBinNumber);
                tempSTABinValue += 1.;                        
                STA2simPtHist->SetBinContent(tempParticleBinNumber, tempSTABinValue);
            }
        }

        
        for(int PtIndex = 1; PtIndex <= (int)(PtScale/2); PtIndex++) {
            double ParticleBinValue = Particle2simPtHist->GetBinContent(PtIndex);
            double STABinValue = STA2simPtHist->GetBinContent(PtIndex);
            if(ParticleBinValue == 0.)
                ParticleBinValue += 1.;
            double EfficiencyBinValue = STABinValue / ParticleBinValue * 100.;
            double EfficiencyBinError = sqrt(EfficiencyBinValue * (100. - EfficiencyBinValue) / ParticleBinValue);
            cout << ParticleBinValue << ", " << STABinValue << ", " << EfficiencyBinValue << endl;
            Efficiency2simPtHist->SetBinContent(PtIndex, EfficiencyBinValue);
            Efficiency2simPtHist->SetBinError(PtIndex, EfficiencyBinError);

            TH1D* ChargeCheckHist = ChargeCheck2simPtHist->ProjectionY("ChargeCheck", PtIndex, PtIndex, "o");
            double ReverseChargeBinValue = ChargeCheckHist->GetBinContent(2);
            double CoverseChargeBinValue = ChargeCheckHist->GetBinContent(4);
            double TotalChargeBinValue = ReverseChargeBinValue + CoverseChargeBinValue;
            if(TotalChargeBinValue == 0.);
                TotalChargeBinValue += 1.;
            double ReverseChargeRato = ReverseChargeBinValue / TotalChargeBinValue;
            InverseChargeRato2simPtHist->SetBinContent(PtIndex, ReverseChargeRato);

            TH1D* DeltaPtHist = DeltaPtmaxPurity2simPtHist->ProjectionY("DeltaPt", PtIndex, PtIndex, "o");
            double DeltaPtMean = DeltaPtHist->GetMean();
            double DeltaPtRMS = DeltaPtHist->GetRMS();
            DeltaPt2simPtHist->SetBinContent(PtIndex, DeltaPtMean);
            DeltaPt2simPtHist->SetBinError(PtIndex, DeltaPtRMS);

            TH1D* DeltaPhiHist = DeltaPhimaxPurity2simPtHist->ProjectionY("DeltaPhi", PtIndex, PtIndex, "o");
            double DeltaPhiMean = DeltaPhiHist->GetMean();
            double DeltaPhiRMS = DeltaPhiHist->GetRMS();
            DeltaPhi2simPtHist->SetBinContent(PtIndex, DeltaPhiMean);
            DeltaPhi2simPtHist->SetBinError(PtIndex, DeltaPhiRMS);

            TH1D* DeltaEtaHist = DeltaEtamaxPurity2simPtHist->ProjectionY("DeltaEta", PtIndex, PtIndex, "o");
            double DeltaEtaMean = DeltaEtaHist->GetMean();
            double DeltaEtaRMS = DeltaEtaHist->GetRMS();
            DeltaEta2simPtHist->SetBinContent(PtIndex, DeltaEtaMean);
            DeltaEta2simPtHist->SetBinError(PtIndex, DeltaEtaRMS);
        }
        myEfficiencyHist->AddLast(Efficiency2simPtHist);
        myParticleHist->AddLast(Particle2simPtHist);
        mySTAHist->AddLast(STA2simPtHist);
        myChargeCheckHist->AddLast(InverseChargeRato2simPtHist);
        myDeltaPtHist->AddLast(DeltaPt2simPtHist);
    }
    double minX = 0;
    double minY = 0;
    double maxX = 110;
    double maxY = 40;

    TCanvas* myCanvas = new TCanvas("Canvas", "Canvas", 800, 600);
    myCanvas->cd();
    TPad* myPad = new TPad("Pad", "Pad", 0, 0, 1, 1);
    myPad->Draw();
    myPad->cd();

    ((TH1D*)(myParticleHist->At(0)))->SetStats(0);
    ((TH1D*)(myParticleHist->At(0)))->GetXaxis()->SetTitle("simPt/Gev");
    ((TH1D*)(myParticleHist->At(0)))->GetXaxis()->CenterTitle(1);
    ((TH1D*)(myParticleHist->At(0)))->Draw();
    for(int Index = 0; Index < FileNumber; Index++) {
	((TH1D*)(mySTAHist->At(Index)))->SetStats(0);
        ((TH1D*)(mySTAHist->At(Index)))->SetLineColor(kRed+Index);
        ((TH1D*)(mySTAHist->At(Index)))->Draw("same");
    }
    TLegend *STALeg = new TLegend(0.6,0.1,0.9,0.3);
    STALeg->SetBorderSize(1);
    TString LegKey = "ParticleTrack";
    STALeg->AddEntry(myParticleHist->At(0), LegKey, "lpf");
    for(int Index = 0; Index < FileNumber; Index++) {
        LegKey = TypeName[Index];
        STALeg->AddEntry(mySTAHist->At(Index), LegKey, "lpf");
    }
    STALeg->Draw();
    string SaveName = OutputPlotNamepreFix + "_STA2simPt" + OutputPlotNameFix;
    myCanvas->SaveAs(SaveName.c_str());

    myPad->Clear();
    myPad->Update();
    double YScale = myPad->GetUymax() / 110.;
    ((TH1D*)(myEfficiencyHist->At(0)))->GetXaxis()->SetTitle("simPt/Gev");
    ((TH1D*)(myEfficiencyHist->At(0)))->GetXaxis()->CenterTitle(1);
    ((TH1D*)(myEfficiencyHist->At(0)))->SetStats(0);
    ((TH1D*)(myEfficiencyHist->At(0)))->Scale(YScale);
    ((TH1D*)(myEfficiencyHist->At(0)))->SetLineColor(kRed);
    ((TH1D*)(myEfficiencyHist->At(0)))->Draw("same,ah");
    for(int Index = 1; Index < FileNumber; Index++) {
	((TH1D*)(myEfficiencyHist->At(Index)))->SetStats(0);
        ((TH1D*)(myEfficiencyHist->At(Index)))->Scale(YScale);
        ((TH1D*)(myEfficiencyHist->At(Index)))->SetLineColor(kRed+Index);
        ((TH1D*)(myEfficiencyHist->At(Index)))->Draw("same,ah");
    }
    myPad->Update();
    if(debug) cout << "Y: " << myPad->GetUymax() << endl;
    double YAxisMinValue=((TH1D*)(myEfficiencyHist->At(0)))->GetYaxis()->GetXmin();
    double YAxisMaxValue=((TH1D*)(myEfficiencyHist->At(0)))->GetYaxis()->GetXmax();
    int YAxisNBins=((TH1D*)(myEfficiencyHist->At(0)))->GetYaxis()->GetNbins();
    TGaxis* YAxis = new TGaxis(myPad->GetUxmin(), myPad->GetUymin(), myPad->GetUxmin(), myPad->GetUymax(), 0, 110, 510, "-R");
    YAxis->SetLineColor(kGreen);
    YAxis->SetLabelColor(kGreen);
    YAxis->SetTitle("Efficiency of STA for simPts");
    YAxis->CenterTitle(1);
    YAxis->Draw();
    double XAxisMinValue=((TH1D*)(myEfficiencyHist->At(0)))->GetXaxis()->GetXmin();
    double XAxisMaxValue=((TH1D*)(myEfficiencyHist->At(0)))->GetXaxis()->GetXmax();
    int XAxisNBins=((TH1D*)(myEfficiencyHist->At(0)))->GetXaxis()->GetNbins();
    TGaxis* XAxis = new TGaxis(myPad->GetUxmin(), myPad->GetUymin(), myPad->GetUxmax(), myPad->GetUymin(), XAxisMinValue, XAxisMaxValue, 510, "+L");
    XAxis->SetTitle("simPt/Gev");
    XAxis->CenterTitle(1);
    XAxis->Draw();
    TLegend *EffLeg = new TLegend(0.1,0.9,0.4,1.0);
    EffLeg->SetBorderSize(1);
    for(int Index = 0; Index < FileNumber; Index++) {
        TString LegKey = TypeName[Index];
        EffLeg->AddEntry(myEfficiencyHist->At(Index), LegKey, "lpf");
    }
    EffLeg->Draw();
    string SaveName = OutputPlotNamepreFix + "_Eff2simPt" + OutputPlotNameFix;
    myCanvas->SaveAs(SaveName.c_str());

    ((TH1D*)(myDeltaPtHist->At(0)))->SetStats(0);
    ((TH1D*)(myDeltaPtHist->At(0)))->GetXaxis()->SetTitle("simPt/Gev");
    ((TH1D*)(myDeltaPtHist->At(0)))->GetXaxis()->CenterTitle(1);
    ((TH1D*)(myDeltaPtHist->At(0)))->GetYaxis()->SetTitle("deltPt/simPt");
    ((TH1D*)(myDeltaPtHist->At(0)))->GetYaxis()->CenterTitle(1);
    ((TH1D*)(myDeltaPtHist->At(0)))->SetLineColor(kRed);
    ((TH1D*)(myDeltaPtHist->At(0)))->Draw("");
    for(int Index = 1; Index < FileNumber; Index++) {
	    ((TH1D*)(myDeltaPtHist->At(Index)))->SetStats(0);
	    //((TH1D*)(myDeltaPtHist->At(Index)))->GetXaxis()->SetTitle("simPt/Gev");
	    //((TH1D*)(myDeltaPtHist->At(Index)))->GetXaxis()->CenterTitle(1);
	    //((TH1D*)(myDeltaPtHist->At(Index)))->GetYaxis()->SetTitle("deltPt/simPt");
	    //((TH1D*)(myDeltaPtHist->At(Index)))->GetYaxis()->CenterTitle(1);
        ((TH1D*)(myDeltaPtHist->At(Index)))->SetLineColor(kRed+Index);
        ((TH1D*)(myDeltaPtHist->At(Index)))->Draw("same");
        //SaveName = OutputPlotNamepreFix + TypeName[Index] + "DeltaPt" + OutputPlotNameFix;
        //myCanvas->SaveAs(SaveName.c_str());
    }
    TLegend *PtLeg = new TLegend(0.6,0.8,0.9,0.9);
    PtLeg->SetBorderSize(1);
    for(int Index = 0; Index < FileNumber; Index++) {
        TString LegKey = TypeName[Index];
        PtLeg->AddEntry(myDeltaPtHist->At(Index), LegKey, "lpf");
    }
    PtLeg->Draw();
    SaveName = OutputPlotNamepreFix + "_DeltaPt" + OutputPlotNameFix;
    myCanvas->SaveAs(SaveName.c_str());
}
void balanceMetVsAj(TString infname,
                    TString insrc, TString metType = "",bool drawLegend = false,
                    bool drawSys = true
                    )
{
   // ===========================================================
   // Get Input
   // ===========================================================
   TFile *inf = new TFile(infname);
   
   // ===========================================================
   // Analysis Setup
   // ===========================================================
   Int_t plotLayer=10; // 0 only >0.5, 1 >0.5 and highpt, 10 ~ all
   const int nBin = 5;
   double bins[nBin+1] = {0.5,1.0,2,4,8,1000};  
   
   const int nBinAj = 4;
   double ajBins[nBinAj+1] = {0.0001,0.11,0.22,0.33,0.49999};
   
   cout << infname << endl;
   
   TH1D *ppos[nBin+1];
   TH1D *pneg[nBin+1];
   TH1D *pe[nBin+1];
   // =================================
   // Get Weighted Mean for each Aj bin
   // =================================
   for (int i=0;i<nBin+1;i++)
   {
      pe[i]=new TH1D(Form("p%d",i),"",nBinAj,ajBins);
      for (int a=0; a<nBinAj; ++a) {
         TString hname = Form("%s_mptx%s_merge%d_%dSigAll",insrc.Data(),metType.Data(),i,a);
         TH1D * hMpt = (TH1D*)inf->Get(hname);
//         cout << hname << " Aj bin: " << a+1 << " mean: " << hMpt->GetMean() << endl;
         pe[i]->SetBinContent(a+1,hMpt->GetMean());
         pe[i]->SetBinError(a+1,hMpt->GetRMS()/sqrt(hMpt->GetEntries()));
      }      
   }
   
   StackHistograms(nBin,pe,ppos,pneg,nBinAj);
   
   TH1D *pall=pe[nBin];
   
   pall->SetXTitle("A_{J}");
   pall->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)");
   pall->GetXaxis()->CenterTitle();
   pall->GetYaxis()->CenterTitle();
   pall->GetXaxis()->SetLabelSize(22);
   pall->GetXaxis()->SetLabelFont(43);
   pall->GetXaxis()->SetTitleSize(24);
   pall->GetXaxis()->SetTitleFont(43);
   pall->GetYaxis()->SetLabelSize(22);
   pall->GetYaxis()->SetLabelFont(43);
   pall->GetYaxis()->SetTitleSize(24);
   pall->GetYaxis()->SetTitleFont(43);
   pall->GetXaxis()->SetTitleOffset(1.8);
   pall->GetYaxis()->SetTitleOffset(2.4);
   pall->SetNdivisions(505);
   pall->SetAxisRange(-59.9,59.9,"Y");
   pall->SetMarkerSize(1);
   pall->SetMarkerColor(kBlack);
   pall->SetMarkerStyle(kFullCircle);
   pall->Draw("E");
   float addSys = 0;
   if ( drawSys==1)   addSys=0; // No sys error at this moment
   
   // ====================
   // Finally Draw
   // ====================
   for (int i=0;i<nBin;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nBin-1) continue;
      ppos[i]->SetLineWidth(1);
      ppos[i]->Draw("hist same");
      pneg[i]->SetLineWidth(1);
      pneg[i]->Draw("hist same");
//      PrintHistogram(ppos[i]);
//      PrintHistogram(pneg[i]);
   }
   
   // ====================
   // Draw Statistical Error bars
   // ====================
   for (int i=0;i<nBin;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nBin-1) continue;
      if ( i==0 )       drawErrorShift(ppos[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(ppos[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(ppos[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(ppos[i],0.016,addSys);
      if ( i==0 )       drawErrorShift(pneg[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(pneg[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(pneg[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(pneg[i],0.016,addSys);
   }
   pall->Draw("E same");
//   PrintHistogram(pall);
   
   // ====================
   // Draw Systematic Errors
   // ====================
   if (drawSys == 1) {
      for(int i = 0; i < nBinAj; ++i){
         double x = pall->GetBinCenter(i+1);
         double y = pall->GetBinContent(i+1);
         // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics
         double errReco = -pe[nBin-1]->GetBinContent(i+1)*0.2;
         double errBck = 3.0; // compare HYDJET+SIG to SIG
         double err = sqrt(errReco*errReco+errBck*errBck);
         DrawTick(y,err,err,x,1,0.02,1);
      }
   }
   
   // ====================
   // Draw Legend
   // ====================
   TLegend *leg = new TLegend(0.10,0.68,0.70,0.96);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(63);
   leg->SetTextSize(16);
   leg->AddEntry(pall,Form("> %.1f GeV/c",bins[0]),"p");
   for (int i=0;i<nBin;++i) {
      if (plotLayer==0) continue;
      if (plotLayer==1&&i!=nBin-1) continue;
      if (i!=nBin-1){
         leg->AddEntry(ppos[i],Form("%.1f - %.1f GeV/c",bins[i],bins[i+1]),"f");
      } else {
         leg->AddEntry(ppos[i],Form("> %.1f GeV/c",bins[i]),"f");
      }
   }
   
   if (drawLegend) leg->Draw();
   
   TLine * l0 = new TLine(0,0,0.5,0);
   l0->SetLineStyle(2);
   l0->Draw();
   
   
   TLine * l1 = new TLine(0.0001,-10,0.0001,10);
   l1->Draw();
}
void advancedNoiseAnalysis( unsigned int runNumber, unsigned int loop = 1) {
  
  string inputFileName = "./histo/run00" + toString( runNumber ) + "-ped-histo.root";
  string outputFileName = "./histo/run00" + toString( runNumber ) + "-adv-noise.root";
  

  // before opening the input and the output files, try to see if they
  // are not opened yet and in case close them before continue   
  TList * listOfOpenedFile = (TList*) gROOT->GetListOfFiles();
  for ( int i = 0; i < listOfOpenedFile->GetSize() ; ++i ) {
    TFile * file = (TFile*) listOfOpenedFile->At( i ) ;
    TString fileName(file->GetName());
    TString inputFileName1( inputFileName.c_str() );
    TString outputFileName1( outputFileName.c_str() );

    if (  ( fileName.Contains( inputFileName1 ) ) ||
	  ( inputFileName1.Contains( fileName ) ) ||
	  ( fileName.Contains( outputFileName1 ) ) ||
	  ( outputFileName1.Contains( fileName ) ) ) {
      cout << "Closing " << fileName << " before reopen " << endl;
      file->Close();
    }
  }


  // close also all the previously opened canvas
  TList * listOfOpenedCanvas = (TList*) gROOT->GetListOfCanvases();
  for ( int i = 0 ; i < listOfOpenedCanvas->GetSize() ; ++i ) {
    TCanvas * canvas = (TCanvas*) listOfOpenedCanvas->At( i );
    TString canvasName2 = canvas->GetName();
    if ( canvasName2.Contains( "det" ) ) {
      canvas->Close();
    }
  }

	 
  // now safely open the file
  TFile * inputFile = TFile::Open( inputFileName.c_str() ) ;
  TFile * outputFile = TFile::Open( outputFileName.c_str(), "RECREATE") ;
  TList * outputHistoList = new TList;

  // look into the inputFile for a folder named
  string pedeProcessorFolderName = "PedestalAndNoiseCalculator";
  TDirectoryFile * pedeProcessorFolder = (TDirectoryFile*) inputFile->Get( pedeProcessorFolderName.c_str() );
  
  if ( pedeProcessorFolder == 0 ) { 
    cerr << "No pedestal processor folder found in file " << inputFileName << endl;
    return ;
  }

  // this folder should contain one folder for each loop.
  string loopFolderName = "loop-" + toString( loop );
  TDirectoryFile * loopFolder = (TDirectoryFile *) pedeProcessorFolder->Get( loopFolderName.c_str() );
  
  if ( loopFolder == 0 ) {
    cerr << "No " << loopFolderName << " found in file " << inputFileName << endl;
    return ;
  }

  // guess the number of sensors from the number of subfolder in the loopfolder
  size_t nDetector = loopFolder->GetListOfKeys()->GetSize();
  cout << "This file contains " << nDetector << " detectors" << endl;

  // prepare arrays to store the mean and the rms of the noise distribution
  if ( noiseMean == NULL ) {
    delete [] noiseMean;
    noiseMean = NULL;
  }
  if ( noiseRMS == NULL ) {
    delete [] noiseRMS;
    noiseRMS = NULL;
  }
  if ( channel == NULL ) {
    delete [] channel;
    channel = NULL;
  }

  noiseMean = new double[ nDetector * kNChan ];
  noiseRMS  = new double[ nDetector * kNChan ];
  channel   = new double[ kNChan ];

  string canvasName = "comparison";
  string canvasTitle = "Noise comparison";

  TCanvas * comparisonCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  comparisonCanvas->Divide(1,2);
  
  TPad * topPad = (TPad*) comparisonCanvas->cd(1);
  topPad->Divide( nDetector );
  
  TPad * middlePad = (TPad *) comparisonCanvas->cd(2);
  middlePad->Divide( kNChan );


  // for each detector we have to get the noise map and to prepare 4
  // separe histos and maps
  for ( unsigned int iDetector = 0; iDetector < nDetector; iDetector++ ) {

    // get the noise map.
    string noiseMapName = "detector-" + toString( iDetector ) ;
    noiseMapName += "/NoiseMap-d" + toString( iDetector )  ;
    noiseMapName += "-l" + toString( loop ) ;
 
    TH2D * noiseMap = ( TH2D* ) loopFolder->Get( noiseMapName.c_str() ); 
    

    // create a folder in the output file
    TDirectory * subfolder = outputFile->mkdir( string( "detector_" + toString( iDetector ) ).c_str(),
						string( "detector_" + toString( iDetector ) ).c_str()
						);
    subfolder->cd();

    
    string canvasName = "det" + toString( iDetector );
    string canvasTitle = "Detector " + toString( iDetector );
    
    TCanvas * canvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
    canvas->Divide( kNChan, 2 );

    // ok now start the loop on channels
    for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) { 
	
      if ( iDetector == 0 ) channel[iChan] = iChan - 0.5;

      string tempName = "NoiseMap_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      string tempTitle = "NoiseMap Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ;

      TH2D * noiseMapCh = new TH2D ( tempName.c_str() , tempTitle.c_str(), 
				     kXPixel / kNChan , -0.5 + xLimit[ iChan ] , -0.5 + xLimit[ iChan + 1 ],
				     kYPixel, -0.5, -0.5 + kYPixel );
      noiseMapCh->SetXTitle("X [pixel]");
      noiseMapCh->SetYTitle("Y [pixel]");
      noiseMapCh->SetZTitle("Noise [ADC]");
      noiseMapCh->SetStats( false );
      outputHistoList->Add( noiseMapCh ) ;

      tempName = "NoiseDist_d" + toString( iDetector ) + "_l" + toString( loop )	+ "_ch" + toString( iChan ) ;
      
      tempTitle = "NoiseDist Det. " + toString( iDetector ) + " - Ch. " + toString( iChan ) ; 

      TH1D * noiseDistCh = new TH1D( tempName.c_str(), tempTitle.c_str(), 50, 0., 10. );
      noiseDistCh->SetXTitle("Noise [ADC]");
      noiseDistCh->SetLineColor( kColor[iDetector]  );
      noiseDistCh->SetLineStyle( iChan + 2 );
      noiseDistCh->SetLineWidth( 2 );
      outputHistoList->Add( noiseDistCh );

      // let's start looping on pixels now
      for ( size_t yPixel = 1 ; yPixel <= kYPixel ; ++yPixel ) {
	for ( size_t xPixel = xLimit[ iChan ] + 1; xPixel <= xLimit[ iChan +1 ] ; ++xPixel ) {
	  double noise = noiseMap->GetBinContent( xPixel , yPixel );
	  noiseMapCh->Fill( xPixel - 1 , yPixel - 1, noise );
	  noiseDistCh->Fill( noise );
	  
	}
      }

      canvas->cd( iChan + 1 ) ;
      noiseMapCh->Draw("colz");
      canvas->cd( iChan + kNChan + 1  );
      noiseDistCh->Draw();
      
      topPad->cd( iDetector + 1 );
      if ( iChan == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }

      middlePad->cd( iChan + 1 );
      if ( iDetector == 0 ) {
	noiseDistCh->Draw();
      } else {
	noiseDistCh->Draw("same");
      }


      noiseMean[ kNChan * iDetector + iChan ] = noiseDistCh->GetMean();
      noiseRMS[ kNChan * iDetector  + iChan ] = noiseDistCh->GetRMS();
    }
    canvas->Write();

  }

  canvasName = "summary";
  canvasTitle = "Noise summary";

  TCanvas * summaryCanvas = new TCanvas( canvasName.c_str(), canvasTitle.c_str(), 1000, 500 );
  summaryCanvas->SetGridx(1);
  TLegend * legend = new TLegend(0.5, 4.8, 1.5, 4.3,"","br");;
  

  for ( size_t iDetector = 0 ; iDetector < nDetector ; ++iDetector ) {
    
    TGraphErrors * gr = new TGraphErrors( kNChan, channel, &noiseMean[ iDetector * kNChan ], NULL, &noiseRMS[ iDetector * kNChan ] );
    gr->SetName( string( "NoisePerChannel_d" + toString( iDetector )).c_str());
    gr->SetTitle(string("Detector " + toString( iDetector )).c_str());
    gr->GetXaxis()->SetTitle("Channel #");
    gr->GetYaxis()->SetTitle("Noise [ADC]");
    gr->GetXaxis()->SetNdivisions( 5 );
    gr->GetXaxis()->SetLabelSize( 0 );
    gr->SetMarkerStyle( iDetector + 1 );
    gr->SetMarkerColor( kColor[iDetector] );
    gr->SetLineColor( kColor[iDetector] );
    gr->SetLineWidth( 2 );

    
    legend->AddEntry( gr, string("Detector " + toString( iDetector )).c_str(), "LP");

    if ( iDetector == 0 ) {
      gr->Draw("ALP");
    } else {
      gr->Draw("LP");
    }
    

  }

  
  
  legend->Draw();

  for ( size_t iChan = 0 ; iChan < kNChan ; ++iChan ) {
    
    TPaveLabel * label = new TPaveLabel( iChan - 0.75 , 3.2 , iChan -0.25 , 3, string("Ch " + toString( iChan ) ).c_str());
    label->Draw();
  }


  summaryCanvas->Write();
  comparisonCanvas->Write();

  outputHistoList->Write();

  

 
} 
Example #25
0
// ----------------------------------
//======= Doing real fit and producing Fit/RMS resolution histograms =======
void projectAndFit(TH2F* th2, TH1F*& hFit, TH1F*& hRMS,int tailSign,string name, bool variableBinning,bool wait){
  TCanvas* canv = new TCanvas("tmp","tmp",500,500); canv->cd();
  //static double sigma;


  int xBins = th2->GetNbinsX();
  //cout << "xBins: " << xBins << endl; 



  //for resolution vs pt
  if(variableBinning){
    hFit = new TH1F("tmp","tmp",xBins,th2->GetXaxis()->GetXbins()->GetArray());
    hRMS = new TH1F("tmp2","tmp2",xBins,th2->GetXaxis()->GetXbins()->GetArray());
  }else{
    //for resolution vs eta
    hFit = new TH1F("tmp","tmp",xBins,th2->GetBinLowEdge(1),th2->GetBinLowEdge(xBins+1));
    hRMS = new TH1F("tmp2","tmp2",xBins,th2->GetBinLowEdge(1),th2->GetBinLowEdge(xBins+1));
  }


  for(int i=1;i<=xBins; i++){
    cout << "i,xLeft: " << i << " , " << th2->GetBinLowEdge(i) << endl;
    TH1D* proj = th2->ProjectionY("prova",i,i+1);
    if(proj->GetEntries()<20){
      //cout << "N entries < 20. Should I continue? " << endl; Wait();
      hRMS->SetBinContent(i,0);
      hRMS->SetBinError(i,0);
      hFit->SetBinContent(i,0);
      hFit->SetBinError(i,0);
      delete proj;
      continue;
    }
    double rms = proj->GetRMS();

    double tmpMean;
    double tmpSigma;


    // quick fit with standard gauss
    double leftBound,rightBound;
    if(tailSign<0){
      leftBound = -1.5*rms;
      rightBound = +1.0*rms;
      cout << "negative tailSign gives: " << leftBound << " , " << rightBound << endl;
    } else if(tailSign>0){
      leftBound = -1.0*rms;
      rightBound = +1.5*rms;
      cout << "positive tailSign gives: " << leftBound << " , " << rightBound << endl;
    }else{
      leftBound = -1.0*rms;
      rightBound = +1.0*rms;
      cout << "null tailSign gives: " << leftBound << " , " << rightBound << endl;
    }
    
    TF1* f1 = new TF1("f1","gaus",leftBound,rightBound);
    TFitResultPtr r = proj->Fit(f1,"S M R L");   
    proj->Draw(); gPad->Update(); 
    stringstream outputName;
    if(i<10)      outputName << name << "_raw_bin_" << "0" << i ; else      outputName << name << "_bin" << i ;
    //printCanvas(canv,outputName.str(),1);    
    
    if(wait) Wait();
    tmpMean = r->Parameter(1);
    tmpSigma = r->Parameter(2);    

    double xMin,xMax;
    xMin = tmpMean - tmpSigma*5.;
    xMax = tmpMean + tmpSigma*5.;



    RooRealVar x("x","x",xMin,xMax) ;

    double meanRangeMin;
    double meanRangeMax;
    if(tmpMean<0){
      meanRangeMin = 1.6*tmpMean;
      meanRangeMax = 0.1*tmpMean;
    }else{
      meanRangeMin = 0.1*tmpMean;
      meanRangeMax = 1.6*tmpMean;
    }

    RooRealVar meanRoo("mean","mean of gaussian",tmpMean,meanRangeMin,meanRangeMax) ;
    RooRealVar sigmaRoo("sigma","width of gaussian",tmpSigma,tmpSigma*0.5,tmpSigma*1.5); 

    RooRealVar a("a","a",3.,2.,10.);
    RooRealVar aDx("aDx","aDx",3.,2.,10.);
    RooRealVar n("n","n",5.,0.,10.);   
    RooRealVar nDx("nDx","nDx",5.,0.,10.);   

    if(tailSign!=0){
      if(tailSign<0){
	a.setVal(1); a.setMin(0.5); a.setMax(3.);
      }else{
	aDx.setVal(1); aDx.setMin(0.5); aDx.setMax(3.);
      }
    }


    RooDoubleCB func1("cb","cb PDF",x,meanRoo,sigmaRoo,a,n,aDx,nDx) ;
    RooPlot* xframe = x.frame(Title("Gaussian p.d.f.")) ;
    
    RooDataHist  dh("dh","dh",x,Import(*proj));
    func1.fitTo(dh);
    dh.plotOn(xframe);
    func1.plotOn(xframe) ;
    //

    xframe->Draw(); gPad->Update();
    stringstream outputName2; 
    if(i<10)      outputName2 << name << "_bin" << "0" << i ; else      outputName2 << name << "_bin" << i ;
    //printCanvas(canv,outputName2.str(),1);    
    if(wait) Wait();
    
    tmpMean = meanRoo.getVal();
    tmpSigma = sigmaRoo.getVal();
 
    double sigma;
    double sigmaErr;
    sigma= sigmaRoo.getVal();
    sigmaErr = sigmaRoo.getError();     

    /*
    proj->SetAxisRange(-5*sigma,5*sigma);
    rms = proj->GetRMS();
    double rmsErr = proj->GetRMSError();
    hFit->SetBinContent(i,sigma);
    hFit->SetBinError(i,sigmaErr);
    hRMS->SetBinContent(i,rms);
    hRMS->SetBinError(i,rmsErr);
    delete proj;
    */


    // ---- NEW IMPLEMENTATION
    double fullIntegral = proj->Integral(0,proj->GetNbinsX()+1);
    //double fullIntegral = proj->Integral();
    //double fullAverage = proj->GetMean();
    double step = proj->GetBinWidth(1);;
    int peakBin = proj->FindBin(tmpMean);

    //double range2nd(0.954);
    double range2nd(0.90);


    //
    bool found68(false);
    double range68(0), uncert68(0.);
    double range95(0), uncert95(0.);
    for(int j=0; j<proj->GetNbinsX()/2 ; j++){
      if((peakBin-j)<1 || (peakBin+j) > proj->GetNbinsX()) break;
      double fraction = proj->Integral(peakBin-j,peakBin+j)/fullIntegral;
      if(fraction>0.682 && !found68){ //2sigma range
	found68=true;
	range68 = step*(2*j+1)*0.5;
	double averageBinContent = (proj->GetBinContent(peakBin-j) + proj->GetBinContent(peakBin+j))/2.0 ; 
	uncert68 = sqrt(0.682*(1-0.682)/fullIntegral)/(averageBinContent/step/fullIntegral);
      }
      if(fraction>range2nd){ //3sigma range
	range95 = step*(2*j+1)*0.5;
	double averageBinContent = (proj->GetBinContent(peakBin-j) + proj->GetBinContent(peakBin+j))/2.0 ; 
	uncert95 = sqrt(range2nd*(1-range2nd)/fullIntegral)/(averageBinContent/step/fullIntegral);
	break;
      }
    }


    // --- OLD IMPLEMENTATION
    /*
    double fullIntegral = proj->Integral();
    double step = sigma/20.;
    //
    double range68(0);
    for(int j=2; j<20000;j++){
      xMin = tmpMean - step*j; 
      xMax = tmpMean + step*j;  
      proj->SetAxisRange(xMin,xMax);
      double fraction = proj->Integral()/fullIntegral;
      if(fraction>0.682){ //2sigma range
	range68 = step*j;
	break;
      }
    }
    //
    double range95(0);
    for(int j=2; j<20000;j++){
      xMin = tmpMean - step*j; 
      xMax = tmpMean + step*j;  
      proj->SetAxisRange(xMin,xMax);
      double fraction = proj->Integral()/fullIntegral;
      if(fraction>range2nd){ //2sigma range
	range95 = step*j;
	break;
      }
    }
    uncert68 = step;
    uncert95 = step;
    */




    //--------
    //hFit->SetBinContent(i,sigma);
    //hFit->SetBinError(i,sigmaErr);
    hFit->SetBinContent(i,range68);
    hFit->SetBinError(i,uncert68);
    hRMS->SetBinContent(i,range95);
    hRMS->SetBinError(i,uncert95);
    delete proj;


    
  }
  hFit->SetDirectory(gROOT);
  hRMS->SetDirectory(gROOT);
  delete canv;
  //hFit->Draw();gPad->Update(); Wait();
}