void LongiProfile(int E, std::string runPeriod)
{
  char inputFile[200];
  sprintf(inputFile,"%s%d%s","/lyoserv/home/ilc/steen/resultRootFile/tb_data/DHCAL_",Run(E,runPeriod),".root");
  std::cout << "inputFile = " << inputFile << std::endl;
  PionTimeCalibration* timeCalib=new PionTimeCalibration(inputFile);
  timeCalib->ShowerBarycenterCut(runPeriod);
  timeCalib->Loop();
  
  std::cout<< timeCalib->longitudinalVec.size()<<std::endl;
  TF1 *func;
  char outputFile[200];
  sprintf(outputFile,"%s%d%s","/home/steen/timeCalib/LongiProfile/calib_",Run(E,runPeriod),".txt");
  fstream out;
  out.open(outputFile,ios::out);
  for(unsigned int k=0; k<48; k++){
    TH2D* hRadPro=new TH2D("hName","",100,0,10,4000,0,200);
    func=new TF1("func","pol2",0,10);
    for(unsigned int i=0; i<timeCalib->nhit1.size(); i++){
      hRadPro->Fill(timeCalib->time.at(i),timeCalib->longitudinalVec.at(i).layer[k]);
    }
    hRadPro->ProfileX()->Fit(func,"NQ");
    out << k 
	<< " " << func->GetParameter(0) << " " << func->GetParError(0) 
	<< " " << func->GetParameter(1) << " " << func->GetParError(1)
	<< " " << func->GetParameter(2) << " " << func->GetParError(2)
	<< " " << func->GetChisquare()/func->GetNDF() << std::endl;
    delete hRadPro;
  }
  out.close();
  delete func;
  delete timeCalib;
}
Exemple #2
0
/************************************************************
*  Fit ADC spectrum
************************************************************/
int FitAdcHist(TH1F *h, float data[NDATA], const int print ) {
  TF1 *fadc;
  TPaveText *adcPT;

  // Protect for null histograms
  if( h == 0 || h->GetEntries()<1000. ) return -1;
  printf("Fitting %s\n",h->GetName());

  gStyle->SetOptStat("emr"); 
  adcPT = new TPaveText(0.58,0.315,0.98,0.635,"NDC");

//  Refit ADC
  Double_t n    = h->GetEntries();
  Double_t rms  = h->GetRMS();
  Double_t mean = h->GetMean();
  Double_t ymin = mean-2*rms;
  if( ymin < 60. ) ymin=60.;
  Double_t ymax = mean+1.5*rms;
  fadc = new TF1("adc_fun",skewnormal,ymin,ymax,4);
  fadc->SetParameters(n,mean,rms,1.5);
  fadc->SetParLimits(1,mean-rms,mean+0.5*rms);
  fadc->SetParLimits(2,rms*0.5,rms*1.5);
  fadc->SetParLimits(3,1.,4.);
  h->Fit("adc_fun","r"); 
//  If skew is too high refit with fixed skew
  if( fadc->GetParameter(3) > 2.5 ) {
    printf("REFIT %s\n",h->GetName());
    fadc->SetParameter(3,1.6);
    fadc->SetParLimits(3,1.6,1.6);
    h->Fit("adc_fun","r") ;
  }
// if have enough hits use fit results  
  if( n > MINHITS ) {
    data[13] = fadc->GetParameter(1);
    data[14] = fadc->GetParError(1);
    data[15] = fadc->GetParameter(2);
    data[16] = fadc->GetParError(2);
    data[17] = fadc->GetParameter(3);
    data[18] = fadc->GetParError(3);
    double dof = fadc->GetNDF();
    if( dof > 0. ) data[19] = fadc->GetChisquare()/dof;
    adcPT->AddText(Form("Peak %.1lf #pm %.1lf",data[13],data[14]));
    adcPT->AddText(Form("Width %.1lf #pm %.1lf",data[15],data[16]));
    adcPT->AddText(Form("Skew %.2lf #pm %.2lf",	data[17],data[18]));
    if( dof > 0. ) adcPT->AddText(Form("#Chi^{2}/DoF     %.2lf",data[19]));
    adcPT->SetTextColor(2);
    adcPT->Draw();
// if have too few hits use fit stats instead of fit results  
  } else {
    data[12] = mean;
    data[13] = h->GetMeanError();
    data[14] = rms;
    data[15] = h->GetRMSError();
    data[16] = h->GetSkewness();
  }
  if( print ) c1->Print(Form("%s_%s.png",fname,h->GetName()));
  return 0;
}    //end FitAdcHist
	void FillFromFunction(TF1& infunc){
		norm = normscale * infunc.GetParameter(0);
		norm_err = normscale * infunc.GetParError(0);
		gamma = infunc.GetParameter(2);
		gamma_err = infunc.GetParError(2);
		ang = infunc.GetParameter(1);
		ang_err = infunc.GetParError(1);
		chi2 = infunc.GetChisquare();
		ndf = infunc.GetNDF();
	}
Exemple #4
0
TF1 *langaufit(TH1F *his, Double_t *fitrange, Double_t *startvalues, Double_t *parlimitslo, Double_t *parlimitshi, Double_t *fitparams, Double_t *fiterrors, Double_t *ChiSqr, Int_t *NDF)
{
   // Once again, here are the Landau * Gaussian parameters:
   //   par[0]=Width (scale) parameter of Landau density
   //   par[1]=Most Probable (MP, location) parameter of Landau density
   //   par[2]=Total area (integral -inf to inf, normalization constant)
   //   par[3]=Width (sigma) of convoluted Gaussian function
   //
   // Variables for langaufit call:
   //   his             histogram to fit
   //   fitrange[2]     lo and hi boundaries of fit range
   //   startvalues[4]  reasonable start values for the fit
   //   parlimitslo[4]  lower parameter limits
   //   parlimitshi[4]  upper parameter limits
   //   fitparams[4]    returns the final fit parameters
   //   fiterrors[4]    returns the final fit errors
   //   ChiSqr          returns the chi square
   //   NDF             returns ndf

   Int_t i;
   Char_t FunName[100];

   sprintf(FunName,"Fitfcn_%s",his->GetName());

   TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
   if (ffitold) delete ffitold;

   TF1 *ffit = new TF1(FunName,langaufun,fitrange[0],fitrange[1],4);
   ffit->SetParameters(startvalues);
   ffit->SetParNames("Width","MP","Area","GSigma");

   for (i=0; i<4; i++) {
      ffit->SetParLimits(i, parlimitslo[i], parlimitshi[i]);
   }

   his->Fit(FunName,"RB0");   // fit within specified range, use ParLimits, do not plot

   ffit->GetParameters(fitparams);    // obtain fit parameters
   for (i=0; i<4; i++) {
      fiterrors[i] = ffit->GetParError(i);     // obtain fit parameter errors
   }
   ChiSqr[0] = ffit->GetChisquare();  // obtain chi^2
   NDF[0] = ffit->GetNDF();           // obtain ndf

   return (ffit);              // return fit function

}
Exemple #5
0
void FillGoodRun(int ihar){
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
    int nrun = GetTotalRun();
    if(nrun<0) exit(1);
     for(int icent=0;icent<ncent;icent++){
 //     for(int ihar=0;ihar<nhar;ihar++){
 //         if(ihar!=1) continue;
       for(int isub=0;isub<nsub;isub++){
            str = choosesub(isub);
            if(str=="ABORT") continue;
            for(int irun=0;irun<nrun;irun++){
      //std::cout<<icent<<" "<<ihar<<" "<<isub<<" "<<irun<<std::endl;
        //fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/%s%s/%d/data/%s.root",dataset.Data(),pro.Data(),taxi,GetRun(irun).Data()));
         fin = TFile::Open(Form("/gpfs/mnt/gpfs02/phenix/plhf/plhf1/xuq/phenix/flow/Run16dAu/work/62GeV/output/%s",GetRun(irun).Data()));
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
      if(hpsi->GetEntries()>1000){
	//hpsi->SetMarkerStyle(20);
	//hpsi->SetMarkerSize(0.6);
	//hpsi->SetMarkerColor(4);
	hpsi->SetMinimum(10);
	hpsi->Fit("fun","QR0");
	//float par=fun->GetParameter(0);
	//hpsi->SetMaximum(1.5*par);
	//hpsi->Draw();
	GoodRunFit[icent][ihar][isub][irun] = fun->GetChisquare()/fun->GetNDF();
        fin->Close();
      }
      else{
        GoodRunFit[icent][ihar][isub][irun] = -9999;
        fin->Close();
     }
     // GoodRunFit[icent][ihar][isub][irun] = 1.;
    }
       }
   //   }
     }
}
void Chi(int num, double* arr)
{
  //double chi[3] = arr;
  //double* pointer = &chi;
  //if(num > -1)
    {
      TF1* f = new TF1("f", "5*(TMath::Power(x,-4))",1,100);
      TH1D* h1 = new TH1D("h1","h1", 100, -0.5, 99.5);

      for(int i = 0; i < 1000000; i++)
	{
	  h1->Fill(f->GetRandom(1,100));
	  //cout << f.GetRandom(1,100) << endl;
	}
      
      //cout << __FILE__ << __LINE__<< endl;

      TF1* pwrLw = new TF1("pwrLw", "[0]*TMath::Power(x,[1])",1,1000);//changed to 0 parameter
      pwrLw->SetParameter(0,5);
      pwrLw->SetParameter(1,-4);
      //cout << pwrLw->GetParameter(0) << "\t" << pwrLw->GetParameter(1) << endl;

      //cout << __FILE__ << __LINE__<< endl;
      
      h1->Fit("pwrLw","0","",2,25);
      TF1* func = h1->GetFunction("pwrLw");
      double chi = func->GetChisquare();
      double dof = func->GetNDF();
      arr[0] = chi/dof;
      double par0 = func->GetParameter(0);
      double par1 = func->GetParameter(1);
      //cout << par0 << "\t" << par1 << endl;
      arr[1] = CalcChiSqr(h1,par0,par1,2,25);
      //chi[2] = CalcChiSqr(h1,5,-4,2,25);
      //cout << "Outputing values from Chi()" << endl;
      //cout << arr[0] << "\t" << arr[1] << endl;//"\t" << chi[2] << endl;
      //DoCleanUp(h1, f, pwrLw);
    }
    //arr = chi;
    //return chi;
}
Exemple #7
0
TF1* getLandau(TH1* InputHisto, double* FitResults, double LowRange, double HighRange)
{
   FitResults[0]         = -0.5;  //MPV
   FitResults[1]         =  0;    //MPV error
   FitResults[2]         = -0.5;  //Width
   FitResults[3]         =  0;    //Width error
   FitResults[4]         = -0.5;  //Fit Chi2/NDF

   // perform fit with standard landau
   TF1* MyLandau = new TF1("MyLandau","landau",LowRange, HighRange);
   MyLandau->SetParameter(1,300);
   InputHisto->Fit("MyLandau","0QR WW");

   // MPV is parameter 1 (0=constant, 1=MPV, 2=Sigma)
   FitResults[0]         = MyLandau->GetParameter(1);  //MPV
   FitResults[1]         = MyLandau->GetParError(1);   //MPV error
   FitResults[2]         = MyLandau->GetParameter(2);  //Width
   FitResults[3]         = MyLandau->GetParError(2);   //Width error
   FitResults[4]         = MyLandau->GetChisquare() / MyLandau->GetNDF();  //Fit Chi2/NDF

   return MyLandau;
}
Exemple #8
0
int main(int argc, char *argv[])
{
  int binCount = 100;
  if (argc > 2) {
    std::cout << "too many argument. exit." << std::endl;
    std::exit(1);
  } else if (argc == 2) {
    binCount = std::atoi(argv[1]);
    --argc;
  }
  TApplication app("app", &argc, argv);
  gStyle->SetOptStat(0);

  TH1D *hist = new TH1D("hist", "ns vs count", binCount, minNanoSec, maxNanoSec);

  char filename[256];
  GetFileName(filename, "../data/muon_lifetime/muon_lifetime.dat");
  std::ifstream ifs(filename);
  for (int i = 0; !ifs.eof(); ++i) {
    Double_t data;
    ifs >> data;
    if (data) {
      NanoSecWithError ns;
      ConvertTdcChannelToNanoSec(i%8, data, &ns);
      hist->Fill(ns.time);
    }
  }
  hist->Draw();

  TF1 *fit = new TF1("fit", "[0] * exp(- x / [1]) + [2]", 1000, 20000);
  fit->SetParameters(200, 2100, 40);
  hist->Fit(fit, "R+");
  std::cout << "chi^2/ndf: ";
  std::cout << fit->GetChisquare() / fit->GetNDF() << std::endl;

  app.Run();
  return 0;
}
Exemple #9
0
void FillGoodRun(int icent,int ihar){
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
    int nrun = GetTotalRun();
    if(nrun<0) exit(1);
       for(int isub=0;isub<nsub;isub++){
            str = choosesub(isub);
            if(str=="ABORT") continue;
            for(int irun=0;irun<nrun;irun++){
      std::cout<<icent<<" "<<ihar<<" "<<isub<<" "<<irun<<std::endl;
         fin = TFile::Open(Form("/store/user/qixu/flow/Run16dAu/62GeV/%s",GetRun(irun).Data()));
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
      if(hpsi->GetEntries()>1000){
	//hpsi->SetMarkerStyle(20);
	//hpsi->SetMarkerSize(0.6);
	//hpsi->SetMarkerColor(4);
	hpsi->SetMinimum(10);
	hpsi->Fit("fun","QR0");
	//float par=fun->GetParameter(0);
	//hpsi->SetMaximum(1.5*par);
	//hpsi->Draw();
	GoodRunFit[icent][ihar][isub][irun] = fun->GetChisquare()/fun->GetNDF();
        fin->Close();
      }
      else{
        GoodRunFit[icent][ihar][isub][irun] = -9999;
        fin->Close();
     }
     // GoodRunFit[icent][ihar][isub][irun] = 1.;
    }
       }
}
Exemple #10
0
float GoodRun(int icent, int ihar, int isub, int irun){
    float pi = acos(-1);
    TF1 *fun = new TF1("fun","pol0",-pi,pi);
    TString str;
    TFile *fin;

     ofstream fout;
        if(isub==1){
         str = "FVTX1S";
        }
        else if(isub==2){
         str = "FVTX2S";
        }
        else return -9999;
         fin = TFile::Open(Form("Run15pAu200MinBias/output_fvtxwithcntEP_%d.root",GetRun(irun)));
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          hpsitemp = (TH1F*)fin->Get(Form("psi_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
        }
      if(hpsi->GetEntries()>10000){
	hpsi->SetMarkerStyle(20);
	hpsi->SetMarkerSize(0.6);
	hpsi->SetMarkerColor(4);
	hpsi->SetMinimum(10);
	hpsi->Fit("fun","QR0");
	float par=fun->GetParameter(0);
	hpsi->SetMaximum(1.5*par);
	//hpsi->Draw();
        fin->Close();
	return fun->GetChisquare()/fun->GetNDF();
      }
      else{
        fin->Close();
        return -9999;
      }
    }
void Nhit5by5Calibration(int E, std::string runPeriod)
{
  char inputFile[200];
  sprintf(inputFile,"%s%d%s","/lyoserv/home/ilc/steen/resultRootFile/tb_data/DHCAL_",Run(E,runPeriod),".root");
  std::cout << "inputFile = " << inputFile << std::endl;
  PionTimeCalibration* timeCalib=new PionTimeCalibration(inputFile);
  timeCalib->ShowerBarycenterCut(runPeriod);
  timeCalib->Loop();
  
  std::cout<< timeCalib->nhit5by5.size()<<std::endl;
  TF1 *func;
  char outputFile[200];
  sprintf(outputFile,"%s%d%s","/home/steen/timeCalib/Nhit5by5/calib_",Run(E,runPeriod),".txt");
  fstream out;
  out.open(outputFile,ios::out);
  TH2D* hRadPro=new TH2D("hName","",100,0,10,600,0,600);
  func=new TF1("func","pol1",0,10);
  for(unsigned int i=0; i<timeCalib->nhit5by5.size(); i++){
    hRadPro->Fill(timeCalib->time.at(i),timeCalib->nhit5by5.at(i));
  }
  //TCanvas *cc=new TCanvas();
  //hRadPro->Draw("colz");
  //cc->Update();
  //cc->WaitPrimitive();
  hRadPro->ProfileX()->Fit(func,"NQ");
  //cc->Update();
  //cc->WaitPrimitive();
  out << func->GetParameter(0) << " " << func->GetParError(0) 
      << " " << func->GetParameter(1) << " " << func->GetParError(1) 
      << " " << func->GetChisquare()/func->GetNDF() << std::endl;
  delete hRadPro;
  out.close();
  delete func;
  delete timeCalib;
  //delete cc;
}
Exemple #12
0
void linfit()
{
   gStyle->SetOptFit();

   Double_t x2[1000], y2[1000], ex2[1000], ey2[1000];
   Int_t n2 = 10;

   TRandom3 random;
   Double_t x0, delta;
   Double_t dy = 10;
   Double_t sigma = 10;

   // parameters of line y = k*x + b
   Double_t k;
   Double_t b;
   // errors on parameters
   Double_t dk;
   Double_t db;
   // intersection with x-axis
   Double_t xint;
   Double_t dx;

   TF1 *fitfunction = 0;

   delta = 100./n2;
   x0 = 0 - delta;
   for (int i=0; i<n2; ++i) {
      x0 += delta;
      x2[i] = x0;
      y2[i] = random.Gaus(x2[i], sigma);
      ex2[i] = 0;
      ey2[i] = dy;         // all weights are equal
      ey2[i] = TMath::Sqrt(y2[i]);
   }

   TGraphErrors *gr2 = new TGraphErrors(n2, x2,y2, ex2, ey2);
   gr2->SetNameTitle("gr2", "gr2");
   gr2->SetMarkerStyle(20);
   gr2->SetMarkerColor(4);
   gr2->SetLineColor(4);

   new TCanvas;
   gr2->Draw("ap");
   gr2->Fit("pol1");

   fitfunction = gr2->GetFunction("pol1");
   b = fitfunction->GetParameter(0);
   db = fitfunction->GetParError(0);
   k = fitfunction->GetParameter(1);
   dk = fitfunction->GetParError(1);
   xint = -b / k;
   dx = TMath::Abs(b/k) * TMath::Sqrt( (db/b)*(db/b) + (dk/k)*(dk/k) );
   gr2->SetTitle(Form("intersection with x-axis: %0.3f #pm %0.3f", xint,dx));
   cout<< "--> intersection with x-axis: " << xint << " +- " << dx <<endl;

   cout<< "--> chi2ndf = " << fitfunction->GetChisquare() / fitfunction->GetNDF();
   cout<<endl<<endl;

   // fast straight line fit y = am + bm*x
   // Source: Kalashnikova, Kozodaev, Detektory Elementarnyx chastic.

   //-- Float_t version of the data
   Float_t xf[1000], yf[1000], eyf[1000];
   Int_t nf = n2;
   for (int i=0; i<nf; ++i) {
      xf[i] = x2[i];
      yf[i] = y2[i];
      eyf[i] = ey2[i];
   }

   Double_t wx = 0;
   Double_t wy = 0;
   Double_t wxy = 0;
   Double_t wx2 = 0;
   Double_t W = 0;

   wx = wy = wxy = wx2 = W = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t w = 1./(yerror*yerror);       // weights are 1/ey

      W += w;
      wx += w*x;
      wx2 += w*x*x;
      wy += w*y;
      wxy += w*x*y;
   }

   Double_t Discriminant = W*wx2 - wx*wx;
   Double_t am = (wy*wx2 - wxy*wx) / Discriminant;    // y = am + bm*x
   Double_t bm = (W*wxy - wx*wy) / Discriminant;

   Double_t chi2 = 0;
   Double_t chi2ndf = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t yfit = am + bm*x;
      Double_t r = (y - yfit) / yerror;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (gr2->GetN() - 2);

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf <<endl;
   //--
   //-- NB: operator
   //-- cout<< "pol1fast(xf,yf,eyf,0,nf, am,bm) = " << pol1fast(xf,yf,eyf,0,nf, am,bm) << " am " << am << " bm " << bm <<endl;
   //-- will be executed from the tail: 
   //-- print __current__ version (before call of pol1fast) of the am and bm first
   //-- and will call pol1fast (and will obtain updated versions of am and bm) after that!!!!!!!!!!!
   //--
   chi2ndf = pol1fast(xf,yf,eyf,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,eyf,0,nf, am,bm) = " << chi2ndf << " am " << am << " bm " << bm <<endl;
   cout<< "for comparizon eyf=0 generates fit with equal weights:" <<endl;
   chi2ndf = pol1fast(xf,yf,0,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,0,0,nf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;

   cout<< "all weights are equal to 1" <<endl;
   wx = wy = wxy = wx2 = W = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      // Double_t yerror = gr2->GetEY()[i];
      // Double_t w = 1./(yerror*yerror);       // weights are 1/ey
      Double_t w = 1.;

      W += w;
      wx += w*x;
      wx2 += w*x*x;
      wy += w*y;
      wxy += w*x*y;
   }

   Discriminant = W*wx2 - wx*wx;
   am = (wy*wx2 - wxy*wx) / Discriminant;
   bm = (W*wxy - wx*wy) / Discriminant;

   chi2 = 0;
   for (int i=0; i<gr2->GetN(); ++i)
   {
      Double_t x = gr2->GetX()[i];
      Double_t y = gr2->GetY()[i];
      Double_t yerror = gr2->GetEY()[i];
      Double_t yfit = am + bm*x;
      Double_t r = (y - yfit) / yerror;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (gr2->GetN() - 2);

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf / dy <<endl;

   // optimized

   cout<< "optimized fit with equal weights" <<endl;

   wx = wy = wxy = wx2 = W = 0;
   W = n2;              // the number of points
   for (int i=0; i<n2; ++i)
   {
      Double_t x = x2[i];
      Double_t y = y2[i];
      wx += x;
      wx2 += x*x;
      wy += y;
      wxy += x*y;
   }

   Discriminant = W*wx2 - wx*wx;
   am = (wy*wx2 - wxy*wx) / Discriminant;    // y = am + bm*x
   bm = (W*wxy - wx*wy) / Discriminant;

   chi2 = 0;
   for (int i=0; i<n2; ++i)
   {
      Double_t x = x2[i];
      Double_t y = y2[i];
      Double_t yfit = am + bm*x;
      Double_t r = y - yfit;
      chi2 += r*r;
   }
   chi2ndf = chi2 / (n2-2);
   cout<< "normalize chi2ndf to dy = 10. NB: in current dataset the weights are different!" <<endl;
   chi2ndf /= dy;

   cout<< "--> fast straight line fit: am " << am << " bm " << bm << " chi2ndf = " << chi2ndf <<endl;

   chi2ndf = pol1fast(nf,xf,yf, am,bm);
   cout<< "pol1fast(nf,xf,yf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;

   // version optimized for point.C
   chi2ndf = pol1fast(xf,yf,0,nf, am,bm);
   cout<< "pol1fast(xf,yf,0,nf, am,bm) / dy = " << chi2ndf / dy << " am " << am << " bm " << bm <<endl;
}
void photonContainmentAnalysis() {

  gStyle->SetOptFit(1111);
  
  TFile *infile = new TFile("contCorrAnalyzer.root");
  infile->ls();
  
  TH1F *theHistos[2];
  theHistos[0] = (TH1F*)infile->Get("contCorrAnalyzer/EB_e25EtrueReference");
  theHistos[1] = (TH1F*)infile->Get("contCorrAnalyzer/EE_e25EtrueReference");
  
  // fitting the distributions to extract the parameter
  TF1 *gausa;
  TF1 *cb_p;
  for(int myH=0; myH<2; myH++) {
  
    // histos parameters
    int peakBin   = theHistos[myH]->GetMaximumBin();
    double h_norm = theHistos[myH]->GetMaximum();
    double h_rms  = theHistos[myH]->GetRMS();
    double h_mean = theHistos[myH]->GetMean();
    double h_peak = theHistos[myH]->GetBinCenter(peakBin);
    
    // gaussian fit to initialize
    gausa = new TF1 ("gausa","[0]*exp(-1*(x-[1])*(x-[1])/2/[2]/[2])",h_peak-10*h_rms,h_peak+10*h_rms);
    gausa ->SetParameters(h_norm,h_peak,h_rms);
    theHistos[myH]->Fit("gausa","","",h_peak-3*h_rms,h_peak+3*h_rms);
    double gausNorm  = gausa->GetParameter(0);
    double gausMean  = gausa->GetParameter(1);
    double gausSigma = fabs(gausa->GetParameter(2));
    double gausChi2  = gausa->GetChisquare()/gausa->GetNDF();
    if (gausChi2>100){ gausMean = h_peak; gausSigma = h_rms; }
    
    // crystalball limits
    double myXmin = gausMean - 7.*gausSigma;
    double myXmax = gausMean + 5.*gausSigma;
    
    // crystalball fit
    cb_p = new TF1 ("cb_p",crystalball,myXmin,myXmax, 5) ;
    cb_p->SetParNames ("Mean","Sigma","alpha","n","Norm","Constant");
    cb_p->SetParameter(0, gausMean);
    cb_p->SetParameter(1, gausSigma);
    cb_p->SetParameter(2, 1.);
    cb_p->SetParLimits(2, 0.1, 5.);
    cb_p->FixParameter(3, 5.);
    cb_p->SetParameter(4, gausNorm);
    theHistos[myH]->Fit("cb_p","lR","",myXmin,myXmax);
    theHistos[myH]->GetXaxis()->SetRangeUser(0.95,1.05); 
    double matrix_gmean      = cb_p->GetParameter(0);
    double matrix_gmean_err  = cb_p->GetParError(0);
    
    c1->Update();
    if(myH == 0) { 
      c1->SaveAs("e25EtrueReference_EB.eps");
      std::cout << "E25 barrel containment: " << matrix_gmean << " +/- " << matrix_gmean_err << std::endl; 
    }
    if(myH == 1) { 
      c1->SaveAs("e25EtrueReference_EE.eps");
      std::cout << "E25 endcap containment: " << matrix_gmean << " +/- " << matrix_gmean_err << std::endl; 
    }
  }
}
Exemple #14
0
/** Make Va1 response
    @param n 
    @param B 
    @param dc 
    @param errors 
    @ingroup simple_script
*/
void 
VA1Response(Int_t n=4, Float_t B=6, Float_t dc=.01, Bool_t errors=kFALSE,
	    Bool_t doFit=kFALSE) 
{
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  gStyle->SetLabelFont(132, "xyz");
  gStyle->SetTitleFont(132, "xyz");
  gStyle->SetTitleSize(0.08, "y");
  gStyle->SetTitleOffset(0.5, "y");
  gStyle->SetTitleSize(0.06, "x");
  gStyle->SetTitleOffset(0.7, "x");

  TCanvas* c = new TCanvas("c", "c", 800, 500);
  c->SetFillColor(0);
  c->SetBorderMode(0);
  c->SetBorderSize(0);
  c->SetTopMargin(0.05);
  c->SetRightMargin(0.05);
  c->SetGridx();
  c->SetGridy();

  TF1* response = new TF1("response", "[0] * (1 - exp(-[1] * x))", 0, 1.4);
  response->SetParameters(1, B);
  response->SetParNames("A", "B");
  response->SetLineColor(2);
  
  TGraph* graph = 0;
  if (n >= 2) {
    if (errors) graph = new TGraphErrors(n);
    else        graph = new TGraph(n);
    for (Int_t i = 0; i < n; i++) {
      Float_t t = Float_t(i + 1) / n;
      Float_t q = gRandom->Gaus(response->Eval(t), dc);
      graph->SetPoint(i, t, q);
      if (errors) ((TGraphErrors*)graph)->SetPointError(i, 0, dc);
    }
  }

  response->Draw();
  response->GetHistogram()->GetYaxis()->SetRangeUser(0, 1.05);
  response->GetHistogram()->GetXaxis()->SetRangeUser(0, 1.1);
  response->GetHistogram()->GetXaxis()->SetNdivisions(6, kTRUE);
  response->GetHistogram()->GetYaxis()->SetNdivisions(10, kTRUE);
  response->GetHistogram()->SetXTitle("t");
  response->GetHistogram()->SetYTitle(Form("1-e^{-%3.1f t}", B));
  
  if (graph) {
    
    
    graph->Draw("P*");
    TString fitOpt("E");
    if (!errors) fitOpt.Append("W");

    if (doFit) {
      TF1* fit = new TF1("fit",  "[0] * (1 - exp(-[1] * x))",  0, 1);
      fit->SetParameters(.5, B/2);
      fit->SetParNames("A", "B");
      fit->SetLineColor(3);
      graph->Fit("fit", fitOpt.Data());
      graph->Fit("fit", fitOpt.Data());
      
      std::cout << "Chi^2/NDF = " << fit->GetChisquare() << "/" << fit->GetNDF()
		<< " = " << std::flush;
      if (fit->GetNDF() == 0) 
	std::cout << " undefined!" << std::endl;
      else
	std::cout << (fit->GetChisquare() / fit->GetNDF()) << std::endl;
      std::cout << "f(t) = " 
		<< fit->GetParameter(0) << "+/-" << fit->GetParError(0) 
		<< " * (1 - exp(" 
		<< fit->GetParameter(1) << "+/-" << fit->GetParError(1) 
		<< " * t))" << std::endl;
    }
  }

  c->Modified();
  c->Update();
  c->cd();
  c->SaveAs("va1_response.png");
}
Exemple #15
0
int main(int argc, char **argv)
{
	TFile *f;
	TFile *newf;
	TNtuple *ntuple;
	TNtuple *newntuple;
	TH1F *h1;
	TF1 *func;
	TString Metal;
	TString dataLoc;
	Int_t dataSL;
	
	if(argc < 5 || argc > 6){
		std::cout << "The number of arguments is incorrect" << std::endl;
		return 0;
	}
	
	dataLoc = argv[1];
	PHI_MIN = (Double_t) std::stod(argv[2]);
	PHI_MAX = (Double_t) std::stod(argv[3]);
	N_PHI = (Int_t) std::stoi(argv[4]);
	if(argc >= 6) Metal = argv[5];
		
	dataSL = dataLoc.Length();
	if(dataLoc(dataSL-1, 1) != "/"){
		dataLoc = dataLoc + "/";
	}	
	
	std::cout << "The following settings are being used" << std::endl;
	std::cout << "Data Directory = " << dataLoc << std::endl;
	std::cout << PHI_MIN << " < PHI < " << PHI_MAX << ", N_PHI = " << N_PHI << std::endl;
	if(argc == 6) std::cout << "Running only for Metal "<< Metal << std::endl;
	else std::cout << "Running all Metals" << std::endl;	
	
	Float_t Q2, Xb, Zh, Pt, Phi, Val, Err;
	Float_t A, Ac, Acc;
	Float_t AErr, AcErr, AccErr;
	Float_t ChiSQ;

	Int_t nentries, empty;

	if(Metal == "") N_METAL = 6;
	else N_METAL = 1;
	
	for(Int_t met = 0; met < N_METAL; met++){
		if(Metal == ""){
			if(met == 0) Metal = "C";
			else if(met == 1) Metal = "Fe";
			else if(met == 2) Metal = "Pb";
			else if(met == 3) Metal = "D_C";
			else if(met == 4) Metal = "D_Fe";
			else if(met == 5) Metal = "D_Pb";
		}
		if(dataLoc == "")
			f = new TFile("../Gen5DimData/" + Metal + "_5_dim_dist.root", "READ");
		else
			f = new TFile(dataLoc + Metal + "_5_dim_dist.root", "READ");
		ntuple = (TNtuple*) f->Get("fit_data");

		nentries = ntuple->GetEntries();
		ntuple->SetBranchAddress("Xb", &Xb);
		ntuple->SetBranchAddress("Q2", &Q2);
		ntuple->SetBranchAddress("Xb", &Xb);
		ntuple->SetBranchAddress("Zh", &Zh);
		ntuple->SetBranchAddress("Pt", &Pt);
		ntuple->SetBranchAddress("Phi", &Phi);
		ntuple->SetBranchAddress("Val", &Val);
		ntuple->SetBranchAddress("Err", &Err);

		newntuple = new TNtuple("AAcAcc_data", "AAcAcc_data", "Q2:Xb:Zh:Pt:A:AErr:Ac:AcErr:Acc:AccErr:ChiSQ");
		func = new TF1("fit", "[0]+TMath::Cos(x*TMath::Pi()/180)*[1]+TMath::Cos(2*x*TMath::Pi()/180)*[2]");

		newf = new TFile(Metal + "newphihist.root", "RECREATE");
		newf->cd();

		for(Int_t i = 0; i < nentries; i = i + N_PHI){
			ntuple->GetEntry(i);
			h1 = new TH1F((const char*) Form("PhiDist Q2=%.3f Xb=%.3f Zh=%.3f Pt=%.3f", Q2, Xb, Zh, Pt), 
							(const char*) Form("PhiDist Q2=%.3f Xb=%.3f Zh=%.3f Pt=%.3f", Q2, Xb, Zh, Pt), N_PHI, PHI_MIN, PHI_MAX);
			empty = 0;
			for(Int_t j = 1; j <= N_PHI; j++){
				ntuple->GetEntry(i+j-1);
				h1->SetBinContent(j, Val);
				if(h1->GetBinContent(j) == 0)
					empty++;
				h1->SetBinError(j, Err*1.04);
			}
			if(empty <= (N_PHI - MIN_BIN)){
				h1->Fit(func, "q");
				h1->Write();
				if(func->GetNDF() != 0){
					ChiSQ = func->GetChisquare();
					A = func->GetParameter(0);
					AErr = func->GetParError(0);
					Ac = func->GetParameter(1);
					AcErr = func->GetParError(1);
					Acc = func->GetParameter(2);
					AccErr = func->GetParError(2);
					newntuple->Fill(Q2, Xb, Zh, Pt, A, AErr, Ac, AcErr, Acc, AccErr, ChiSQ);
				}
			}
			h1->Delete();
		}
		
		Metal = "";
		
		delete ntuple;
		
		newf->cd();
		newntuple->Write();
		newntuple->Delete();
		newf->Close();
		delete newf;
		f->Close();
		delete f;
	}
	return 0;
}
int main(int argc, char* argv[]) {

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

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

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

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

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

  gErrorIgnoreLevel = kWarning;

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

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

  cout<< etaBinningSize << endl;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   
  return 0;
}
//===============================
void FitSignalBG(Double_t nSigma, Int_t iRapBin, Int_t iPTBin){	

  gStyle->SetOptFit(kTRUE);
  gStyle->SetOptStat(kFALSE);

  Char_t name[100];
  //1.) perform the fit to the continuum, using the sidebands
  sprintf(name, "c1_rap%d_pT%d", iRapBin, iPTBin);
  TCanvas *c1 = new TCanvas(name);
  sprintf(name, "Counts per %1.0f MeV", 1000.*binWidth);
  c1->SetFillColor(0);
  c1->SetLeftMargin(0.15);
  hMass->SetYTitle(name);
  hMass->SetXTitle("M_{#mu#mu} [GeV]");
  hMass->SetTitleOffset(1.5, "y");
  hMass->SetStats(0);
  hMass->Draw();

  //starting values for fit:
  Double_t a = -2.0e6, b = 5.e5, c = -2.4e4;
  Double_t range_min = 8.6, range_max = 11.4;
  Double_t normY1S = hMass->GetMaximum() / binWidth;
  Double_t normY2S = 0.3*normY1S; 
  Double_t normY3S = 0.15*normY1S;
  Double_t sigma1S = 0.1, mean1S = 9.45;
  Double_t alpha = 1.33, n = 6.6; //CB-tail parameters

  printf("will be fitting the continuum between %1.2f < M < %1.2f\n", range_min, range_max);
  sprintf(name, "fCont");
  TF1* fCONT = new TF1(name, fitContinuum, range_min, range_max, 3);
  fCONT->SetParameters(a, b, c);
  hMass->Fit(fCONT, "0", "", range_min, range_max);
  fCONT = hMass->GetFunction(name);

  Double_t chisqrd = fCONT->GetChisquare();
  Int_t NDF = fCONT->GetNDF();
  Double_t redChi2 = chisqrd/NDF;
  printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3f\n\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF));

  fCONT->GetParameters(fitParBG);
  for(int iPar = 0; iPar < 3; iPar++){
	  fitParBGerr[iPar]=fCONT->GetParError(iPar);
  }

  //2.) fit the peaks on the top of a fixed continuum
  sprintf(name,"fPeaks");
  Int_t const npar = 10;
  fRECO = new TF1(name, fitPolyCrystal3, peak_min, peak_max, npar);
  fRECO->SetParNames("normY1S", "mass_Ups1S", "sigma_Ups1S", "normY2S", "normY3S", "n", "alpha", "a", "b", "c");
  fRECO->SetParameters(normY1S, mean1S, sigma1S, normY2S, normY3S, n, alpha, a, b, c);
  fRECO->FixParameter(7,fitParBG[0]);
  fRECO->FixParameter(8,fitParBG[1]);
  fRECO->FixParameter(9,fitParBG[2]);
  //fix alpha and n from the fit to all bins
  if(iPTBin > 0 && iRapBin > 0){

    Char_t fileName[100];
    if(iRapBin == 0)
      sprintf(fileName, "tmpFiles/CBParameters.root");
    else
      sprintf(fileName, "tmpFiles/CBParameters_rap%d.root", iRapBin);
    TFile *fIn = new TFile(fileName);
    TTree *treeIn = (TTree *) gDirectory->Get("CBPars");
    Double_t alphaAll, nAll;
    TBranch *b_alphaAll, *b_nAll;
    treeIn->SetBranchAddress("alphaAll", &alphaAll, &b_alphaAll);
    treeIn->SetBranchAddress("nAll", &nAll, &b_nAll);
    Long64_t iEntry = treeIn->LoadTree(0);
    treeIn->GetEntry(0);
    printf("alpha and n from File: %1.3f, %1.3f\n", alphaAll, nAll);
    fRECO->FixParameter(5, nAll);
    fRECO->FixParameter(6, alphaAll);
  }

  hMass->Fit(fRECO, "0", "", peak_min, peak_max);

  fRECO = hMass->GetFunction(name);
  fRECO->SetLineWidth(1);

  Double_t fitParTot[npar];
  fRECO->GetParameters(fitParTot);
  normY1S = fitParTot[0];   printf("normY1S = %1.3e\n", normY1S);
  mean1S = fitParTot[1];
  sigma1S = fitParTot[2];
  normY2S = fitParTot[3];
  normY3S = fitParTot[4];
  n = fitParTot[5];  printf("n = %1.3f\n", n);
  alpha = fitParTot[6];  printf("alpha = %1.3f\n", alpha);

  sigma1S_save[iRapBin][iPTBin]=sigma1S;

  chisqrd = fRECO->GetChisquare();
  NDF = fRECO->GetNDF();
  redChi2 = chisqrd/NDF;
  printf("\nChisqrd = %1.3f, NDF = %d, Chisqrd/NDF = %1.3f, Prob = %1.3e\n", chisqrd, NDF, redChi2, TMath::Prob(chisqrd,NDF));

  //save alpha and n parameters if fit is 
  //for integrated bins in y and pT:
  if(iPTBin == 0)
    SaveCBParameters(iRapBin, iPTBin, alpha, n, fRECO->GetParError(6), fRECO->GetParError(5));

  Double_t mean2S = mean1S*(massPDG2S/massPDG1S);
  Double_t mean3S = mean1S*(massPDG3S/massPDG1S);
  Double_t sigma2S = sigma1S*(massPDG2S/massPDG1S);
  Double_t sigma3S = sigma1S*(massPDG3S/massPDG1S);

  printf("=========================================\n");
  printf("Calculate the number of Y's in the sample\n");
  printf("=========================================\n");

  TF1 *CB[kNbSpecies];
  Double_t intCBFit[kNbSpecies]; //integral values of a CB with N=Nfit and fixed alpha, n, sigma, width

  for(int iUps = 0; iUps < kNbSpecies; iUps++){
    sprintf(name, "CB_%d", iUps);
    CB[iUps] = new TF1(name, CBFunction, range_min, range_max, 5);
    CB[iUps]->SetParameter(0, 1.);
    if(iUps == 0){
      CB[iUps]->FixParameter(1, mean1S);
      CB[iUps]->FixParameter(2, sigma1S);
    }
    else if(iUps == 1){
      CB[iUps]->FixParameter(1, mean2S);
      CB[iUps]->FixParameter(2, sigma2S);
    }
    else if(iUps == 2){
      CB[iUps]->FixParameter(1, mean3S);
      CB[iUps]->FixParameter(2, sigma3S);
    }
    CB[iUps]->FixParameter(3, alpha);
    CB[iUps]->FixParameter(4, n);
    intCB[iUps] = CB[iUps]->Integral(range_min, range_max);
  }

  nY[UPS1S] = normY1S * intCB[UPS1S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS3S] = normY3S * intCB[UPS3S];

  printf("rapidity bin %d, pT bin %d\n", iRapBin, iPTBin);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS1S], intCB[UPS1S], specName[UPS1S], nY[UPS1S]);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS2S], intCB[UPS2S], specName[UPS2S], nY[UPS2S]);
  printf("the integral of the fitted CB for the %s is: %1.3e --> #%s = %1.3e\n", specName[UPS3S], intCB[UPS3S], specName[UPS3S], nY[UPS3S]);

  //calculate the fraction of BG in a given mass interval
  massMin[UPS1S] = mean1S - nSigma*sigma1S;
  massMin[UPS2S] = mean2S - nSigma*sigma2S;
  massMin[UPS3S] = mean3S - nSigma*sigma3S;
  massMax[UPS1S] = mean1S + nSigma*sigma1S;
  massMax[UPS2S] = mean2S + nSigma*sigma2S;
  massMax[UPS3S] = mean3S + nSigma*sigma3S;
  for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){
    printf("integrating histos between %1.3f and %1.3f GeV (+- %1.1f sigma window)\n",
	   massMin[iSpecies], massMax[iSpecies], nSigma);
  }

  fUps1S =  new TF1("fUps1S", CBFunction, range_min, range_max, 5);
  fUps1S->FixParameter(0, normY1S * binWidth);
  fUps1S->FixParameter(1, mean1S);
  fUps1S->FixParameter(2, sigma1S);
  fUps1S->FixParameter(3, alpha);
  fUps1S->FixParameter(4, n);

  fUps2S = new TF1("fUps2S", CBFunction, range_min, range_max, 5);
  fUps2S->FixParameter(0, normY2S * binWidth);
  fUps2S->FixParameter(1, mean2S);
  fUps2S->FixParameter(2, sigma2S);
  fUps2S->FixParameter(3, alpha);
  fUps2S->FixParameter(4, n);

  fUps3S = new TF1("fUps3S", CBFunction, range_min, range_max, 5);
  fUps3S->FixParameter(0, normY3S * binWidth);
  fUps3S->FixParameter(1, mean3S);
  fUps3S->FixParameter(2, sigma3S);
  fUps3S->FixParameter(3, alpha);
  fUps3S->FixParameter(4, n);


  Double_t nUps[kNbSpecies];
  nUps[UPS1S] = fUps1S->Integral(massMin[UPS1S], massMax[UPS1S]);
  nUps[UPS2S] = fUps2S->Integral(massMin[UPS2S], massMax[UPS2S]);
  nUps[UPS3S] = fUps3S->Integral(massMin[UPS3S], massMax[UPS3S]);


  fBG = new TF1("fBG", DrawContinuum, range_min, range_max, 3);
  for(int iPar = 0; iPar < 3; iPar++){
    fBG->FixParameter(iPar, fitParBG[iPar]);
    fBG->SetParError(iPar, fitParBGerr[iPar]);
//    printf("fBG par %f +- %f\n", fBG->GetParameter(iPar), fBG->GetParError(iPar));

  }
  Double_t nBG[kNbSpecies];
  nBG[UPS1S] = fBG->Integral(massMin[UPS1S], massMax[UPS1S]);
  nBG[UPS2S] = fBG->Integral(massMin[UPS2S], massMax[UPS2S]);
  nBG[UPS3S] = fBG->Integral(massMin[UPS3S], massMax[UPS3S]);


/*  intCB[UPS3S] = CB[UPS3S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  intCB[UPS2S] = CB[UPS2S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  intCB[UPS1S] = CB[UPS1S]->Integral(massMin[UPS3S], massMax[UPS3S]);
  nY[UPS3S] = normY3S * intCB[UPS3S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS1S] = normY1S * intCB[UPS1S];
  printf("3S region:::1sigma integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]);
  printf("3S region:::1sigma integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]);
  printf("3S region:::1sigma integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]);
  printf("3S region:::1sigma integral BKG  = %1.3f, normBkg = %1.3f, nBkg = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S]) ,1/binWidth,fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth);
  printf("3S region:::1sigma CB3S background fraction = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]));
  printf("3S region:::1sigma NumEvents = %1.3f\n",fBG->Integral(massMin[UPS3S], massMax[UPS3S])/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]);

  intCB[UPS3S] = CB[UPS3S]->Integral( range_min, range_max);
  intCB[UPS2S] = CB[UPS2S]->Integral( range_min, range_max);
  intCB[UPS1S] = CB[UPS1S]->Integral( range_min, range_max);
  nY[UPS3S] = normY3S * intCB[UPS3S];
  nY[UPS2S] = normY2S * intCB[UPS2S];
  nY[UPS1S] = normY1S * intCB[UPS1S];

  printf("3S region:::FullRegion integral CB3S = %1.3f, normY3S = %1.3f, nY3S = %1.3f\n",intCB[UPS3S] ,normY3S,nY[UPS3S]);
  printf("3S region:::FullRegion integral CB2S = %1.3f, normY2S = %1.3f, nY2S = %1.3f\n",intCB[UPS2S] ,normY2S,nY[UPS2S]);
  printf("3S region:::FullRegion integral CB1S = %1.3f, normY1S = %1.3f, nY1S = %1.3f\n",intCB[UPS1S] ,normY1S,nY[UPS1S]);
  printf("3S region:::FullRegion integral background = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth);
  printf("3S region:::FullRegion NumEvents = %1.3f\n",fBG->Integral(range_min, range_max)/binWidth+nY[UPS1S]+nY[UPS2S]+nY[UPS3S]);

  double tempBfrac=fBG->Integral(massMin[UPS3S], massMax[UPS3S])/(fBG->Integral(massMin[UPS3S], massMax[UPS3S])+fUps1S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps2S->Integral(massMin[UPS3S], massMax[UPS3S])+fUps3S->Integral(massMin[UPS3S], massMax[UPS3S]));
  printf("3S region:::1sigma fUps background fraction = %1.3f\n",tempBfrac);
*/
  if(iRapBin == 0 || iPTBin == 0)
    printf("rapidity bin %d, pTBin %d\n", iRapBin, iPTBin);	   
  else{
    printf("rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", 
	   iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], 
	   iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]);
  }

  FILE *fInfo = fopen("tmpFiles/statistics.txt", "a");
  if(iRapBin == 0 || iPTBin == 0)
    fprintf(fInfo, "rapidity bin %d, pTBin %d\n", iRapBin, iPTBin);	   
  else{
    fprintf(fInfo, "rapidity bin %d (%1.1f - %1.1f), pT bin %d (%1.0f - %1.0f GeV/c)\n", 
	   iRapBin, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin], 
	   iPTBin, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin]);
  }
  for(int iSpecies = 0; iSpecies < kNbSpecies; iSpecies++){
    fracBG[iSpecies] = nBG[iSpecies] / (nBG[iSpecies] + nUps[iSpecies]);
    // printf("nUps = %1.3f\n", nUps[iSpecies]);
    // printf("nBG = %1.3f\n", nBG[iSpecies]);
    printf("%s: fraction of BG in a +- %1.1f sigma window is %1.3f (not correct)\n",specName[iSpecies], nSigma, fracBG[iSpecies]);
    printf("%s: Number of BG events in a +- %1.1f sigma window is %1.3f, number of signal events is %1.3f\n",nSigma, nBG[iSpecies], nUps[iSpecies]);

    fprintf(fInfo, "integral of the fitted CB for the %s is (norm factor= %1.3e): %7.0f\n", specName[iSpecies], intCB[iSpecies], nY[iSpecies]);
  }
  fclose(fInfo);

//  if(iPTBin > 0 && iRapBin > 0)
	if(iPTBin > -1 && iRapBin > -1)
    SaveFitPars(iRapBin, iPTBin);

}
I2GFvalues I2GFmainLoop(TH1F *htemp, int N_iter, float N_sigma_range, bool ShowFit)
//Arguments: (histo to be fit, N iterations to find peak using gaus fit, fit range param., do or do not plot fit on histo)
{
  I2GFvalues myI2GFvalues;

  //Set initial values...(in case fit fails)
  myI2GFvalues.rchi2 = -100;
  myI2GFvalues.mean = -100;
  myI2GFvalues.mean_err = -100;
  myI2GFvalues.sigma = -100;
  myI2GFvalues.sigma_err = -100;


  TSpectrum *s = new TSpectrum(); //TSpectrum(1,1)->Argument: (Number of peaks to find, Distance to neighboring peak: "1"-->3sigma)
  Int_t NPeaks;
  Float_t *Peak;                     //TSpectrum *s = new TSpectrum(); --> No warning message 
  Float_t *PeakAmp;                    
  float peak_pos = 0;
  float peak_pos_amp = 0;  //Initial value, assuming positive going peaks
  int peak_pos_bin = 0;
  
  int binMaxCnt = 0;
  float binMaxCnt_value = 0;
  int binMaxCnt_counts = 0;

  int Nbins = 0;
  Int_t zero_value_bin = 0;
  float low_limit = 0;
  float high_limit = 0;
  float peak_pos_count = 0;
  float zero_bin_value = 0;
  float max_bin_value = 0;
 

  TF1 *func;
  TF1 *func1;
  TF1 *func2;
  TF1 *func3;
  float Chi2;
  int NDF = 1;
   

  float f_RChi2 = 1; 
  float f_const = 1;
  float f_mean = 1;
  float f_mean_err = 1;
  float f_sigma = 1;
  float f_sigma_err = 1;
  
  float peak = 1;  

  float f_const2 = 1;
  float f_mean2 = 1;
  float f_mean_err2 = 1;
  float f_sigma2 = 1;
  float f_sigma_err2 = 1;

  //---------Basic Histo Peak Finding Parameters----------
  binMaxCnt = htemp->GetMaximumBin();  //Finds bin w/ max counts (can be dubious, so use TSpectrum)
  binMaxCnt_value = (Double_t) htemp->GetXaxis()->GetBinCenter(binMaxCnt); //if the bin number is known and the bin value (in x-axis units) is wanted
  binMaxCnt_counts = (Int_t) htemp->GetBinContent(binMaxCnt); //Finds counts within particular bin

  //---------TSpectrum Peak Finding Parameters--------
  if (ShowFit) NPeaks = s->Search(htemp, 2, "goff", 0.5); //opens a canvas (one time in a loop), even with:  s->Search(htemp, 2, "nodraw", 0.9);
  //else  NPeaks = s->Search(htemp, 2, "", 0.5);  //s->Search(htemp, 2, "nodraw", 0.9);

  //Npeaks = s->GetNPeaks(); //If using this, need pointer in declaration above: Int_t *NPeaks
  //N_peaks =  Npeaks[0];

  Peak = s->GetPositionX();
  PeakAmp = s->GetPositionY();

  for (int i=0; i<NPeaks; i++)
    {
      if (peak_pos_amp < PeakAmp[i])
	{
	    peak_pos_amp = PeakAmp[i]; //TSpectrum finds peak counts
	    peak_pos = Peak[i]; //TSpectrum finds pos. of peak in x-axis units
	}
    }
  peak_pos_bin = htemp->GetXaxis()->FindBin(peak_pos); //if the bin value (in x-axis units) is known and the bin number is wanted
  peak_pos_count = htemp->GetBinContent(peak_pos_bin);  //counts in particular bin

  //------------------------------------------------------------------------------------------------------------------  

  zero_value_bin = htemp->GetXaxis()->FindBin(0.0); //if the bin value (in x-axis units) is known and the bin number is wanted
  Nbins = htemp->GetSize() - 2; //total number of bins in histo
  zero_bin_value =  htemp->GetXaxis()->GetBinCenter(0); //if the bin number is known and the bin value (in x-axis units) is wanted.
  max_bin_value =  htemp->GetXaxis()->GetBinCenter(Nbins); //if the bin number is known and the bin value (in x-axis units) is wanted.
 
  int TS = 0;
  if (peak_pos >= zero_bin_value  &&  peak_pos <= max_bin_value)  //Make sure that TSpectrum peak is within histo range
    {                                                             //if not, use Par initial values from Basic Histo Peak Find
             
      TS=1; //for cout below                        
      low_limit = peak_pos - (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos-10% of full range of histo
      high_limit = peak_pos + (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos+10% of full range of histo
                                                       
      func = new TF1("func", "gaus");
      //func->FixParameter(1,0);
      //func->SetParLimits(0, 0, 1000000);
      func->SetParameter(0, peak_pos_count);
      func->SetParameter(1, peak_pos);
    }
  else
    {

      low_limit = binMaxCnt_value - (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos-10% of full range of histo
      high_limit = binMaxCnt_value + (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos+10% of full range of histo
      
      func = new TF1("func", "gaus");
      //func->SetParLimits(0, 0, 1000000);
      func->SetParameter(0, binMaxCnt_counts);
      func->SetParameter(1, binMaxCnt_value);
    }
  
  htemp->Fit("gaus", "Q0", "", low_limit, high_limit); //low_limit, high_limit); //  To Show fit: htemp->Fit("gaus"); //better fit?-> Fit("gaus", "MQ", "", "", ""); 
  func  = htemp->GetFunction("gaus");
  Chi2 = func->GetChisquare();
  NDF = func->GetNDF();
  if (NDF != 0) f_RChi2 = Chi2/NDF;
  f_const = func->GetParameter(0);
  f_mean = func->GetParameter(1);
  f_mean_err = func->GetParError(1);
  f_sigma = func->GetParameter(2);
  f_sigma_err = func->GetParError(2);
 


 /*
  if (N_sigma_range == 7)
    {
      cout<<""<<endl;
      cout<<"---Basic Histo Peak Find---"<<endl;
      cout<<"binMaxCnt: "<<binMaxCnt<<endl;
      cout<<"binMaxCnt_value: "<<binMaxCnt_value<<endl;
      cout<<"binMaxCnt_counts: "<<binMaxCnt_counts<<endl;
      cout<<""<<endl;
      if (TS == 1) cout<<"---TSpectrum Peak Find: Succeeded!---"<<endl;
      else cout<<"---TSpectrum Peak Find: Failed!---"<<endl;
      cout<<"NPeaks: "<<NPeaks<<endl;
      cout<<"peak_pos (find max peak): "<<peak_pos<<endl;
      cout<<"peak_pos_amp (eval. amp of max peak) : "<<peak_pos_amp<<endl;
      cout<<""<<endl;
      cout<<"----------------------------------------"<<endl;
      cout<<"peak_pos_bin: "<<peak_pos_bin<<endl;
      cout<<"peak_pos_count: "<<peak_pos_count<<endl;
      cout<<"zero_value_bin: "<<zero_value_bin<<", Nbins: "<<Nbins<<endl;
      cout<<"zero_bin_value: "<<zero_bin_value<<", max_bin_value: "<<max_bin_value<<endl;
      cout<<"low, high limit: "<<low_limit<<", "<<high_limit<<endl;
    }
  */




  //for (int i=0; i< (N_iter - 1); i++)
  for (int i=0; i< 2; i++)  //8 seems to work well, so let's keep it constant here.
    {
      //htemp->Fit("gaus", "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //show fit
      htemp->Fit("gaus", "Q0", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //don't show fit
      func  = htemp->GetFunction("gaus");
      Chi2 = func->GetChisquare();
      NDF = func->GetNDF();
      if (NDF != 0) f_RChi2 = Chi2/NDF;
      f_const = func->GetParameter(0);
      f_mean = func->GetParameter(1);
      f_mean_err = func->GetParError(1);
      f_sigma = func->GetParameter(2);
cout << " sigma " << f_sigma << endl;
      f_sigma_err = func->GetParError(2);
    }

  peak =  func->GetParameter(0); //Amplitude

  float bgd_h = 0.25; //background height ~ bgd_h*gaus_amp

  func1 = new TF1("func1", "gaus");
  //-----------Fit Parameter constraints not needed here (see below):
  //func1->SetParLimits(0, 0, 1000000);
  //func1->SetParameters(f_const, f_mean, f_sigma);    //Here: (Par1 initial value, Par2 initial value, Par3 initial value, etc)
  //func1->SetParameter(0, 200);  //Here: Initial value of Par 0 = 200
  //func1->SetParLimits(0, f_const*(1-bgd_h-0.2),f_const*(1-bgd_h+0.2) );  //Here: (Par_lower limit, Par upper limit)
  //func1->SetParLimits(1, f_mean-(f_sigma/2),f_mean+(f_sigma/2) );
  //func1->SetParLimits(2, f_sigma-(f_sigma/2),f_sigma+(f_sigma/2) );
  
  func2 = new TF1("func2", "gaus");
  //-----------Fit Parameter constraints not needed here (see below):
  //func2->SetParameters(f_const/10, f_mean, 4*f_sigma); //(const, mean, sigma)     
  //func2->SetParLimits(0,-1,(0.1*peak_pos_amp) );        //(const)     
  //func2->SetParameters(1, f_mean, 4*f_sigma); //(mean)      
  //func2->SetParameters(2, 4*f_sigma);         //(sigma)     
  //func2->SetParLimits(0, 0, f_const*(0.1) );                                      
  //func2->SetParLimits(1, f_mean-(4*f_sigma),f_mean+(4*f_sigma) );
  //func2->SetParLimits(2, f_sigma-(10*f_sigma),f_sigma+(10*f_sigma) ); 
  //func2->FixParameter(0, 40); //Test     

  //cout<<"peak amp: "<<0.1*peak_pos_amp<<endl;

  //func2 = new TF1("func2", "pol2");
  
  func3 = new TF1("func3", "func1 + func2", (f_mean - 3*f_sigma), (f_mean + 3*f_sigma) );
  //-----------Fit Parameter constraints:
  func3->SetParameters(f_const, f_mean, f_sigma, f_const/10, f_mean, 4*f_sigma); //Set Initial Valules
  //func3->SetParLimits(0, 0, 1000000);
  //func3->SetParLimits(1, 0, 1000000);
  //func3->SetParLimits(2, 0, 1000000);
  func3->SetParLimits(3, 0, (0.05*peak_pos_amp) ); //Max=5% of peak amp //************Set peak limit of background sigma*************
  //func3->SetParLimits(4, 0, 1000000);
  //func3->SetParLimits(5, 0, 1000000);

  //htemp->Fit("func3");//, "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //Show Fit
  htemp->Fit("func3", "Q0"); //Don't show fit
  func  = htemp->GetFunction("func3");
  Chi2 = func3->GetChisquare();
  NDF = func->GetNDF();
  if (NDF != 0) f_RChi2 = Chi2/NDF;
  f_const = func3->GetParameter(0);
  f_mean = func3->GetParameter(1);
  f_mean_err = func3->GetParError(1);
  f_sigma = func3->GetParameter(2);
  f_sigma_err = func3->GetParError(2);
  
  f_const2 = func3->GetParameter(3);
  f_mean2 = func3->GetParameter(4);
  f_mean_err2 = func3->GetParError(4);
  f_sigma2 = func3->GetParameter(5);
  f_sigma_err2 = func3->GetParError(5);
  func3->SetParNames("Primary Constant", "Primary Mean", "Primary Sigma", "Background Constant", "Background Mean", "Background Sigma");
  //for (int j=0; j< (N_iter - 1); j++)
  for (int j=0; j<4; j++)
    {
      func3->SetParameters(f_const, f_mean, f_sigma, f_const2, f_mean2, f_sigma2);
      //htemp->Fit("func3", "Q", "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); 
      
      //----------------Show or don't show fit----------------- 
      if (ShowFit) htemp->Fit("func3", "Q");//*************Show Histo & Fit in quiet mode
      else htemp->Fit("func3", "Q0"); //*****************Don't show Histo & Fit in quiet mode
      //-------------------------------------------------------     

      func3  = htemp->GetFunction("func3");
      func3->SetLineColor(2);
      //htemp->SetLineColor(2);
      Chi2 = func3->GetChisquare();
      NDF = func3->GetNDF();
      if (NDF != 0) f_RChi2 = Chi2/NDF;
      f_const = func3->GetParameter(0);
      f_mean = func3->GetParameter(1);
      f_mean_err = func3->GetParError(1);
      f_sigma = func3->GetParameter(2);
      f_sigma_err = func3->GetParError(2);
      f_const2 = func3->GetParameter(3);
      f_mean2 = func3->GetParameter(4);
      f_mean_err2 = func3->GetParError(4);
      f_sigma2 = func3->GetParameter(5);
      f_sigma_err2 = func3->GetParError(5);
    }

  

  //gStyle->SetOptFit(kTRUE);

  //if (f_const > f_const2)
  if (abs(f_const-peak) < abs(f_const2-peak))
    {
      myI2GFvalues.rchi2 = f_RChi2;
      myI2GFvalues.mean = f_mean;
      myI2GFvalues.mean_err = f_mean_err;
      myI2GFvalues.sigma = abs(f_sigma);
      myI2GFvalues.sigma_err = f_sigma_err;
      //myI2GFvalues.fit_func = new TF1("fit_func", "func3"); //not needed
    }
  else
    {
      myI2GFvalues.rchi2 = f_RChi2;
      myI2GFvalues.mean = f_mean2;
      myI2GFvalues.mean_err = f_mean_err2;
      myI2GFvalues.sigma = abs(f_sigma2);
      myI2GFvalues.sigma_err = f_sigma_err2;
      //myI2GFvalues.fit_func = new TF1("fit_func", "func3"); //not needed
    }
  
  return myI2GFvalues;

  delete s;
  delete func;
  delete func1;
  delete func2;
  delete func3;
    
}
Exemple #19
0
TCanvas* fitting(TCanvas* c1, TH1F* ratio, TString jetFlavor, TFile* f){

	char labelCons[150];
	char labelLine[150];
	char labelPoly[150];

	ratio->SetTitle("DiJet Ratio");
	ratio->GetXaxis()->SetTitle("DiJet Mass (in GeV)");
	ratio->GetXaxis()->SetRangeUser(330.,7600.);
        if (!strcmp(jetFlavor,"ratioGen") || !strcmp(jetFlavor,"ratioCalo") || !strcmp(jetFlavor,"ratioCor") )
		ratio->GetYaxis()->SetRangeUser(0.,1.2);
	else 
		ratio->GetYaxis()->SetRangeUser(0.6,1.6);
        if (!strcmp(jetFlavor,"ratioGen") || !strcmp(jetFlavor,"ratioCalo") || !strcmp(jetFlavor,"ratioCor") )
		ratio->GetYaxis()->SetTitle("Ratio=N(|#eta|<0.5)/N(0.5<|#eta|<1)");
	else
		ratio->GetYaxis()->SetTitle("Ratio(CorrectedJets/GenJets)");

	ratio->GetYaxis()->SetTitleOffset(1.3);
	ratio->SetStats(kFALSE);
	ratio->Draw("E1P");
	
	TF1* f1 = new TF1("f1", "pol0");
	f1->SetLineColor(1);
	ratio->Fit("f1");
	TF1* fit = ratio->GetFunction("f1");
	float constChi2 = fit->GetChisquare();
	float constP0 = fit->GetParameter(0);
	float constP0Er = fit->GetParError(0);
	int constNDF = fit->GetNDF();
	float constChi = constChi2/constNDF;
	sprintf(labelCons, "y = %5.3f #pm %5.3f, #chi^{2} = %5.3f, NDF = %d, #chi^{2}/NDF = %5.3f", constP0, constP0Er, constChi2, constNDF, constChi);
	
	
	TF1* f2 = new TF1("f2", "pol1");
	f2->SetLineColor(3);
	ratio->Fit("f2", "+");
	f2->Draw("SAME");
	TF1* fit = ratio->GetFunction("f2");
	float lineChi2 = fit->GetChisquare();
	float lineP0 = fit->GetParameter(0);
	float lineP1 = fit->GetParameter(1);
	int lineNDF = fit->GetNDF();
	float lineChi = lineChi2/lineNDF;
	sprintf(labelLine, "y = %5.3e*x + %5.3f, #chi^{2} = %5.3f, NDF = %d, #chi^{2}/NDF = %5.3f", lineP1, lineP0, lineChi2, lineNDF, lineChi);
	
	TF1* f3 = new TF1("f3", "pol2");
	f3->SetLineColor(4);
	ratio->Fit("f3", "+");
	TF1* fit = ratio->GetFunction("f3");
	float polyChi2 = fit->GetChisquare();
	float polyP0 = fit->GetParameter(0);
	float polyP1 = fit->GetParameter(1);
	float polyP2 = fit->GetParameter(2);
	int polyNDF = fit->GetNDF();
	float polyChi = polyChi2/polyNDF;
	sprintf(labelPoly, "y = %5.3e*x^{2} + %5.3e*x + %5.3f, #chi^{2} = %5.3f, NDF = %d, #chi^{2}/NDF = %5.3f",polyP2, polyP1, polyP0, polyChi2, polyNDF, polyChi);

        if (!strcmp(jetFlavor,"ratioGen"))
	TLegend *leg = new TLegend(0.25,0.7,0.9,0.9, "Generated Jets");
	else if (!strcmp(jetFlavor,"ratioCalo"))
	TLegend *leg = new TLegend(0.25,0.7,0.9,0.9, "Calorimetry Jets");
	else if (!strcmp(jetFlavor,"ratioCor"))
	TLegend *leg = new TLegend(0.25,0.7,0.9,0.9, "Corrected Jets");
	else if (!strcmp(jetFlavor,"R0_CorGen"))
	TLegend *leg = new TLegend(0.25,0.7,0.9,0.9, "|#eta| < 0.5");
	else
	TLegend *leg = new TLegend(0.25,0.7,0.9,0.9, "|#eta| < 1.0");

	leg->AddEntry(f1,labelCons,"L");
	leg->AddEntry(f2,labelLine,"L");
	leg->AddEntry(f3,labelPoly,"L");
	leg->Draw();
	//save ratio histo into the root file
        if (!strcmp(jetFlavor,"ratioGen")){
		TH1F* ratioGen = (TH1F*)ratio->Clone("ratioGen");
		f->cd();
		ratioGen->Write();
	}
        else if (!strcmp(jetFlavor,"ratioCalo")){
		TH1F* ratioCalo = (TH1F*)ratio->Clone("ratioCalo");
		f->cd();
		ratioCalo->Write();
	}
        if (!strcmp(jetFlavor,"ratioCor")){
		TH1F* ratioCor = (TH1F*)ratio->Clone("ratioCor");
		f->cd();
		ratioCor->Write();
	}
	
	c1->Print("c1.ps");

	return c1;
}// fitting
Exemple #20
0
////////////////// New version for ISS //////////////////
double TrTasClusterR::Fit(TH1 *hist, int ibeam, int mode, double *par,
			                                  double *per)
{
  if (!par) return -1;

  if (!TkDBc::Head) TkDBc::GetFromTDV(1325000000, 5);
  if (!TrTasDB::Filled()) {
    TString sdb = getenv("AMSDataDir");
    sdb += "/v5.01/tasdb";

    if (getenv("TasDB")) sdb = getenv("TasDB");
    TrTasDB::Load(sdb);
  }

  for (int i = 0;        i < 5; i++) par[i] = 0;
  for (int i = 0; per && i < 5; i++) per[i] = 0;

  TString stt = hist->GetTitle();
  if (stt == "Type: 00CC TkID:  310") hist->SetBinContent(133, 0);
  if (stt == "Type: 30CC TkID: -606") hist->SetBinContent(102, 0);
  if (stt == "Type: 31CC TkID: -609") hist->SetBinContent(129, 0);
  if (stt == "Type: 31CC TkID: -609") hist->SetBinContent(131, 0);
  if (stt == "Type: 40CC TkID: -609") hist->SetBinContent( 79, 0);

  int id = TrTasDB::Find(hist->GetTitle(), ibeam);
  if (id < 0) return -1;

  static TF1 *func = 0;
  if (!func) func = new TF1("func", TrTasClusterR::SGaus, 0, 1, 5);

  double csq = -1;
  double mn = TrTasDB::Mean(id);
  int    tf = TrTasDB::Tfit(id);
  int  tkid = TrTasDB::TkID(id);

  if (mn > 0) {
    hist->GetXaxis()->SetRangeUser(mn-15, mn+15);

    Int_t    rng = tf%10;
    Int_t    ib1 = hist->FindBin(mn-rng);
    Int_t    ib2 = hist->FindBin(mn+rng);
    Double_t sum = hist->Integral(ib1, ib2);
    if (sum < 100) return -1;

    if (mode > 100) {
      Int_t nb1 = (mode/10)%10;
      Int_t nb2 =  mode    %10;
      Int_t ib  = hist->FindBin(mn);
      Double_t sx = 0;
      Double_t sw = 0;

      for (Int_t i = 0; i <= nb1; i++) {
	if (hist->GetBinContent(ib-i) > 0) {
	  sx += hist->GetBinContent(ib-i)*hist->GetBinCenter(ib-i);
	  sw += hist->GetBinContent(ib-i);
	}
      }
      for (Int_t i = 1; i <= nb2; i++) {
	if (hist->GetBinContent(ib+i) > 0) {
	  sx += hist->GetBinContent(ib+i)*hist->GetBinCenter(ib+i);
	  sw += hist->GetBinContent(ib+i);
	}
      }
      if (sw != 0) sx /= sw;
      par[0] = hist->GetBinContent(hist->FindBin(sx));
      par[1] = sx;
      par[2] = sw;
      csq = 1;
    }
    else if (mode == 2 || (mode == 0 && tf > 10)) {
      double hmax = hist->GetMaximum();
      func->SetParameters(hmax*1.5, mn, 3, hmax, 500);
      func->FixParameter(4, 25);
      func->ReleaseParameter(3);

      hist->Fit(func, "q0", "", mn-rng, mn+rng);
      for (int i = 0;        i < 4; i++) par[i] = func->GetParameter(i);
      for (int i = 0; per && i < 4; i++) per[i] = func->GetParError (i);

      if (func->GetNDF() > 0) csq = func->GetChisquare()/func->GetNDF();
    }
    else {
      hist->Fit("gaus", "q0", "", mn-rng, mn+rng);

      TF1 *fg = hist->GetFunction("gaus");
      for (int i = 0; fg &&        i < 3; i++) par[i] = fg->GetParameter(i);
      for (int i = 0; fg && per && i < 3; i++) per[i] = fg->GetParError (i);

      if (fg && fg->GetNDF() > 0) csq = fg->GetChisquare()/fg->GetNDF();
    }
    if (par[2] < 0) par[2] = TMath::Abs(par[2]);

    float    xch = 830;
    float    ych = par[1];
    int       ml = TkCoo::GetMaxMult (tkid, xch);
    float     lx = TkCoo::GetLocalCoo(tkid, xch, ml-1);
    float     ly = TkCoo::GetLocalCoo(tkid, ych, ml-1);
    AMSPoint coo = TkCoo::GetGlobalA (tkid, lx, ly);
    par[4] = coo.y();
    if (per) per[4] = per[1]*TkDBc::Head->_PitchS;
  }

  return csq;
}
void makeSamePhiPlots() 
{
   gSystem->AddIncludePath("-I${EVENT_READER_DIR}");
   gSystem->AddIncludePath("-I${PLOTTER_DIR}");
   //  cout << gSystem->GetIncludePath() <<endl;
   
   gSystem->Load("libMathMore.so");
   gSystem->Load("/usr/lib64/libfftw3.so");
   gSystem->Load("libAnitaEvent.so");
   gSystem->Load("libAnitaCorrelator.so");
   TChain *deltaTTree = new TChain("deltaTTree");
   //   TFile *fp = new TFile("deltaTFile1027.root");
   //   TTree *deltaTTree = (TTree*) fp->Get("deltaTTree");
   deltaTTree->Add("deltaTFileClock*.root");
   
   AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();



   char plotCond[180];
   char plotTitle[180];
   char histName[180];
   TF1 *fitty = new TF1("fitty","gaus",-1,1);

   TH1F *histMeanDiff = new TH1F("histMeanDiff","histMeanDiff",100,-1,1);
   TH1F *histChiSq = new TH1F("histChiSq","histChiSq",100,0,3);
   TH1F *histSigma = new TH1F("histSigma","histSigma",100,0,10);
   TH1F *histConstant = new TH1F("histConstant","histConstant",100,0,100);

   ofstream Output("diffsDown.txt");

   for(int ant=0;ant<16;ant++) {
      TCanvas *can = new TCanvas();//"can","can");
      can->Divide(2,2);
      int topAnt=ant; 
      int bottomAnt=fGeomTool->getAzimuthPartner(topAnt); 
      for(int chip=0;chip<4;chip++) {
	 fitty->SetParameters(10,0,0.05);
	 //	 fitty->SetParLimits(2,0,0.1);

	 can->cd(chip+1);
	 sprintf(plotCond,"((firstAnt==%d && secondAnt==%d))  && labChip==%d && (corPeak/corRMS)>6",topAnt,bottomAnt,chip);	 
	 sprintf(plotTitle,"Ant %d -  Ant %d (Chip %d)",topAnt,bottomAnt,chip);
	 sprintf(histName,"histDt_%d_%d",ant,chip);
	 TH1F *histDt11 = new TH1F(histName,plotTitle,40,-0.5,0.5);

	 deltaTTree->Project(histName,"deltaT-deltaTExpected",plotCond);
	 //	 cout << plotCond << endl;
	 histDt11->Draw();
	 histDt11->Fit("fitty","Q");
	 Int_t numUnder= histDt11->GetBinContent(0);
	 Int_t numOver =histDt11->GetBinContent(1+histDt11->GetNbinsX());
// 	 cout << topAnt << "\t" << bottomAnt << "\t" << chip << "\t" << histDt11->GetEntries() << "\t"
// 	      << (histDt11->GetEntries()-(numOver+numUnder)) << "\t" << histDt11->GetMean() << "\t" << histDt11->GetRMS() << "\t"
// 	      << fitty->GetParameter(1) << "\t" << fitty->GetParError(1) << "\t" << fitty->GetParameter(2) << "\t"
// 	      << fitty->GetParError(2)  << "\t" << fitty->GetChisquare() << "\t" << fitty->GetNDF() << "\n";
	 histMeanDiff->Fill(fitty->GetParameter(1));
	 histChiSq->Fill(fitty->GetChisquare()/Double_t(fitty->GetNDF()));
	 histSigma->Fill(fitty->GetParameter(2));
	 histConstant->Fill(fitty->GetParameter(0));


	 Double_t constant=histDt11->GetMean();
	 Double_t error=0;
	 if(histDt11->GetEntries())
	    error=histDt11->GetRMS()/TMath::Sqrt(histDt11->GetEntries());
	 Int_t entries=(histDt11->GetEntries()-(numOver+numUnder));

	 if(TMath::Abs(fitty->GetParameter(1)-histDt11->GetMean())<0.01 || (entries>=20 && fitty->GetParError(1)<0.08)) {
	    constant=fitty->GetParameter(1);
	    error=fitty->GetParError(1);
	 }
	 else {
	    cout << topAnt << "\t" << bottomAnt << "\t" << chip << "\n";
	 }
	 Output << topAnt << "\t" << bottomAnt << "\t" << chip << "\t" << constant << "\t" << error << "\t"
		<< entries << "\n";
      }
	 
   }
   TCanvas *canSum = new TCanvas();
   canSum->Divide(2,2);
   canSum->cd(1);
   histChiSq->Draw();
   canSum->cd(2);
   histConstant->Draw();
   canSum->cd(3);
   histMeanDiff->Draw();
   canSum->cd(4);
   histSigma->Draw();    

      
}
Exemple #22
0
int main(int argc, char* argv[]){
    UImanager uimanager(argc, argv, "dndt_fit");
//work directory    
    TString workdir(getenv("WORKDIR"));
//***************************set constant ****************************************
    Double_t acdntl_corr = 1., respf_corr = 1.;
	Double_t eff_corr = uimanager.get_adcerr() * uimanager.get_br_corr() * uimanager.get_ta_corr() * acdntl_corr * respf_corr;//	adcerr x tdiff_cut_eff x veto_eff x pi0 decay products abs. (set to 1, since included in current rmat) x bkg_in_fit (not in current rmat)
    if(uimanager.best_tdiff()) eff_corr *= uimanager.get_bit_corr();
    if(uimanager.ismc()) eff_corr = uimanager.get_ta_corr(); 

    cout << eff_corr << " " << uimanager.flux() << " " << uimanager.get_tgt_lumi() << endl;
	Double_t f_l = uimanager.flux() * uimanager.get_tgt_lumi() * eff_corr;

//************ start reading files *******************************
//read tables/eflux.dat [tables/effcor.dat] tables/dfp1_xx.dat or current_foler/dfp1_xx.dat
//get echn flux
	Double_t flw[180];
	ifstream eflux(workdir+"tables/eflux.dat");
	if (!eflux.is_open()) {
		cout << "eflux doesn't exist" << endl;
		exit(1);
 	}
	for(int i=0;i<180;i++)eflux>>flw[i];
//get efficiency table
    TString dfp;
    if (!uimanager.target()) dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_si.dat";
    else dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_c12.dat";

	ifstream profile;
    profile.open(dfp);
    if (profile.is_open()) {
        cout << "use local efficiency table: " << dfp << endl;
    } else {
        //profile.open(workdir+"efficiency2/tables/"+dfp);
        profile.open(workdir+"/tables/"+dfp);
        if(!profile.is_open()) cout << " can't open table " << dfp << endl;
        cout << " use efficiency table in tables: " << dfp << endl;
    }
	
    const int phy = 5;
	const int ech = 180;
	Double_t dfprob[phy][nangle][ech];
	Double_t coulm[nangle], ncohe[nangle], cosfiint[nangle], sinfiint[nangle], ninco[nangle];
	for(int i=0;i<nangle;i++){
		coulm[i]=0;
        ncohe[i]=0;
		cosfiint[i]=0;
		sinfiint[i]=0;
		ninco[i]=0;
	}

	for(int i = 0;i < 180;i++)
		for(int j = 0;j < nangle;j++)
			for(int k = 0;k < 5;k++){
				Double_t f_l_j=f_l;
				int ic = 0;
				int jc = 0;
				int kc = 0;
				profile>>ic>>jc>>kc>>dfprob[k][j][i];
                if(ic!=i+1||jc!=j+1||kc!=k+1){
					cout << i << " " << j << " " << k << endl;
					cout << ic << " " << jc << " " << kc << " " << dfprob[k][j][i] << endl;
					cout<<"Bad data given for dfprob"<<endl;
					exit(1);
				}
				if(kc==1)coulm[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==2)cosfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==3)ncohe[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==4)ninco[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else sinfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
            }

	for(int i=1;i<=nangle;i++){
		hcoulm->SetBinContent(i,coulm[i-1]);
		hcosfiint->SetBinContent(i,cosfiint[i-1]);
		hncohe->SetBinContent(i,ncohe[i-1]);
		hninco->SetBinContent(i,ninco[i-1]);
		hsinfiint->SetBinContent(i,sinfiint[i-1]);
    }
//read yield
    TString inrootname("pi0alt" + uimanager.input_filename("fit") + ".root");

	TFile *yield = new TFile(inrootname);
    if (!yield->IsOpen()) exit(open_err(inrootname));
	TH1F *yieldhist = (TH1F*)yield->Get("hyield");
	//TH1F *yieldhist = (TH1F*)yield->Get("hyield_mc_nocut");
	yieldhist->SetDirectory(0);
	if (!uimanager.target() && !uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/o tran.)");
    else if (!uimanager.target()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/ tran.)");
    else if (!uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/o tran.)");
    else yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/ tran.)");
    
    double nyield = 0, nyield_err = 0;
    for(int i = 1; i<=125; i++) {
        nyield += yieldhist->GetBinContent(i);
        nyield_err += yieldhist->GetBinError(i)*yieldhist->GetBinError(i);
    }
    nyield_err = sqrt(nyield_err);
//***************** end reading files **************************************
    
	gStyle->SetOptFit(1);
	gStyle->SetOptStat(0);
	gStyle->SetPaperSize(12,24);
	//Double_t parameter[4] = {7.9, 1.0, 1.0, 0.8};
	Double_t parameter[4] = {7.7, 1.0, 0.8, 0.5};

	TF1 *ftot = new TF1("ftot", dndt, 0., dndt_fit_range, 4);
	ftot->SetParNames("#Gamma","C1","#phi","C2");

	ftot->SetParameter(0,parameter[0]);
	ftot->SetParameter(1,parameter[1]);
	ftot->SetParameter(2,parameter[2]);
	ftot->SetParameter(3,parameter[3]);
/*
	ftot->FixParameter(0,parameter[0]);
	ftot->FixParameter(1,parameter[1]);
	ftot->FixParameter(2,parameter[2]);
	ftot->FixParameter(3,parameter[3]);
*/
    ftot->SetParLimits(0, 3, 10);
    ftot->SetParLimits(1, 0.3, 1.5);
    ftot->SetParLimits(2, 0, 3.1415936/2);
    ftot->SetParLimits(3, 0., 10.0);

	yieldhist->Fit("ftot", "RMBE0");

	Double_t chi2 = ftot->GetChisquare()/ftot->GetNDF();
	parameter[0]=ftot->GetParameter(0);
	parameter[1]=ftot->GetParameter(1);
	parameter[2]=ftot->GetParameter(2);
	parameter[3]=ftot->GetParameter(3);
	
    Double_t e1 = ftot->GetParError(0);
    Double_t e2 = ftot->GetParError(1);
    Double_t e3 = ftot->GetParError(2);
    Double_t e4 = ftot->GetParError(3);

	//cout<<chi2<<" "<<parameter[0]<<" "<<parameter[1]<<" "<<parameter[2]<<" "<<parameter[3]<<endl;
    TString fname = "fitresult" + uimanager.input_filename("fit") + ".dat";
    ofstream output(fname);
    output<<nyield<<" "<<nyield_err<<" "<<chi2<<" "<<parameter[0]<<" "<<e1<<" "<<parameter[1]<<" "<<e2<<" "<<parameter[2]<<" "<<e3<<" "<<parameter[3]<<" "<<e4<<endl;

	TH1F *fithist = new TH1F("fithist", "fithist", fit_nangle, 0, dndt_fit_range);
	TH1F *fitcoulm = new TH1F("fitcolum", "fitcolum", fit_nangle, 0, dndt_fit_range);
	TH1F *fitncohe = new TH1F("fitncohe", "fitncohe", fit_nangle, 0, dndt_fit_range);
	TH1F *fitit = new TH1F("fitit", "fitit", fit_nangle, 0, dndt_fit_range);
	TH1F *fitninco = new TH1F("fitninco", "fitninco", fit_nangle, 0, dndt_fit_range);

	yieldhist->SetLineWidth(2);
	fithist->SetLineWidth(2);
	fitcoulm->SetLineWidth(2);
	fitncohe->SetLineWidth(2);
	fitit->SetLineWidth(2);
	fitninco->SetLineWidth(2);

	float accfit[fit_nangle], acchist[fit_nangle], acchisterr[fit_nangle], diff[fit_nangle];

	for(int i=1;i<=fit_nangle;i++){
		fithist->SetBinContent(i,ftot->Eval(max_angle/nangle*(i-0.5)));
		fitcoulm->SetBinContent(i,parameter[0]*hcoulm->GetBinContent(i));
		fitncohe->SetBinContent(i,parameter[1]*hncohe->GetBinContent(i));
		fitit->SetBinContent(i,TMath::Sqrt(parameter[0]*parameter[1])*(TMath::Cos(parameter[2])*hcosfiint->GetBinContent(i)+TMath::Sin(parameter[2])*hsinfiint->GetBinContent(i)));
		fitninco->SetBinContent(i,parameter[3]*hninco->GetBinContent(i));
		if (i == 1) {
			accfit[0] = fithist->GetBinContent(1);
			acchist[0] = yieldhist->GetBinContent(1);
			acchisterr[0] = yieldhist->GetBinError(1) * yieldhist->GetBinError(1);
		}
		if (i != fit_nangle) {
			acchist[i] = yieldhist->GetBinContent(i) + acchist[i - 1];
			accfit[i] = fithist->GetBinContent(i) + accfit[i - 1];
			acchisterr[i] = acchisterr[i - 1] + yieldhist->GetBinError(i) * yieldhist->GetBinError(i);
		}
	}

	for(int i = 0; i < fit_nangle; ++i) {
		
		diff[i] = acchist[i] - accfit[i];
		acchisterr[i] = sqrt(acchisterr[i]);
	}

	TString outfilename("fyield" + uimanager.input_filename("fit"));

	float angles[fit_nangle], ex[fit_nangle];
	for(int i=0;i<fit_nangle;i++) {
		angles[i] = 0.02*(i+0.5);
        ex[i] = 0;
    }

	TGraphErrors ge(fit_nangle, angles, diff, ex, acchisterr);
	TGraphErrors ge1(fit_nangle, angles, acchist, ex, acchisterr);
	TGraph ge2(fit_nangle, angles, accfit);

	TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
	c1->SaveAs(outfilename+".pdf[");
	yieldhist->SetMinimum(0);
	yieldhist->SetMaximum(yieldhist->GetMaximum()*1.05);
	yieldhist->Draw("e1");
	fitcoulm->SetLineColor(kBlue);
	fitcoulm->Draw("sameC");
	fitncohe->SetLineColor(32);
	fitncohe->Draw("sameC");
	fitit->SetLineColor(kBlack);
	fitit->Draw("sameC");
	fitninco->SetLineColor(kYellow);
	fitninco->Draw("sameC");
	fithist->SetLineColor(kRed);
	fithist->Draw("sameC");

	TLegend *leg = new TLegend(0.1,0.7,0.45,0.9);
	leg->SetFillColor(0);
	leg->SetTextSize(0.03);
	leg->AddEntry(fitcoulm,"Primakoff","L");
	leg->AddEntry(fitncohe,"Nuclear Coherent","L");
	leg->AddEntry(fitit,"Interference","L");
	leg->AddEntry(fitninco,"Nuclear Incoherent","L");
	//leg->Draw();

	c1->SaveAs(outfilename+".pdf");

	ge.SetMarkerStyle(20);
	ge.SetMarkerColor(kBlue);
	ge.SetTitle("accumulated yield - fit vs. #theta");
	ge.Draw("ap");
	c1->SaveAs(outfilename + ".pdf");

	ge1.SetMarkerStyle(20);
	ge1.SetMarkerColor(kBlue);
	ge1.SetTitle("accumulated yield and fitting vs. #theta");
	ge1.Draw("ap");
	ge2.SetLineColor(kRed);
	ge2.Draw("sameC");
	c1->SaveAs(outfilename + ".pdf");

	c1->SaveAs(outfilename+".pdf]");

	TFile *ftyd = new TFile(outfilename+".root", "RECREATE");
	yieldhist->Write();
	fithist->Write();
	fitcoulm->Write();
	fitncohe->Write();
	fitit->Write();
	fitninco->Write();
    hcoulm->Write();
    hncohe->Write();
    hninco->Write();
	hcosfiint->Write();
    hsinfiint->Write();
    ftyd->Close();
    
	return 0;
}
//*************************************************************
std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > fitResidualsCB(TH1 *hist)
//*************************************************************
{
  
  //hist->Rebin(2);

  float mean  = hist->GetMean();
  float sigma = hist->GetRMS();
  //int   nbinsX   = hist->GetNbinsX();
  float nentries = hist->GetEntries();
  float meanerr  = sigma/TMath::Sqrt(nentries);
  float sigmaerr = TMath::Sqrt(sigma*sigma*TMath::Sqrt(2/nentries));

  float lowBound  = hist->GetXaxis()->GetBinLowEdge(1);
  float highBound = hist->GetXaxis()->GetBinLowEdge(hist->GetNbinsX()+1);

  if(TMath::IsNaN(mean) || TMath::IsNaN(sigma)){  
    mean=0;
    sigma= - lowBound + highBound;
  }
  
  TF1 func("tmp", "gaus", mean - 1.*sigma, mean + 1.*sigma); 
  if (0 == hist->Fit(&func,"QNR")) { // N: do not blow up file by storing fit!
    mean  = func.GetParameter(1);
    sigma = func.GetParameter(2);
  }
  
  // first round
  TF1 *doubleCB = new TF1("myDoubleCB",DoubleSidedCB,lowBound,highBound,7);
  doubleCB->SetParameters(mean,sigma,1.5,1.5,2.5,2.5,100);
  doubleCB->SetParLimits(0,mean-meanerr,mean+meanerr);
  doubleCB->SetParLimits(1,0.,sigma+2*sigmaerr);
  doubleCB->SetParLimits(2,0.,30.);
  doubleCB->SetParLimits(3,0.,30.);
  doubleCB->SetParLimits(4,0.,50.);
  doubleCB->SetParLimits(5,0.,50.);
  doubleCB->SetParLimits(6,0.,100*nentries);

  doubleCB->SetParNames("#mu","#sigma","#alpha_{L}","#alpha_{R}","n_{L}","n_{R}","N");
  doubleCB->SetLineColor(kRed);
  doubleCB->SetNpx(1000);
  // doubleCB->SetRange(0.8*lowBound,0.8*highBound);

  hist->Fit(doubleCB,"QM");

  // second round

  float p0 = doubleCB->GetParameter(0);
  float p1 = doubleCB->GetParameter(1);
  float p2 = doubleCB->GetParameter(2);
  float p3 = doubleCB->GetParameter(3);
  float p4 = doubleCB->GetParameter(4);
  float p5 = doubleCB->GetParameter(5);
  float p6 = doubleCB->GetParameter(6);
  
  float p0err = doubleCB->GetParError(0);
  float p1err = doubleCB->GetParError(1);
  float p2err = doubleCB->GetParError(2);
  float p3err = doubleCB->GetParError(3);
  float p4err = doubleCB->GetParError(4);
  float p5err = doubleCB->GetParError(5);
  float p6err = doubleCB->GetParError(6);

  if( (doubleCB->GetChisquare()/doubleCB->GetNDF()) >5){

    std::cout<<"------------------------"<<std::endl;
    std::cout<<"chi2 1st:"<<doubleCB->GetChisquare()<<std::endl;

    //std::cout<<"p0: "<<p0<<"+/-"<<p0err<<std::endl;
    //std::cout<<"p1: "<<p1<<"+/-"<<p1err<<std::endl;
    //std::cout<<"p2: "<<p2<<"+/-"<<p2err<<std::endl;
    //std::cout<<"p3: "<<p3<<"+/-"<<p3err<<std::endl;
    //std::cout<<"p4: "<<p4<<"+/-"<<p4err<<std::endl;
    //std::cout<<"p5: "<<p5<<"+/-"<<p5err<<std::endl;
    //std::cout<<"p6: "<<p6<<"+/-"<<p6err<<std::endl;

    doubleCB->SetParameters(p0,p1,3,3,6,6,p6);
    doubleCB->SetParLimits(0,p0-2*p0err,p0+2*p0err);
    doubleCB->SetParLimits(1,p1-2*p1err,p0+2*p1err);
    doubleCB->SetParLimits(2,p2-2*p2err,p0+2*p2err);
    doubleCB->SetParLimits(3,p3-2*p3err,p0+2*p3err);
    doubleCB->SetParLimits(4,p4-2*p4err,p0+2*p4err);
    doubleCB->SetParLimits(5,p5-2*p5err,p0+2*p5err);
    doubleCB->SetParLimits(6,p6-2*p6err,p0+2*p6err);

    hist->Fit(doubleCB,"MQ");

    //gMinuit->Command("SCAn 1");
    //TGraph *gr = (TGraph*)gMinuit->GetPlot();
    //gr->SetMarkerStyle(21);
    //gr->Draw("alp"); 

    std::cout<<"chi2 2nd:"<<doubleCB->GetChisquare()<<std::endl;
    
  }

  float res_mean  = doubleCB->GetParameter(0);
  float res_width = doubleCB->GetParameter(1);
  
  float res_mean_err  = doubleCB->GetParError(0);
  float res_width_err = doubleCB->GetParError(1);

  std::pair<Double_t,Double_t> resultM;
  std::pair<Double_t,Double_t> resultW;

  resultM = std::make_pair(res_mean,res_mean_err);
  resultW = std::make_pair(res_width,res_width_err);

  std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > result;
  
  result = std::make_pair(resultM,resultW);
  return result;

}
Exemple #24
0
//Noise section
Stat_t AnalysisClass::doNoiseFit(Int_t RunNumber, Char_t *Variable, Char_t *SubDetName, Char_t *Layer, Char_t *label){
  TH1 *hNtoFit=0;
  if (debug) cout << d1->GetTitle() << " " << Variable << " " << SubDetName << endl;
  pPar[0]=0; pPar[1]=0;
  TIter it(d1->GetListOfKeys());
  TObject * o;
  while ( (o = it()))  
    {
      TObject * d =  d1->Get(o->GetName());
      if(d->IsA()->InheritsFrom("TDirectory") && strstr(d->GetName(),SubDetName)){
	if (debug) cout << "Found " << SubDetName << endl;
	TIter it2(((TDirectoryFile * )d)->GetListOfKeys());
	TObject *o2;
	while( ( o2 = it2()) ){
	  TObject *d2 = ((TDirectoryFile * )d)->Get(o2->GetName());
	  if(d2->IsA()->InheritsFrom("TDirectory") && strstr(d2->GetName(),Layer) ){
	    if (debug) cout << "Found Layer" << Layer << endl;
	    TIter it3(((TDirectoryFile * )d2)->GetListOfKeys());
	    TObject *o3;
	    while( ( o3 = it3()) ){
	      TObject *d3 = ((TDirectoryFile * )d2)->Get(o3->GetName());
	      if(strstr(d3->GetName(),Variable) && strstr(d3->GetName(),label)){
		hNtoFit = (TH1*) d3;
		if (debug) cout << "Found " << Variable << endl;
		if (hNtoFit->GetEntries()!=0) {
		  cout<<"Fitting "<< hNtoFit->GetTitle() <<endl;
		  // Setting fit range and start values
		  Double_t fr[2];
		  Double_t sv[3], pllo[3], plhi[3];
		  fr[0]=hNtoFit->GetMean()-5*hNtoFit->GetRMS();
		  fr[1]=hNtoFit->GetMean()+5*hNtoFit->GetRMS();
		  
		  Int_t imax=hNtoFit->GetMaximumBin();
		  Double_t xmax=hNtoFit->GetBinCenter(imax);
		  Double_t ymax=hNtoFit->GetBinContent(imax);
		  Int_t i[2];
		  Int_t iArea[2];
		  
		  i[0]=hNtoFit->GetXaxis()->FindBin(fr[0]);
		  i[1]=hNtoFit->GetXaxis()->FindBin(fr[1]);
		  
		  iArea[0]=hNtoFit->GetXaxis()->FindBin(fr[0]);
		  iArea[1]=hNtoFit->GetXaxis()->FindBin(fr[1]);
		  Double_t AreaFWHM=hNtoFit->Integral(iArea[0],iArea[1],"width");
		  
		  sv[2]=AreaFWHM/(4*ymax);
		  sv[1]=xmax;
		  sv[0]=hNtoFit->Integral(i[0],i[1],"width");
		  
		  plhi[0]=1000000.0; plhi[1]=10.0; plhi[2]=10.;
		  pllo[0]=1.5 ; pllo[1]=0.1; pllo[2]=0.3;
		  Char_t FunName[100];
		  sprintf(FunName,"FitfcnLG_%s%d",hNtoFit->GetName(),fRun);
		  TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
		  if (ffitold) delete ffitold;
		  
		  gausFit = new TF1(FunName,Gauss,fr[0],fr[1],3);
		  gausFit->SetParameters(sv);
		  gausFit->SetParNames("Constant","GaussPeak","Sigma");
		  
		  for (Int_t i=0; i<3; i++) {
		    gausFit->SetParLimits(i,pllo[i],plhi[i]);
		  }
		  hNtoFit->Fit(gausFit,"R0");
		  
		  gausFit->SetRange(fr[0],fr[1]);
		  pGausS=gausFit->GetParameters();
		  epGausS=gausFit->GetParErrors();
		  
		  chi2GausS =langausFit->GetChisquare(); // obtain chi^2
		  nDofGausS = langausFit->GetNDF();// obtain ndf
		  
		  TCanvas *cAllN = new TCanvas("NoiseFit",hNtoFit->GetTitle(),1);
		  Char_t fitFileName[60];
		  sprintf(fitFileName,"Fits/Run_%d/%s/Fit_%s.png",RunNumber,SubDetName,hNtoFit->GetTitle());
		  hNtoFit->Draw("pe");
		  gStyle->SetOptFit(1111111);
		  gausFit->Draw("lsame");
   
		  cAllN->Print(fitFileName,"png");
		}else {
		  pGausS[0]=-10; pGausS[1]=-10; pGausS[2]=-10;
		  epGausS[0]=-10; epGausS[1]=-10; epGausS[2]=-10;
		}
	      }
	    }
	  }
	}
      }
    }
 
  return hNtoFit->GetEntries();
}
Exemple #25
0
void fitLOW(const char *run="19020_19035",
	    int arm=0, int lyr=2, int sen=21, int mpd=0,
	    bool draw=true,
	    //int old_xfit_min=12, int old_xfit_max=82,
	    int old_xfit_min=8, int old_xfit_max=62,
	    double xfit_min=2.5, double xfit_max=18.5) {
  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  TString inname = Form("%s/adc/LO_ARM%d_LYR%d_S%d_M%d.root",run,arm,lyr,sen,mpd);
  TString prename = Form("HI_ARM%d_LYR%d_S%d_M%d_%d_%d",arm,lyr,sen,mpd,old_xfit_min,old_xfit_max);
  TString outname = Form("LO_ARM%d_LYR%d_S%d_M%d_%.0f_%.0f",arm,lyr,sen,mpd,xfit_min,xfit_max);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;
  cout << prename.Data() << endl;
  cout << outname.Data() << endl;

  TF1 *fitH = GetFit(run,prename.Data(),outname.Data());
  if(!fitH) return;
  if(lda<1) return;

  // data
  TH1D *out = (TH1D*) file->Get("out");
  double ymax = out->GetMaximum();
  int entries = out->Integral(xfit_min,xfit_max);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");

  // fit
  TCanvas *main = new TCanvas("main","main");
  main->SetLogy(1);
  out->Draw("HE");
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-4.5,50.5);

  out->Fit(fitH,"QENIML","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);

  double sLDA = fitH->GetParameter(0);
  double eLDA= fitH->GetParError(0);
  double sSGM = fitH->GetParameter(1);
  double eSGM = fitH->GetParError(1);
  double ncs = fitH->GetChisquare()/fitH->GetNDF();

  double ldalow = lda*sLDA;
  double sgmlow = sgm*sSGM;

  double eldalow = TMath::Abs(ldalow)*TMath::Sqrt( elda/lda*elda/lda + eLDA/sLDA*eLDA/sLDA );
  double esgmlow = TMath::Abs(sgmlow)*TMath::Sqrt( esgm/sgm*esgm/sgm + eSGM/sSGM*eSGM/sSGM );

  ofstream outfit;
  outfit.open( Form("%s/fit/%s.dat",run,outname.Data()) );
  outfit << sLDA << " " << eLDA << endl;
  outfit << sSGM << " " << eSGM << endl;
  outfit << ldalow << endl;
  outfit << sgmlow << endl;
  outfit << ncs << endl;
  outfit.close();

  // draw
  if(!draw) return;

  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(1, TMath::Exp(1.03*TMath::Log(ymax)), inname );
  text->DrawLatex(20, TMath::Exp(0.93*TMath::Log(ymax)), Form("Entries  %d",entries) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(44, TMath::Exp(0.83*TMath::Log(ymax)),  Form("#chi^{2} / NDF  %.2f",ncs) );
  text->DrawLatex(20, TMath::Exp(0.83*TMath::Log(ymax)),  Form("S_{#lambda}  %.3f #pm %.3f",sLDA,eLDA) );
  text->DrawLatex(20, TMath::Exp(0.73*TMath::Log(ymax)),  Form("S_{#sigma}  %.3f #pm %.3f",sSGM,eSGM) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(20, TMath::Exp(0.60*TMath::Log(ymax)),  Form("#lambda^{H}  %.1f #pm %.1f   #rightarrow  #lambda^{L}  %.1f #pm %.1f",lda,elda,ldalow,eldalow) );
  text->DrawLatex(20, TMath::Exp(0.50*TMath::Log(ymax)),  Form("#sigma^{H}  %.1f #pm %.1f   #rightarrow  #sigma^{L}  %.1f #pm %.1f",sgm,esgm,sgmlow,esgmlow) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.04);
  main->SaveAs( Form("%s/fiteps/%s.png",run,outname.Data()), "png" );
  return;
}
Exemple #26
0
void checkflat(int icent = 0, int ihar=0){
    int color[nsub]={1,2,3,4,5,6,7,8};
    float pi = acos(-1.0);
    TString str;
    TFile *fin;
        TH1::SetDefaultSumw2();
        gStyle->SetOptStat(kFALSE);
        int iharE=0;
     if(nhar==1||nhar==2) iharE=1;
        int n = ihar+1.0+iharE;
    int nrun = GetTotalRun();
    float FitGood[nsub][1000];
    float FitGooderr[nsub][1000];
    float runlist[1000];
        TH1F* hpsi = new TH1F("psi","psi",100,-pi,pi);
        TH1F* hunpsi = new TH1F("unpsi","unpsi",100,-pi,pi);
        TH1F* h = new TH1F("h","",100,-4,4);
        for(int irun=0;irun<nrun;irun++){
        std::ifstream corrs("run15pAl200MBPro104.Lst");
        int index=0; int run=0;
        for(int jrun=0;jrun<irun+1;jrun++){
        corrs>>index>>run;
        }
        runlist[irun] = run;
       // system(Form("hadd -f /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root /phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d_*.root",run,run));
        fin = TFile::Open(Form("/phenix/plhf/xuq/taxi/Run15pAl200MBPro104/10241/data/%d.root",run));
        for(int isub=0;isub<nsub;isub++){
        str = choosesub(isub);
        if(str=="ABORT") continue;
        hpsi->Reset();
        hunpsi->Reset();
        for(int ibbcz=0;ibbcz<nbbcz;ibbcz++){
          TH1F* hunpsitemp = (TH1F*)fin->Get(Form("psi_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          TH1F* hpsitemp = (TH1F*)fin->Get(Form("psiFla_0_0_%d_%d_%d_%d",icent,ibbcz,ihar,isub));
          hpsi->Add(hpsitemp);
          hunpsi->Add(hunpsitemp);
        }
        TF1 *fun = new TF1("fun","pol0",-pi,pi);
        TCanvas *c1 = new TCanvas("c1","c1",600,450);
        h->GetXaxis()->SetTitle(Form("#Psi_{%d}",n));
        h->GetYaxis()->SetTitle(Form("# of events"));
        h->GetYaxis()->SetRangeUser(hunpsi->GetBinContent(hunpsi->GetMinimumBin())*0.9,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.1);
        h->Draw("C");
       // h->GetYaxis()->SetRangeUser(0,hunpsi->GetBinContent(hunpsi->GetMaximumBin())*1.2);
      if(hpsi->GetEntries()>1000){
	hpsi->Fit("fun","QR0");
	float par=fun->GetParameter(0);
	float parerr=fun->GetParError(0);
        FitGood[isub][irun]=fun->GetChisquare()/fun->GetNDF();
        FitGooderr[isub][irun]=0;
        fun->SetLineColor(4);
        fun->Draw("same");
      }
        else{
        FitGood[isub][irun]=0;
        FitGooderr[isub][irun]=0;
        }
        if(irun!=104) continue;
	hpsi->SetMarkerStyle(20);
	hpsi->SetMarkerSize(0.8);
	hpsi->SetMarkerColor(2);
	hpsi->SetLineColor(2);
	hunpsi->SetMarkerStyle(20);
	hunpsi->SetMarkerSize(0.8);
	hunpsi->SetMarkerColor(1);
	hunpsi->SetLineColor(1);
        TLegend *leg = new TLegend(0.4,0.7,0.8,0.85);
        leg->SetTextSize(0.04);
        leg->SetFillColor(0);
        leg->SetBorderSize(0);
        leg->AddEntry(hunpsi,Form("Run%d %s",run,str.Data()));
        leg->AddEntry(hunpsi,"before flattening","L");
        leg->AddEntry(hpsi,"After flattening","L");
        hpsi->Draw("Csame");
        hunpsi->Draw("Csame");
        leg->Draw("same");
        c1->Print(Form("run-by-run/checkflat_%d_%d_%d_%d.png",icent,ihar,isub,irun));
        delete c1;
        }
        fin->Close();
    }  
        TGraphErrors *grRun[nsub];
    TCanvas *c1 = new TCanvas("c1","c1",600,450);
    TCanvas *c2 = new TCanvas("c2","c2",600,450);
    TH1F* h1 = new TH1F("h1","",4000,436000,439000);
    h1->GetXaxis()->SetTitle(Form("Run Number"));
    h1->GetYaxis()->SetTitle("Fit #chi^{2}/Ndf");
    h1->GetXaxis()->SetRangeUser(runlist[0]-15,runlist[nrun-1]+15);
    h1->GetYaxis()->SetRangeUser(0,4);
    TLegend *leg = new TLegend(0.65,0.75,0.88,0.85);
    leg->SetTextSize(0.035);
    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    c1->cd();
    h1->Draw("0");
        for(int isub=0;isub<nsub;isub++){
            if(isub!=4 && isub!=5) continue;
            grRun[isub] = new TGraphErrors(nrun,runlist,FitGood[isub],0,FitGooderr[isub]);
            grRun[isub] -> SetMarkerColor(isub-3);
            grRun[isub] -> SetMarkerSize(1.);
            grRun[isub] -> SetMarkerStyle(16+isub);
            grRun[isub] -> SetLineColor(isub-3);
            grRun[isub] -> Draw("Psame");
            leg->AddEntry(grRun[isub],choosesub(isub).Data(),"P");
        leg->Draw("same");
        }
      c1->Print(Form("run-by-run/fitsum%d.png",n));
}
Exemple #27
0
void fit(const char *run="428211_429133_5s",
	 int key=1, int bmin=10, bool draw=true, bool pa=false) {
  int minentries=1000;
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  int state = findstate(key);
  printf("state %d\n",state);
  // data
  TString inname = Form("%s/adc/HI_KEY%05d.root",run,key);
  TString outname = Form("HI_KEY%05d",key);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;

  TH1D *out = (TH1D*) file->Get("out");
  double xfit_min=out->GetBinLowEdge(bmin);
  double xfit_max=122.5;
  int bmax = out->GetXaxis()->FindBin(xfit_max);
  int entries = out->Integral(bmin,bmax);
  if(entries<minentries) {
    cout << "not enough entries: ";
    cout << entries << endl;
    return;
  }

  // fit
  TCanvas *main = new TCanvas("main","main");
  int pkt=0;
  if(pa)
    pkt = (key%(8*4*12*64))/(4*12*64);
  TF1 *fitH = GetFit( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) ,pkt,xfit_min);
  out->Fit(fitH,"MELIR","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);
  TF1 *BGR = GetBGR(fitH,xfit_min);

  double amp = fitH->GetParameter(0);
  double eamp= fitH->GetParError(0);
  double lda = fitH->GetParameter(1);
  double elda= fitH->GetParError(1);
  double sg1 = fitH->GetParameter(2);
  double esg1= fitH->GetParError(2);
  double fr2 = fitH->GetParameter(3);
  double efr2= fitH->GetParError(3);
  double fr3 = fitH->GetParameter(4);
  double efr3= fitH->GetParError(4);
  double fr4 = fitH->GetParameter(5);
  double efr4= fitH->GetParError(5);
  double fr1 = 1 - fr2 - fr3 - fr4;
  double ncs = fitH->GetChisquare()/fitH->GetNDF();
  double ba = fitH->GetParameter(6);
  double eba= fitH->GetParError(6);
  double bsl = fitH->GetParameter(7);
  double ebsl= fitH->GetParError(7);

  // saving fit
  ofstream outfit;
  outfit.open( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) );
  outfit << amp << " " << eamp << endl;
  outfit << lda << " " << elda << endl;
  outfit << sg1 << " " << esg1 << endl;
  outfit << fr2 << " " << efr2 << endl;
  outfit << fr3 << " " << efr3 << endl;
  outfit << fr4 << " " << efr4 << endl;
  outfit << ba  << " " << eba  << endl;
  outfit << bsl << " " << ebsl << endl;
  outfit << ncs << endl;
  outfit.close();
  cout << "Parameters saved to ";
  cout << outname.Data() << ".dat" << endl;

  // draw
  if(!draw) return;

  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  out->Draw("HE");
  double ymax = out->GetBinContent( out->FindBin(xfit_min) )*1.5;
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-5,125);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");
  out->GetXaxis()->SetTitle("ADC-PED (a.u.)");
  BGR->Draw("SAME");
  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(0, (1.03*(ymax)), inname.Data() );
  text->DrawLatex(30, (0.83*(ymax)), Form("Entries  %d",entries) );
  text->DrawLatex(30, (0.73*(ymax)), Form("State  %d",state) );
  text->DrawLatex(30, (0.53*(ymax)), Form("#lambda  %.1f #pm %.1f",lda,elda) );
  text->DrawLatex(30, (0.43*(ymax)), Form("#sigma  %.1f #pm %.1f",sg1,esg1) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(30, (0.63*(ymax)), Form("#Chi^{2} / NDF  %.2f",ncs) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(75, (0.73*(ymax)), Form("#Alpha  %.0f #pm %.0f",fitH->GetParameter(0),fitH->GetParError(0)) );
  text->SetTextColor(kCyan-3);
  text->DrawLatex(75, (0.63*(ymax)), Form("f_{1}  %.2f",fr1) );
  text->SetTextColor(kGreen-3);
  text->DrawLatex(75, (0.53*(ymax)), Form("f_{2}  %.2f #pm %.2f",fr2,efr2) );
  text->SetTextColor(kOrange-3);
  text->DrawLatex(75, (0.43*(ymax)), Form("f_{3}  %.2f #pm %.2f",fr3,efr3) );
  text->SetTextColor(kMagenta-3);
  text->DrawLatex(75, (0.33*(ymax)), Form("f_{4}  %.2f #pm %.2f",fr4,efr4) );
  text->SetTextColor(kGray);
  text->DrawLatex(75, (0.83*(ymax)), Form("b  %.2f",bsl) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.035);
  text->SetTextColor( kRed-3 );
  text->DrawLatex(30, (0.93*(ymax)), "e^{bx} + #Alpha ( f_{1} L_{1}(x) + f_{2} L_{2}(x) + f_{3} L_{3}(x) + f_{4} L_{4}(x))");
  main->SaveAs( Form("%s/SEN%03d/%s.eps",run,key/128,outname.Data()), "eps" );
  return;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int MCClosure(){

 
  
  TGraphErrors* intrinsic, *full;
  TGraphErrors* Ratio;
  TGraphErrors* RatioAbs;
  
  
  TCanvas* canvas[4];
  TCanvas* canvas2[4];
  TCanvas* canvas3[4];
  TFile *file;
  TString fileName;

  const int eta_int = 4;
  double etaBorders[eta_int+1] = {0};
  TString etaRegion; 
  etaBorders[0] = 0.0;
  etaBorders[1] = 0.5;
  etaBorders[2] = 1.1; 
  etaBorders[3] = 1.7; 
  etaBorders[4] = 2.3; 

  for(int j=0; j<4; j++){

    if(j == 0) etaRegion.Form("|#eta| < %4.1f", etaBorders[j+1]);
    else       etaRegion.Form("%4.1f < #eta < %4.1f",etaBorders[j], etaBorders[j+1]);

    fileName.Form("c%i",j);
    canvas[j] = new TCanvas(fileName,fileName,0,0,500,500);

    canvas[j] ->cd();

    //char file1[100] = "_JetHemisphere_widthDivMean";
    char file1[100] = "";
    char file2[100] = "";

    fileName.Form("root_files%s/Resolution_for_%i_eta_bin_PFCHS_mc.root",file1,j+1);
    //fileName.Form("root_files/Scale_for_%i_eta_bin_PFCHS_mc.root",j+1);
    file = TFile::Open(fileName);
    file->GetObject("Graph",full);
    full -> SetMarkerColor(3);
    full -> SetLineColor(3);
    full -> GetFunction("fResolution")->SetLineColor(3);
    full ->SetMaximum(0.12);
    full ->SetMinimum(0.04);
    full ->Draw("AP");
    delete file;


    fileName.Form("root_files%s/Resolution_for_%i_eta_bin_intrinsic_PFCHS_mc.root",file1,j+1);
    //fileName.Form("root_files/Scale_for_%i_eta_bin_intrinsic_PFCHS_mc.root",j+1);
    file = TFile::Open(fileName);
    file->GetObject("Graph",intrinsic);
    intrinsic -> SetMarkerColor(2);
    intrinsic -> SetLineColor(2);
    
    intrinsic -> GetFunction("fResolution")->SetLineColor(2);
    intrinsic ->Draw("Psame"); 
    
   
    TLegend *legend  = new TLegend(0.6,0.7,0.9,0.9);
    legend -> SetFillColor(0);
    legend -> SetTextSize(0.033);
    legend -> AddEntry(intrinsic,"intrinsic","l");
    legend -> AddEntry(full,"full resolution","l");

    legend->Draw("same");

    fileName.Form("Resolution_intrinsic_full_for_%i_eta_bin%s.pdf",j+1,file1);
    canvas[j]->SaveAs(fileName);



    delete file;

    const int numEntries = 9;
    double xIntrinsic[numEntries] = {0};
    double yIntrinsic[numEntries] = {0};
    double xIntrinsicError[numEntries] = {0};
    double yIntrinsicError[numEntries] = {0};
    double xFull[numEntries] = {0};
    double yFull[numEntries] = {0};
    double xFullError[numEntries] = {0};
    double yFullError[numEntries] = {0};

    double x[numEntries] = {0};
    double y[numEntries] = {0};
    double xError[numEntries] = {0};
    double yError[numEntries] = {0};

    for(int i=0; i<numEntries; i++){
      intrinsic   -> GetPoint(i+0,xIntrinsic[i],yIntrinsic[i]);
      full        -> GetPoint(i+0,xFull[i],yFull[i]);

      cout<<"xFull["<<i<<"] = "<<xFull[i]<<endl;
      cout<<"xIntrinsic["<<i<<"] = "<<xIntrinsic[i]<<endl;

      xIntrinsicError[i] = intrinsic -> GetErrorX(i+0);
      yIntrinsicError[i] = intrinsic -> GetErrorY(i+0);
      xFullError[i]      = full      -> GetErrorX(i+0);
      yFullError[i]      = full      -> GetErrorY(i+0);
      
      y[i] = yFull[i]/yIntrinsic[i] -1 ;
      x[i] = 1./2.*(xFull[i]+xIntrinsic[i]);
      
      yError[i] =  TMath::Sqrt(TMath::Power((1./yIntrinsic[i]),2)*TMath::Power(yFullError[i],2)+TMath::Power((yFull[i]/(TMath::Power(yIntrinsic[i],2))),2)*TMath::Power(yIntrinsicError[i],2));
      //cout<<"y["<<i<<"] = "<<y[i]*100<<endl<<endl;
      //cout<<"yError["<<i<<"] = "<<yError[i]*100<<endl<<endl;

      xError[i] = 1./2.*TMath::Sqrt(TMath::Power(xFullError[i],2)+TMath::Power(xIntrinsicError[i],2));
    }

    fileName.Form("c2%i",j);
    canvas2[j] = new TCanvas(fileName,fileName,0,0,500,500);
    canvas2[j] ->SetBottomMargin(0.15);
    canvas2[j] ->SetLeftMargin(0.17);
    canvas2[j] ->cd();

    Ratio = new TGraphErrors(numEntries,x,y,xError,yError);

    
    char titleName[100] = {0};
    sprintf(titleName,"MC Closure Test  %s",file2);
    Ratio->SetTitle(titleName);
    Ratio->GetXaxis()->SetTitleSize(0.06);
    Ratio->GetYaxis()->SetTitleSize(0.04);
    Ratio-> GetXaxis()->SetTitle("p_{T}^{#gamma}");
    Ratio -> GetXaxis()->SetLimits(0,600);
    Ratio-> GetYaxis()->SetTitle("#frac{predic. intrinsic}{intrinsic} -1");
    Ratio->GetYaxis()->SetTitleOffset(1.5); 
    Ratio->SetMarkerStyle(20);
    Ratio->SetMarkerSize(1.1);
    Ratio ->SetMaximum(0.3);
    Ratio ->SetMinimum(-0.3);
    Ratio->Draw("AP");

    TF1* line = new TF1("line","0.",0,600);
    
    line->SetLineColor(2);
    line->Draw("same");

    TLatex*  info   = new TLatex();
    char legname[100] = {0};
    info->SetTextFont(132);
    info-> SetNDC();
    info->SetTextSize(0.040);
    info->DrawLatex(0.60,0.80,etaRegion);

    fileName.Form("MCClosure_for_%i_eta_bin%s.pdf",j+1,file1);
    canvas2[j]->SaveAs(fileName);


    canvas3[j] = new TCanvas(fileName,fileName,0,0,500,500);
    canvas3[j] ->cd();

    for(int i=0; i<numEntries; i++) y[i] = std::abs(y[i]);
    RatioAbs = new TGraphErrors(numEntries,x,y,xError,yError);
  
    TF1* fit = new TF1("fit","pol0",0,600);
    //TF1* fit = new TF1("fit","expo(0)",0,600);
    sprintf(titleName,"MCClosure - %s absolute Values",file2);
    RatioAbs -> SetTitle(titleName);
    RatioAbs -> GetXaxis()->SetTitle("p_{T}^{#gamma}");
    RatioAbs -> GetXaxis()->SetLimits(0,600);
    RatioAbs -> GetYaxis()->SetTitle("JER/intrinsic -1");
    RatioAbs -> GetYaxis()->SetTitleOffset(1.5); 
    RatioAbs -> SetMarkerStyle(20);
    RatioAbs -> SetMarkerSize(1.1);
    RatioAbs -> SetMaximum(0.25);
    RatioAbs -> SetMinimum(-0.05);
    RatioAbs -> Fit("fit","Q");
    RatioAbs -> Draw("AP");

    line ->Draw("same");
    fit -> SetLineColor(3);
    fit -> Draw("esame");

    delete info;
    info   = new TLatex();   
    info->SetTextFont(132);
    info-> SetNDC();
    info->SetTextSize(0.040);
    sprintf(legname,"%i. eta Bin",j+1);
    info->DrawLatex(0.60,0.80,legname);

    
    sprintf(legname,"fit = %4.3f #pm %4.3f",fit->GetParameter(0),fit->GetParError(0));
    info -> DrawLatex(0.60,0.70,legname);
    info -> Draw("same");

    sprintf(legname,"Chi^2 = %4.3f",fit->GetChisquare());
    info -> DrawLatex(0.60,0.63,legname);
    info -> Draw("same");
    sprintf(legname,"ndof = %i",fit->GetNDF());
    info -> DrawLatex(0.60,0.56,legname);
    info -> Draw("same");

    fileName.Form("MCClosure_for_%i_eta_bin%s_absoluteValues.pdf",j+1,file1);
    canvas2[j]->SaveAs(fileName);

  }

  return 0;

}
Exemple #29
0
void doit(const char *basename, const int nbins, const double lofit, const double hifit)
{

  // --- read in the data and create a vector with all the values
  // --- note that this code requires an duplicates to have already been cleaned out
  // --- this is automatically fixed with the new version of the DAQ/stepper code
  // --- but the user would do well do double check all output files anyway
  ifstream fin1(Form("TEMP/%s_Unaveraged_VMin1.txt",basename));
  double content;
  vector<double> voltage1;
  while(fin1>>content)
    {
      voltage1.push_back(content);
    }
  fin1.close();
  cout << voltage1.size() << endl;

  // --- do the same for SiPM2
  ifstream fin2(Form("TEMP/%s_Unaveraged_VMin2.txt",basename));
  vector<double> voltage2;
  while(fin2>>content)
    {
      voltage2.push_back(content);
    }
  fin2.close();
  cout << voltage2.size() << endl;

  // --- get the number of entries and the min and max
  int number = voltage1.size();
  double max = *max_element(voltage1.begin(),voltage1.end());
  double min = *min_element(voltage1.begin(),voltage1.end());
  cout << max << endl;
  cout << min << endl;
  // --- use the min and max to calculate a range for the histogram
  double newmax = min*-0.95;
  double newmin = max*-1.05 - newmax*0.1;
  // --- create the new histogram
  TH1D *h1 = new TH1D("h1","",nbins,newmin,newmax);
  TH1D *h2 = new TH1D("h2","",nbins,newmin,newmax);
  TH1D *hsum = new TH1D("hsum","",nbins,2*newmin,2*newmax);
  TH2D *hh1v2 = new TH2D("hh1v2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA = new TH2D("hhSvA","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut1 = new TH2D("hh1v2_cut1","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut1 = new TH2D("hhSvA_cut1","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  TH2D *hh1v2_cut2 = new TH2D("hh1v2_cut2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
  TH2D *hhSvA_cut2 = new TH2D("hhSvA_cut2","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
  vector<double> sum;
  vector<double> asym;
  // --- loop over the vector to fill the histogram
  for(int i=0; i<number; i++)
    {
      // --- SiPM1
      h1->Fill(-voltage1[i]);
      // --- SiPM2
      h2->Fill(-voltage2[i]);
      // --- SiPM1 vs SiPM2
      hh1v2->Fill(-voltage1[i],-voltage2[i]);
      // --- sum vs asymmetry
      double tempsum = -voltage1[i] + -voltage2[i];
      double tempasym = (voltage1[i] - voltage2[i]) / (-voltage1[i] + -voltage2[i]);
      hsum->Fill(tempsum);
      hhSvA->Fill(tempsum,tempasym);
      sum.push_back(tempsum);
      asym.push_back(tempasym);
      // --- now do some cuts...
      if(fabs(tempasym)<0.4)
	{
	  hh1v2_cut1->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut1->Fill(tempsum,tempasym);
	}
      if((voltage1[i]<(voltage2[i]+20*peconvert))&&(voltage2[i]<(voltage1[i]+20*peconvert)))
	{
	  hh1v2_cut2->Fill(-voltage1[i],-voltage2[i]);
	  hhSvA_cut2->Fill(tempsum,tempasym);
	}
    }

  // --- make a canvas and draw the histogram
  TCanvas *c1 = new TCanvas("c1","",800,800);

  // --- rescale the histograms from volts to photoelectrons
  h1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  h1->GetXaxis()->SetTitle("Number of photoelectrons");
  h1->GetYaxis()->SetTitle("Counts");

  // --- define Landau function and draw
  // --- don't fit yet because the data have tons of ugly low voltage1 background
  double height = 1049;
  double mu = 23;
  double sigma = 3;
  //TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",newmin/peconvert,newmax/peconvert);
  TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",2*newmin/peconvert,2*newmax/peconvert);
  fun->SetParameter(0,height);
  fun->SetParameter(1,mu);
  fun->SetParameter(2,sigma);


  double bgscale = 650; // guess...





  c1->SetLogy(0);
  c1->Clear();
  hh1v2->Draw("colz");
  hh1v2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2->GetYaxis()->SetTitle("#pe SiPM2");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_log.pdf",basename));

  hhSvA->Draw("colz");
  hhSvA->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA->GetXaxis()->SetTitle("Sum");
  hhSvA->GetYaxis()->SetTitle("Asymmetry");
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_log.pdf",basename));


  // --- now for some cuts...

  c1->SetLogz(0);
  hh1v2_cut1->Draw("colz");
  hh1v2_cut1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut1->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut1->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex1 = new TLatex(0.2,0.8,"|Asymmetry|<0.4");
  tex1->SetTextSize(0.05);
  tex1->SetNDC(kTRUE);
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.pdf",basename));

  hhSvA_cut1->Draw("colz");
  hhSvA_cut1->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut1->GetXaxis()->SetTitle("Sum");
  hhSvA_cut1->GetYaxis()->SetTitle("Asymmetry");
  tex1->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.pdf",basename));




  c1->SetLogz(0);
  hh1v2_cut2->Draw("colz");
  hh1v2_cut2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
  hh1v2_cut2->GetXaxis()->SetTitle("#pe SiPM1");
  hh1v2_cut2->GetYaxis()->SetTitle("#pe SiPM2");
  TLatex *tex2 = new TLatex(0.2,0.8,"SiPMA < SiPMB + 20");
  tex2->SetTextSize(0.05);
  tex2->SetNDC(kTRUE);
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.pdf",basename));

  hhSvA_cut2->Draw("colz");
  hhSvA_cut2->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  hhSvA_cut2->GetXaxis()->SetTitle("Sum");
  hhSvA_cut2->GetYaxis()->SetTitle("Asymmetry");
  tex2->Draw();
  c1->SetLogz(0);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.pdf",basename));
  c1->SetLogz(1);
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.png",basename));
  c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.pdf",basename));



  hsum->SetLineColor(kBlack);
  hsum->SetLineWidth(2);
  hsum->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
  //hsum->GetXaxis()->SetRangeUser(0.0,120.0);
  hsum->GetXaxis()->SetTitle("Number of photoelectrons SiPM1+SiPM2");
  hsum->Draw();
  c1->Print(Form("Cosmics/%s_temp.png",basename));
  c1->Print(Form("Cosmics/%s_temp.pdf",basename));
  hsum->SetMaximum(30);
  c1->Print(Form("Cosmics/%s_templow.png",basename));
  c1->Print(Form("Cosmics/%s_templow.pdf",basename));
  c1->SetLogy();
  hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templog.png",basename));
  c1->Print(Form("Cosmics/%s_templog.pdf",basename));


  // ---------------------------------------------------------
  bgscale = 100;
  h1->Fit(fun,"","",lofit,hifit);
  fun->SetLineColor(kRed);
  fun->SetLineWidth(2);
  fun->Draw("same");

  cout << fun->GetChisquare() << "/" << fun->GetNDF() << endl;

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempfit.pdf",basename));
  h1->SetMaximum(175);
  c1->Print(Form("Cosmics/%s_templowfit.png",basename));
  c1->Print(Form("Cosmics/%s_templowfit.pdf",basename));
  h1->SetMaximum(100);
  c1->Print(Form("Cosmics/%s_tempLOWfit.png",basename));
  c1->Print(Form("Cosmics/%s_tempLOWfit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogfit.png",basename));
  c1->Print(Form("Cosmics/%s_templogfit.pdf",basename));

  c1->Clear();
  h1->Draw();
  double hax = fun->GetParameter(0);
  double mux = fun->GetParameter(1);
  double six = fun->GetParameter(2);
  fun->SetParameter(0,0.95*hax);
  fun->SetParameter(1,mux);
  fun->SetParameter(2,1.1*six);
  //fun->Draw("same");
  //h1->Fit(simplefun,"","",0,60);

  TF1 *fun2 = new TF1("fun2","([0]/sqrt(6.28))*TMath::Exp(-0.5*((x-[1])/[2] + TMath::Exp(-(x-[1])/[2])))",2*newmin/peconvert,2*newmax/peconvert);
  // fun2->SetParameter(0,hax);
  // fun2->SetParameter(1,mux);
  // fun2->SetParameter(2,six);
  // fun2->SetParameter(0,93);
  // fun2->SetParameter(1,35);
  // fun2->SetParameter(2,5);
  fun2->SetParameter(0,93);
  fun2->SetParameter(1,500);
  fun2->SetParameter(2,100);
  //fun2->SetLineColor(kBlack);

  h1->Fit(fun2,"","",lofit,hifit);
  fun2->Draw("same");

  cout << fun2->GetChisquare() << "/" << fun2->GetNDF() << endl;

  double par1 = fun2->GetParameter(1);
  TLine line(par1,0,par1,0.24*fun2->GetParameter(0));
  line.Draw();

  c1->SetLogy(0);
  c1->Print(Form("Cosmics/%s_tempffit.png",basename));
  c1->Print(Form("Cosmics/%s_tempffit.pdf",basename));
  h1->SetMaximum(25);
  c1->Print(Form("Cosmics/%s_templowffit.png",basename));
  c1->Print(Form("Cosmics/%s_templowffit.pdf",basename));
  h1->SetMaximum(0.3*fun2->GetParameter(0));
  TLatex *tex = new TLatex(0.6,0.8,Form("MPV = %.1f #pm %.1f",fun2->GetParameter(1),fun2->GetParError(1)));
  tex->SetNDC();
  tex->SetTextSize(0.05);
  tex->Draw();
  //h1->GetXaxis()->SetRangeUser(0.0,130.0); // new...
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.png",basename));
  c1->Print(Form("Cosmics/SmallTileCosmics_%s_tempLOWffit.pdf",basename));
  c1->SetLogy(1);
  h1->SetMaximum(1.1*h1->GetBinContent(h1->GetMaximumBin()));
  c1->Print(Form("Cosmics/%s_templogffit.png",basename));
  c1->Print(Form("Cosmics/%s_templogffit.pdf",basename));



}
Exemple #30
0
Stat_t AnalysisClass::doFit(Int_t RunNumber,Char_t *Variable, Char_t *SubDetName, Char_t *Layer,Char_t *label){
  TH1 *htoFit=0; 
  pLanGausS[0]=0; pLanGausS[1]=0; pLanGausS[2]=0; pLanGausS[3]=0;
  epLanGausS[0]=0; epLanGausS[1]=0; epLanGausS[2]=0; epLanGausS[3]=0;

  if (debug)   cout << d1->GetTitle() << " " << Variable << " " << SubDetName << endl;
  pPar[0]=0; pPar[1]=0;
  TIter it(d1->GetListOfKeys());
  TObject * o;
  while ( (o = it()))  
    {
      TObject * d =  d1->Get(o->GetName());
      if(d->IsA()->InheritsFrom("TDirectory") && strstr(d->GetName(),SubDetName)){
	if (debug) cout << "Found " << SubDetName << endl;
	TIter it2(((TDirectoryFile * )d)->GetListOfKeys());
	TObject *o2;
	while( ( o2 = it2()) ){
	  TObject *d2 = ((TDirectoryFile * )d)->Get(o2->GetName());
	  if(d2->IsA()->InheritsFrom("TDirectory") && strstr(d2->GetName(),Layer) ){
	    if (debug) cout << "Found Layer" << Layer << endl;
	    TIter it3(((TDirectoryFile * )d2)->GetListOfKeys());
	    TObject *o3;
	    while( ( o3 = it3()) ){
	      TObject *d3 = ((TDirectoryFile * )d2)->Get(o3->GetName());
	      if(strstr(d3->GetName(),Variable) && strstr(d3->GetName(),label)){
		htoFit = (TH1*) d3;
		if (debug) cout << "Found " << Variable << endl;
		
		if (htoFit->GetEntries()!=0) {
		  cout<<"Fitting "<< htoFit->GetTitle() <<endl;
		  // Setting fit range and start values
		  Double_t fr[2];
		  Double_t sv[4], pllo[4], plhi[4];
		  fr[0]=0.5*htoFit->GetMean();
		  fr[1]=3.0*htoFit->GetMean();
	      
		  // (EM) parameters setting good for signal only 
		  Int_t imax=htoFit->GetMaximumBin();
		  Double_t xmax=htoFit->GetBinCenter(imax);
		  Double_t ymax=htoFit->GetBinContent(imax);
		  Int_t i[2];
		  Int_t iArea[2];
	      
		  i[0]=htoFit->GetXaxis()->FindBin(fr[0]);
		  i[1]=htoFit->GetXaxis()->FindBin(fr[1]);
		  
		  iArea[0]=htoFit->GetXaxis()->FindBin(fr[0]);
		  iArea[1]=htoFit->GetXaxis()->FindBin(fr[1]);
		  Double_t AreaFWHM=htoFit->Integral(iArea[0],iArea[1],"width");
		  
		  sv[1]=xmax;
		  sv[2]=htoFit->Integral(i[0],i[1],"width");
		  sv[3]=AreaFWHM/(4*ymax);
		  sv[0]=sv[3];
		  
		  plhi[0]=25.0; plhi[1]=200.0; plhi[2]=1000000.0; plhi[3]=50.0;
		  pllo[0]=1.5 ; pllo[1]=10.0 ; pllo[2]=1.0      ; pllo[3]= 1.0;
		  
		  // create different landau+gaussians for different runs
		  Char_t FunName[100];
		  sprintf(FunName,"FitfcnLG_%s%d",htoFit->GetName(),fRun);  
		  TF1 *ffitold = (TF1*)gROOT->GetListOfFunctions()->FindObject(FunName);
		  if (ffitold) delete ffitold;
		  
		  langausFit = new TF1(FunName,langaufun,fr[0],fr[1],4);
		  langausFit->SetParameters(sv);
		  langausFit->SetParNames("Width","MP","Area","GSigma");
		  
		  for (Int_t i=0; i<4; i++) {
		    langausFit->SetParLimits(i,pllo[i],plhi[i]);
		  }  
		  
		  htoFit->Fit(langausFit,"R0");  // "R" fit in a range,"0" quiet fit
		  
		  langausFit->SetRange(fr[0],fr[1]);
		  pLanGausS=langausFit->GetParameters();
		  epLanGausS=langausFit->GetParErrors();
		  
		  chi2GausS =langausFit->GetChisquare();  // obtain chi^2
		  nDofGausS = langausFit->GetNDF();           // obtain ndf
		  
		  Double_t sPeak, sFWHM;
		  langaupro(pLanGausS,sPeak,sFWHM);
		  pLanConv[0]=sPeak;
		  pLanConv[1]=sFWHM;
		  cout << "langaupro:  max  " << sPeak << endl;
		  cout << "langaupro:  FWHM " << sFWHM << endl;
		  
		  TCanvas *cAll = new TCanvas("Fit",htoFit->GetTitle(),1);
		  Char_t fitFileName[60];
		  sprintf(fitFileName,"Fits/Run_%d/%s/Fit_%s.png",RunNumber,SubDetName,htoFit->GetTitle());
		  htoFit->Draw("pe");
		  htoFit->SetStats(100);
		  langausFit->Draw("lsame");
		  gStyle->SetOptFit(1111111);
		  
		  cAll->Print(fitFileName,"png");
		}
		else {  
		  pLanGausS[0]=-10; pLanGausS[1]=-10; pLanGausS[2]=-10; pLanGausS[3]=-10;
		  epLanGausS[0]=-10; epLanGausS[1]=-10; epLanGausS[2]=-10; epLanGausS[3]=-10;
		  pLanConv[0]=-10;   pLanConv[1]=-10;   chi2GausS=-10;  nDofGausS=-10;    
		}
	      }
	    }
	  }
	}
      }
    }
	
  return htoFit->GetEntries();
  
}