Пример #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));

   }
}
Пример #2
0
TGraphErrors* plot_point(
			     const TString infile,
			     double R,
			     double R_sig
			     )
{

  TTree *TData = new TTree();
  TData->ReadFile(infile, "t/D:x:y:z:B1:B1Range:B2:B2Range:B3:B3Range:V:T1:T2:T3:T4:T5:T6:T7:T8");

  TH1D *h = new TH1D("h", "", 10000, 0, 10000);
  TH1D *h2 = new TH1D("h2", "", 10000, 0, 10000);
  TData->Draw("TMath::Abs(B2)>>h", "", "goff");
  TData->Draw("TMath::Abs(B3)>>h2", "", "goff");

  vector<double> B_ext, B_in, Bratio, u, u_err, B_err;

  B_in.push_back(h2->GetMean(1));
  B_ext.push_back(h->GetMean(1));

  Bratio.push_back(B_in[0] / B_ext[0]);
  u.push_back( (Bratio[0]*(R**2) + Bratio[0] - 2 - 2*sqrt((Bratio[0]**2)*(R**2) - Bratio[0]*(R**2) - Bratio[0] + 1 ) ) / (Bratio[0]*(R**2) - Bratio[0]) );

  B_err.push_back( 0.00 );
  u_err.push_back( 0.00 );

  TGraphErrors *g_uvB = new TGraphErrors(u.size(), &B_ext[0], &u[0], &B_err[0], &u_err[0]);

  h->Delete();
  h2->Delete();

  return g_uvB;

}
Пример #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();
      }
   }
}
Пример #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 ;
}
Пример #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;
}
Пример #7
0
void GetRandomTest(){
	double k0=1.39;
	double k1 = 0.425;
	double theta0 = 3.41;
	double theta1 = 1.30;
	int iNpart=2;
	double k_=k0+k1*(iNpart-2);
        double theta_=theta0+theta1*TMath::Log(iNpart-1);
	TF1 *f = new TF1("f","TMath::GammaDist(x,[0],0,[1])",0,200);
	f->SetParameters(k1,theta_);
	cout<<"Value at 0 = "<<f->Eval(0)<<endl;
	cout<<"Value at 1e-11 = "<<f->Eval(1e-11)<<endl;
	cout<<"Integral 1= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	f->SetRange(1e-12,200);
	cout<<"Integral 2= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	cout<<"fXmin = "<<f->GetXmin()<<"\tfXmax = "<<f->GetXmax()<<"\tfNpx = "<<f->GetNpx()<<endl;
	f->SetNpx(1e5);
	TCanvas *c1 = new TCanvas();
	c1->SetLogy();
	cout<<"f mean = "<<f->Mean(0,200)<<endl;
	cout<<"math mean = "<<f->GetParameter(0)*f->GetParameter(1)<<endl;
	TH1D* h = new TH1D("h","h",1000,0,200);
	for(int i=0;i<1e6;i++){
		double para = f->GetRandom();
		h->Fill(para);
	}
	h->Scale(1.0/h->Integral()*1000/200);
	h->GetYaxis()->SetRangeUser(1e-10,1);
	h->SetMarkerStyle(24);
	h->SetMarkerColor(4);
	h->SetMarkerSize(1.1);
	TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
        leg->SetFillColor(0);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0);
        leg->SetTextFont(42);
        leg->SetTextSize(0.03);
        leg->AddEntry(f,"function","lp");
        leg->AddEntry(h,"filled histogram","lp");
	h->Draw("P");
	f->Draw("same");
        leg->Draw("same");
	cout<<"h mean = "<<h->GetMean(1)<<endl;
	c1->Print("TestGetRandom.png");
	}
Пример #8
0
inputValues getInputValues(TString fileName, double pw, string cutString) {

    TFile * file = new TFile(fileName, "READ");
    TTree * tree = (TTree*)file->Get("Channel_1");
    tree->Draw("(-1)*Min>>hist(300, 0, 30)");
    TH1D * hist = (TH1D*)gDirectory->Get("hist");
    
    inputValues inVal;
    
    inVal.pw = pw;
    inVal.n = hist->GetEntries();
    inVal.v = pow(hist->GetStdDev(), 2);
    inVal.e = hist->GetMean(); 
    inVal.a = tree->Draw("Min", (TString)cutString);
    inVal.h = hist;
    
    return inVal;
}
Пример #9
0
scalePair energyCorrectionDiff(TCut centCut1, float lowPt, float highPt, float lowEta, float highEta,TCut addCut) { 
   
   TString fname1 = "forest/barrelHiForestPhoton_MCphoton50_51k.root";
   if ( lowPt > 90 ) 
      fname1 = "forest/barrelHiForestPhoton_MCphoton80_28k.root";
   TFile *f1  =new TFile(fname1.Data());
   TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
   photon1->AddFriend("yEvt=yongsunHiEvt"    ,fname1.Data());
   photon1->AddFriend("ySkim=yongsunSkimTree"   ,fname1.Data());
   photon1->AddFriend("yHlt=yongsunHltTree"     ,fname1.Data());
   
   TCut collisionCut = "ySkim.pcollisionEventSelection==1";
   
   TCut hoeCut = "hadronicOverEm<0.2";
   TCut isoCut = "cc4 + cr4 + ct4j20 < 5 && sigmaIetaIeta<0.011";
   TCut ptCut  = Form("genMatchedPt>%.f && genMatchedPt <%.f",lowPt, highPt);
   TCut etaCut = Form("abs(eta)>%f && abs(eta)<%f",lowEta,highEta);
      
   TCut finalCut1 = genMatchCut1 && collisionCut && centCut1 && hoeCut && isoCut && ptCut && etaCut && addCut ; 
   TString variable1 = "pt/genMatchedPt";
   
   TH1D* hScale = new TH1D("hScale","",100,.5,1.5);
   TH1D* hdpt = new TH1D("hdpt","",100,-20,20);
   photon1->Draw(Form("%s>>%s",variable1.Data(),hScale->GetName()), finalCut1);
   photon1->Draw(Form("pt-genMatchedPt>>%s",hdpt->GetName()),       finalCut1);
   cout << "cut = " << finalCut1.GetTitle() <<endl;
   hScale->Draw();
   hdpt->Draw();
   TF1* ff =  cleverGaus(hScale);
   
   scalePair ret;
   double *ps = ff->GetParameters();
   ret.val = ps[1];
   ret.err = ff->GetParError(1);
   // resErr = ff->GetParError(2);
   ret.res  = ps[2];
   ret.resErr = ff->GetParError(2);  
   ret.absVal = hdpt->GetMean();
   cout <<"scale = " << ret.val << " +-" << ret.err << endl;
   return ret;
}
Пример #10
0
void getMeanPtBins( Double_t * binArr, TF1* func) {
  Double_t atlas_Bin[nAtlasBin+1] = {8, 9.5, 11.5, 14, 20, 30};
  
  TH1D* firhist = (TH1D*)func->GetHistogram();
  for ( int i=1 ; i<= nAtlasBin ; i++) {
    float lowPtCut = atlas_Bin[i-1];
    float highPtCut = atlas_Bin[i];
    
    TH1D* tempHist = (TH1D*)firhist->Clone("tempHist");
    for ( int xbin = 1 ;xbin<=tempHist->GetNbinsX() ; xbin++) {
      if ( (tempHist->GetBinCenter(xbin) > highPtCut) || (tempHist->GetBinCenter(xbin) < lowPtCut) \
	   )
      tempHist->SetBinContent(xbin,0);
    }
    float meanPt = tempHist->GetMean();
    cout << " meanPt = " << meanPt << endl;
    binArr[i-1] = meanPt;
    delete tempHist;
    
  }
  
}
Пример #11
0
inputValues getInputValues(TString fileName, double pw, bool cm, string cutString) {

    TFile * file = new TFile(fileName, "READ");
    TTree * tree = (TTree*)file->Get("Channel_8");
    tree->Draw("Charge>>hist"); 
    TH1D * hist = (TH1D*)gDirectory->Get("hist");
    
    inputValues inVal;
    
    inVal.pw = pw;
    inVal.cm = cm;
    inVal.n  = hist->GetEntries();
    inVal.v  = pow(hist->GetStdDev(), 2);
    inVal.e  = -hist->GetMean(); // Flip sign
    inVal.a  = tree->Draw("Charge", (TString)cutString);
    inVal.h  = hist;
    
    // Debugging
    cout << inVal.pw << " " << inVal.e  << " " << (float)inVal.a/inVal.n << " " << inVal.cm << endl;

    return inVal;
}
void getMeanPtBins( Double_t * binArr, TF1* func) {
  Double_t lhcb_Bin[nLHCbBin+1] = {0,1,2,3,4,5,6,7,14};
  
  TH1D* firhist = (TH1D*)func->GetHistogram();
  for ( int i=1 ; i<= nLHCbBin ; i++) {
    float lowPtCut = lhcb_Bin[i-1];
    float highPtCut = lhcb_Bin[i];

    TH1D* tempHist = (TH1D*)firhist->Clone("tempHist");
    for ( int xbin = 1 ;xbin<=tempHist->GetNbinsX() ; xbin++) {
      if ( (tempHist->GetBinCenter(xbin) > highPtCut) || (tempHist->GetBinCenter(xbin) < lowPtCut) )
	tempHist->SetBinContent(xbin,0);
    }
    float meanPt = tempHist->GetMean();
    if ( meanPt <0.1 )   // fit is not applied
      meanPt = (lowPtCut+highPtCut)/2.;

    cout << " meanPt = " << meanPt << endl;
    binArr[i-1] = meanPt;
    delete tempHist;

  }

}
void TestEnergy() {
  TFile *file = TFile::Open("PPCollisionUps1sMilNoTune.root");
  TFile *file2 = TFile::Open("PPCollisionMilNoTune.root");
  TNtuple* PPTupleUps = (TNtuple*)file->Get("PPTuple");
  TNtuple* PPTupleND = (TNtuple*)file2->Get("PPTuple");
  TH1D* NCharUps = new TH1D("NCharUps", "Sum of Energy at mid rapdity", 30000, 0, 300);
  PPTupleUps->Draw("(ETmid-mu1pT-mu2pT)>>NCharUps", "NChar>2 && abs(deta1) < 1.93 && abs(deta2) < 1.93  && mu1pT > 4 && mu2pT > 4");
//  NCharUps->Scale(3.35e-6);
  double sum, percent = 0, centAr[21];
  int c, centa[21], i;
  sum = 0;
  centAr[0] = 180;
  centAr[20] = 0;
  c = 1;
	//Find Activity Ranges
  double min = 0, average[20], bins;
  i = 0;
  //Activity Range Calculations for Track Count
  TH1D* Tracks = new TH1D("Tracks", "Number of Tracks", 10000, 0, 300);
  PPTupleND->Draw("ETmid>>Tracks", "NChar > 0");
  double MinBiasEvents;
  MinBiasEvents = Tracks->GetEntries();
  NCharUps->Draw();
  Tracks->Draw();
  Tracks->Scale(1./Tracks->GetEntries());
  int TrackCent[21];
  percent = .02;
  TrackCent[0] = 300;
  TrackCent[20] = 0;
  c = 1;
  double Ranges[12];
  int counter = 1;
  Ranges[0] = 0;
	//Loop To Get Activity Range Values
  for (i=0; percent <= .02; percent += .02) {
        sum = 0;
  	cout << c << "		";
        for(i=0; sum < percent && i != 10000; i++) {
                sum += Tracks->GetBinContent(10000-i); }
       	 cout << 100*percent - 2 << "-" << 100*percent << "%" << "      " << MinBiasEvents*sum  << "      " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values
	Ranges[counter] = sum;
	counter++;		
        TrackCent[c] = Tracks->GetBinCenter(10000-i);
        c++;}
  percent = .08;
  for (i=0; percent <= .08; percent += .02) {
        sum = 0;
        cout << c << "		";
        for(i=0; sum < percent || percent == 1; i++) {
                sum += Tracks->GetBinContent(10000-i); }
                         cout << 100*percent - 2 << "-" << 100*percent << "%" << "      " << MinBiasEvents*sum  << "      " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values
	Ranges[counter] = sum;
        counter++;
        TrackCent[c] = Tracks->GetBinCenter(10000-i);
        c++;}
  percent = .20;
  for (i=0; percent <= .20; percent += .04) {
        sum = 0;
        cout << c << "		";
        for(i=0; sum < percent || percent == 1; i++) {
                sum += Tracks->GetBinContent(10000-i); }
                         cout << 100*percent - 4 << "-" << 100*percent << "%" << "      " << MinBiasEvents*sum  << "      " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values
	Ranges[counter] = sum;
        counter++;
        TrackCent[c] = Tracks->GetBinCenter(10000-i);
        c++;}
	percent = .30;
//  for (i=0; percent <= .30; percent += .05) {
  //      sum = 0;
//	cout << c << "\n";
//        for(i=0; sum < percent || percent == 1; i++) {
 //               sum += Tracks->GetBinContent(10000-i); }
  //                       cout << 100*percent - 5 << "-" << 100*percent << "%" << "      " << sum  << "      " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values
 //       TrackCent[c] = Tracks->GetBinCenter(10000-i) + .5;
   //     c++; }
//	percent = .40;
  for (i=0; percent <= 1; percent += .10) {
        sum = 0;
	cout << c << "		";
        for(i=0; sum <= percent && i != 10000; i++) {
                sum += Tracks->GetBinContent(10000-i); }
                         cout << 100*percent - 10 << "-" << 100*percent << "%" << "      " << MinBiasEvents*sum  << "      " << i << " " << Tracks->GetBinCenter(10000-i) << "\n"; // Use to check Activity Range Values
	Ranges[counter] = sum;
        counter++;
        TrackCent[c] = Tracks->GetBinCenter(10000-i);
        c++; }
  cout << "\n" << "Activity Range Values from Array" << "\n";
  for(c = 0; c < 11; c++) {
    	cout << c << ")   "  << TrackCent[c] << "\n"; }
  min = 0;
  double TrackAverage[20];

  cout << "\n" << NCharUps->GetBinCenter(30000) << "\n";

  i = 0;
  double TotalUps = 0;
  //cout << "\n" << "Activity Bin Averages" << "\n";
	//Loop To Get Average In Each Activity Region
  for(c = 0; NCharUps->GetBinCenter(30000-i) > TrackCent[c+1] && NCharUps->GetBinCenter(30000-i) <= TrackCent[c]; c++) {
        sum = 0;
        bins = 0;
        for(i = min; (NCharUps->GetBinCenter(30000-i) > TrackCent[c+1] && NCharUps->GetBinCenter(30000-i) <= TrackCent[c]) && i != 30000; i++) {
                sum += NCharUps->GetBinContent(30000-i)*(NCharUps->GetBinCenter(30000-i));
                bins += NCharUps->GetBinContent(30000-i); }
        TrackAverage[c] = sum/bins;
	TotalUps += bins;
	cout << "Point " << c << ": " << bins << " +- " << sqrt(bins) << "   Upsilons" << "\n";
        min = i; }
	cout << NCharUps->GetBinCenter(100) << "\n";
       	// cout << 10*c << "-" << 10*(c+1) << "%" << "     " << TrackAverage[c] << "\n";  }
  cout << "Total number of Upsilons: " << TotalUps << "\n";
  cout << "\n" << "Corrected X/Y Track values" << "\n";
  double TrackYpoints[20];
  for(i = 0; i < 12; i++) {
	cout << (Ranges[i+1] - Ranges[i])*MinBiasEvents << "\n"; }

	//Take Average Values and Divide by ND Average to Get X points
 // for(c = 0; c < 4; c++) {
//	TrackAverage[c] = TrackAverage[c]/Tracks->GetMean();
//	TrackYpoints[c] = (50./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 );
//	cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] <<  ")" <<  "\n"; }
  //for(c = 4; c < 7; c++) {
    //    TrackAverage[c] = TrackAverage[c]/Tracks->GetMean();
  //      TrackYpoints[c] = (25./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 );
    //    cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] <<  ")" <<  "\n"; }
//  for(c = 7; c < 10; c++) {
 //       TrackAverage[c] = TrackAverage[c]/Tracks->GetMean();
   //     TrackYpoints[c] = (20./NCharUps->Integral(0,25000))*NCharUps->Integral(TrackCent[c+1], TrackCent[c]-1 );
//	cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] <<  ")" <<  "\n"; }


TrackAverage[0] = TrackAverage[0]/Tracks->GetMean();
        TrackYpoints[0] = (50./NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[1], 100*(TrackCent[0]-1) );
	cout << "(" <<TrackAverage[0] << "," << TrackYpoints[0] <<  ")" <<  "\n";

TrackAverage[1] = TrackAverage[1]/Tracks->GetMean();
        TrackYpoints[1] = (16.67/NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[2], 100*TrackCent[1]-100 );
	cout << "(" <<TrackAverage[1] << "," << TrackYpoints[1] <<  ")" <<  "\n";

TrackAverage[2] = TrackAverage[2]/Tracks->GetMean();
        TrackYpoints[2] = (8.33/NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[3], 100*TrackCent[2]-100 );
	cout << "(" <<TrackAverage[2] << "," << TrackYpoints[2] <<  ")" <<  "\n";

 for(c = 3; c < 14; c++) {
        TrackAverage[c] = TrackAverage[c]/Tracks->GetMean();
        TrackYpoints[c] = (10./NCharUps->Integral(0,30000))*NCharUps->Integral(100*TrackCent[c+1], 100*TrackCent[c]-100 );
        cout << "(" <<TrackAverage[c] << "," << TrackYpoints[c] <<  ")" <<  "\n"; } 
  TF1* line = new TF1("line", "x", 0, 4.5);
  TF1* line2 = new TF1("line2", "1.8*x", 0, 4.5);
  line2->SetLineColor(kWhite);
  sum = 0;
  double scaledSumE = 0, scaleSumT = 0;
  scaleSumT = NCharUps->Integral(0,30000);
  TCanvas* can2 = new TCanvas("can2", "Centrality");
  can2->cd();
  line->SetLineColor(1);
  line2->GetYaxis()->SetTitle("#varUpsilon(1S)/<#varUpsilon(1S)>");
  line2->GetXaxis()->SetTitle("#Sigma E_{T}^{|#eta| < 2.4}/<#Sigma E_{E}^{|#eta| < 2.4}>");
  line2->SetTitle("#varUpsilon(1S) Cross Section vs Track Multiplicity");
  line2->Draw();
  line->SetLineStyle(3);
  line->Draw("same");
   for(c = 0; c < 18; c++) { cout << TrackCent[c] << "           Bin Average: " << 10.32*TrackAverage[c] <<  "\n";}
  double Test, Testaverage, Testsum, Testbin, count = 0, TestY = 0;
  Test = NCharUps->Integral(38,100);
  for(i = 38; i < 100; i++) {
	Testsum += NCharUps->GetBinContent(i)*NCharUps->GetBinCenter(i);
	Testbin += NCharUps->GetBinContent(i); }
  Testaverage = Testsum/Testbin;
  TestY = (10./NCharUps->Integral(0,30000))*NCharUps->Integral(38, 100);
  cout << "\n" << "\n" << TestY << "\n" << "\n";

  TH1D* modelT = new TH1D("modelT", "Pythia model", 5000, 0, 5);
  //Fill Histogram with points from Model
  for(i = 0; i < 20; i++) {
	//Track Values
	modelT->SetBinContent(1000*TrackAverage[i], TrackYpoints[i]);
        modelT->SetBinError(1000*TrackAverage[i], .01); }
  modelT->SetMarkerStyle(20);
  modelT->SetMarkerColor(kBlue);
  modelT->SetLineColor(kBlue);
  modelT->Draw("sameE");
  //Histogram for STAR Data Points
  TH1D* data = new TH1D("data", "CMS Data", 4000, 0, 4);
  data->SetMarkerStyle(20);
  data->SetMarkerColor(kRed);
  data->SetLineColor(kRed);
  data->SetBinContent(3262, 6.67);
  data->SetBinError(3262, .26);
  data->SetBinContent(2010, 3.12);
  data->SetBinError(2010, .15);
  data->SetBinContent(1240, 1.4);
  data->SetBinError(1240, .06);
  data->SetBinContent(630, .240);
  data->SetBinError(630, .01);
  data->Draw("sameE");
  TLegend* leg = new TLegend(.1,.74,.30,.9);
  leg->SetHeader("For |#eta| < 2.4");
  leg->AddEntry(modelT->DrawCopy("same"), "Pythia 8 Model", "l");
  leg->AddEntry(data->DrawCopy("same"), "CMS data", "l");
  leg->Draw("same");
  return; }
Пример #14
0
//void electron_master(const char* file_list="checkP10ic/electrons.list",const char* output="checkP10ic/electroncalib.root", const char* dbDate="2009-04-10 00:11:00", const char* geantfile="geant_func.root", const char* gfname="checkP10ic/mip.gains", const char* ngname="checkP10ic/electron.gains", const char* rgname="matrel.gains",const char* ffname="checkP10ic/electron.fits"){
void electron_master(const char* file_list="checkP11id/electrons.list",const char* output="checkP11id/electroncalib2.root", const char* dbDate="2009-04-10 00:11:00", const char* gfname="checkP11id/mip.gains", const char* ngname="checkP11id/electron2.gains",const char* ffname="checkP11id/electron2.fits"){
  //**********************************************//
  //Load Libraries                                //
  //**********************************************//
  gROOT->Macro("LoadLogger.C");
  gROOT->Macro("loadMuDst.C");
  gSystem->Load("StTpcDb");
  gSystem->Load("StDaqLib");
  gSystem->Load("StDetectorDbMaker");
  gSystem->Load("St_db_Maker");
  gSystem->Load("StDbUtilities");
  gSystem->Load("StEmcRawMaker");
  gSystem->Load("StMcEvent");
  gSystem->Load("StMcEventMaker");//***
  gSystem->Load("StEmcSimulatorMaker");//***
  gSystem->Load("StEmcADCtoEMaker");
  gSystem->Load("StEpcMaker");
  gSystem->Load("StDbBroker");
  gSystem->Load("StEEmcUtil");
  gSystem->Load("StAssociationMaker");
  gSystem->Load("StEmcTriggerMaker");
  gSystem->Load("StTriggerUtilities");
  gSystem->Load("StEmcOfflineCalibrationMaker");

  cout<<"input filelist: "<<file_list<<endl;
  cout<<"output:          "<<output<<endl;
  cout<<"db Date:        "<<dbDate<<endl;


  //**********************************************//
  //Initialize Stuff                              //
  //**********************************************//

  CalibrationHelperFunctions *helper = new CalibrationHelperFunctions();
	
  StBemcTablesWriter *bemctables = new StBemcTablesWriter();
  bemctables->loadTables(dbDate,"sim");
  StEmcDecoder* decoder = bemctables->getDecoder();


  //chain all input files together
  char file[300];
  TChain* tree = new TChain("skimTree");
  ifstream filelist(file_list);
  while(1){
    filelist >> file;
    if(!filelist.good()) break;
    cout<<file<<endl;
    tree->Add(file);
  }

  const int ntowers = 4800;
  const int nrings = 40;
  const int ncrates = 30;
  float gains[ntowers];
  int status[ntowers];
  float peaks[ntowers];
  float peakerr[ntowers];
  float gainerr[ntowers];

  ifstream gainfile(gfname);
  while(1){
    int id,stat;
    float peak,err,gain,eta,theta;
    gainfile >> id >> peak >> err >> stat;
    if(!gainfile.good())break;
    eta = helper->getEta(id);
    theta = helper->getTheta(id);
    gain = 0.264*(1+0.056*eta*eta)/(sin(theta)*peak);
    peaks[id-1] = peak;
    gains[id-1] = gain;
    if(status[id-1] != 1 || stat != 1) status[id-1] = stat;
    peakerr[id-1] = err;
    //cout<<id<<" "<<gain;
  }


  TFile* geant_file = new TFile("geant_fits.root","READ");
  TF1* geant_fits[20];
  for(int i = 0; i < 20; i++){
    TString fname = "fit_";
    fname += i;
    geant_fits[i] = (TF1*)geant_file->Get(fname);
  }


  TFile outfile(output,"RECREATE");

  TH1 *crate_histo[ncrates];
  TF1 *crate_fit[ncrates];
  TH1 *electron_histo[ntowers];
  TF1 *fit[ntowers];
  TH1 *prs_histo[ntowers];
  TH1 *ring_histo[nrings];
  TH1 *ring2_histo[nrings/2];
  TF1 *ring2fit[nrings/2];

  TH1 *etacrate_histo[ncrates*20];
  TH1 *etacrate_histo_p[ncrates*20];
  TH1 *etacrate_histo_n[ncrates*20];

  TH1 *bghisto[21];
  TH2F* drvsep = new TH2F("drvsep","drvsep",60,0,3.0,100,0.0,0.03);

  TF1 *ringfit[nrings];
  TH2F* ring_pve[nrings];
  TH2F* jan_pve[6];
  float eta;
  int etaindex;
  TH1F* ringprec = new TH1F("ringprec","",40,-1.0,1.0);
  TH1F* ringprec2 = new TH1F("ringprec2","",40,-1.0,1.0);
  ringprec->SetYTitle("E/p");
  ringprec->SetXTitle("#eta");
  ringprec2->SetYTitle("E/p");
  ringprec2->SetXTitle("#eta");
  TH1F* ring2prec = new TH1F("ring2prec","",nrings/2,-1.0,1.0);
  TH1F* ring2prec2 = new TH1F("ring2prec2","",nrings/2,-1.0,1.0);
  ring2prec->SetYTitle("E/p");
  ring2prec->SetXTitle("#eta");
  ring2prec2->SetYTitle("E/p");
  ring2prec2->SetXTitle("#eta");
  double ew[nrings];

  TH2F* trgcheck = new TH2F("trgcheck","trgcheck",2,-0.5,1.5,3,-0.5,2.5);

  TH1F* crateprec = new TH1F("crateprec","",30,0.5,30.5);
  crateprec->SetXTitle("Crate");
  crateprec->SetYTitle("E/p");

  TH2F *energyleak = new TH2F("energyleak","",20,0.0,0.03,20,0.0,1.0);
  TH2F *findbg = new TH2F("findbg","",20,0.0,0.03,30,0.0,5.0);
  TH1F *energymean = new TH1F("energymean","",20,0.0,0.03);
  TH1F *leakmean = new TH1F("leakmean","",20,0.0,0.03);
  energyleak->SetXTitle("#DeltaR");
  energyleak->SetYTitle("leaked energy / total energy");
  findbg->SetXTitle("#DeltaR");
  findbg->SetYTitle("Total energy / track momentum");
  TH2F *tevsp = new TH2F("tevsp","",50,0.0,20.0,50,0.0,30.0);
  TH1F *pmean = new TH1F("pmean","",20,0.0,15.0);
  tevsp->SetXTitle("track momentum (GeV)");
  tevsp->SetYTitle("Total Energy (GeV)");
  TH2F *tevspcent = new TH2F("tevspcent","",20,0.0,15.0,20,0.0,15.0);
  tevspcent->SetXTitle("track momentum (GeV)");
  tevspcent->SetYTitle("Energy in central tower (GeV)");
  TH1F *cmean = new TH1F("cmain","",20,0.0,15.0);
  TH2F *sistertracks = new TH2F("sistertracks","",20,0.0,8.0,20,0.0,8.0);
  sistertracks->SetXTitle("Track momentum (GeV)");
  sistertracks->SetYTitle("Neighbor momentum (GeV)");
  TH2F* dEdxvsp = new TH2F("dEdxvsp","",100,0.15,1.3,100,-5.7,-5.);
  dEdxvsp->SetXTitle("Log(p)");
  dEdxvsp->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_east = new TH2F("dEdxvsp_east","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_east->SetXTitle("Log(p)");
  dEdxvsp_east->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_west = new TH2F("dEdxvsp_west","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_west->SetXTitle("Log(p)");
  dEdxvsp_west->SetYTitle("Log(dE/dx)");
  TH2F* energyleak2 = new TH2F("energyleak2","",20,0.0,0.03,20,0.0,1.0);
  TH1F* energymean2 = new TH1F("energymean2","",20,0.0,0.03);
  TH1F* towermult = new TH1F("towermult","",9,0.0,9.0);
  energyleak2->SetXTitle("#DeltaR");
  energyleak2->SetYTitle("leaked energy/total energy");
  towermult->SetXTitle("Neighbors with energy");
  TH2F* multvsp = new TH2F("multvsp","",20,0.0,20.0,9,0.0,9.0);
  multvsp->SetXTitle("Track momentum (GeV)");
  multvsp->SetYTitle("Neighbors with energy");
  TH1F* multmean = new TH1F("multmean","",20,0.0,20.0);
  TH2F* tep3 = new TH2F("tep3","2 < p < 3",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep5 = new TH2F("tep5","3 < p < 5",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep10 = new TH2F("tep10","5 < p < 10",20,0.0,0.03,20,0.0,4.0);
  tep3->SetXTitle("DeltaR");
  tep3->SetYTitle("Total energy / track momentum");
  tep5->SetXTitle("DeltaR");
  tep5->SetYTitle("Total energy / track momentum");
  tep10->SetXTitle("DeltaR");
  tep10->SetYTitle("Total energy / track momentum");
  TH1F* tep3mean = new TH1F("tep3mean","",20,0,0.03);
  TH1F* tep5mean = new TH1F("tep5mean","",20,0,0.03);
  TH1F* tep10mean = new TH1F("tep10mean","",20,0,0.03);
  TH1F* multen = new TH1F("multen","",40,0.0,1.0);
  multen->SetXTitle("Energy in neighbor towers (GeV)");
  TH1F* east_histo = new TH1F("east_histo","Electron E/p in East",40,0.0,2.0);
  TH1F* west_histo = new TH1F("west_histo","Electron E/p in West",40,0.0,2.0);
  TH1F* all_histo = new TH1F("all_histo","Electron E/p",40,0.0,2.0);
  TH1F* notrg = new TH1F("notrg","Electron E/p",40,0.0,2.0);
  TH2F* pvsep = new TH2F("pvsep","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep->SetYTitle("p (Gev)");
  pvsep->SetXTitle("E/p");
  TH2F* pvsep0 = new TH2F("pvsep0","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep0->SetYTitle("p (Gev)");
  pvsep0->SetXTitle("E/p");
  TH2F* evsep = new TH2F("evsep","Electron E vs E/p",120,0,3.0,20,0,20.0);
  evsep->SetYTitle("E (GeV)");
  evsep->SetXTitle("E/p");

  TH1F* bsmde = new TH1F("bsmde","BSMDE ADC TOT",1500,0,1500);
  TH1F* bsmdp = new TH1F("bsmdp","BSMDP ADC TOT",1500,0,1500);

  TH1F* bsmde_central = new TH1F("bsmde_central","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_mid = new TH1F("bsmde_mid","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_outer = new TH1F("bsmde_outer","BSMDE ADC TOT",100,0,1500);

  TH2F* bsmdep = new TH2F("bsmdep","BSMDE v BSMDP",100,0,1500,100,0,1500);

  TH2F* bsmdevp = new TH2F("bsmdevp","BSMDE v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdpvp = new TH2F("bsmdpvp","BSMDP v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdevep = new TH2F("bsmdevep","BSMDE v E/p",100,0.0,2.0,100,0,1500);
  TH2F* bsmdpvep = new TH2F("bsmdpvep","BSMDP v E/p",100,0.0,2.0,100,0,1500);

  TH2F* bsmdeve = new TH2F("bsmdeve","BSMDE v E",100,1.0,30.0,100,0,1500);
  TH2F* bsmdpve = new TH2F("bsmdpve","BSMDP v E",100,1.0,30.0,100,0,1500);

  TH1F* httrig = new TH1F("httrig","HT Trigger",5,-0.5,4.5);

  TH1F* pplus = new TH1F("pplus","e+ p",100,0,20);
  TH1F* pminus = new TH1F("pminus","e- p",100,0,20);

  TH1F* posep = new TH1F("posep","e+ E/p",60,0,3.0);
  TH1F* negep = new TH1F("negep","e- E/p",60,0,3.0);


   //create the tower histograms
  char name1[100];

  for(int i = 0; i < ncrates; i++){
    for(int j = 0; j < 20; j++){
      TString ecname,ecnamep,ecnamen;
      ecname += "etacrate_";
      int cr = i+1;
      int et = j;
      ecname += cr;
      ecname += "_";
      ecname += et;
      ecnamep += ecname;
      ecnamen += ecname;
      ecnamep.ReplaceAll("te_","te_p_");
      ecnamen.ReplaceAll("te_","te_n_");
      etacrate_histo[i*20+j] = new TH1F(ecname.Data(),ecname.Data(),60,0.0,3.0);
      etacrate_histo_p[i*20+j] = new TH1F(ecnamep.Data(),ecnamep.Data(),60,0.0,3.0);
      etacrate_histo_n[i*20+j] = new TH1F(ecnamen.Data(),ecnamen.Data(),60,0.0,3.0);

    }
  }

  for(int i=0; i<ntowers; i++){
    char nameeh[100];
    sprintf(nameeh,"electron_histo_%i",i+1);
    electron_histo[i] = new TH1D(nameeh,"",60,0.,3.0);
    electron_histo[i]->SetXTitle("E/p");
    //sprintf(name1,"prs_histo_%i",i+1);
    //prs_histo[i] = new TH1D(name1,"",60,0.,500.);
    //prs_histo[i]->SetXTitle("ADC");
  }

  for(int i = 0; i < 21; i++){
    TString namebg;
    namebg += "bg_";
    namebg += i+25;
    bghisto[i] = new TH1F(namebg.Data(),namebg.Data(),60,0,3.0);
  }

  for(int i = 0; i < ncrates; i++){
    char name[100];
    char title[100];
    sprintf(name,"crate_%i",i+1);
    sprintf(title,"E/p for Crate %i",i+1);
    crate_histo[i] = new TH1F(name,title,60,0.,3.0);
    crate_histo[i]->SetXTitle("E/p");
  }

  for(int i = 0; i < nrings/2; i++){
    char name[100];
    sprintf(name,"ring2_histo_%i",i);
    ring2_histo[i] = new TH1F(name,"",60,0.,3.0);
    ring2_histo[i]->SetXTitle("E/p");
  }

  char name2[100];
  for(int i=0; i<nrings;i++)
    {
      sprintf(name2,"ring_histo_%i",i);
      //ring_histo[i] = new TH1D(name2,"",30,0.,140.0);
      //ring_histo[i]->SetXTitle("ADC / GeV Sin(#theta)");
      ring_histo[i] = new TH1D(name2,"",60,0.,3.0);
      ring_histo[i]->SetXTitle("E/p");
      char namerpve[100];
      sprintf(namerpve,"ring_pve_%i",i);
      ring_pve[i] = new TH2F(namerpve,"",20,0,20.0,20,0,20.0);
      ring_pve[i]->SetXTitle("E (GeV)");
      ring_pve[i]->SetYTitle("p (GeV)");
    }

  for(int i = 0; i < 6; i++){
    char jname[100];
    sprintf(jname,"jan_pve_%i",i);
    jan_pve[i] = new TH2F(jname,"",120,0,3.0,20,0,20.0);
    jan_pve[i]->SetXTitle("E/p");
    jan_pve[i]->SetYTitle("p (GeV)");
  }
  //global graphics functions
  gStyle->SetOptStat("oue");
  gStyle->SetOptFit(111);
  gStyle->SetCanvasColor(10);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetOptTitle(0);
  gStyle->SetPalette(1);
  gStyle->SetStatColor(0);

  StEmcOfflineCalibrationTrack* track = new StEmcOfflineCalibrationTrack();
  StEmcOfflineCalibrationCluster* cluster = new StEmcOfflineCalibrationCluster();
  tree->SetBranchAddress("clusters",&cluster);

  //**********************************************//
  //Loop Over Tracks, Fill Histograms             //
  //**********************************************//

  int nentries = tree->GetEntries();
  cout<<nentries<<endl;
  int ngoodhit = 0;
  int nplt10 = 0;
  int nnosis = 0;
  int nfinal = 0;
  int nbsmdgood = 0;
  int nnottrig = 0;
  int nfidu = 0;
  int nenterexit = 0;
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;
    if(j % 500000 == 0) cout<<"reading "<<j<<" of "<<nentries<<endl;

    httrig->Fill((float)track->htTrig);

    if(track->charge > 0)pplus->Fill(track->p);
    if(track->charge < 0)pminus->Fill(track->p);

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;

    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);

    double geant_scale = geant_fits[geantetaindex]->Eval(dR);
    scaled_adc /= geant_scale;
    //double geant_scale = geant_fit->Eval(dR);
    //scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;

    //now rescale dR for last ring to make cuts work
    if(geantetaindex == 19)dR *= 0.025/0.017;

    //double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1];
    double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;
    ngoodhit++;
    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] <= 2400)dEdxvsp_west->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] > 2400)dEdxvsp_east->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    trgcheck->Fill(track->nonhtTrig,track->htTrig);

    if(track->tower_id[0] != track->tower_id_exit)continue;
    nenterexit++;

    if(status[index-1]!=1)continue;

    pvsep0->Fill(scaled_adc*tgain,track->p);
    if(track->p > 10)continue;	
    nplt10++;		

    //if(track->p < 1.5)continue;
    //if(track->p < 3.0)continue;
    if(track->htTrig == 2 && track->nonhtTrig == 0)continue;
    nnottrig++;
    //change the fiducial cut to a square with diagonal = 0.06 in deta, dphi space
    float squarefid = 0.02;//0.03/TMath::Sqrt(2.0);
    //if(TMath::Abs(track->deta) > squarefid || TMath::Abs(track->dphi) > squarefid)continue;

    //calculate geant scaled, pedestal subtracted adc
    //if(dR > 0.0125)continue;
    int numsis = tracks->GetEntries();
    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }

    if(track->dEdx > 3.5e-6 && track->dEdx <5.0e-6 && numsis ==0 &&maxId == 0)drvsep->Fill(scaled_adc*tgain,dR);
    if(dR > 0.02)continue;
    nfidu++;
    //if(track->p > 6.0)continue;				
    //if(track->p > 15)continue;
    //cout<<track->dEdx<<endl;


    //if(track->dEdx*1000000 > 4.5 || track->dEdx*1000000 < 3.5)continue;

    //cout<<track->htTrig<<endl;

    for(int i = 0; i < 21; i++){
      if(numsis > 0)break;
      if(maxId != 0)break;
      if(track->dEdx*1e7 > 25 + i && track->dEdx*1e7 < 26+i)bghisto[i]->Fill(scaled_adc*tgain);
    }

    //if(track->dEdx < 3.5e-6 || track->dEdx > 5.0e-6)continue;
    if(track->dEdx < 3.5e-6 || track->dEdx > 4.5e-6)continue;
    //if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;
    nbsmdgood++;
    //if(bsmdeadctot < 500) continue;

    //if(bsmdeadctot < 84.*track->p)continue;
    //if(bsmdeadctot > 200.*track->p + 1500)continue;

    //if(bsmdpadctot < 800)continue;

    if(numsis > 0)continue;

    nnosis++;
    if(maxId != 0) continue;


    nfinal++;
    if(track->htTrig!=2)notrg->Fill(scaled_adc*tgain);

    //if(!track->nonhtTrig)continue;
    //if(track->nHits < 25)continue;
    //if(status[index-1]==1)ring_histo[etaindex]->Fill(scaled_adc*gains[index-1]);

    //scaled_adc = totalbtow/track->p;
    //tgain = 1.0;

    float phi = helper->getPhi(index);
    int crate,sequence;
    decoder->GetCrateFromTowerId(index,crate,sequence);
    etacrate_histo[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge > 0)etacrate_histo_p[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge < 0)etacrate_histo_n[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);

    electron_histo[index-1]->Fill(scaled_adc*tgain);
    ring_histo[etaindex]->Fill(scaled_adc*tgain);
    if(etaindex == 0 || etaindex == 39){
      //cout<<etaindex<<" "<<tgain<<" "<<track->p<<" "<<scaled_adc*tgain*track->p<<" "<<scaled_adc*tgain<<endl;
    }
    //cout<<index<<" "<<gains[index-1]<<" "<<scaled_adc*track->p<<" "<<track->p<<" "<<status[index-1]<<endl;
    ring_pve[etaindex]->Fill(scaled_adc*tgain*track->p,track->p);

    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    float abseta = TMath::Abs(eta);
    if(abseta > 0.95){
      jan_pve[5]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.9){
      jan_pve[4]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.6){
      jan_pve[3]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.3){
      jan_pve[2]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.05){
      jan_pve[1]->Fill(scaled_adc*tgain,track->p);
    }else{
      jan_pve[0]->Fill(scaled_adc*tgain,track->p);
    }

    all_histo->Fill(scaled_adc*tgain);
    pvsep->Fill(scaled_adc*tgain,track->p);
    evsep->Fill(scaled_adc*tgain,track->p*scaled_adc*tgain);
    tevsp->Fill(track->p,scaled_adc*tgain*track->p);

    if(track->charge > 0)posep->Fill(scaled_adc*tgain);
    if(track->charge < 0)negep->Fill(scaled_adc*tgain);

    //if(scaled_adc*tgain < 0.7 || scaled_adc*tgain > 5.0)continue;
    bsmde->Fill(bsmdeadctot);
    bsmdp->Fill(bsmdpadctot);
    bsmdep->Fill(bsmdeadctot,bsmdpadctot);

    if(abseta > 0.6){
      bsmde_outer->Fill(bsmdeadctot);
    }else if(abseta > 0.3){
      bsmde_mid->Fill(bsmdeadctot);
    }else{
      bsmde_central->Fill(bsmdeadctot);
    }

    bsmdevp->Fill(track->p,bsmdeadctot);
    bsmdpvp->Fill(track->p,bsmdpadctot);
    bsmdevep->Fill(scaled_adc*tgain,bsmdeadctot);
    bsmdpvep->Fill(scaled_adc*tgain,bsmdpadctot);

    bsmdeve->Fill(scaled_adc*tgain*track->p,bsmdeadctot);
    bsmdpve->Fill(scaled_adc*tgain*track->p,bsmdpadctot);

    if(dR > 0.015)continue;
    if(track->tower_id[0] <= 2400){
      west_histo->Fill(scaled_adc*tgain);
    }
    if(track->tower_id[0] > 2400){
      east_histo->Fill(scaled_adc*tgain);
    }

  }
  cout<<"processed electron tree"<<endl;
  cout<<"ngoodhit: "<<ngoodhit<<endl;
  cout<<"nenterexit: "<<nenterexit<<endl;
  cout<<"n not trig: "<<nnottrig<<endl;
  cout<<"n p < 10: "<<nplt10<<endl;
  cout<<"n in fidu: "<<nfidu<<endl;
  cout<<"nbsmdhit: "<<nbsmdgood<<endl;
  cout<<"n no sis: "<<nnosis<<endl;
  cout<<"n final: "<<nfinal<<endl;

  //double ew[21];
  for(int h=0;h<21;h++){
    TH1D* projection = energyleak->ProjectionY("projection",h,h);
    float mean = projection->GetMean();
    energymean->SetBinContent(h,mean);
    TH1D* projection1 = findbg->ProjectionY("projection1",h,h);
    float mean1 = projection1->GetMean();
    leakmean->SetBinContent(h,mean1);
    TH1D* projection2 = tevsp->ProjectionY("projection2",h,h);
    float mean2 = projection2->GetMean();
    pmean->SetBinContent(h,mean2);
    //ew[h] = projection2->GetRMS();
    TH1D* projection3 = tevspcent->ProjectionY("projection3",h,h);
    float mean3 = projection3->GetMean();
    cmean->SetBinContent(h,mean3);
    TH1D* projection4 = energyleak2->ProjectionY("projection4",h,h);
    float mean4 = projection4->GetMean();
    energymean2->SetBinContent(h,mean4);
    TH1D* projection5 = multvsp->ProjectionY("projection5",h,h);
    float mean5 = projection5->GetMean();
    multmean->SetBinContent(h,mean5);
    TH1D* projection6 = tep3->ProjectionY("projection6",h,h);
    float mean6 = projection6->GetMean();
    tep3mean->SetBinContent(h,mean6);
    TH1D* projection7 = tep3->ProjectionY("projection7",h,h);
    float mean7 = projection7->GetMean();
    tep5mean->SetBinContent(h,mean7);
    TH1D* projection8 = tep3->ProjectionY("projection8",h,h);
    float mean8 = projection8->GetMean();
    tep10mean->SetBinContent(h,mean8);
  }

  TF1* fitleak = new TF1("fitleak","[0]",0,0.03);
  fitleak->SetLineWidth(0.1);
  leakmean->Fit(fitleak,"rq");


  //**********************************************//
  //Fit Tower Histograms                          //
  //**********************************************//
  /*
  for(int i=0; i<ntowers; i++){
	  
    if(i%600 == 0) cout<<"fitting tower "<<i+1<<" of "<<ntowers<<endl;
		
    sprintf(name,"fit_%i",i+1);
		
		//this fit is for the electron tree
    fit[i] = new TF1(name,fit_function,0.,140.,6);
    fit[i]->SetParameter(1,65.);
    fit[i]->SetParameter(2,10.);
    fit[i]->SetParameter(3,10.); //relative height of peak to bg
    fit[i]->SetParameter(4,10.);
    fit[i]->SetParameter(5,3.);
    fit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
		
    fit[i]->SetLineColor(kGreen);
    fit[i]->SetLineWidth(0.6);
		
    electron_histo[i]->Fit(fit[i],"rq");
  }
  */
  //**********************************************//
  //Fit Ring Histograms                           //
  //**********************************************//

  for(int i=0; i<nrings; i++){
	  
    //cout<<"fitting ring "<<i+1<<" of "<<nrings<<endl;
		
    sprintf(name,"ring_fit_%i",i);
    /*
    ringfit[i] = new TF1(name,fit_function,0.,140.,6);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParameter(5,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
    */		
    //TF1* ffff = new TF1("ffff","expo(0) + gaus(2)",0.4,1.7);

    ring_histo[i]->Sumw2();
    //ring_histo[i]->Rebin(3);

    ringfit[i] = new TF1(name,"pol1(0) + gaus(2)");
    ringfit[i]->SetParLimits(0,0,10.0*ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParLimits(1,-10000,0);
    ringfit[i]->SetParLimits(2,0,10.0*ring_histo[i]->GetMaximum());
    ringfit[i]->SetParLimits(3,0,10);
    ringfit[i]->SetParameter(0,ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParameter(1,-ring_histo[i]->GetBinContent(1)/6.0);
    ringfit[i]->SetParameter(2,ring_histo[i]->GetMaximum());
    ringfit[i]->SetParameter(3,0.95);
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    /*
    ringfit[i] = new TF1(name,fit_function2,0.1,2.5,8);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.25);
    ringfit[i]->SetParameter(5,0.15);
    ringfit[i]->SetParameter(7,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma","Bg2 constant","Bg2 decay");
    	
    */
    ringfit[i]->SetLineColor(kBlue);
    ringfit[i]->SetLineWidth(0.6);
    
    ring_histo[i]->Fit(ringfit[i],"rql","",0.2,1.7);
		
    ringprec->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec->SetBinError(i+1,ringfit[i]->GetParameter(4));
    ringprec2->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec2->SetBinError(i+1,ringfit[i]->GetParError(3));
    //ew[i] = 4066/(60*(fit[i]->GetParameter(2))*(fit[i]->GetParameter(2)));

    float mean = ringfit[i]->GetParameter(3);
    float merr = ringfit[i]->GetParError(3);
    cout<<"ring "<<i<<" "<<mean<<" "<<merr/mean<<" "<<ring_histo[i]->GetEntries()<<endl;
  }

  for(int i = 0; i < nrings/2; i++){
    ring2_histo[i]->Add(ring_histo[2*i]);
    ring2_histo[i]->Add(ring_histo[2*i+1]);
    sprintf(name,"ring2_fit_%i",i);
    ring2fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);

    ring2_histo[i]->Rebin(3);

    ring2fit[i]->SetParLimits(0,0,10.0*ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParLimits(1,-10000,0);
    ring2fit[i]->SetParLimits(2,0,10.0*ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParLimits(3,0,10);
    ring2fit[i]->SetParLimits(4,0.17,0.175);
    ring2fit[i]->SetParameter(0,ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParameter(1,-ring2_histo[i]->GetBinContent(1)/6.0);
    ring2fit[i]->SetParameter(2,ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParameter(3,0.95);
    ring2fit[i]->SetParameter(4,0.11245);
    ring2fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");

    ring2_histo[i]->Fit(ring2fit[i],"rql","",0.3,1.7);

    ring2prec->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec->SetBinError(i+1,ring2fit[i]->GetParameter(4));
    ring2prec2->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec2->SetBinError(i+1,ring2fit[i]->GetParError(3));

    cout<<"ring2 "<<i<<" "<<ring2fit[i]->GetParameter(3)<<" "<<ring2fit[i]->GetParError(3)<<endl;
  }

  for(int i = 0; i < ntowers; i++){
    char name[100];
    sprintf(name,"electron_fit_%i",i+1);
    /*
    fit[i] = new TF1(name,"pol1(0)+gaus(2)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,-10000,0);
    fit[i]->SetParLimits(2,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(3,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,-electron_histo[i]->GetBinContent(1)/6.0);
    fit[i]->SetParameter(2,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(3,0.95);
    fit[i]->SetParameter(4,0.15);
    fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    */
    fit[i] = new TF1(name,"pol0(0)+gaus(1)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(2,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(2,0.95);
    fit[i]->SetParameter(3,0.15);
    fit[i]->SetParNames("constant1","constant2","Mean","Sigma");

    electron_histo[i]->Fit(fit[i],"rql","",0.3,1.7);
  }

  ofstream fitfile(ffname);

  TF1* etacrate_fit[ncrates*20];
  for(int ii = 0; ii < ncrates; ii++){
    for(int j = 0; j < 20; j++){
      TString ecname;
      ecname += "fit";
      int cr = ii+1;
      int et = j;
      int i = ii*20 + j;
      //ecname += cr;
      //ecname += "_";
      //ecname += et;
      etacrate_fit[i] = new TF1(ecname.Data(),"pol1(0) + gaus(2)",0.25,1.6);
      //etacrate_fit[i]->SetParLimits(0,0,10.0*etacrate_histo[i]->GetBinContent(1));
      etacrate_histo[i]->Rebin();
      etacrate_fit[i]->SetParLimits(1,-10000,0);
      etacrate_fit[i]->SetParLimits(2,0,10.0*etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParLimits(3,0,10);
      etacrate_fit[i]->SetParameter(0,etacrate_histo[i]->GetBinContent(2));
      etacrate_fit[i]->SetParameter(1,-etacrate_histo[i]->GetBinContent(2)/3.0);
      etacrate_fit[i]->SetParameter(2,etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParameter(3,0.96134);
      etacrate_fit[i]->SetParameter(4,0.141123);
      etacrate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
      
      etacrate_histo[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_p[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_n[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      fitfile << i << " " << etacrate_histo[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_p[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_n[i]->GetFunction("fit")->GetParameter(3) << endl;

    }
  }

  ofstream newgain(ngname);
  

  float gains2[ntowers];
  float gerr2[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    int crate,sequence;
    decoder->GetCrateFromTowerId(i+1,crate,sequence);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);
    TString ecname;
    ecname += "fit";
    //int cr = ii+1;
    //int et = j;
    //int i = ii*20 + j;
    //ecname += crate;
    //ecname += "_";
    //ecname += geantetaindex;
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    int etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    //float adjust = ring2fit[(int)etaindex/2]->GetParameter(3);
    //cout<<etaindex<<" "<<(int)etaindex/2<<" "<<adjust<<endl;
    //float adjust = fit[i]->GetParameter(3);
    float ng = 0;
    float ne = 0;
    if(status[i] == 1){
      //float og = bemctables->calib(1,i+1)*gains[i];
      float og = gains[i];
      //float aerr = ring2fit[(int)etaindex/2]->GetParError(3);
      float adjust = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParameter(3);
      float aerr = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParError(3);
      if(geantetaindex == 19){
	adjust = ringfit[etaindex]->GetParameter(3);
	aerr = ringfit[etaindex]->GetParError(3);
      }
      ng = og/adjust;
      float gerr = peakerr[i]*gains[i]/peaks[i];
      ne = sqrt(pow(og*aerr/(adjust*adjust),2) + pow(gerr/adjust,2));
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains2[i] = ng;
    gerr2[i] = ne;


  }

  newgain.close();

    ///////////////////////////////////////
   //Using new gains regenerate by crate//
  ///////////////////////////////////////


  /*
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;
    double geant_scale = geant_fit->Eval(dR);
    scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;
    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);

    double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1]*gains2[index-1];
    //double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;

    if(track->tower_id[0] != track->tower_id_exit)continue;

    if(track->htTrig == 2)continue;
    if(track->p > 6)continue;	

    if(dR > 0.025)continue;

    if(track->dEdx < 3.4e-6)continue;
    if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;

    int numsis = tracks->GetEntries();
    if(numsis > 0)continue;

    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }
    if(maxId != 0) continue;

    eta = helper->getEta(index);
    float phi = helper->getPhi(index);
    int crate = lookup_crate(eta,phi);
    if(status[index-1]==1)crate_histo[crate-1]->Fill(scaled_adc*tgain);
  }

  for(int i = 0; i < ncrates; i++){
    sprintf(name,"crate_fit_%i",i);
    crate_histo[i]->Sumw2();	
    crate_histo[i]->Rebin(4);	

    crate_fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);
    crate_fit[i]->SetParLimits(0,0,10.0*crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParLimits(1,-10000,0);
    crate_fit[i]->SetParLimits(2,0,10.0*crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParLimits(3,0,10);
    crate_fit[i]->SetParameter(0,crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParameter(1,-crate_histo[i]->GetBinContent(1)/6.0);
    crate_fit[i]->SetParameter(2,-crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParameter(3,0.929);
    crate_fit[i]->SetParameter(4,0.156);
    crate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    crate_fit[i]->SetLineColor(kBlue);
    crate_fit[i]->SetLineWidth(0.6);


    crate_histo[i]->Fit(crate_fit[i],"rql","",0.3,1.8);
    float mean = crate_histo[i]->GetFunction(name)->GetParameter(3);
    float merr = crate_histo[i]->GetFunction(name)->GetParError(3);
    crateprec->SetBinContent(i+1,mean);
    crateprec->SetBinError(i+1,merr);
    cout<<"crate "<<i+1<<" "<<mean<<" "<<merr/mean<<endl;
  }
  
  ofstream newgain(ngname);

  float gains3[ntowers];
  float gerr3[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    float phi = helper->getPhi(i+1);
    int crate = lookup_crate(eta,phi);
    float adjust = crate_fit[crate-1]->GetParameter(3);
    float og = bemctables->calib(1,i)*gains[i]*gains2[i];
    float ng = og;
    float aerr = crate_fit[crate-1]->GetParError(3);
    float ne = sqrt(pow(gains[i]*gerr2[i],2) + pow(gains2[i]*gainerr[i],2));
    if(fabs(adjust-1)/aerr > 1.5){
      ne = sqrt(pow(ne/(adjust),2)+pow(og*aerr/(adjust*adjust),2));
      ng /= adjust;
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains3[i] = ng;
    gerr3[i] = ne;
  }

  newgain.close();
  */
  outfile.Write();
  outfile.Close();

}
Пример #15
0
double GetMeanpTass(int jass)
{
		    TH1D* hptass = (TH1D*) gInputfile->Get(Form("%spt_ass_%d",subdir.Data(),jass));
                    double ptass = hptass->GetMean();
                    return ptass;
}
Пример #16
0
void plotQ(){


	int nBins = sizeof(dEtaBins)/ sizeof(dEtaBins[0]) - 1;

	const vector<double> dEtaBinsVector;
	for(int i = 0; i < nBins + 1; i++){

		dEtaBinsVector.push_back( dEtaBins[i] );
		cout << "dEta: " << dEtaBins[i] << endl;
	}

	TFile* file = new TFile("../rootfiles/CME_QvsdEta_PbPb_30_40_v12..root");
	TH2D* QPlusPlus = file->Get("ana/QvsdEtaPlusPlus");
	TH2D* QMinusMinus = file->Get("ana/QvsdEtaMinusMinus");
	TH2D* QPlusMinus = file->Get("ana/QvsdEtaPlusMinus");
	//TH2D* QMinusPlus = file->Get("ana/QvsdEtaMinusPlus");
	
	TH1D* QaQb = file->Get("ana/c2_ab");
	TH1D* QaQc = file->Get("ana/c2_ac");
	TH1D* QcQb = file->Get("ana/c2_cb");
	TH1D* Ntrk = file->Get("ana/Ntrk");

	// double integral = 0;
	// for(int i = 0; i < evtWeightedQp3->GetNbinsX(); i++ ){

	// 	double temp = evtWeightedQp3->GetBinContent(i+1);
	// 	double center = evtWeightedQp3->GetBinCenter(i+1);
	// 	if(temp != 0 ){

	// 		cout << "found in bin " << i+1 <<", bin center = " << evtWeightedQp3->GetBinCenter(i+1) <<  ", with entires = " << temp << endl;
	// 		integral = integral + temp*center;
	// 	}
	// }

	double meanQaQb = QaQb->GetMean();
	double meanQaQc = QaQc->GetMean();
	double meanQcQb = QcQb->GetMean();

	double v2_b = sqrt(meanQaQb*meanQcQb/meanQaQc);
	double v2_a = sqrt(meanQaQb*meanQaQc/meanQcQb );
	double v2_ab = sqrt( meanQaQb ); 

	cout << "v2_a: " << v2_a << endl;
	cout << "v2_b: " << v2_b << endl;
	cout << "v2_ab: " << v2_ab << endl;
	
	TH1D* Qplusplus1D[48];
	TH1D* Qminusminus1D[48];
	TH1D* Qplusminus1D[48];
	TH1D* Qminusplus1D[48];

	for(int eta = 0; eta < nBins; eta++){

		Qplusplus1D[eta] = (TH1D*) QPlusPlus->ProjectionY(Form("Qplusplus1D_%d", eta), eta+1, eta+2);
		Qminusminus1D[eta] = (TH1D*) QMinusMinus->ProjectionY(Form("Qminusminus1D_%d", eta), eta+1, eta+2);
		Qplusminus1D[eta] = (TH1D*) QPlusMinus->ProjectionY(Form("Qplusminus1D_%d", eta), eta+1, eta+2);
		//Qminusplus1D[eta] = (TH1D*) QMinusPlus->ProjectionY(Form("Qminusplus1D_%d", eta), eta+1, eta+2);

	}

	TCanvas* c1 = makeCanvas("c1","");
	gPad->SetLeftMargin(0.15);
	gPad->SetBottomMargin(0.15);
	gPad->SetTicks();

	TH1D* hist = makeHist("hist","","#Delta eta", "<cos(#phi_{1}+#phi_{2}-2#phi_{3})>/v_{2,3}", 47,0.1,4.8, kBlack);
	
	TH1D* hist1 = makeHistDifferentBins("hist1","", "","",21,dEtaBins,kBlack);
	TH1D* hist2 = makeHistDifferentBins("hist2","", "","",21,dEtaBins,kRed);
	TH1D* hist3 = makeHistDifferentBins("hist3","", "","",21,dEtaBins,kBlue);
	TH1D* hist4 = makeHistDifferentBins("hist4","", "","",21,dEtaBins,kGreen-3);

	for(int eta = 0; eta < nBins; eta++){

		hist1->SetBinContent(eta+1, Qplusplus1D[eta]->GetMean() );
		hist2->SetBinContent(eta+1, Qminusminus1D[eta]->GetMean() );
		hist3->SetBinContent(eta+1, Qplusminus1D[eta]->GetMean() );

		hist1->SetBinError(eta+1, Qplusplus1D[eta]->GetMeanError() );
		hist2->SetBinError(eta+1, Qminusminus1D[eta]->GetMeanError() );
		hist3->SetBinError(eta+1, Qplusminus1D[eta]->GetMeanError() );

		//hist4->SetBinContent(eta+1, Qminusplus1D[eta]->GetMean() );

	}

	hist->GetXaxis()->SetTitleColor(kBlack);
	hist->GetYaxis()->SetRangeUser(-0.0009,0.0009);
	hist->Draw();
	hist1->Scale(1.0/v2_ab);
	hist2->Scale(1.0/v2_ab);
	hist3->Scale(1.0/v2_ab);
	//hist4->Scale(1.0/v2_ab);
	
	hist1->Draw("Psame");
	hist2->Draw("Psame");
	hist3->Draw("Psame");
	//hist4->Draw("Psame");

	TLegend *w1 = new TLegend(0.2,0.20,0.45,0.43);
    w1->SetLineColor(kWhite);
    w1->SetFillColor(0);
    w1->AddEntry(hist1,"++","P");
    w1->AddEntry(hist2,"--","P");
    w1->AddEntry(hist3,"+-/-+","P");
    w1->Draw("same");
	



}
Пример #17
0
void harvestAsymptotic(string fileName, string fileMassesName){
 
  cout<<"\n\nAnalyzing file "<<fileName.c_str()<<"  at MassFile = "<< fileMassesName.c_str()<<endl;
  TFile *f = new TFile(fileName.c_str());
  TTree* t = (TTree* ) f->Get("limit");
  double limit, mh; float quant;
  //  int ntoys = t->GetEntries();
  t->SetBranchAddress("mh",&mh);
  t->SetBranchAddress("limit",&limit);
  t->SetBranchAddress("quantileExpected",&quant);


  ifstream fMasses(fileMassesName.c_str(),ios::in);
  double M=0;

  double mhnew, quantnew,limitnew;
  const double quant95=0.025, quant68=0.16,quant50=0.5;
  const double quant95down=quant95,quant95up=1-quant95,quant68down=quant68,quant68up=1-quant68;
  TFile *fout=new TFile("higgsCombineGrav2L2Q_Asymptotic.RSGrav05.0b.root","RECREATE");
  fout->cd();
  TTree *tout=new TTree("limit","Harvested limits");
  tout->Branch("limit",&limitnew,"limit/D");
  tout->Branch("mh",&mhnew,"mh/D");
  tout->Branch("quantileExpected",&quantnew,"quantileExpected/D");

 while (fMasses.good()){
    int ntoys=0;
    fMasses>>M;
    cout<<"\n\n----------\nMASS = "<<M<<endl;
    int nBins=30000;
    double maxBin=75.0;
    TH1D *hOBS = new TH1D("hobs","hobs",nBins,0,maxBin);
    TH1D *h95down = new TH1D("h95down","h95down",nBins,0,maxBin);
    TH1D *h95up = new TH1D("h95up","h95up",nBins,0,maxBin);
    TH1D *h68down = new TH1D("h68down","h68down",nBins,0,maxBin);
    TH1D *h68up = new TH1D("h68up","h68up",nBins,0,maxBin);
    TH1D *hMedian = new TH1D("hmedian","hmedian",nBins,0,maxBin);
    int c=0;
    for(int iEvt=0; iEvt<t->GetEntries(); iEvt++){
    
      t->GetEntry(iEvt);
      if(mh==M&&limit<maxBin&&limit>0.0){
	
	if(quant==-1.0)hOBS->Fill(limit);
	else if(double(quant)>=quant95down*0.99 && double(quant)<=quant95down*1.01     )h95down->Fill(limit);
	else if(double(quant)>=quant95up*0.98 && double(quant)<=quant95up*1.02  )h95up->Fill(limit);
	else if(quant>=quant68down*0.99 && double(quant)<=quant68down*1.01  )h68down->Fill(limit);
	else if(quant>=quant68up*0.99 && double(quant)<=quant68up*1.01  )h68up->Fill(limit);
	else if(quant>=quant50*0.99 && double(quant)<=quant50*1.01  )hMedian->Fill(limit);
	else{cout<<"Warning: m_H= "<<mh<<"  Quantile = "<<quant<<"  Limit = "<<limit<<endl;}
	c++;
      }
 
   }//end loop on tree entries
    cout<<"  Filled "<<c<<endl;
    double low95p= (double)h95down->GetMean();
    cout << "lower 95%: " <<low95p  <<"  "<<h95down->GetEntries()<< endl;
    limitnew=low95p ;
    quantnew=quant95down;
    mhnew=M;
    tout->Fill();

  double up95p= (double)h95up->GetMean();
  cout << "upper 95%: " <<up95p  <<"  "<<h95up->GetEntries()<< endl;
  limitnew=up95p ;
  quantnew=quant95up;
  mhnew=M;
  tout->Fill();


  double low68p= (double)h68down->GetMean();
  cout << "lower 68%: " << low68p <<"  "<<h68down->GetEntries()<< endl;
  limitnew=low68p ;
  quantnew=quant68down;
  mhnew=M;
  tout->Fill();   

  double up68p=(double)h68up->GetMean();
  cout << "upper 68%: " << up68p <<"  "<<h68up->GetEntries()<< endl;
  limitnew=up68p ;
  quantnew=quant68up;
  mhnew=M;
  tout->Fill();

  double medianp=(double)hMedian->GetMean();
  cout << "median: " << medianp <<"  "<<hMedian->GetEntries()<< endl;
  limitnew=medianp ;
  quantnew=quant50;
  mhnew=M;
  tout->Fill();

  double obsp=(double)hOBS->GetMean();
  cout << "observed: " << obsp <<"  "<<hOBS->GetEntries()<< endl;
  limitnew=obsp ;
  quantnew=-1.0;
  mhnew=M;
  tout->Fill();

  delete hOBS; delete hMedian;
  delete h95down ; delete h95up; 
  delete h68down; delete h68up;

  }//end while loop on masses
 
 tout->Write();
 fout->Close();
 delete fout;
 delete t;
 delete f;



}
Пример #18
0
int makeGraphMC(){

 
  TGraphErrors * graph;
  double x[7],y[7],xErr[7],yErr[7];
  TH2D* histo2D;
  

  TFile *file = TFile::Open("PhotonPtNVtx_2d_PF_mc.root");
  file->GetObject("Photon Pt against Number of Vertices",histo2D);

  TH1D * histoVtx = (TH1D*)histo2D->ProjectionY("histoVtx",0,1200);

  
  TH1D* histo1D = (TH1D*)histo2D->ProjectionX("histo1D",1,5);
  TH1D* histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histoVtxPart->SetBinContent(1,histoVtx->GetBinContent(1));
  histoVtxPart->SetBinContent(2,histoVtx->GetBinContent(2));
  histoVtxPart->SetBinContent(3,histoVtx->GetBinContent(3));
  histoVtxPart->SetBinContent(4,histoVtx->GetBinContent(4));
  histoVtxPart->SetBinContent(5,histoVtx->GetBinContent(5));
  y[0] = histo1D->GetMean();
  yErr[0] = histo1D->GetMeanError();  
  x[0] = histoVtxPart->GetMean();
  xErr[0] = histoVtxPart->GetMeanError();

  cout<<"x0 = "<<x[0]<<endl;
  cout<<"x0Err = "<<xErr[0]<<endl;

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",6,10);
  histoVtxPart->SetBinContent(6,histoVtx->GetBinContent(6));
  histoVtxPart->SetBinContent(7,histoVtx->GetBinContent(7));
  histoVtxPart->SetBinContent(8,histoVtx->GetBinContent(8));
  histoVtxPart->SetBinContent(9,histoVtx->GetBinContent(9));
  histoVtxPart->SetBinContent(10,histoVtx->GetBinContent(10));
  y[1] = histo1D->GetMean();
  yErr[1] = histo1D->GetMeanError();
  x[1] = histoVtxPart->GetMean();
  xErr[1] = histoVtxPart->GetMeanError();
  

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",11,15);
  histoVtxPart->SetBinContent(11,histoVtx->GetBinContent(11));
  histoVtxPart->SetBinContent(12,histoVtx->GetBinContent(12));
  histoVtxPart->SetBinContent(13,histoVtx->GetBinContent(13));
  histoVtxPart->SetBinContent(14,histoVtx->GetBinContent(14));
  histoVtxPart->SetBinContent(15,histoVtx->GetBinContent(15));
  y[2] = histo1D->GetMean();
  yErr[2] = histo1D->GetMeanError();
  x[2] = histoVtxPart->GetMean();
  xErr[2] = histoVtxPart->GetMeanError();
  

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",16,20);
  histoVtxPart->SetBinContent(16,histoVtx->GetBinContent(16));
  histoVtxPart->SetBinContent(17,histoVtx->GetBinContent(17));
  histoVtxPart->SetBinContent(18,histoVtx->GetBinContent(18));
  histoVtxPart->SetBinContent(19,histoVtx->GetBinContent(19));
  histoVtxPart->SetBinContent(20,histoVtx->GetBinContent(20));
  y[3] = histo1D->GetMean();
  yErr[3] = histo1D->GetMeanError();
  x[3] = histoVtxPart->GetMean();
  xErr[3] = histoVtxPart->GetMeanError();
  

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",21,25);
  histoVtxPart->SetBinContent(21,histoVtx->GetBinContent(21));
  histoVtxPart->SetBinContent(22,histoVtx->GetBinContent(22));
  histoVtxPart->SetBinContent(23,histoVtx->GetBinContent(23));
  histoVtxPart->SetBinContent(24,histoVtx->GetBinContent(24));
  histoVtxPart->SetBinContent(25,histoVtx->GetBinContent(25));
  y[4] = histo1D->GetMean();
  yErr[4] = histo1D->GetMeanError();
  x[4] = histoVtxPart->GetMean();
  xErr[4] = histoVtxPart->GetMeanError();
  

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",26,30);
  histoVtxPart->SetBinContent(26,histoVtx->GetBinContent(26));
  histoVtxPart->SetBinContent(27,histoVtx->GetBinContent(27));
  histoVtxPart->SetBinContent(28,histoVtx->GetBinContent(28));
  histoVtxPart->SetBinContent(29,histoVtx->GetBinContent(29));
  histoVtxPart->SetBinContent(30,histoVtx->GetBinContent(30));
  y[5] = histo1D->GetMean();
  yErr[5] = histo1D->GetMeanError();
  x[5] = histoVtxPart->GetMean();
  xErr[5] = histoVtxPart->GetMeanError();
  

  delete histoVtxPart;
  histoVtxPart = new TH1D("vtx","vtx_part",60,1,60);
  histo1D = (TH1D*)histo2D->ProjectionX("bla",31,35);
  histoVtxPart->SetBinContent(31,histoVtx->GetBinContent(31));
  histoVtxPart->SetBinContent(32,histoVtx->GetBinContent(32));
  histoVtxPart->SetBinContent(33,histoVtx->GetBinContent(33));
  histoVtxPart->SetBinContent(34,histoVtx->GetBinContent(34));
  histoVtxPart->SetBinContent(35,histoVtx->GetBinContent(35));
  y[6] = histo1D->GetMean();
  yErr[6] = histo1D->GetMeanError();
  x[6] = histoVtxPart->GetMean();
  xErr[6] = histoVtxPart->GetMeanError();
 

  graph = new TGraphErrors(7,x,y,xErr,yErr);
  TF1* f1 = new TF1("pol1","pol1"); 
  graph -> Fit(f1,"Q","",5.0,35.0);

  char legEntry[100];


  cout<<"par0 = "<<f1->GetParameter(0)<<endl;
  cout<<"par1 = "<<f1->GetParameter(1)<<endl;
  sprintf(legEntry,"%4.2f + %4.2f (#pm %4.2f) * x",f1->GetParameter(0),f1->GetParameter(1),f1->GetParError(1));

  TLegend* leg_hist       =  0 ;
  leg_hist = new TLegend(0.5,0.75,0.9,0.9);
  leg_hist->SetTextSize(0.033);
  leg_hist->SetHeader(legEntry);
  leg_hist -> SetFillColor(0);
  

  graph -> SetTitle("Pile-up dependence of Photon pT (MC)");
  graph -> GetXaxis() -> SetTitle("#Vtx"); 
  graph -> GetYaxis() -> SetTitle("Photon pT");
  graph -> SetMaximum(230);
  graph  -> GetYaxis() -> SetTitleOffset(1.3); 
  

  TCanvas* canvas = new TCanvas("c","c",0,0,500,500);
  canvas ->cd();
  graph->Draw("AP");
  leg_hist->Draw("same");

  canvas->SaveAs("PUDependence_MC.pdf");

  return 0;

}
Пример #19
0
void makeCLsCards(TString decay_mode, TString SignalRegion, int MSTOP, int MLSP){


          std::ostringstream ostr1;
          ostr1 << MSTOP;
          std::string stop = ostr1.str();

          std::ostringstream ostr2;
          ostr2 << MLSP;
          std::string neut = ostr2.str();


          TFile sig("ntp_8/"+decay_mode+".root");

          TH1D* signal= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalBVetoBCUp= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"BVetoBCUp_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalBVetoBCDown= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"BVetoBCDown_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalBVetoLightUp= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"BVetoLightUp_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalBVetoLightDown= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"BVetoLightDown_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalJESUp= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"JESUp_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalJESDown= (TH1D*)sig.Get("Events_"+decay_mode+"_"+SignalRegion+"JESDown_S"+TString(stop)+"_N"+TString(neut));
          TH1D* signalGEN = (TH1D*)sig.Get("Events_NGenSignal_S"+TString(stop)+"_N"+TString(neut));
      		
      	  TFile datafile("ntp_8/data.root");
          TH1D* datahist= (TH1D*)datafile.Get("Events_"+decay_mode+"_"+SignalRegion+"_S0_N0");

          double nsignal = signal->Integral();
          double nsignal_RAW = signal->GetEntries();
          double nsignalBVetoBCUp = signalBVetoBCUp->Integral();
          double nsignalBVetoBCDown = signalBVetoBCDown->Integral();
          double nsignalBVetoLightUp = signalBVetoLightUp->Integral();
          double nsignalBVetoLightDown = signalBVetoLightDown->Integral();
          double nsignalJESUp = signalJESUp->Integral();
          double nsignalJESDown = signalJESDown->Integral();
          double totalsignal = signalGEN->GetMean();

	  	  double bkg = 0.; 
          double bkg_err = 0.; 
          double bkg_err_percentage = 0.; 

      	  double ndata = datahist->Integral();


	  if (decay_mode == "T2bw025") {

		if (SignalRegion == "offShell") {
		  bkg = backgroundPrediction_cutAndCount_T2bw025_offShell().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw025_offShell().second ; 
		  }

		if (SignalRegion == "lowMasses") {
		  bkg = backgroundPrediction_cutAndCount_T2bw025_lowMasses().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw025_lowMasses().second ; 
		  }

		if (SignalRegion == "highMasses") {
		  bkg = backgroundPrediction_cutAndCount_T2bw025_highMasses().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw025_highMasses().second ; 
		  }

	  }



	  else if (decay_mode == "T2bw050") {

		if (SignalRegion == "offShell") {
		  bkg = backgroundPrediction_cutAndCount_T2bw050_offShell().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw050_offShell().second ; 
		  }

		if (SignalRegion == "lowMasses") {
		  bkg = backgroundPrediction_cutAndCount_T2bw050_lowMasses().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw050_lowMasses().second ; 
		  }

		if (SignalRegion == "mediumDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2bw050_mediumDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw050_mediumDeltaM().second ; 
		  }

		if (SignalRegion == "highDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2bw050_highDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw050_highDeltaM().second ; 
		  }

	  }



	   if (decay_mode == "T2bw075") {


		if (SignalRegion == "lowDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2bw075_lowDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw075_lowDeltaM().second ; 
		  }

		if (SignalRegion == "mediumDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2bw075_mediumDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw075_mediumDeltaM().second ; 
		  }

		if (SignalRegion == "highDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2bw075_highDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2bw075_highDeltaM().second ; 
		  }

	  }



	  else if (decay_mode == "T2tt") {

		if (SignalRegion == "offShellLoose") {
		  bkg = backgroundPrediction_cutAndCount_T2tt_offShellLoose().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2tt_offShellLoose().second ; 
		  }

		if (SignalRegion == "offShellTight") {
		  bkg = backgroundPrediction_cutAndCount_T2tt_offShellTight().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2tt_offShellTight().second ; 
		  }

		if (SignalRegion == "lowDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2tt_lowDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2tt_lowDeltaM().second ; 
		  }

		if (SignalRegion == "mediumDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2tt_mediumDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2tt_mediumDeltaM().second ; 
		  }

		if (SignalRegion == "highDeltaM") {
		  bkg = backgroundPrediction_cutAndCount_T2tt_highDeltaM().first  ; 
		  bkg_err = backgroundPrediction_cutAndCount_T2tt_highDeltaM().second ; 
		  }

	  }




          bkg_err_percentage = (bkg_err / bkg) + 1. ;

          double JESUp = 100 * fabs((nsignal - nsignalJESUp ))/nsignal;
          double JESDown = 100 * fabs((nsignal - nsignalJESDown ))/nsignal;
          double JEStot =  (JESUp + JESDown)/ 2.;
          double BVetoBCUp = 100 * fabs((nsignal - nsignalBVetoBCUp ))/nsignal;
          double BVetoBCDown = 100 * fabs((nsignal - nsignalBVetoBCDown ))/nsignal;
          double BVetoBCtot =  (BVetoBCUp + BVetoBCDown)/ 2.;
          double BVetoLightUp = 100 * fabs((nsignal - nsignalBVetoLightUp ))/nsignal;
          double BVetoLightDown = 100 * fabs((nsignal - nsignalBVetoLightDown ))/nsignal;
          double BVetoLighttot =  (BVetoLightUp + BVetoLightDown)/ 2. ;
          double BVetoBCtot =  (BVetoBCUp + BVetoBCDown)/ 2. ;
          double BVetotot = sqrt (BVetoBCtot*BVetoBCtot + BVetoLighttot*BVetoLighttot);

		  double stat_err_a = 1 /nsignal_RAW + 1 / totalsignal;
		  double stat_err_b = 1 /(sqrt(nsignal_RAW * totalsignal));
	      double stat_err;
		  if (stat_err_b > stat_err_a) stat_err = 100 * sqrt(stat_err_a);
			else stat_err = 100 * sqrt(stat_err_a - stat_err_b);

		  TFile PDF_err_file("PDFUncertainties/"+decay_mode+"_presel.root");
		  TH2D* PDF_err_hist= (TH2D*)PDF_err_file.Get("twodplot");
		  int max_binX = PDF_err_hist->GetXaxis()->FindBin(MSTOP);
	      int max_binY = PDF_err_hist->GetYaxis()->FindBin(MLSP);
	  	  double PDF_err = PDF_err_hist->GetBinContent(max_binX,max_binY);

		  if (PDF_err > 25.) PDF_err = 20.;
		  if (PDF_err == 0) PDF_err = 10.;
		  if (PDF_err != PDF_err) PDF_err = 10.;

          if (JEStot > 20.) JEStot = 20.;       // put upper bound on JES uncertainty
          if (BVetotot > 10.) BVetotot = 10.;     // put upper bound on JES uncertainty
          if (stat_err != stat_err) stat_err = 0.;

          double tot_err = sqrt(stat_err*stat_err + BVetotot*BVetotot + JEStot*JEStot + 3*3 + 5*5 + 2.2*2.2 + PDF_err*PDF_err);
		  double sig_err_percentage = tot_err/100. + 1.;

          createTableCLsCNC(decay_mode, SignalRegion, MSTOP, MLSP, ndata, nsignal, sig_err_percentage, bkg, bkg_err_percentage);

}
Пример #20
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());

}
Пример #21
0
void recenter()
{
  TFile* f = new TFile("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/outputs_312/HIData_Minbias_2760GeV/merged/chargedepcorr_cent4050_pttrg033_ptassallweight_etaass445_eff0_bin03_v20.root");
//  TFile* f = new TFile("/net/hisrv0001/home/davidlw/OSG_CMSSW/CMSSW_5_3_20/src/FlowCorrAna/DiHadronCorrelationAnalyzer/cfg/chargedepcorr_recenter.root");
//  TFile* f = new TFile("/net/hisrv0001/home/davidlw/scratch1/DiHadronCorrelations/outputs_312/HydjetReco_Minbias_2760GeV/merged/chargedepcorr_recenter_mc_cent080_pttrg033_ptassallweight_etaass445_eff0_v16.root");

  const int ntrg = 1;
  const int MAXETATRGBINSPT = 16;
  TString dirname("chargedepcorr_ana_HI");

  TH1D* hSumNTrgPos[ntrg];
  TH1D* hSumNTrgNeg[ntrg];
  TH1D* hSumNCosTrgPos[ntrg];
  TH1D* hSumNCosTrgNeg[ntrg];
  TH1D* hSumNSinTrgPos[ntrg];
  TH1D* hSumNSinTrgNeg[ntrg];
  TH1D* hSumNCos2TrgPos[ntrg];
  TH1D* hSumNCos2TrgNeg[ntrg];
  TH1D* hSumNSin2TrgPos[ntrg];
  TH1D* hSumNSin2TrgNeg[ntrg];
  TH1D* hSumTrgPos[MAXETATRGBINSPT][ntrg];
  TH1D* hSumTrgNeg[MAXETATRGBINSPT][ntrg];
  TH1D* hSumCosTrgPos[MAXETATRGBINSPT][ntrg];
  TH1D* hSumSinTrgPos[MAXETATRGBINSPT][ntrg];
  TH1D* hSumCosTrgNeg[MAXETATRGBINSPT][ntrg];
  TH1D* hSumSinTrgNeg[MAXETATRGBINSPT][ntrg];
  TH1D* hSumCos2TrgPos[MAXETATRGBINSPT][ntrg];
  TH1D* hSumSin2TrgPos[MAXETATRGBINSPT][ntrg];
  TH1D* hSumCos2TrgNeg[MAXETATRGBINSPT][ntrg];
  TH1D* hSumSin2TrgNeg[MAXETATRGBINSPT][ntrg]; 

  TH1D* hSumAssFor = (TH1D*)f->Get(Form("%s/sumassfor",dirname.Data()));
  TH1D* hSumAssBak = (TH1D*)f->Get(Form("%s/sumassbak",dirname.Data()));
  TH1D* hSumCosAssFor = (TH1D*)f->Get(Form("%s/sumcosassfor",dirname.Data())); 
  TH1D* hSumSinAssFor = (TH1D*)f->Get(Form("%s/sumsinassfor",dirname.Data())); 
  TH1D* hSumCosAssBak = (TH1D*)f->Get(Form("%s/sumcosassbak",dirname.Data())); 
  TH1D* hSumSinAssBak = (TH1D*)f->Get(Form("%s/sumsinassbak",dirname.Data())); 
  TH1D* hSumCos2AssFor = (TH1D*)f->Get(Form("%s/sumcos2assfor",dirname.Data()));
  TH1D* hSumSin2AssFor = (TH1D*)f->Get(Form("%s/sumsin2assfor",dirname.Data()));
  TH1D* hSumCos2AssBak = (TH1D*)f->Get(Form("%s/sumcos2assbak",dirname.Data()));
  TH1D* hSumSin2AssBak = (TH1D*)f->Get(Form("%s/sumsin2assbak",dirname.Data()));

  for(int itrg=0;itrg<ntrg;itrg++)
  {
    hSumNTrgPos[itrg] = new TH1D(Form("sumntrgpos_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNTrgNeg[itrg] = new TH1D(Form("sumntrgneg_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNCosTrgPos[itrg] = new TH1D(Form("sumncostrgpos_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNCosTrgNeg[itrg] = new TH1D(Form("sumncostrgneg_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNSinTrgPos[itrg] = new TH1D(Form("sumnsintrgpos_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNSinTrgNeg[itrg] = new TH1D(Form("sumnsintrgneg_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNCos2TrgPos[itrg] = new TH1D(Form("sumncos2trgpos_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNCos2TrgNeg[itrg] = new TH1D(Form("sumncos2trgneg_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNSin2TrgPos[itrg] = new TH1D(Form("sumnsin2trgpos_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);
    hSumNSin2TrgNeg[itrg] = new TH1D(Form("sumnsin2trgneg_pt%d",itrg),";#eta",MAXETATRGBINSPT+2,-2.4-4.8/MAXETATRGBINSPT,2.4+4.8/MAXETATRGBINSPT);

    for(int ll=0;ll<MAXETATRGBINSPT;ll++)
    {
      hSumTrgPos[ll][itrg] = (TH1D*)f->Get(Form("%s/sumtrgpos_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumTrgNeg[ll][itrg] = (TH1D*)f->Get(Form("%s/sumtrgneg_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumCosTrgPos[ll][itrg] = (TH1D*)f->Get(Form("%s/sumcostrgpos_eta%d_pt%d",dirname.Data(),ll,itrg));  
      hSumSinTrgPos[ll][itrg] = (TH1D*)f->Get(Form("%s/sumsintrgpos_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumCosTrgNeg[ll][itrg] = (TH1D*)f->Get(Form("%s/sumcostrgneg_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumSinTrgNeg[ll][itrg] = (TH1D*)f->Get(Form("%s/sumsintrgneg_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumCos2TrgPos[ll][itrg] = (TH1D*)f->Get(Form("%s/sumcos2trgpos_eta%d_pt%d",dirname.Data(),ll,itrg));  
      hSumSin2TrgPos[ll][itrg] = (TH1D*)f->Get(Form("%s/sumsin2trgpos_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumCos2TrgNeg[ll][itrg] = (TH1D*)f->Get(Form("%s/sumcos2trgneg_eta%d_pt%d",dirname.Data(),ll,itrg));
      hSumSin2TrgNeg[ll][itrg] = (TH1D*)f->Get(Form("%s/sumsin2trgneg_eta%d_pt%d",dirname.Data(),ll,itrg));

      hSumNTrgPos[itrg]->SetBinContent(ll+2,hSumTrgPos[ll][itrg]->GetMean());
      hSumNTrgPos[itrg]->SetBinError(ll+2,hSumTrgPos[ll][itrg]->GetMeanError());
      hSumNTrgNeg[itrg]->SetBinContent(ll+2,hSumTrgNeg[ll][itrg]->GetMean());
      hSumNTrgNeg[itrg]->SetBinError(ll+2,hSumTrgNeg[ll][itrg]->GetMeanError());
      hSumNCosTrgPos[itrg]->SetBinContent(ll+2,hSumCosTrgPos[ll][itrg]->GetMean());
      hSumNCosTrgPos[itrg]->SetBinError(ll+2,hSumCosTrgPos[ll][itrg]->GetMeanError());
      hSumNSinTrgPos[itrg]->SetBinContent(ll+2,hSumSinTrgPos[ll][itrg]->GetMean());
      hSumNSinTrgPos[itrg]->SetBinError(ll+2,hSumSinTrgPos[ll][itrg]->GetMeanError());
      hSumNCosTrgNeg[itrg]->SetBinContent(ll+2,hSumCosTrgNeg[ll][itrg]->GetMean());
      hSumNCosTrgNeg[itrg]->SetBinError(ll+2,hSumCosTrgNeg[ll][itrg]->GetMeanError());
      hSumNSinTrgNeg[itrg]->SetBinContent(ll+2,hSumSinTrgNeg[ll][itrg]->GetMean());
      hSumNSinTrgNeg[itrg]->SetBinError(ll+2,hSumSinTrgNeg[ll][itrg]->GetMeanError());
      hSumNCos2TrgPos[itrg]->SetBinContent(ll+2,hSumCos2TrgPos[ll][itrg]->GetMean());
      hSumNCos2TrgPos[itrg]->SetBinError(ll+2,hSumCos2TrgPos[ll][itrg]->GetMeanError());
      hSumNSin2TrgPos[itrg]->SetBinContent(ll+2,hSumSin2TrgPos[ll][itrg]->GetMean());
      hSumNSin2TrgPos[itrg]->SetBinError(ll+2,hSumSin2TrgPos[ll][itrg]->GetMeanError());
      hSumNCos2TrgNeg[itrg]->SetBinContent(ll+2,hSumCos2TrgNeg[ll][itrg]->GetMean());
      hSumNCos2TrgNeg[itrg]->SetBinError(ll+2,hSumCos2TrgNeg[ll][itrg]->GetMeanError());
      hSumNSin2TrgNeg[itrg]->SetBinContent(ll+2,hSumSin2TrgNeg[ll][itrg]->GetMean());
      hSumNSin2TrgNeg[itrg]->SetBinError(ll+2,hSumSin2TrgNeg[ll][itrg]->GetMeanError());      
    }
    hSumNTrgPos[itrg]->SetBinContent(1,hSumAssFor->GetMean());
    hSumNTrgPos[itrg]->SetBinError(1,hSumAssFor->GetMeanError());
    hSumNTrgNeg[itrg]->SetBinContent(1,hSumAssFor->GetMean());
    hSumNTrgNeg[itrg]->SetBinError(1,hSumAssFor->GetMeanError());
    hSumNTrgPos[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumAssBak->GetMean());
    hSumNTrgPos[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumAssBak->GetMeanError());
    hSumNTrgNeg[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumAssBak->GetMean());
    hSumNTrgNeg[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumAssBak->GetMeanError());
    hSumNCosTrgPos[itrg]->SetBinContent(1,hSumCosAssFor->GetMean());
    hSumNCosTrgPos[itrg]->SetBinError(1,hSumCosAssFor->GetMeanError());
    hSumNCosTrgPos[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumCosAssBak->GetMean());
    hSumNCosTrgPos[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumCosAssBak->GetMeanError());
    hSumNSinTrgPos[itrg]->SetBinContent(1,hSumSinAssFor->GetMean());
    hSumNSinTrgPos[itrg]->SetBinError(1,hSumSinAssFor->GetMeanError());
    hSumNSinTrgPos[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumSinAssBak->GetMean());
    hSumNSinTrgPos[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumSinAssBak->GetMeanError());
    hSumNCosTrgNeg[itrg]->SetBinContent(1,hSumCosAssFor->GetMean());
    hSumNCosTrgNeg[itrg]->SetBinError(1,hSumCosAssFor->GetMeanError());
    hSumNCosTrgNeg[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumCosAssBak->GetMean());
    hSumNCosTrgNeg[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumCosAssBak->GetMeanError());
    hSumNSinTrgNeg[itrg]->SetBinContent(1,hSumSinAssFor->GetMean());
    hSumNSinTrgNeg[itrg]->SetBinError(1,hSumSinAssFor->GetMeanError());
    hSumNSinTrgNeg[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumSinAssBak->GetMean());
    hSumNSinTrgNeg[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumSinAssBak->GetMeanError());
    hSumNCos2TrgPos[itrg]->SetBinContent(1,hSumCos2AssFor->GetMean());
    hSumNCos2TrgPos[itrg]->SetBinError(1,hSumCos2AssFor->GetMeanError());
    hSumNCos2TrgPos[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumCos2AssBak->GetMean());
    hSumNCos2TrgPos[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumCos2AssBak->GetMeanError());
    hSumNSin2TrgPos[itrg]->SetBinContent(1,hSumSin2AssFor->GetMean());
    hSumNSin2TrgPos[itrg]->SetBinError(1,hSumSin2AssFor->GetMeanError());
    hSumNSin2TrgPos[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumSin2AssBak->GetMean());
    hSumNSin2TrgPos[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumSin2AssBak->GetMeanError());
    hSumNCos2TrgNeg[itrg]->SetBinContent(1,hSumCos2AssFor->GetMean());
    hSumNCos2TrgNeg[itrg]->SetBinError(1,hSumCos2AssFor->GetMeanError());
    hSumNCos2TrgNeg[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumCos2AssBak->GetMean());
    hSumNCos2TrgNeg[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumCos2AssBak->GetMeanError());
    hSumNSin2TrgNeg[itrg]->SetBinContent(1,hSumSin2AssFor->GetMean());
    hSumNSin2TrgNeg[itrg]->SetBinError(1,hSumSin2AssFor->GetMeanError());
    hSumNSin2TrgNeg[itrg]->SetBinContent(MAXETATRGBINSPT+2,hSumSin2AssBak->GetMean());
    hSumNSin2TrgNeg[itrg]->SetBinError(MAXETATRGBINSPT+2,hSumSin2AssBak->GetMeanError());
  }
return;
  TFile* fout = new TFile("recenter_cent4050_pttrg033_etaass445_eff0_bin03.root","recreate");
//  TFile* fout = new TFile("recenter_mc_cent080_pttrg033_etaass445_eff0_bin03.root","recreate");
  for(int itrg=0;itrg<ntrg;itrg++)
  {
    hSumNTrgPos[itrg]->Write();
    hSumNTrgNeg[itrg]->Write();
    hSumNCosTrgPos[itrg]->Write();
    hSumNCosTrgNeg[itrg]->Write();
    hSumNSinTrgPos[itrg]->Write();
    hSumNSinTrgNeg[itrg]->Write();
    hSumNCos2TrgPos[itrg]->Write();
    hSumNCos2TrgNeg[itrg]->Write();
    hSumNSin2TrgPos[itrg]->Write();
    hSumNSin2TrgNeg[itrg]->Write();
  }
  fout->Close();
}
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());
}
Пример #23
0
/** 
 * 
 * 
 * @param o 
 * @param useWeights 
 * @param correct
 *
 * @ingroup pwglf_forward_scripts_tests
 */
void
TestPoisson(Double_t o=.3, bool useWeights=false, bool correct=true)
{
  const char* load = "$ALICE_PHYSICS/PWGLF/FORWARD/analysis2/scripts/LoadLibs.C";
  if (!gROOT->GetClass("AliAODForwardMult")) {
    gROOT->Macro(load);
    gROOT->GetInterpreter()->UnloadFile(gSystem->ExpandPathName(load));
  }
  
  // --- Parameters of this script -----------------------------------
  Int_t      nBin =  5;  // Our detector matrix size 
  Int_t      nMax = TMath::Max(Int_t(nBin * nBin * o + .5)+nBin/2,nBin);  
  Int_t      nEv  = 10000; // Number of events
  Double_t   mp   = o;   // The 'hit' probability 


  TH2D* base = new TH2D("base", "Basic histogram", 
			nBin,-.5, nBin-.5, nBin, -.5, nBin-.5);
  base->SetXTitle("#eta");
  base->SetYTitle("#varphi");
  base->SetDirectory(0);
  base->SetOption("colz");

  Int_t tN1=nMax;    Double_t tMin1; Double_t tMax1;
  Int_t tN2=nMax*10; Double_t tMin2; Double_t tMax2=nMax;
  MakeIntegerAxis(tN1, tMin1, tMax1);
  MakeIntegerAxis(tN2, tMin2, tMax2);
  TH2D* corr = new TH2D("comp", "Comparison", 
			tN1, tMin1, tMax1, tN2, tMin2, tMax2);
  corr->SetXTitle("Input");
  corr->SetYTitle("Poisson");
  corr->SetDirectory(0);
  corr->SetOption("colz");
  corr->SetStats(0);
  TLine* lcorr = new TLine(0, 0, tMax2, tMax2);

  Int_t mm = TMath::Max(Int_t(nBin * o + .5),nBin/2);
  tN2=mm*10; tMax2 = mm;
  MakeIntegerAxis(tN2, tMin2, tMax2);
  Info("", "Making mean w/nbins=%d,range=[%f,%f]", tN2, tMin2, tMax2);
  TH2D* mean = new TH2D("mean", "Mean comparison", 
			tN2, tMin2, tMax2, tN2, tMin2, tMax2);
  mean->SetXTitle("Input");
  mean->SetYTitle("Poisson");
  mean->SetDirectory(0);
  mean->SetOption("colz");
  mean->SetStats(0);
  TLine* lmean = new TLine(tMin2, tMin2, tMax2, tMax2);

  TH1D* dist = new TH1D("dist", "Distribution of hits", tN1, tMin1, tMax1);
  dist->SetXTitle("s");
  dist->SetYTitle("P(s)");
  dist->SetFillColor(kRed+1);
  dist->SetFillStyle(3001);
  dist->SetDirectory(0);

  TH1D* diff = new TH1D("diff", "P-T", 100, -25, 25);
  diff->SetXTitle("Difference");
  diff->SetFillColor(kRed+1);
  diff->SetFillStyle(3001);
  diff->SetYTitle("Prob");

  AliPoissonCalculator* c = new AliPoissonCalculator("ignored");
  c->Init(nBin ,nBin);

  for (Int_t i = 0; i < nEv; i++) { 
    c->Reset(base);
    base->Reset();

    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	// Throw a die 
	Int_t m = gRandom->Poisson(mp);
	dist->Fill(m);

	// Fill into our base histogram 
	base->Fill(iEta, iPhi, m);

	// Fill into poisson calculator 
	c->Fill(iEta, iPhi, m > 0, (useWeights ? m : 1));
      }
    }
    // Calculate the result 
    TH2D* res = c->Result(correct);
    
    // Now loop and compare 
    Double_t mBase = 0;
    Double_t mPois = 0;
    for (Int_t iEta = 0; iEta < nBin; iEta++) { 
      for (Int_t iPhi = 0; iPhi < nBin; iPhi++) { 
	Double_t p = res->GetBinContent(iEta, iPhi);
	Double_t t = base->GetBinContent(iEta, iPhi);

	mBase += t;
	mPois += p;
	corr->Fill(t, p);
	diff->Fill(p-t);
      }
    }
    Int_t nn = nBin * nBin;
    mean->Fill(mBase / nn, mPois / nn);
  }

  TCanvas* cc = new TCanvas("c", "c", 900, 900);
  cc->SetFillColor(0);
  cc->SetFillStyle(0);
  cc->SetBorderMode(0);
  cc->SetRightMargin(0.02);
  cc->SetTopMargin(0.02);
  cc->Divide(2,2);
  
  TVirtualPad* pp = cc->cd(1);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  corr->Draw();
  lcorr->Draw();

  pp = cc->cd(2);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.02);
  pp->SetTopMargin(0.02);
#if 0
  c->GetMean()->Draw();
#elif 1 
  pp->SetLogy();
  diff->Draw();
#elif 1
  c->GetOccupancy()->Draw();
#else
  pp->SetLogy();
  dist->SetStats(0);
  dist->Scale(1. / dist->Integral());
  dist->Draw();
  TH1D* m1 = c->GetMean();
  m1->Scale(1. / m1->Integral());
  m1->Draw("same");
  Double_t eI;
  Double_t ii = 100 * dist->Integral(2, 0);
  TLatex* ll = new TLatex(.97, .85, 
			  Form("Input #bar{m}: %5.3f", mp));
  ll->SetNDC();
  ll->SetTextFont(132);
  ll->SetTextAlign(31);
  ll->Draw();
  ll->DrawLatex(.97, .75, Form("Result #bar{m}: %5.3f", dist->GetMean()));
  ll->DrawLatex(.97, .65, Form("Occupancy: #int_{1}^{#infty}P(s)ds = %6.2f%%",
			       ii));
			 
#endif

  pp = cc->cd(3);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetGridx();
  pp->SetGridy();
  c->GetCorrection()->Draw();

  pp = cc->cd(4);
  pp->SetFillColor(0);
  pp->SetFillStyle(0);
  pp->SetBorderMode(0);
  pp->SetRightMargin(0.15);
  pp->SetTopMargin(0.02);
  pp->SetLogz();
  pp->SetGridx();
  pp->SetGridy();
  mean->Draw();
  lmean->Draw();

  cc->cd();
}
Пример #24
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;
}
Пример #25
0
void plot_PIDs_weighted(){

    // Run this at the command line by doing
    // root -l sidebandSubtraction.C
    
    // Import formatting template
    gROOT->ProcessLine(".L ~/cern/scripts/lhcbStyle.C");


    // Definition of variables

    const std::string    filename_MC = "/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/Lb2chicpK_MC_2012_signal_cut.root";
    const std::string filename_weights = "/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/weighted_data_2012.root";
    const std::string         treename = "DecayTree";
    const std::string treename_weights = "ds";
    const std::string            yaxis = "Candidates";
  
    // Opening files and trees


    TFile* f_MC = TFile::Open( filename_MC.c_str() );
    if( !f_MC ) std::cout << "file " << filename_mc << " does not exist" << std::endl;
    
    TTree* t_MC = (TTree*)f_MC->Get( treename.c_str() );
    if( !t_MC ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    TFile* f_sw = TFile::Open( filename_weights.c_str() );
    if( !f_sw ) std::cout << "file " << filename_weights << " does not exist" << std::endl;
    
    TTree* t_sw = (TTree*)f_sw->Get( treename_weights.c_str() );
    if( !t_sw ) std::cout << "tree " << treename_weights << " does not exist" << std::endl;
    

    
    // Including the LHCb name, formatting
    lhcbName = new TPaveText(gStyle->GetPadLeftMargin() + 0.03,
            0.87 - gStyle->GetPadTopMargin(),
            gStyle->GetPadLeftMargin() + 0.13,
            0.95 - gStyle->GetPadTopMargin(),
            "BRNDC");
    lhcbName->AddText("LHCb");
    lhcbName->SetFillColor(0);
    lhcbName->SetTextAlign(12);
    lhcbName->SetBorderSize(0);

    gStyle->SetOptStat(0);	

    // Defining histograms, drawing, for proton

    TH1D* h1_p = new TH1D ("h1_p", "proton_ProbNNpcorr", 20, 0., 1.);
    TH1D* h2_p = new TH1D ("h2_p", "proton_ProbNNp", 20, 0., 1.);    
    TH1D* h3_p = new TH1D ("h3_p", "proton_ProbNNp", 20, 0., 1.);
 	
    t_MC->Draw("proton_ProbNNpcorr>>h1_p", "", "goff");
    t_sw->Draw("proton_ProbNNp>>h2_p", "sigYield_sw", "goff");   
    t_MC->Draw("proton_ProbNNp>>h3_p", "", "goff");


    // Defining histograms, drawing, for kaon
    TH1D* h1_k = new TH1D ("h1_k", "kaon_ProbNNkcorr", 20, 0., 1.);
    TH1D* h2_k = new TH1D ("h2_k", "kaon_ProbNNk", 20, 0., 1.);    
    TH1D* h3_k = new TH1D ("h3_k", "kaon_ProbNNk", 20, 0., 1.);

    t_MC->Draw("kaon_ProbNNkcorr>>h1_k", "", "goff"); 	
    t_sw->Draw("kaon_ProbNNk>>h2_k", "sigYield_sw", "goff");
    t_MC->Draw("kaon_ProbNNk>>h3_k", "", "goff");

/*    
    // Plotting the results of the signal selection
    TCanvas* c1 = new TCanvas("c1");
    c1->Divide(1,1);
    c1->cd(1);

    h1->Draw();
    h1->GetXaxis()->SetTitle("proton_ProbNNp");
    h2->GetYaxis()->SetTitle( yaxis.c_str() );
    lhcbName->Draw();
    
    c1->SaveAs("~/cern/plots/signal_region_proton_ProbNNp.png");

    // Plotting the results of the sideband selection
    TCanvas* c2 = new TCanvas("c2");
    c2->Divide(1,1);
    c2->cd(1);

    h2->Draw();
    h2->GetXaxis()->SetTitle("proton_ProbNNp");
    h2->GetYaxis()->SetTitle( yaxis.c_str() );
    lhcbName->Draw();

    c2->SaveAs("~/cern/plots/sideband_region_proton_ProbNNp.png");
*/



    // Scaling the sideband histo to the signal histo, and subtracting, for proton
    //h_sb_p->Scale(0.5);
    //h_sg_p->Add(h_sb_p, -1);

    // Scaling the Monte Carlo data
    int NMC = t_MC->GetEntries();
    int Ndata = t_sw->GetEntries();  

    TH1D* yield = new TH1D ("yield", "sigYield_sw", 25, -10., 10.);
    t_sw->Draw("sigYield_sw>>yield", "", "goff");
    double signal = yield->GetMean() * yield->GetEntries();
    
    h1_p->Scale( signal / double(NMC));
    h3_p->Scale( signal / double(NMC));


    // Plotting the results of the sideband subtraction alongside the scaled MC data, for proton
    h2_p->Sumw2();
    h2_p->SetMarkerStyle(20);
    h2_p->SetMarkerColor(1);
    h1_p->SetMarkerColor(kRed);
    h1_p->SetLineColor(kRed);
    h3_p->SetMarkerColor(8);
    h3_p->SetLineColor(8);     

    TCanvas* c_p = new TCanvas("c_p");
    c_p->Divide(1,1);
    c_p->cd(1);
    
    h3_p->Draw();
    h2_p->Draw("same");
    h1_p->Draw("same");
    h3_p->GetXaxis()->SetTitle("2012 proton_ProbNNp");	
    h3_p->GetYaxis()->SetTitle( yaxis.c_str() );
    //lhcbName->Draw();


    leg1 = new TLegend(0.15,0.65,0.4,0.85);
    leg1->SetHeader("#bf{Key:}");
    leg1->AddEntry(h1_p,"MC(corrected)","l");
    leg1->AddEntry(h3_p,"MC (uncorrected)","l");
    leg1->AddEntry(h2_p,"sWeighted data","p");
    leg1->Draw();

    c_p->SaveAs("~/cern/plots/sideband_subtractions/2012_proton_ProbNNp_sweights_PID-corrected.png");


    // Scaling the sideband histo to the signal histo, and subtracting, for kaon
    //h_sb_k->Scale(0.5);
    //h_sg_k->Add(h_sb_k, -1);

    // Scaling the Monte Carlo data   
    int NMCk = t_MC->GetEntries();
    int Ndatak = t_sw->GetEntries();
    
    
    
    h1_k->Scale( signal / double(NMCk));
    h3_k->Scale( signal / double(NMCk));
    //h3_k->Scale(float(Ndata)/float(NMC_sw));
    //int new_NMC = h_un_p->GetEntries();




    // Plotting the results of the sideband subtraction alongside the scaled MC data, for kaon
    h2_k->Sumw2();
    h2_k->SetMarkerStyle(20);
    h2_k->SetMarkerColor(1);
    h1_k->SetMarkerColor(kRed);
    h1_k->SetLineColor(kRed);   
    h3_k->SetMarkerColor(8);
    h3_k->SetLineColor(8); 
    
    TCanvas* c_k = new TCanvas("c_k");
    c_k->Divide(1,1);
    c_k->cd(1);

    h3_k->Draw();
    h2_k->Draw("same");
    h1_k->Draw("same");
    h3_k->GetXaxis()->SetTitle("2012 kaon_ProbNNk");	
    h3_k->GetYaxis()->SetTitle( yaxis.c_str() );
    //lhcbName->Draw();


    leg2 = new TLegend(0.15,0.65,0.4,0.85);
    leg2->SetHeader("#bf{Key:}");
    leg2->AddEntry(h1_k,"MC(corrected)","l");
    leg2->AddEntry(h3_k,"MC (uncorrected)","l");
    leg2->AddEntry(h2_k,"sWeighted data","p");
    leg2->Draw();

    c_k->SaveAs("~/cern/plots/sideband_subtractions/2012_kaon_ProbNNk_sweights_PID-corrected.png");
  
    
    
std::cout << "\n" << signal << " signal events" << std::endl;
std::cout << "\n" << NMC << "  Monte Carlo events" << "\n" << std::endl;
//std::cout << new_NMC << std::endl;
}
Пример #26
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();
	
}
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();

  

 
} 
Пример #28
0
double GetMeanpTtrg(int itrg)
{
		    TH1D* hpttrg = (TH1D*) gInputfile->Get(Form("%spt_trg_%d",subdir.Data(),itrg));
                    double pttrg = hpttrg->GetMean();
                    return pttrg;
}
Пример #29
0
void Getvn(int iangle1, int iangle2, bool usingCNTEP=0){
    TString str;
    int nrun = GetTotalRun();
    std::cout<<"Totally we have "<<nrun<<" runs/segments!"<<std::endl;
    FillGoodRun();
    std::cout<<"Filling Good run finished!"<<std::endl;

    if(nrun<0) exit(1);

     ofstream fout, foutraw, fout1, fout2;
     int iharE=0;
     if(nhar==1) iharE=1;
     TFile *fin;

    cout<<"iangle1 = "<<iangle1<<" iangle2 = "<<iangle2<<endl;

     for(int icent=0;icent<ncent;icent++){
      for(int ihar=0;ihar<nhar;ihar++){
       for(int isub=0;isub<nsub;isub++){
        int n = ihar+1.0+iharE;
        str = choosesub(isub);
        TString UseCNTEP;
        if(str=="ABORT") continue;
        if(usingCNTEP)
         UseCNTEP = "UseCNTEP";
        else
         UseCNTEP = "NoUseCNTEP";
        std::cout<<UseCNTEP<<std::endl;
        std::cout<<"starting doing "<<str<<" v"<<n<<" analysis!"<<std::endl;
         fout1.open(Form("Result/%s/res_%d%d_%d_%d_%s.dat",UseCNTEP.Data(),iangle1,iangle2,n,icent,str.Data())); //using str as event plane detector
         fout2.open(Form("Result/%s/psi_%d%d_%d_%d_%s.dat",UseCNTEP.Data(),iangle1,iangle2,n,icent,str.Data())); //using str as event plane detector
         float reso = GetReso(iangle1, iangle2, icent,ihar,isub,usingCNTEP);
         fout1<<reso<<std::endl;
         if(reso<=0) {std::cout<<"resolution is wrong!"<<std::endl; reso = 1.0;}
        for(int irun=0;irun<nrun;irun++){
         fout2<<GetRun(irun)<<" "<<GoodRunFit[icent][ihar][isub][irun]<<std::endl;
        }
         TH1D* hvobsall = new TH1D(Form("hvobsall_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),Form("hvobsall_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),60,0,6);
         TH1D* hvobsallsq = new TH1D(Form("hvobsallsq_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),Form("hvobsallsq_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),60,0,6);
         TH1D* hvobs2all = new TH1D(Form("hvobs2all_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),Form("hvobs2all_%d%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub),60,0,6);

        for(int iphi=0;iphi<nphi+1;iphi++){
         TH1D* hvobs = new TH1D(Form("hvobs_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),Form("hvobs_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),60,0,6);
         TH1D* hvobssq = new TH1D(Form("hvobssq_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),Form("hvobssq_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),60,0,6);
         TH1D* hvobs2 = new TH1D(Form("hvobs2_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),Form("hvobs2_%d%d_%d_%d_%d_%d",iangle1,iangle2,icent,ihar,isub,iphi),60,0,6);
         string phistr = (iphi==0)?"_east":"_west";
         if(iphi==nphi) phistr = "";
         cout<<"open v2 file"<<endl;
         fout.open(Form("Result/%s/v%d_%d%d_%d%s_%s.dat",UseCNTEP.Data(),n,iangle1,iangle2,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         cout<<"open v2raw file"<<endl;
         foutraw.open(Form("Result/%s/v%draw_%d%d_%d%s_%s.dat",UseCNTEP.Data(),n,iangle1,iangle2,icent,phistr.c_str(),str.Data())); //using str as event plane detector
         if(iphi<nphi){
        for(int irun=0;irun<nrun;irun++){
         //std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<irun<<" "<<phistr<<std::endl;
         fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/%s%s/%d/data/%s.root",dataset.Data(),pro.Data(),taxi,GetRun(irun).Data()));
         if(!(GoodRunFit[icent][ihar][isub][irun]>0.2 && GoodRunFit[icent][ihar][isub][irun]<3.0)){
         std::cout<<"cent = "<<icent<<"; n = "<<n<<" ;isub = "<<str<<" ;run = "<<GetRun(irun)<<" is bad run!"<<std::endl;
         fin->Close();
        continue;
         }
         TProfile* hvobstemp = (TProfile*)fin->Get(Form("vobs%s_%d_%d_%d_%d_%d",str.Data(),iangle1,iangle2,icent,ihar,iphi));
         TProfile* hvobssqtemp = (TProfile*)fin->Get(Form("vobs%ssq_%d_%d_%d_%d_%d",str.Data(),iangle1,iangle2,icent,ihar,iphi));
         TH1D* hvobssumtemp = (TH1D*)hvobstemp->ProjectionX(Form("vobssum%s_%d_%d_%d",str.Data(),icent,ihar,iphi),"W");
         TH1D* hvobssqsumtemp = (TH1D*)hvobssqtemp->ProjectionX(Form("vobssqsum%s_%d_%d_%d",str.Data(),icent,ihar,iphi),"W"); //Add weighted v2
         TH1D* hvobssum2temp = (TH1D*)hvobstemp->ProjectionX(Form("vobssum2%s_%d_%d_%d",str.Data(),icent,ihar,iphi),"B");//Add Entries
         hvobs->Add(hvobssumtemp);
         hvobssq->Add(hvobssqsumtemp);
         hvobs2->Add(hvobssum2temp);
         fin->Close();
        }
         }
        hvobsall->Add(hvobs);
        hvobsallsq->Add(hvobssq);
        hvobs2all->Add(hvobs2);
        if(iphi==nphi){
        hvobs = hvobsall;
        hvobssq = hvobsallsq;
        hvobs2 = hvobs2all;
        }
         for(int ipt=0;ipt<npt-1;ipt++){
             int xbinmin = hvobs->GetXaxis()->FindBin(ptbin[ipt]+eps);
             int xbinmax = hvobs->GetXaxis()->FindBin(ptbin[ipt+1]-eps);
           //  std::cout<<xbinmin<<" "<<xbinmax<<std::endl;
           //  std::cout<<ptbin[ipt]<<" "<<ptbin[ipt+1]<<std::endl;
           // TH1F* hvobsProj = (TH1F*)hvobs->ProjectionY(Form("hvobsProj_%d",ipt),xbinmin,xbinmax);
           // TH1F* hvobssqProj = (TH1F*)hvobssq->ProjectionY(Form("hvobssqProj_%d",ipt),xbinmin,xbinmax);
            float Ntracks = hvobs2->Integral(xbinmin,xbinmax);
            float vobs = hvobs->Integral(xbinmin,xbinmax)/Ntracks;
            float vobssq = hvobssq->Integral(xbinmin,xbinmax)/Ntracks;
           // float vobssq = hvobssqProj->GetMean();
            float v = vobs/reso;
//            float verr = hvobsProj->GetRMS()/reso/sqrt(Ntracks);
            float verr = sqrt(vobssq-vobs*vobs)/reso/sqrt(Ntracks);
            TH1D* hvobsclone = (TH1D*)hvobs2->Clone("hvobsclone");
            hvobsclone->GetXaxis()->SetRangeUser(ptbin[ipt],ptbin[ipt+1]);
            float pt = hvobsclone->GetMean();
            fout<<pt<<" "<<v<<" "<<verr<<" "<<std::endl;
            foutraw<<pt<<" "<<vobs<<" "<<verr*reso<<" "<<std::endl;
         }
        fout.close();
        foutraw.close();
         }
        fout1.close();
        fout2.close();
        }
        }
     }

}
Пример #30
0
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();
}