Ejemplo n.º 1
0
/*============================================================================*/
void gaus1peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[5],epar[5],x[4],y[4];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  setcanvas(1);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

  //--**-- Linear background estimation --**--//
  x[0] = x1;
  x[1] = x2;
  x[2] = x3;
  x[3] = x4;
  Int_t bin1 = hist->FindBin(x1);
  y[0] = hist->GetBinContent(bin1);
  Int_t bin2 = hist->FindBin(x2);
  y[1] = hist->GetBinContent(bin2);
  Int_t bin3 = hist->FindBin(x3);
  y[2] = hist->GetBinContent(bin3);
  Int_t bin4 = hist->FindBin(x4);
  y[3] = hist->GetBinContent(bin4);
  TGraph *g = new TGraph(4,x,y);
  TF1 *fpol1 = new TF1("POL1","pol1",x1,x4);
  g->Fit(fpol1,"RQN");
  par[3]=fpol1->GetParameter(0);
  par[4]=fpol1->GetParameter(1);

  //--**-- Gaussian Peak estimation without background --**--//
  TF1 *fgaus = new TF1("GAUS","gaus",x2,x3);
  hist->Fit(fgaus,"RQN");
  fgaus->GetParameters(&par[0]);

  //--**-- Final Peak Fit with Background --**--//
  TF1 *func = new TF1("FGAUS","gaus(0)+pol1(3)",x1,x4);
  func->SetParameters(par);
  hist->Fit(func,"R+QN");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  Double_t fwhm = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N0 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r0 = epar[0]/par[0];
  Double_t r2 = epar[2]/par[2];
  Double_t eN0= N0*TMath::Sqrt(r0*r0+r2*r2);
  printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
          par[1],epar[1],fwhm,efwhm,N0,eN0);
  //printf("%11.4f %11.4f %11.0f %11.0f\n",
  //        par[1],epar[1],N0,eN0);
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
}
Ejemplo n.º 2
0
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;
}
Ejemplo n.º 3
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
Ejemplo n.º 4
0
	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();
	}
Ejemplo n.º 5
0
// Loop through detector layers to report 
// various parameters
residu(TString baseName, double min=-1.5, double max=1.5)
{
  double xMin, xMax;
  TString name;
  name = baseName;
  name += "_a";     TH1D * amp  = new TH1D(name,name,55,0,54.);
  name = baseName;
  name += "_mean";  TH1D * mean = new TH1D(name,name,55,0,54.);
  name = baseName;
  name += "_rms";   TH1D * rms = new TH1D(name,name,55,0,54.);
  TString thisL;
  TH1D *h=0;
  TF1 * f;
  int ii;
  for(int i=0; i<51;i++)
    {
      thisL=baseName+i;
      if (i<6)
	{
	  xMin = -0.2;
	  xMax = 0.2;
	}
      else
	{
	  xMin = min;
	  xMax = max;
	}
      h=(TH1D*)gDirectory->Get(thisL);
      h->Fit("gaus","","",xMin,xMax);
      double entries = h->GetEntries();
      if (entries>0)
	{
	  ii = i+1;
	  f = h->GetFunction("gaus");
	  double a = f->GetParameter("Constant"); double ea = f->GetParError(0);
	  double m = f->GetParameter("Mean");double em = f->GetParError(1);
	  double r = f->GetParameter("Sigma");double er = f->GetParError(2);
	  amp->SetBinContent(ii,a);amp->SetBinError(ii,ea);
	  mean->SetBinContent(ii,m);mean->SetBinError(ii,em);
	  rms->SetBinContent(ii,r);rms->SetBinError(ii,er);
	}
    }
  cout << "Fitting completed" << endl;

  c1->Clear();
  c1->Divide(1,3);
  c1->cd(1); amp->Draw();
  c1->cd(2); mean->Draw();
  c1->cd(3); rms->Draw();
  
}
Ejemplo n.º 6
0
void fitBarea(TString infname="",bool doweight = 1)
{
  if (doweight==0) weight="1";
  if (infname=="") infname=inputdata.Data();
  TFile *inf = new TFile(infname.Data());
  TTree *nt = (TTree*) inf->Get("ntKp");

  TFile *infMC = new TFile(inputmc.Data());
  TTree *ntGen = (TTree*)infMC->Get("ntGen");
  TTree *ntGen2 = (TTree*)inf->Get("ntGen");
  TTree *ntMC = (TTree*)infMC->Get("ntKp");
    
  ntGen->AddFriend(ntMC);
  ntGen2->AddFriend(ntMC);
    
  const int nBins = 1;
  double ptBins[nBins+1] = {10,60};
//  const int nBins = 1;
//  double ptBins[nBins+1] = {10,60};
  TH1D *hPt = new TH1D("hPt","",nBins,ptBins);

  for (int i=0;i<nBins;i++)
    {
      TF1 *f = fit(nt,ntMC,ptBins[i],ptBins[i+1]);
      double yield = f->Integral(5,6)/0.02;
      double yieldErr = f->Integral(5,6)/0.02*f->GetParError(0)/f->GetParameter(0);
      hPt->SetBinContent(i+1,yield/(ptBins[i+1]-ptBins[i]));
      hPt->SetBinError(i+1,yieldErr/(ptBins[i+1]-ptBins[i]));
    }
  
}
Ejemplo n.º 7
0
void ThrowPSEME(int me_i, bool use_old=false){

  // ====================================================
  //                       Create a fit
  // ====================================================
  TF1 *ftot = new TF1("fitFunction",fitFunction,-100,0,2);

  //threw one data PSE  and fill it
  if (use_old){
    cout<<"OLD"<<endl;
    siggnal = MEWH_old[me_i];
    background = MEWBB_old[me_i];
  }else{
    cout<<"NEW"<<endl;
    siggnal = MEWH[me_i];
    background = MEWBB[me_i];
  }

  TH1F * Err = new TH1F("Err","Err",1000,0,1);

  for (int pse=0;pse<100;pse++){

    //Get one PSE
    TH1F * data  =  MakeOnePSE(siggnal,1000,background,2000);
    
    //fit it
    data->Fit("fitFunction","b");   
    Err->Fill(ftot->GetParError(1));
    delete data;

  }
  Err->Draw();

}//ThrowPSEME
Ejemplo n.º 8
0
TF1* fit_xy_res(double &x, double &xe, double &max, bool do_fit, int idel, int ipad, TCanvas *tc,
		TH1F* h, const char *meth, const char *var_tag, const char *det_tag, const char *var, const char *det_desc) {

  tc->cd(1+ipad);

  //cout << "var_tag = " << var_tag << endl;
  TLatex *tt = new TLatex();
  tt->SetTextSize(0.08);
  tt->SetTextColor(4);
  tt->SetNDC(true);

  double fmx = 2.2;
  double fit_min= h->GetMean()-fmx*h->GetRMS();
  double fit_max= h->GetMean()+fmx*h->GetRMS();
  TF1* f = new TF1(Form("fxres_%s_%d_%s",det_tag,idel,meth), "gaus",fit_min,fit_max);

  if (do_fit) {

    h->Fit(f,"R+Q");
    x = f->GetParameter(2);
    xe = f->GetParError(2);

    if (f->GetParameter(1) < f->GetParError(1))
      cout << "   OK: ";
    else
      cout << " OOPS: ";
    cout << var_tag << " " << meth << " " << det_tag << idel;
    cout << " mean= " << f->GetParameter(1) << " pm " << f->GetParError(1);
    cout << " sigma= " << f->GetParameter(2) << " pm " << f->GetParError(2) << endl;

  } else {

    max = TMath::Max(max, x);
    h->Draw();
    //tt->DrawLatex(0.12,0.15, h->GetTitle());
  }

  tt->DrawLatex(0.65,0.8, meth);
  tt->DrawLatex(0.65,0.7, var);
  tt->DrawLatex(0.65,0.6, det_desc);
  tt->DrawLatex(0.65,0.5, Form("#delta = %d%%",idel-5 ));

  max = TMath::Max(max, x);
  gPad->SetGridx();
  return f;
}
Ejemplo n.º 9
0
void histspec(TH1* hist, Double_t &mean, Double_t &ermean, Double_t &rms, 
		Double_t range=4, Double_t rangef=2.5, int mode=0) {

  Double_t xmin,xmax,rmsmin,meanf,ermeanf,rmsf;
  char ctit[145];

  mean=hist->GetMean();
  rms=hist->GetRMS();
  xmin=hist->GetXaxis()->GetXmin();
  xmax=hist->GetXaxis()->GetXmax();
  int nb=hist->GetNbinsX();
  rmsmin=(xmax-xmin)/(nb+1);
  if (rms==0) rms=rmsmin;

  for (int i=0;i<2;i++) {
    hist->SetAxisRange(mean-range*rms,mean+range*rms);
    mean=hist->GetMean();
    rms=hist->GetRMS();
    if (rms==0) rms=rmsmin;
  }
  
  if (rangef>0) {
    for (int i=0;i<2;i++) {
      hist->SetAxisRange(mean-rangef*rms,mean+rangef*rms);
      mean=hist->GetMean();
      rms=hist->GetRMS();
      if (rms==0) rms=rmsmin;
    }
  }
  
  ermean=hist->GetMeanError();
  if (abs(mode)>0) {
    if (mode<0) {
      //sprintf(ctit,"cHistSpecs%4d",nHistSpecs++);
      //TCanvas *ccxx = new TCanvas("ccxx","ccxx",900,0,450,450);
      //hist->SetMinimum(0);
      //hist->Draw();
      hist->Fit("gaus","LI","same",mean-rangef*rms,mean+rangef*rms);
      //ccxx->Update();
      for (int i=0;i<1e3;i++) for (int j=0;j<1e3;j++) {} 
    }
    else hist->Fit("gaus","LI0","",mean-rangef*rms,mean+rangef*rms);
    TF1 *f = hist->GetFunction("gaus");
    meanf=f->GetParameter(1);
    ermeanf=f->GetParError(1);
    rmsf=f->GetParameter(2);
    if (fabs(mean-meanf)/(fabs(mean+meanf)+0.0001)<0.8 && 
	fabs(ermean-ermeanf)/(fabs(ermean+ermeanf)+0.0001)<0.8) {
      mean=meanf;
      ermean=ermeanf;
      rms=rmsf;
    }
  }
  hist->SetAxisRange(xmin,xmax);
  return;
}
Ejemplo n.º 10
0
double Fit511Photopeak(TH1* h, double* error=0)
{
  TSpectrum spec(1);
  spec.Search(h);
  h->GetXaxis()->SetTitle("Energy [photoelectrons]");
  h->Draw("e");
  TH1* bg = spec.Background(h);
  TH1* sig = (TH1*)(h->Clone());
  sig->SetLineColor(kGreen);
  
  sig->Add(bg,-1);
  sig->Draw("same e");
  sig->Fit("gaus","m","same e");
  TF1* gaus = sig->GetFunction("gaus");
  if(gaus)
    gaus->SetLineColor(kGreen);
  
  bg->SetLineColor(kRed);
  bg->Draw("same e");
  
  TLine* line = new TLine(gaus->GetParameter(1),0,
			  gaus->GetParameter(1),h->GetMaximum());
  line->SetLineColor(kBlue);
  line->SetLineWidth(2);
  line->Draw();
  

  double yield = spec.GetPositionX()[0]/epeak;
  double err = 0;
  
  cout<<"Results from TSpectrum: \n\t"
      <<"Peak = "<<spec.GetPositionX()[0]<<" p.e.; Light Yield = "
      <<yield<<" p.e./keV"<<endl;
  if(gaus){
    yield = gaus->GetParameter(1)/epeak;
    err = gaus->GetParError(1)/epeak;
    cout<<"Results from BG Subtracted Gaus Fit: \n\t"
	<<"Peak = "<<gaus->GetParameter(1)<<" p.e.; Light Yield = "
	<<yield<<" +/- "<<err<<" p.e./keV"<<endl;
    err = max(err, TMath::Abs(yield-spec.GetPositionX()[0]/epeak));
    
  }
  TLegend* leg = new TLegend(.6,.6,.9,.9);
  leg->AddEntry(h,"Raw Spectrum","lpe");
  leg->AddEntry(bg,"Background","lpe");
  leg->AddEntry(sig,"Signal","lpe");
  char title[20];
  sprintf(title,"Yield = %.2f pe/keV",yield);
  leg->AddEntry(line, title ,"l");
  leg->Draw();

  if(error) *error = err;
  return yield;
}
Ejemplo n.º 11
0
drawGraph( TGraph* gr, const Char_t* ytitle = 0 ) 
{
	gr->Draw( "AP*" );
	TH1* h = gr->GetHistogram( );

	std::cout << gr->GetMean( ) << std::endl;

	gr->Fit( "pol0", "Q", "SAME" );
	TF1* fit = gr->GetFunction( "pol0" );	
	Double_t chi2 	= fit->GetChisquare( );
	Double_t par0 	= fit->GetParameter( 0 );
	Double_t err 	= fit->GetParError( 0 );	

	TLatex* l = new TLatex;
	l->SetNDC( );
	l->DrawLatex( 0.85, 0.80, Form( "#splitline{Entries = %i}{RMS = %2.3f}",
		gr->GetN(), gr->GetMean(2)) );

	TLatex* l2 = new TLatex;
	l2->SetNDC( );
	l2->DrawLatex( 0.85, 0.7, Form("#splitline{fit = %2.3f#pm%2.3f}{#chi^{2} = %2.3f}", 
		par0, chi2, err) );
		
//	TLegend* leg = new TLegend( 0.8, 0.9, 0.95, 0.95 );
//	leg->SetFillColor( kWhite );
//	leg->SetBorderSize( 0 );
//	leg->AddEntry( "gr", "CPU+AFAR+MBED+ATWD+AMPS", "P" );
//	leg->Draw( );

	if( h != 0 ) 
	{
		h->GetXaxis()->SetTimeFormat("%m/%d %H:%M");
		h->GetXaxis()->SetNdivisions( 10, 10, 0 );
		h->GetXaxis()->SetTimeDisplay( 1 );
		h->GetXaxis()->SetTitle("Date / Time (UTC)");
		h->GetXaxis()->SetLabelSize( 0.06 );
		h->GetYaxis()->SetLabelSize(0.07);
		h->GetYaxis()->SetTitleSize(0.06);
		h->GetXaxis()->SetTitleSize(0.055);
		h->GetYaxis()->SetTitleOffset( 0.9 );
		h->GetXaxis()->SetTitleOffset( 0.9 );
		h->SetMarkerSize( 5 );

		if( ytitle != 0 ) 
		{
			h->GetYaxis()->SetTitle(ytitle);
      	}
	}
   
	if( gPad != 0 ) 
	{
		gPad->Update();
	}
}
Ejemplo n.º 12
0
scalePair energyCorrectionDiff(TCut centCut1, float lowPt, float highPt, float lowEta, float highEta,TCut addCut) { 
   
   TString fname1 = "forest/barrelHiForestPhoton_MCphoton50_51k.root";
   if ( lowPt > 90 ) 
      fname1 = "forest/barrelHiForestPhoton_MCphoton80_28k.root";
   TFile *f1  =new TFile(fname1.Data());
   TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
   photon1->AddFriend("yEvt=yongsunHiEvt"    ,fname1.Data());
   photon1->AddFriend("ySkim=yongsunSkimTree"   ,fname1.Data());
   photon1->AddFriend("yHlt=yongsunHltTree"     ,fname1.Data());
   
   TCut collisionCut = "ySkim.pcollisionEventSelection==1";
   
   TCut hoeCut = "hadronicOverEm<0.2";
   TCut isoCut = "cc4 + cr4 + ct4j20 < 5 && sigmaIetaIeta<0.011";
   TCut ptCut  = Form("genMatchedPt>%.f && genMatchedPt <%.f",lowPt, highPt);
   TCut etaCut = Form("abs(eta)>%f && abs(eta)<%f",lowEta,highEta);
      
   TCut finalCut1 = genMatchCut1 && collisionCut && centCut1 && hoeCut && isoCut && ptCut && etaCut && addCut ; 
   TString variable1 = "pt/genMatchedPt";
   
   TH1D* hScale = new TH1D("hScale","",100,.5,1.5);
   TH1D* hdpt = new TH1D("hdpt","",100,-20,20);
   photon1->Draw(Form("%s>>%s",variable1.Data(),hScale->GetName()), finalCut1);
   photon1->Draw(Form("pt-genMatchedPt>>%s",hdpt->GetName()),       finalCut1);
   cout << "cut = " << finalCut1.GetTitle() <<endl;
   hScale->Draw();
   hdpt->Draw();
   TF1* ff =  cleverGaus(hScale);
   
   scalePair ret;
   double *ps = ff->GetParameters();
   ret.val = ps[1];
   ret.err = ff->GetParError(1);
   // resErr = ff->GetParError(2);
   ret.res  = ps[2];
   ret.resErr = ff->GetParError(2);  
   ret.absVal = hdpt->GetMean();
   cout <<"scale = " << ret.val << " +-" << ret.err << endl;
   return ret;
}
Ejemplo n.º 13
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;
}
Ejemplo n.º 14
0
double findDelPhiAngle(TH1D *input, int parorErr){
  
  TF1 *fitter = new TF1("fitter","gaus",-2,2);
  //input->Scale(1./(input->GetEntries()));
  fitter->SetParameters(1./input->GetMaximum(),-0.1,1.0);
  input->Fit("fitter","qN0","",-1.5,1.5);
  if(parorErr==1){
    return fitter->GetParameter(1);
  }
  else if(parorErr==2){
    return fitter->GetParError(1);
  }
  else return 0;
}
Ejemplo n.º 15
0
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;
}
Ejemplo n.º 16
0
void fitMassHisto(TString inputfile="outfiles/MassHisto", TString outputfile="outfiles/YieldHisto",
                  Float_t centmin=0., Float_t centmax=100.)
{
  infname = inputfile;
  centMin = centmin;
  centMax = centmax;

  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);

  TF1* fit(TH1D* h, TH1D* hMCSignal, TH1D* hMCSwapped, Float_t ptmin, Float_t ptmax, Int_t j);
  TH1D** hYield = new TH1D*[4];
  for(int i=0;i<4;i++) hYield[i] = new TH1D(Form("hYield_%s",tfend[i].Data()),"",nPtBins,ptBins);
  for(int i=0;i<nPtBins;i++)
    {
      TFile* infile = new TFile(Form("%s_cent_%.0f_%.0f_pt_%.0f_%.0f.root",infname.Data(),centMin,centMax,ptBins[i],ptBins[i+1]));
      TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");
      TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");
      for(int j=0;j<4;j++)
        {
          TH1D* h = (TH1D*)infile->Get(Form("h_%s",tfend[j].Data()));
          TF1* f = fit(h,hMCSignal,hMCSwapped,ptBins[i],ptBins[i+1],j);
          Double_t yield = f->Integral(minhisto,maxhisto)/binwidthmass;
          Double_t yieldErr = f->Integral(minhisto,maxhisto)/binwidthmass*f->GetParError(0)/f->GetParameter(0);
          hYield[j]->SetBinContent(i+1,yield);
          hYield[j]->SetBinError(i+1,yieldErr);
          delete h;
        }
      delete hMCSwapped;
      delete hMCSignal;
      delete infile;
    }

  TFile* outf = new TFile(Form("%s_cent_%.0f_%.0f.root",outputfile.Data(),centmin,centmax),"recreate");
  outf->cd();
  for(int i=0;i<4;i++) hYield[i]->Write();
  outf->Close();
  delete []hYield;
  delete outf;

  cout<<endl;
}
Ejemplo n.º 17
0
Archivo: langaus.C Proyecto: Y--/root
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

}
Ejemplo n.º 18
0
void prefit() {

    TFile *f = TFile::Open("/afs/cern.ch/user/x/xniu/WZXSection/CMSSW_7_6_3_patch2/src/MitEwk13TeV/XControl/f_bkgfail.root");
    TFile *fbkg = new TFile("fbkg.root","RECREATE");
    TH1D *h[24];
    TH1D *hbkg[24];

//	TF1 *fq = new TF1("fq","[0]+[1]*x+[2]*x*x",60.,120.);
//	TF1 *fl = new TF1("fl","[0]+[1]*x",60.,120.);

//	TF1 *fq = new TF1("fq",myfunction,60.,120.,3);

    TF1 *fq = new TF1("fq","x**(-1.*[0])",60.,120.);

    for(int i = 0; i < 24; i++) {
        char name[20];
        char namebkg[20];
        sprintf(name, "histFail_%d", i);
        sprintf(namebkg, "histbkgFail_%d", i);

        h[i] = (TH1D*) f->Get(name);
        hbkg[i] = new TH1D(namebkg, "", 60, 60., 120.);

        for(int ib = 0; ib < 20; ib++) {
            hbkg[i]->SetBinContent(ib+1, h[i]->GetBinContent(ib+1));
            hbkg[i]->SetBinError(ib+1, h[i]->GetBinError(ib+1));
        }

        for(int ib = 40; ib < 60; ib++) {
            hbkg[i]->SetBinContent(ib+1, h[i]->GetBinContent(ib+1));
            hbkg[i]->SetBinError(ib+1, h[i]->GetBinError(ib+1));
        }
        //hbkg[i]->Write();
        hbkg[i]->Fit("fq");
        std::cout<<"ibin = "<<i<<": "<<fq->GetParameter(0)<<","<<fq->GetParError(0)<<" ,"<<fq->GetParameter(1)<<","<<fq->GetParError(1)<<","<<fq->GetParameter(2)<<","<<fq->GetParError(2)<<std::endl;
//		if(i==10){
//		hbkg[i]->Fit("fl");
//		std::cout<<"ibin = "<<i<<": "<<fl->GetParameter(0)<<","<<fl->GetParError(0)<<","<<fl->GetParameter(1)<<","<<fl->GetParError(1)<<std::endl;
//		}
    }

    fbkg->Write();
    fbkg->Close();
    f->Close();
}
Ejemplo n.º 19
0
void scan()
{
   TFile *outf = new TFile("result.root","recreate");

   TH1D *h = new TH1D("h","",6,20,50);
   int bin=1;
   for (int i=20;i<50;i+=5)
   {
      TF1 *f = bFeedDownFraction(i,i+5);
      h->SetBinContent(bin,f->GetParameter(2));
      h->SetBinError(bin,f->GetParError(2));
      bin++;
   }
   
   TCanvas *cResult = new TCanvas("cResult","",600,600);
   h->SetXTitle("D^{0} p_{T} (GeV/c)");
   h->SetYTitle("Prompt Fraction");
   h->Draw("e");
}
Ejemplo n.º 20
0
	void GetFitParameterErrorDoubleFit(TH1* &histo, bool autorange = true, double innerRange=0.1 , double outerRange=1, bool excludeCenter=false){

			Double_t errors[6] = {0,0,0,0,0,0};
			TF1 * fit;

			if(excludeCenter){
				fit = andi::doubleGaussFitExcludeCenter(histo, false, innerRange, outerRange);
			}
			else{
				fit = doubleGaussFit(histo, autorange, innerRange, outerRange);
			}

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

				errors[i]=fit->GetParError(i);
			}


			//return parameter;
		}
Ejemplo n.º 21
0
void Fithistograms(TH1D * histo[], TH1D * mc_matched_signal[], TH1D * mc_matched_kpiswapped[], TString MBorDtrig, int iptstart, int iptend, bool isPbPb, int centlow, int centhigh, TH1D * dNdpt, TString fitoption)
{
	for(int ipt = iptstart; ipt < iptend; ipt++)
	{       
		TF1* signalfittedfunc = NULL;

		int iptmc = ipt;
//		if( ipt > 2 ) 
//			iptmc = ipt;
//		else    
//			iptmc = 3;

        if( fitoption == "poly3bkg_floatwidth")
            signalfittedfunc = fit_histo_poly3bkg_floatwidth( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

        if( fitoption == "expobkg_2nd_floatwidth")
            signalfittedfunc = fit_histo_expobkg_2nd_floatwidth( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

        if( fitoption == "poly2bkg_floatwidth")
            signalfittedfunc = fit_histo_poly2bkg_floatwidth( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

        if( fitoption == "poly3bkg")
            signalfittedfunc = fit_histo_poly3bkg( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

        if( fitoption == "expobkg_2nd")
            signalfittedfunc = fit_histo_expobkg_2nd( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

        if( fitoption == "poly2bkg")
            signalfittedfunc = fit_histo_poly2bkg( isPbPb, centlow, centhigh, histo[ipt], mc_matched_signal[iptmc], mc_matched_kpiswapped[iptmc], ipt, MBorDtrig);

		double histomassbinsize = histo[ipt]->GetBinWidth(10);
		double yield = signalfittedfunc->Integral(massmin,massmax)/histomassbinsize;
		double yieldErr = signalfittedfunc->Integral(massmin,massmax)/histomassbinsize * signalfittedfunc->GetParError(0)/signalfittedfunc->GetParameter(0);
		dNdpt->SetBinContent(ipt+1,yield/(ptbins[ipt+1]-ptbins[ipt]));
		dNdpt->SetBinError(ipt+1,yieldErr/(ptbins[ipt+1]-ptbins[ipt]));
	}   
}
Ejemplo n.º 22
0
Double_t sr_fitError(Double_t *xx, Double_t *p) {

  assert(_sr_fitError_func);
  assert(_sr_fitError_emat);
  double x = *xx;
  double k = p[0];
  TF1 *f = _sr_fitError_func;
  int n = f->GetNpar();
  TMatrixD &emat = (*_sr_fitError_emat);
  assert(emat.GetNrows()==n);
  assert(emat.GetNcols()==n);
  
  vector<double> df(n);
  for (int i = 0; i != n; ++i) {

    double p = f->GetParameter(i);
    double dp = 0.1*f->GetParError(i);
    f->SetParameter(i, p+dp);
    double fup = f->Eval(x);
    f->SetParameter(i, p-dp);
    double fdw = f->Eval(x);
    f->SetParameter(i, p);
    df[i] = (dp ? (fup - fdw) / (2.*dp) : 0);
  }

  double sumerr2(0);
  for (int i = 0; i != n; ++i) {
    for (int j = 0; j != n; ++j) {
      sumerr2 += emat[i][j]*df[i]*df[j];
    }
  }

  double err = sqrt(sumerr2);

  return (f->Eval(x) + k*err);
}
Ejemplo n.º 23
0
void unfoldPt(int mode=0)
{

   // Matched Tracklets
   TFile *inf = new TFile("match-10TeV-12.root");
   TNtuple *nt = (TNtuple*)inf->FindObjectAny("nt");

   // Test sample
   TFile *infTest = new TFile("./TrackletTree-Run123596.root");
   TNtuple *ntTest = (TNtuple*)infTest->FindObjectAny("TrackletTree12");
   
   TFile *pdfFile;
   if (mode==0) pdfFile = new TFile("pdf.root","recreate");
           else pdfFile = new TFile("pdf.root");

   double nPtBin=15;
   double minPt=log(0.05);
   double maxPt=log(10);
   double nDphiBin=600;
   double maxDphi=0.4;
   
   char* mycut = Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f",minPt,maxPt);
   char* mycut1=Form("abs(eta)<2&&log(pt)>%f&&log(pt)<%f&&abs(eta-eta1)<0.01&&abs(deta)<0.01",minPt,maxPt);

   TH2F *h;
   TH1F *hdphi = new TH1F("hdphi","",nDphiBin,0,maxDphi);
   TH1F *hdphi2;
   TH1F *hpt;
   TH1F *hptH = new TH1F("hptH","",nPtBin,minPt,maxPt);
   
   TH1F *hptUnfold = new TH1F("hptUnfold","",nPtBin,minPt,maxPt);
   TH1F *hptMC = new TH1F("hptMC","",nPtBin,minPt,maxPt);
   TH1F *hptTemp = new TH1F("hptTemp","",nPtBin,minPt,maxPt);

   // Delta phi as a function of matched genparticle transverse momentum
   TCanvas *c = new TCanvas("c","",600,600);
   
   if (mode == 0) {
      h = new TH2F("h","",nPtBin,minPt,maxPt,nDphiBin,0,maxDphi);
      hdphi2 = new TH1F("hdphiMC","",nDphiBin,0,maxDphi);
      hpt = new TH1F("hpt","",nPtBin,minPt,maxPt);      
      h->SetXTitle("ln(P_{T}) GeV/c");
      h->SetYTitle("|#Delta#phi|");
      nt->Draw("abs(dphi):log(pt)>>h",mycut1,"col");
      // used to generate pdf
      nt->Draw("abs(dphi)>>hdphiMC",mycut,"");
      nt->Draw("log(pt)>>hpt",mycut,"");
      h->Write();      
      hpt->Write();      
      hdphi2->Write();      
   } else {
      h = (TH2F*) pdfFile->FindObjectAny("h");
      hdphi2 = (TH1F*) pdfFile->FindObjectAny("hdphiMC");
      hpt = (TH1F*) pdfFile->FindObjectAny("hpt");
   }
   // Delta phi fit
   TCanvas *c2 = new TCanvas("c2","",600,600);
   c2->SetLogy();
   c2->SetLogx();

 
   // dphi for unfolding and MC truth:  
   ntTest->Draw("abs(dphi)>>hdphi","abs(eta1)<2&&abs(deta)<0.1","",200000);
   ntTest->Draw("log(pt)>>hptH",mycut,"",200000);
   
   histFunction2D *myfun = new histFunction2D(h);
   
   TF1 *test = new TF1("histFun",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);
   TF1 *test2 = new TF1("histFunMC",myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

   for (int i=0;i<nPtBin+1;i++)
   {  
      test->SetParameter(i,1);   
   }


   hdphi2->SetXTitle("|#Delta#phi|");
   hdphi2->SetYTitle("Arbitrary Normalization");
   hdphi2->Fit("histFunMC","M");

   hdphi->SetXTitle("|#Delta#phi|");
   hdphi->SetYTitle("Arbitrary Normalization");
   hdphi->Fit("histFun","M");
   hdphi->SetStats(0);
   hdphi->Draw();

   
   for (int i=0;i<nPtBin+1;i++) {
      TF1 *testPlot = new TF1(Form("histFun%d",i),myfun,&histFunction2D::evaluate,0,maxDphi,nPtBin+1);

      testPlot->SetParameter(i,test->GetParameter(i));
      testPlot->SetLineColor(i+2);
      testPlot->Draw("same");
   }
   
   int total=0,totalMC=0;


   for (int i=0;i<nPtBin;i++){
      if (test->GetParameter(i)==0) continue;
      hptUnfold->SetBinContent(i+1,fabs(test->GetParameter(i)));
      hptUnfold->SetBinError(i+1,test->GetParError(i));

      hptMC->SetBinContent(i+1,fabs(test2->GetParameter(i)));
      hptMC->SetBinError(i+1,test2->GetParError(i));

      total+=fabs(test->GetParameter(i));
      totalMC+=fabs(test2->GetParameter(i));
   }

   hptUnfold->SetEntries(total);
   hptMC->SetEntries(totalMC);
   
   TCanvas *c3 = new TCanvas("c3","",600,600);
   hpt->Sumw2();
   hptH->Sumw2();
   //hptMC->Sumw2();
   
   double normMC=0;
   double norm=0;
   double normTruth=0;
   

   hptUnfold->SetMarkerColor(2);
   hptUnfold->SetMarkerStyle(4);
//   hptUnfold->Scale(1./hptUnfold->GetEntries());
   TH1F *hptCorrected = (TH1F*)hptUnfold->Clone();
   hptCorrected->SetName("hptCorrected");
   hptMC->Divide(hpt);
   hptCorrected->Divide(hptMC);
   
   for (int i=0;i<nPtBin;i++){
      if (hptMC->GetBinContent(i)<=0.001)hptCorrected->SetBinContent(i,0);
   }
   hptCorrected->Scale(1./(hptCorrected->GetSum()));
   hptCorrected->SetMarkerStyle(20);

   hpt->Scale(1./hpt->GetEntries());
   if (hptH->GetEntries())hptH->Scale(1./hptH->GetEntries());

   hptTemp->SetXTitle("ln(P_{T}) GeV/c");
   hptTemp->SetYTitle("Arbitrary Normalization");
   hptTemp->Draw();
   

   hptH->SetXTitle("ln(P_{T}) GeV/c");
   hptH->SetYTitle("Arbitrary Normalization");
   hptH->Draw("hist");
   hptH->SetLineColor(4);
   
   hpt->Draw("hist same ");
   
   hptCorrected->Draw("same");
   
   TH1F *hptUnfoldRatio = (TH1F*)hptUnfold->Clone();
   hptUnfoldRatio->SetName("hptUnfoldRatio");
   hptUnfoldRatio->Scale(1./hptUnfoldRatio->GetSum());
   //hptUnfoldRatio->Divide(hptH);

   TH1F *hptCorrectedRatio = (TH1F*)hptCorrected->Clone();
   hptCorrectedRatio->SetName("hptCorrectedRatio");
   hptCorrectedRatio->SetMarkerColor(2);
   //hptCorrectedRatio->Divide(hptH);

   TCanvas *c4 = new TCanvas("c4","",600,600);
   TLine *l = new TLine(-2.5,1,2.5,1);
   hptUnfoldRatio->Draw();
   hptMC->Draw("same");
   hptCorrectedRatio->Draw("same");
   l->Draw("same");
}
Ejemplo n.º 24
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);

}
Ejemplo n.º 25
0
void fitGausExample()
{
	int bins = 100;
	int min = 0;
	int max = 1600;
	sigMin = 500;
	sigMax = 800;
	double bgMin = 100;
	double bgMax = 1300;
	double xpos;
	
	TCanvas *testCanvas = new TCanvas("testCanvas","testCanvas",600,400); //x,y
	pad1  =  new  TPad("pad1","pad1",0.0000,0.0000,1.0000,1.0000,0,0,0);
	pad1->Draw();

	pad1->cd();
	TH1F *h1 = new TH1F("h1","Fitting Example",bins,min,max);	
	TH1F *h2 = new TH1F("h2","h2",bins,min,max);	
	TH1F *h3 = new TH1F("h3","Fitting Example",bins,min,max);	
	TH1F *bg = new TH1F("bg","bg",bins,min,max);	

	// The section below will fill h1 with a guassian
	// function with a mean of 670 and a sigma of 20
	// and fill h2 with a "uniform" random background
	// from bgMin<x<bgMax
	for (int i=0; i<10000000; i++)
	{
//		h1->Fill(gRandom->Uniform(10,1400));
		h1->Fill(gRandom->Uniform(0,1600));
		h1->Fill(gRandom->Exp(1400));
	}
	for (int i=0; i<100000; i++)
	{
//		h1->Fill(gRandom->Uniform(1400,1500));
	}
	for (int i=0; i<50000; i++)
	{
		h1->Fill(gRandom->Gaus(670,20));
	}
	for (int i=0; i<bins; i++)
	{
//		xpos = i*((max-min)/bins)+min;
//		cout << "xpos: " << xpos << endl;
//		h1->Fill(xpos,100*exp((-1)*xpos));
//		h2->Fill(i*((max-min)/bins)+min,i*500);
	}



//	h1->Add(h2,-1);
	h1->SetMinimum(0);
	h1->SetMaximum(300000);
	h1->Draw();

	TF1 *bgFit = new TF1("bgFit","[0]+[1]*x",bgMin,bgMax);
//	TF1 *bgFit = new TF1("bgFit","expo",bgMin,bgMax);
//	TF1 *bgFit = new TF1("bgFit","exp([1]*x+[0])+[2]",bgMin,bgMax);
	TF1 *bgFit = new TF1("bgFit",fline,bgMin,sigMin,3);
	bgFit->SetLineColor(kOrange);
	bgFit->SetParameter(0,1);
	bgFit->SetParameter(1,1/1600);
	bgFit->SetParameter(2,1);
	bgFit->SetParName(0,"Offset");
	bgFit->SetParName(1,"Tau");
	bgFit->SetParName(2,"Background");
	reject = kTRUE;
	h1->Fit(bgFit,"R");
	reject = kFALSE;
	TF1 *fleft = new TF1("fleft",fline,bgMin,sigMin,3);
	fleft->SetLineColor(kOrange);
	fleft->SetParameters(bgFit->GetParameters());
	h1->GetListOfFunctions()->Add(fleft);
	gROOT->GetListOfFunctions()->Remove(fleft);
	TF1 *fright = new TF1("fright",fline,sigMax,bgMax,3);
	fright->SetLineColor(kOrange);
	fright->SetParameters(bgFit->GetParameters());
	h1->GetListOfFunctions()->Add(fright);
	gROOT->GetListOfFunctions()->Remove(fright);
//	h1->SetMaximum(300000);
	h1->Draw();

	double fitOffset = bgFit->GetParameter(0);
	double fitTau = bgFit->GetParameter(1);
//	double fitBackground = bgFit->GetParameter(2);
	double fitOffsetErr = bgFit->GetParError(0);
	double fitTauErr = bgFit->GetParError(1);
//	double fitBackgroundErr = bgFit->GetParError(2);

	cout << "Number of Bins: " << h1->GetSize()-2 << endl;;
	cout << "fitOffset: " << fitOffset << endl;;
	cout << "fitTau: " << fitTau << endl;;
	for (int i=0; i<(h1->GetSize()-2); i++)
	{
		xpos = i*((max-min)/bins)+min;
//		h2->Fill(xpos,i*500);
		bg->Fill(xpos,(fitOffset + fitTau*xpos));
//		bg->Fill(xpos,(exp(fitTau*xpos + fitOffset) + fitBackground));
	}
	bg->SetLineColor(kBlue);
	bg->Draw("same");

	h3->Add(h1);
	h3->Add(bg,-1);
	h3->SetLineColor(kRed);
	h3->SetMinimum(0);
	h3->Draw("same");


	cout << "sigMin: " << sigMin << ", sigMax: " << sigMax << endl;
	TF1 *sigFit = new TF1("sigFit","gaus",sigMin,sigMax);
	sigFit->SetLineColor(kBlue);
	sigFit->SetParameter(0,1000);
	sigFit->SetParameter(1,690);
	sigFit->SetParameter(2,20);
	sigFit->SetParameter(3,1);
	sigFit->SetParName(0,"Weight");
	sigFit->SetParName(1,"Mean");
	sigFit->SetParName(2,"Sigma");
//	sigFit->SetParName(3,"Background");
	h3->SetMaximum(300000);
	h3->Fit(sigFit,"R");
	sigFit->Draw("same");	
	

	double fitWeight = sigFit->GetParameter(0);
	double fitMean = sigFit->GetParameter(1);
	double fitSigma = sigFit->GetParameter(2);
	double fitWeightErr = sigFit->GetParError(0);
	double fitMeanErr = sigFit->GetParError(1);
	double fitSigmaErr = sigFit->GetParError(2);
	fitResults = new TPaveText(0.11,0.70,0.4,0.89,"NDC");
	TString WeightStr = "Weight = ";
	WeightStr += fitWeight;
	WeightStr += " ± ";
	WeightStr += fitWeightErr;
	TString MeanStr = "Mean = ";
	MeanStr += fitMean;
	MeanStr += " ± ";
	MeanStr += fitMeanErr;  
	TString SigmaStr = "Sigma = ";
	SigmaStr += sqrt(fitSigma*fitSigma);
	SigmaStr += " ± ";
	SigmaStr += fitSigmaErr; 
	TString OffsetStr = "Offset = ";
	OffsetStr += fitOffset;
	OffsetStr += " ± ";
	OffsetStr += fitOffsetErr; 
	TString TauStr = "Tau = ";
	TauStr += fitTau;
	TauStr += " ± ";
	TauStr += fitTauErr; 
	TString BackgroundStr = "BackgroundConst = ";
	BackgroundStr += fitBackground;
	BackgroundStr += " ± ";
	BackgroundStr += fitBackgroundErr; 
	TText *t1 = fitResults->AddText(WeightStr);
	TText *t2 = fitResults->AddText(MeanStr);
	TText *t3 = fitResults->AddText(SigmaStr);
	TText *t4 = fitResults->AddText(BackgroundStr);
	TText *t5 = fitResults->AddText(TauStr);
	TText *t6 = fitResults->AddText(OffsetStr);

	h1->Draw("same");
	TString theFitStr = "(";
	theFitStr += fitWeight;
	theFitStr += "*exp(-0.5*((x-";
	theFitStr += fitMean;
	theFitStr += ")/";
	theFitStr += fitSigma;
	theFitStr += ")^2))+";
	theFitStr += fitBackground;
	theFitStr += "+exp(";
	theFitStr += fitTau;
	theFitStr += "*x+";
	theFitStr += fitOffset;
	theFitStr += ")";
	TF1 *theFit = new TF1("theFit",theFitStr,bgMin,bgMax);
	theFit->SetLineColor(kMagenta);
	theFit->Draw("same");

        double integralOfPeak;
        integralOfPeak = sigFit->Integral((fitMean - 3*sqrt(fitSigma*fitSigma)),(fitMean + 3*sqrt(fitSigma*fitSigma)));
        TString peakInt = "Integral of Peak: ";
        peakInt +=  integralOfPeak;
        cout << peakInt << endl;
        TText *t7 = fitResults->AddText(peakInt);

	pad1->Update();

	TString outputPlotsHere = "/home/ellie/physics/e05-102/analysis-scripts/devel/test_stuff/";
        TString testOutTitle = outputPlotsHere;
        testOutTitle += "test_out_step_1";
	testOutTitle += ".svg";


	fitResults->Draw("same");

}
Ejemplo n.º 26
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;
}
Ejemplo n.º 27
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
Ejemplo n.º 28
0
//________________________________________________________________________________
void peaks(TH1* h, Int_t np=10, Int_t ij=0) {
  if (! h) return;
  npeaks = TMath::Abs(np);
  if (! c1)  c1 = new TCanvas();
  else       c1->Clear();
  if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();}
  c1->Divide(1,2);
  c1->cd(1);
  h->Draw();
  TH1F *h2 = (TH1F*)h->Clone("h2");
  //Use TSpectrum to find the peak candidates
  TSpectrum *s = new TSpectrum(2*npeaks);
  Int_t nfound = s->Search(h,5,"",0.05);
  printf("Found %d candidate peaks to fit\n",nfound);
  if (! nfound) return;
  //Estimate background using TSpectrum::Background
  TH1 *hb = s->Background(h,20,"same");
  hb->Draw("same");
  c1->Update();
  if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();}
  if (np <0) return;

  //estimate linear background using a fitting method
  c1->cd(2);
  TF1 *fline = new TF1("fline","pol1",0,1000);
  fline->FixParameter(1,0.);
  h->Fit("fline","qnlw");
  if (c2 && ij > 0) {c2->cd(ij+1); h->Draw(); c2->Update(); c1->cd(2);}
  //Loop on all found peaks. Eliminate peaks at the background level
  Double_t par[3000];
  par[0] = fline->GetParameter(0);
  par[1] = fline->GetParameter(1);
  npeaks = 0;
  Float_t *xpeaks = s->GetPositionX();
  Float_t ymax = 0;
  for (Int_t p=0;p<nfound;p++) {
    Float_t xp = xpeaks[p];
    Int_t bin = h->GetXaxis()->FindBin(xp);
    Float_t yp = h->GetBinContent(bin);
    if (yp-3*TMath::Sqrt(yp) < fline->Eval(xp)) continue;
    par[3*npeaks+2] = yp;
    if (yp > ymax) ymax = yp;
    par[3*npeaks+3] = xp;
    par[3*npeaks+4] = 3;
    npeaks++;
  }
  cout << "Found " << npeaks << " useful peaks to fit" << endl;
  Int_t NP = 0;
  Int_t nbad = 0;
  TString LineH("  {\"");  LineH +=  h->GetName(); LineH += "\"";
  TString Line("");
  struct ParErr_t {Double_t par, err;};
  ParErr_t parErr[10];
  TF1 *fit = 0;
  if (ymax > 2*par[0]) {
    cout << "Now fitting: Be patient" << endl;
    fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks);
    TVirtualFitter::Fitter(h2,10+3*npeaks); //we may have more than the default 25 parameters
    fit->SetParameter(0,par[0]);
    fit->FixParameter(1,0.);
    for (Int_t p = 0; p < npeaks; p++) {
      fit->SetParName(3*p+2,Form("A%i",p));
      fit->SetParLimits(3*p+2,0,1e6);
      fit->SetParameter(3*p+2,par[3*p+2]);
      fit->SetParName(3*p+3,Form("#mu%i",p));
      fit->SetParLimits(3*p+3,TMath::Max(0.,par[3*p+3]-2), TMath::Min(240.,par[3*p+3]+2));
      fit->SetParameter(3*p+3,par[3*p+3]);
      fit->SetParName(3*p+4,Form("#sigma%i",p));
      fit->SetParLimits(3*p+4,0.01,20);
      fit->SetParameter(3*p+4,par[3*p+4]);
    }
    fit->SetNpx(1000);
    h2->SetStats(0);
    h2->Fit("fit","l");
    if (c2 && ij > 0) {c2->cd(ij); h2->Draw("same"); c2->Update(); c1->cd(2);}
    fit->GetParameters(par);
    for (Int_t p = 0; p<np;p++) {
      if (p < npeaks && par[3*p+2] > 5*fit->GetParError(3*p+2) && 
	  par[3*p+2] > par[0]) {
	if (TMath::Abs(par[3*p+4]) > 5.0) nbad++;
	//      Line += Form(",%f,%f,%7.2f,%5.2f",par[3*p+2],fit->GetParError(3*p+2),par[3*p+3],TMath::Abs(par[3*p+4]));
	parErr[NP].par = par[3*p+3];
	parErr[NP].err = TMath::Abs(par[3*p+4]);
	for (Int_t i = 0; i < NP; i++) {
	  if (parErr[i].par > parErr[NP].par) {
	    ParErr_t temp = parErr[i];
	    parErr[i] = parErr[NP];
	    parErr[NP] = temp;
	  }
	}
	NP++;
      } 
    }
  }
  for (Int_t p = 0; p < np; p++) {
    if (p < NP) Line += Form(",%7.2f,%5.2f",parErr[p].par,parErr[p].err);
    else  Line += ",0,0";
  }
  Line += "},";
  if (nbad > 1) NP = -NP; // reject whole hybrid
  LineH +=  Form(",%3i",NP);
  cout << LineH << Line << endl;
  out  << LineH << Line << endl;
  c1->Update();
  if (c2) c2->Update();
  delete fit;
  delete s;
}
Ejemplo n.º 29
0
int piRandom() {

  TRandom                  r0;
  TRandom1                  r1;
  TRandom2                 r2; 
  TRandom3                 r3; 
  //Random<GSLRngRand>       r1;
//   Random<GSLRngTaus>       r2;
//   Random<GSLRngRanLux>     r3;

  double n = NEVT; 
  int nloop = NLOOP;
  double dy = 15/std::sqrt(n);

  TH1D * h0 = new TH1D("h0","TRandom delta",100,-dy,dy);
  TH1D * h1 = new TH1D("h1","TRandom1 delta",100,-dy,dy);
  TH1D * h2 = new TH1D("h2","TRandom2 delta",100,-dy,dy);
  TH1D * h3 = new TH1D("h3","TRandom3 delta",100,-dy,dy);

  double sigma = std::sqrt( PI * (4 - PI)/n );
  std::cout << "**********************************************************" << std::endl; 
  std::cout << " Generate " << int(n) << " for " << nloop      << " times " << std::endl; 
  std::cout << "**********************************************************" << std::endl; 
  std::cout << "\tExpected Sigma = " << sigma << std::endl; 

#define INTERACTIVE
#ifdef INTERACTIVE

  double del, err;
  TCanvas * c1 = new TCanvas("c1_piRandom","PI Residuals");
  gStyle->SetOptFit(1111);
  gStyle->SetOptLogy();
  c1->Divide(2,2);
  c1->cd(1);
  generate(r0,h0);
  h0->Fit("gaus");
  h0->Draw();
  TF1 * fg = (TF1*) h0->FindObject("gaus");
  if (fg) { 
    del = (fg->GetParameter(2)-sigma); 
    err = fg->GetParError(2);
  }
  else { del = -999; err = 1; }

  char text[20];
  sprintf(text,"Spread %8.4f",del/err);
  TPaveLabel * pl0 = new TPaveLabel(0.6,0.3,0.9,0.4,text,"brNDC");  
  pl0->Draw();
   


  
  c1->cd(2);
  generate(r1,h1);
  h1->Fit("gaus"); 
  h1->Draw();
  fg = (TF1*) h1->FindObject("gaus");
  if (fg) { 
    del = (fg->GetParameter(2)-sigma); 
    err = fg->GetParError(2);
  }
  else { del = -999; err = 1; }

  sprintf(text,"Spread %8.4f",del/err);
  TPaveLabel * pl1 = new TPaveLabel(0.6,0.3,0.9,0.4,text,"brNDC");  
  pl1->Draw();


  c1->cd(3);
  generate(r2,h2);
  h2->Fit("gaus"); 
  h2->Draw();
  fg = (TF1*) h2->FindObject("gaus");
  if (fg) { 
    del = (fg->GetParameter(2)-sigma); 
    err = fg->GetParError(2);
  }
  else { del = -999; err = 1; }

  sprintf(text,"Spread %8.4f",del/err);
  TPaveLabel * pl2 = new TPaveLabel(0.6,0.3,0.9,0.4,text,"brNDC");  
  pl2->Draw();


  c1->cd(4);
  generate(r3,h3);
  h3->Fit("gaus"); 
  h3->Draw();
  fg = (TF1*) h3->FindObject("gaus");
  if (fg) { 
    del = (fg->GetParameter(2)-sigma); 
    err = fg->GetParError(2);
  }
  else { del = -999; err = 1; }

  sprintf(text,"Spread %8.4f",del/err);
  TPaveLabel * pl3 = new TPaveLabel(0.6,0.3,0.9,0.4,text,"brNDC");  
  pl3->Draw();
  
#else 
  generate(r0,h0);
  generate(r1,h1);
  generate(r2,h2);
  generate(r3,h3);
#endif

  return 0;

}
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;
    
}