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
void Scan( TString tgt = "full", Int_t chan = 300, Bool_t plot = kTRUE,
		UInt_t rebin = 1)
{
	UInt_t bin;
	TString name;

	TH1D* h1;
	TH2D* h2;

	if ( tgt == "full") h2 = h2d_f;
	else if ( tgt == "empty") h2 = h2d_e;

	if ( ( chan >= 0) && ( chan <= 351)) {
		bin = h2->GetXaxis()->FindBin( chan);
		name = Form( "Channel %d", chan);
		h1 = h2->ProjectionY( name, bin, bin);
		name = Form( "E_{#gamma} = %5.1f #pm %3.1f MeV", tcd[chan].energy,
				tcd[chan].denergy);
	}
	else if ( chan == -1) {
		name = "All Channels";
		h1 = h2->ProjectionY( name, 0, 351);
	}
	else {
		cout << "Error: channels must be 0-351 or -1" << endl;
		break;
	}

	h1->SetTitle( name);

	TString opt;
	opt = "NQR+";
	if ( plot == kTRUE) {
		h1->Draw();
		opt = "QR+";
	}

	TF1 *f1 = new TF1( "f1", "pol1", 20, 80);
	TF1 *f2 = new TF1( "f2", "gaus", 95, 105);
	h1->Fit( "f1", "NQR");
	f1->GetParameters( &par[0]);
	h1->Fit( "f2", "NQR+");
	f2->GetParameters( &par[2]);
	TF1 *fall = new TF1( "fall", "pol1(0) + gaus(2)", 20, 180);
	fall->SetParameters( par);
	h1->Fit( "fall", opt);
	Int_t bins = h1->GetXaxis()->FindBin( 180) - h1->GetXaxis()->FindBin( 20);
	red_chisq = fall->GetChisquare()/(bins-5);

//	gStyle->SetOptStat( 0);
	gStyle->SetOptFit( 1);

	cout << chan;
	cout << " " << par[3];
	cout << " " << par[4];
	cout << " " << red_chisq;
	cout << endl;

}
Exemple #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
	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 #5
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();
	}
}
Exemple #6
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 #7
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 #9
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 #10
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 #11
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 #12
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 #14
0
int main()
{

  float const conS =.3/2.35;
  ofstream fout("cal/backN.cal");
  ofstream fwhm("cal/fwhmback.dat");
  TFile f("sort.root");
  TCanvas* canvas[14];
  int Ntele = 14;
  int Nstrip = 32;
  ostringstream outstring;
  TH2I frame("frame","",10,4.5,9.5,10,0,130);
  frame.SetStats(kFALSE);

  double xx[14*32];
  double yy[14*32];

  TF1 *func = new TF1("fit",ThPeaks,3,9,4);
  double para[5];
  ifstream file("cal/back.cal");
  float intercept, slope;
  int i1,i2;
  string name;

  TH1F con("con","",500,0,10);
  for (int itele=0;itele<Ntele;itele++)
    {
      outstring.str("");
      outstring << "B"<<itele;
      name = outstring.str();
      canvas[itele] = new TCanvas(name.c_str());
      canvas[itele]->Divide(6,6);
      for (int istrip =0;istrip<Nstrip;istrip++)
        {
      
          canvas[itele]->cd(istrip+1);
          file >> i1 >> i2  >> slope >> intercept;


          outstring.str("");
          outstring << "back/cal/EBC"<<itele<<"_"<<istrip;
          string name = outstring.str();
          cout <<  name << endl;
          TH1I * hist = (TH1I*) f.Get(name.c_str());
	  frame.Draw();


          hist->SetStats(kFALSE);
          hist->GetXaxis()->SetRangeUser(4.5,9.5);
          con.GetXaxis()->SetRangeUser(4.5,9.5);
	  for (int i=1;i<=500;i++)
	    for (int j=1;j<500;j++)
	    {
              float deltax = hist->GetBinCenter(i)-con.GetBinCenter(j);
	      if (fabs(deltax) > 10.*conS)continue;
              float fact = gauss(deltax,0.,conS);
	      float y = fact*hist->GetBinContent(i)*hist->GetBinWidth(i);
              con.SetBinContent(j,y+con.GetBinContent(j));
	    }



	  for (int i=1;i<=500;i++) 
	    {
	      hist->SetBinContent(i,con.GetBinContent(i));
	      con.SetBinContent(i,0.);
	    }

          hist->Draw("same");



          func->SetParameter(0,0);
          func->SetParameter(1,1.);
	  func->FixParameter(2,conS);
          //func->SetParameter(2,0.1);
          func->SetParameter(3,8.);
          func->SetLineColor(2);
          //func->Draw("same");



	  hist->Fit(func);
          func->GetParameters(para);
          cout << "chisq=" << func->GetChisquare() << endl;
           if (fabs(para[1]-1.) < .2) 
	     { 

              slope *= para[1];
              intercept = intercept*para[1] + para[0];
	     }
            fout << itele << " " << istrip << " " 
                 << slope << " " << intercept << endl;
            fwhm << itele << " " << istrip << " " 
                  << para[2]*2.35 << endl;
            int ii = itele*32+istrip;
            xx[ii] = (float)ii;
            yy[ii] = para[2]*2.35;
            cout << para[0] << " " << para[1] << " " << para[2] << endl;

        }
    }

  TFile g("ThBack.root","RECREATE");
  for (int itele=0;itele<Ntele;itele++) canvas[itele]->Write();
  TCanvas fwhmCan("fwhm");
  TH2I frame2("frame2","",10,0,448,10,0,0.12);
  frame2.SetStats(kFALSE);
  frame2.GetYaxis()->SetTitle("FWHM [MeV]");
  frame2.GetXaxis()->SetTitle("back strip");
  frame2.Draw();
  TGraph graph(32*14,xx,yy);
  graph.Draw("*");
  graph.Write();
  fwhmCan.Write();
  g.Write();
}
void RPCChambersCluster::variousStudyExperimentalFunction(TFile * fileToSave,TH1F * histo[10],const int & eventNum){
  
  // Save file is used to save all the reconstructed graphs with tracks in order to inspect them
  
  RPCChamber * currentChamberObj;
  RPCChamber * triggerObj;
  RPCLinkBoardChannel * currentChannelObj;
  int numberOfChambers = this->getNumberOfChambers();
  triggerObj = this->getTriggerObjectNumber(1);
  TGraphErrors * graphToFit;
  //currentChamberObj = this->getChamberNumber(1);
  int numberOfReferenceChambers = 0; // change this value for the three cases - CERN, Ghent and BARC
  vector<int> tempCluster;
  
  TH1F * hist1,* hist2,* hist3,* hist4, * numberOfClustersHisto, * topMinusEachChamberAvg, * bottomMinusEachChamberAvg,*clsSize ,
  * numberOfClustersInSamePartitions, * histClustersPartitionDistr, * SingleMultiHits;
  
  hist1 = histo[0];
  hist2 = histo[1];
  hist3 = histo[2];
  hist4 = histo[3];
  numberOfClustersHisto = histo[4];
  topMinusEachChamberAvg = histo[5];
  bottomMinusEachChamberAvg = histo[6];
  clsSize = histo[7];
  histClustersPartitionDistr = histo[8];
  SingleMultiHits = histo[9];
  
  int timeReference = 0;
  int timeWindow = 0;
  int firstScintilatorTime = 0 ;
  int secondScintilatorTime = 0;
  int difference_reference = 0;
  int coincidence_time = 0 ;
  if (triggerObj->getChannel(32)->hasHit()){
    coincidence_time = triggerObj->getChannel(32)->getHits().at(0);
  }
  
  ESiteFileType siteType = kIsCERNrawFile; // later make the method to take file type argument and to use it in here
  
  //TH1F * firstTriggerEntries  = new TH1F("ScintStats1","ScintStats1",0,500,500);
  //firstTriggerEntries->SetLineColor(kBlue);
  //firstTriggerEntries->SetFillColor(kBlue);
  
  switch (siteType) 
  {
    case kIsCERNrawFile:
      
      timeWindow = 500;
      
      numberOfReferenceChambers = 3;
      
      int countTwoHits=0;
      for (int i = 0 ; i < 13 ; i++){
	if(triggerObj->getChannel(i+1)->hasHit() ){
	  
	  if ( difference_reference == 0 || ( coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0) ) < difference_reference ) {
	    
	    difference_reference = coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0);
	    firstScintilatorTime = triggerObj->getChannel(i+1)->getHits().at(0);
	    
	  }
	}
      }
      
      difference_reference = 0;
      
      for (int i = 13 ; i < 31 ; i++) {
	if(triggerObj->getChannel(i+1)->hasHit() ){
	  
	  if ( difference_reference == 0 || ( coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0) ) < difference_reference ) {
	    
	    difference_reference = coincidence_time - triggerObj->getChannel(i+1)->getHits().at(0);
	    secondScintilatorTime = triggerObj->getChannel(i+1)->getHits().at(0);
	    
	  }
	}
      }
      
      //timeReference = timeReference/2;
      /*
    case kIsGENTrawFile:
      timeWindow = 20;
      for(int i = 0 ; i < 32 ; i++){
	if(triggerObj->getChannel(i+1)->hasHit()) {
	  triggerObj->getChannel(i+1)->getHits().at(0);
	}
	break;
      }
    case kIsBARCrawFile:
      timeWindow = 0; 
      timeReference = 0;
      */
      
  }
  
  timeReference = (firstScintilatorTime+secondScintilatorTime)/2;
  
  //cout << " time reference : " << timeReference << endl;
  //cout << " trigger entries : ";
  for (int i=0; i < 32 ; i++){
    if (triggerObj->getChannel(i+1)->hasHit()){
//       cout << " trig channel : " << i+1 << " " << triggerObj->getChannel(i+1)->getHits().at(0) << " ";
    }
  }
  
  cout << endl;
//   cout << " most close trigger entries : top " << firstScintilatorTime << " bottom : " << secondScintilatorTime;
//   cout << endl;
  
  
  hist1->Fill(abs(firstScintilatorTime-secondScintilatorTime));
  hist2->Fill(coincidence_time - firstScintilatorTime);
  hist3->Fill(coincidence_time - secondScintilatorTime);
  
//   cout << "difference : " << firstScintilatorTime-secondScintilatorTime << endl;
  
  for (int totalChambers = 0 ; totalChambers < numberOfChambers ; totalChambers++){
    
    currentChamberObj = this->getChamberNumber(totalChambers+1);
     cout << "Chamber " << totalChambers+1 ;
    for (int j=0 ; j < 96 ;j++){
      
      currentChamberObj = this->getChamberNumber(totalChambers+1);
      currentChannelObj = currentChamberObj->getChannel(j+1);      
      if (currentChannelObj->hasHit()){
 	cout << " channel " << currentChannelObj->getOnlineNumber() << " time " << currentChannelObj->getHits().at(0);
      }
    }
     cout << endl;
    currentChamberObj->findAllClustersForTriggerTimeReferenceAndTimeWindow(timeReference,timeWindow);    
    // now check the clusterization methods
    // fill number of cluster when there is at least one
    if(currentChamberObj->getNumberOfClusters()){
      numberOfClustersHisto->Fill(currentChamberObj->getNumberOfClusters());
    }
  }
  
  cout << "-------------------" << endl;
//   cout << "Check new cluster methods" << endl;
  
  
  for (int totalChambers = 0 ; totalChambers < numberOfChambers ; totalChambers++){
    
    currentChamberObj = this->getChamberNumber(totalChambers+1);
//     cout << "Chamber " << totalChambers+1 ;
    for (int i = 0 ; i < currentChamberObj->getNumberOfClusters() ; i++){
      
      // make the difference to get the tolerance within one cluster 
      
      int smallestTime = 0;
      int biggestTime = 0;
      int currentValue = 0;
      int sizeOfCurrentCluster = currentChamberObj->getClusterNumber(i+1).size();
      tempCluster = currentChamberObj->getClusterNumber(i+1);
      int numberOfHits = 0 ;
      for (int j = 0 ; j < sizeOfCurrentCluster; j++){
	// Fill the size here
	SingleMultiHits->Fill(currentChamberObj->getStrip(tempCluster.at(j))->getHits().size());
	
      }
      
      clsSize->Fill(sizeOfCurrentCluster);
      
      for (int j = 0 ; j < sizeOfCurrentCluster ; j++ ){
	
	currentValue = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j);
	
	if ( j == 0 ) {
	  // init the values
	  smallestTime = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j);
	  biggestTime = currentChamberObj->getStripsHitsTimesForCluster(i+1).at(j);
	}
	else{
	  
	  if ( smallestTime >= currentValue ){
	    smallestTime = currentValue;
	  }
	  if( biggestTime <= currentValue){
	    biggestTime = currentValue;
	  } 
	}
      }
      
      if (biggestTime - smallestTime != 0){
	hist4->Fill(biggestTime-smallestTime);
      }
      int avgTimeForCluster = currentChamberObj->getAverageTimeForCluster(i+1);
      topMinusEachChamberAvg->Fill(abs(firstScintilatorTime - avgTimeForCluster));
      bottomMinusEachChamberAvg->Fill(abs(secondScintilatorTime - avgTimeForCluster));
      
//       cout << endl << "Cluster " << i+1 << " toptime " << biggestTime << " leasttime " << smallestTime ;
      
    }
    
//     cout << endl;
  }
  
//   cout << "-------Second check done-----------" << endl;
  
  // try with single cluster per chamber 
  
  vector<int> vectorOfReferenceChambers;
  
  for (int i=0; i < this->getNumberOfChambers() ; i ++){
    currentChamberObj = this->getChamberNumber(i+1);
    if (currentChamberObj->isReferenceChamber() && !currentChamberObj->getNumberOfClusters()){
      // the reference chamber does not have a hit (cluster), probably inefficient (or else) , skip the execution
      
      break;
    }
  }
  
  // remove the following when the configuration object is introduced // done, change the implementation
  vectorOfReferenceChambers.push_back(1); vectorOfReferenceChambers.push_back(4); vectorOfReferenceChambers.push_back(6);
  
  /** Determination of track starts here */ // Move this part in separated method 
  
  //TFile * goodTracks = new TFile("GoodTracks.root","UPDATE");
  //TFile * badTracks = new TFile("BadTracks.root","UPDATE");
  int globalCount = 1;
  for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){
    for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){
      for( int k = 0 ; k < this->getChamberNumber(vectorOfReferenceChambers[2])->getNumberOfClusters() ; k++ ){
	
	// check the multiplicity. use 5 as upper limit number
	// with the test run 2202 - CERN channel 33 is noisy so there is a condition only for it here TO DO - remove the channel 33 condition // old function
	
	/** Hits : first , use the time to distinguish useless crap - like noisy channels 
	 *  
	 * 2. Check the partition plane (YZ plane) for vertical tracks. If the track is vertical don't search for consecutiveness and don't fill the YZ histo
	 * 3. Check the partitions plane for consecutiveness - one could not expect track that passes 3 -> 1 -> 3 partitions
	 * 
	*/ 
	
	if(this->getChamberNumber(vectorOfReferenceChambers[0])->getSizeOfCluster(i+1) > 5 ||
	  this->getChamberNumber(vectorOfReferenceChambers[1])->getSizeOfCluster(j+1) > 5 ||
	  this->getChamberNumber(vectorOfReferenceChambers[2])->getSizeOfCluster(k+1) > 5
	  ) continue;
	
	// the partition logic start  here - track could pass more than one partition
	int direction = 0 ; // direction should describe how the partition changes from one reference chamber to another. It 
	int RefChamberClusterPartition[3] ;
	int currentDifference = 0;
	bool positive = false;
	bool negative = false;
	int partitionPenetrated = 1;
	// the Y coordinate is the partition number ( 1 2 or 3 - A B or C)
	
	RefChamberClusterPartition[0] = this->getChamberNumber(vectorOfReferenceChambers[0])->getXYCoordinatesOfCluster(i+1).at(1);
	RefChamberClusterPartition[1] = this->getChamberNumber(vectorOfReferenceChambers[1])->getXYCoordinatesOfCluster(j+1).at(1);
	RefChamberClusterPartition[2] = this->getChamberNumber(vectorOfReferenceChambers[2])->getXYCoordinatesOfCluster(k+1).at(1);
	
	for ( int ii = 0; ii < 2 ; ii++ ){
	  direction = (RefChamberClusterPartition[ii] - RefChamberClusterPartition[ii+1]);
	  if (direction != 0) { 
	    direction = direction/abs(direction); 
	    partitionPenetrated++;
	  } // get only the sign ( +1 or -1)
	  if (direction && direction == -1)  positive = true;
	  if (direction && direction == 1 )  negative = true;
	  
	}
	
	// cannot have a track that goes in both direction
	// partition logic end here
	stringstream ss;
	ss << globalCount;
	string histoCounter = ss.str();
	
	
	TH2F * histXZ = new TH2F(histoCounter.c_str(),"XZ plane",110,0,110,68,0,34);
	
	
	histXZ->SetMarkerColor(kBlue);
	histXZ->SetMarkerStyle(kOpenTriangleDown); //  - open triangle down not found on noise server ? 
	
	double * xc = new double[3];
	double * yc = new double[3];
	double * zc = new double[3];
	
	vector<double> coordinates ;
	double xCoordinate = 0;
	int yCoordinate = 0;
	int zCoorinate = 0;
	
	coordinates = this->getChamberNumber(1)->getXYCoordinatesOfCluster(i+1);
	xCoordinate = coordinates.at(0);
	yCoordinate = coordinates.at(1);
	zCoorinate = 10*vectorOfReferenceChambers[0];
	
	int prevPartition = yCoordinate;
	xc[0] = xCoordinate;
	yc[0] = yCoordinate;
	zc[0] = 1*10;
	
	histXZ->Fill(zc[0],xCoordinate);
	cout << xCoordinate << " " << yCoordinate << endl;
	
	coordinates = this->getChamberNumber(4)->getXYCoordinatesOfCluster(j+1);
	xCoordinate = coordinates.at(0);
	yCoordinate = coordinates.at(1);
	
	xc[1] = xCoordinate;
	yc[1] = yCoordinate;
	zc[1] = 4*10;
	
	histXZ->Fill(zc[1],xCoordinate);
	prevPartition = yCoordinate;
	
	cout << xCoordinate << " " << yCoordinate << endl;	
	coordinates = this->getChamberNumber(6)->getXYCoordinatesOfCluster(k+1);
	xCoordinate = coordinates.at(0);
	yCoordinate = coordinates.at(1);
	
	xc[2] = xCoordinate;
	yc[2] = yCoordinate;
	zc[2] = 6*10;
	
	histXZ->Fill(zc[2],xCoordinate);
	cout << xCoordinate << " " << yCoordinate << endl;
	
	if ( positive && negative ) continue;
	
	TF1 * fitfunc = new TF1("FitTrack","[0]+x*[1]",0,100);
	Double_t * params = new Double_t[2];
	histXZ->Fit(fitfunc);
	fitfunc->GetParameters(params);
	cout << "par1 " << params[0] << " par2 " << params[1] << " chi2 " << fitfunc->GetChisquare() << endl;
	double channelToSearchHitIn ;
	
	for (int jj = 0 ; jj < this->getNumberOfChambers() ; jj++){
	  if (jj+1 != vectorOfReferenceChambers[0] || jj+1 != vectorOfReferenceChambers[1] || jj+1 != vectorOfReferenceChambers[1])
	    // add additional rule that the chamber should exist in the calibration object 
	  {
	    
	    channelToSearchHitIn = fitfunc->Eval((jj+1)*10);
	    cout << "Evaluated for chamber number " << jj+1 << " value : " << channelToSearchHitIn << endl;
	    
	  }
	  
	}
	// now here - what to return, and how to get the hits in the chambers under test from the function
	
	
	
	if (fitfunc->GetChisquare() > 20) continue; // cut the execution 
	if(fitfunc->GetChisquare() < 20){
	  //goodTracks->Write(trackHistoName.c_str());
	  histClustersPartitionDistr->Fill(partitionPenetrated);
	  //histXZ->SaveAs((trackHistoName+".root").c_str());  
	  // here search for hits in the chambers under test  
	  
	}
	
	/*
	else{
	  badTracks->Write(trackHistoName.c_str());
	}	
	*/
	
	//trackHistoName+=".root";
	//histXZ->SaveAs(trackHistoName.c_str());
	
	histXZ->Delete();
	
      }
    }
  }
//   badTracks->Close("R");
//   badTracks->Delete();
//   goodTracks->Close("R");
//   goodTracks->Delete();

}
//*************************************************************
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 #17
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;
}
Exemple #18
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();
}
Exemple #19
0
int fitfunc(int *energy, int *gopt, int append, char* addname){
  if(setlogy==0){
    //double labelx[6]={380,800,1200,1700,2400,5000}, labely[6]={80,45,25,21,25,15}; //Position
  }else{
    //double labelx[6]={300,750,1400,1800,2700,5000}, labely[6]={130,75,50,30,25,5}; //Position
  }

  //void fitfunc(int energy[5], int gopt[5]){
  for(int i=0; i<6; i++){
    cout<<energy[i]<<" "<<gopt[i]<<endl;
  }
  
  if(histname=="p2p"){
    char* dirsim = "../output/rec";
  }else if(histname=="p3p"){
    //char* dirsim = "../output/rec_p3p";
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }else{// if(histname=="h23"){
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }

  char* outname = Form("../output/fit/%s_%i_%i_%i_%i_%i_%i%s",histname, energy[0],energy[1],energy[2],energy[3],energy[4],energy[5],addname); // .pdf .png .C .root will be created


  ofstream fpara(Form("%s_fitresult.txt",outname));
  if(append == 1){
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname),ios_base::app);
  }else{
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname));    
  fitlist<<"E0, E1, E2, E3, E4, E5, CS0, CS1, CS2, CS3, CS4, CS5, ER0, ER1, ER2, ER3, ER4, ER5, Chi-sq"<<endl;
  }
  
  gStyle->SetOptStat(kFALSE);
  
  gROOT->ProcessLine( ".L fit78Ni.h" );
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadGridX(false);
  gStyle->SetPadGridY(false);
  //gStyle->SetOptLogy(1);

  char temp[300];
  int minBin = 0;
  //int maxBin = 5500;
  int maxBin = 6000;
  int binning = 100;
  int numBin = (maxBin-minBin)/binning;
  
  //Id starts with one!!!
  int daliIDMin = 1;
  int daliIDMax = 186;

  //****************************************************************************
  // The simulated peaks
  TFile *sim[6];
  for(int i=0; i<6; i++){
    if(energy[i]>0){
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,energy[i]));
    }else{
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,2620));//dummy
      gopt[i] = 0;
    }
  }

  //The experimental data:
  TFile *exp[1];
  //exp[0] = new TFile(Form("%s/MINOStest.root",direxp));
  exp[0] = new TFile(direxp);

  TCanvas *fCanvas=new TCanvas("Canvas","Response function",700,700);
  fCanvas->SetBorderSize(0);
  fCanvas->SetBorderMode(0);
  fCanvas->SetFrameBorderMode(0);
  fCanvas->SetFrameFillColor(0);
  fCanvas->SetBottomMargin(0.15);
  fCanvas->SetLeftMargin(0.15);
  fCanvas->cd();

  TFile *fout = new TFile(Form("%s.root",outname),"RECREATE");
  fout->cd();

  // Main
  TPad *c_m = new TPad("c_m", "c_m",0.0,0.0,1.0,1.0);
  c_m->Draw();
  c_m->cd();
  c_m->SetFillColor(0);
  //c_m->SetFillStyle(0);
  c_m->SetBorderSize(0);
  c_m->SetRightMargin(0.05);
  c_m->SetTopMargin(0.03);
  c_m->SetBottomMargin(0.15);
  c_m->SetLeftMargin(0.15);
  if(setlogy>0) c_m->SetLogy();
  fCanvas->cd();

  //****************************************************************************
  //The simulated spectra:
  TH1F *hsim[6];
  for(int i=0;i<6;i++) {
    sprintf(temp,"hsim[%i]",i);  
    hsim[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
    hsim[i] = (TH1F*)sim[i]->Get("h_doppler_addback[0]");
  }
  /*
  hsim[0] = (TH1F*)sim[0]->Get("h_doppler_addback[0]");
  hsim[1] = (TH1F*)sim[1]->Get("h_doppler_addback[0]");
  hsim[2] = (TH1F*)sim[2]->Get("h_doppler_addback[0]");
  hsim[3] = (TH1F*)sim[3]->Get("h_doppler_addback[0]");
  hsim[4] = (TH1F*)sim[4]->Get("h_doppler_addback[0]");
  */

  //The experimental spectra:
  TH1F *hexp[1];
  for(int i=0;i<1;i++) {
    sprintf(temp,"hexp[%i]",i);  
    hexp[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
  }

  //Getting the experimental spectrum
  //78Ni
  hexp[0] = (TH1F*)exp[0]->Get(histname);
  //hexp[0] = (TH1F*)exp[0]->Get("h23;1");
  //hexp[0]->Rebin(2);

  
  for(int i=0;i<1;i++) {
    hexp[i]->SetStats(0);
    hexp[i]->SetFillColor(0);
    hexp[i]->SetLineColor(kBlue);
    hexp[i]->SetLineStyle(0);
    
    //hexp[i]->GetXaxis()->SetRangeUser(0,maxBin);
    hexp[i]->GetXaxis()->SetRangeUser(minBin,maxBin);
    //hexp[i]->GetXaxis()->SetRangeUser(0,6000);
    if(setlogy==0){
      hexp[i]->GetYaxis()->SetRangeUser(0,yrangemax);
    }else {
      hexp[i]->GetYaxis()->SetRangeUser(0.5,yrangemax);
    }

    hexp[i]->GetXaxis()->SetNdivisions(305);
    hexp[i]->GetYaxis()->SetNdivisions(305);
  
    hexp[i]->GetYaxis()->SetTitle(Form("Counts / %i keV",binning));
     hexp[i]->GetXaxis()->SetTitle("Energy (keV)");
    
    hexp[i]->GetXaxis()->SetTitleOffset(0.9);  
    hexp[i]->GetYaxis()->SetTitleOffset(0.9);
    
    hexp[i]->GetXaxis()->SetTitleFont(132);
    hexp[i]->GetYaxis()->SetTitleFont(132);
    
    /*
    hexp[i]->GetXaxis()->SetTitleSize(0.08);
    hexp[i]->GetYaxis()->SetTitleSize(0.08);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.08);
    hexp[i]->GetYaxis()->SetLabelSize(0.08);
    */
    hexp[i]->GetXaxis()->SetTitleSize(0.05);
    hexp[i]->GetYaxis()->SetTitleSize(0.05);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.05);
    hexp[i]->GetYaxis()->SetLabelSize(0.05);

    //How to get error bar for each bin
    hexp[i]->SetDefaultSumw2(kTRUE);
    

    hexp[i]->SetTitle("");
  }   
   
  //*****************************************************************************
  peak1g = new TGraph(hsim[0]);
  peak2g = new TGraph(hsim[1]);
  peak3g = new TGraph(hsim[2]);
  peak4g = new TGraph(hsim[3]);
  peak5g = new TGraph(hsim[4]);
  peak6g = new TGraph(hsim[5]);
  /*TGraph *peak1g = new TGraph(hsim[0]);
  TGraph *peak2g = new TGraph(hsim[1]);
  TGraph *peak3g = new TGraph(hsim[2]);
  TGraph *peak4g = new TGraph(hsim[3]);
  TGraph *peak5g = new TGraph(hsim[4]);
  */
  //******************Function Definition****************************************
  //*****************************************************************************
  const Double_t fitmin=300.;
  const Double_t fitmax=(Double_t)maxBin;//4000.;
   
  c_m->cd();
  TF1 *whole = new TF1( "whole", ex_respf,fitmin,fitmax,10);
  whole->SetParameters(0.0001,0.01,0.00,0.0001,0.001,0.001,3.,-1e-03,3,-1.e-3);
  //whole->SetParameters(0.0001,0.0001,0.0001, 5.9,-0.00080 );

  for(int i=0; i<6; i++){
    if(gopt[i]==1){
      whole->SetParLimits(i,0.0,parlimit[i]);
    }else{
      whole->FixParameter(i,0.0);
    }
  }
  whole->SetParLimits(6,0,10);
  whole->SetParLimits(7,-1e-02,0.);
  whole->SetParLimits(8,0,5);
  whole->SetParLimits(9,-1e-02,-1e-5);
  //whole->FixParameter(8,1.426);
  //whole->FixParameter(9,-8.1e-5);
  whole->SetLineColor(1);
  whole->SetLineWidth(2);
  whole->SetNpx(200); 
  hexp[0]->Fit(whole,"R LL");
  //hexp[0]->Fit(whole,"");
  //cout<<"test"<<endl;
  //hexp[0]->Draw("");

  //hexp[0]->GetXaxis()->SetRangeUser(0,5000);


  //fCanvas->Print(Form("%s.png",outname));

  fpara<<"Chisquare\t"<< whole->GetChisquare()<<endl;
  fpara<<"para\tvalue\terror\tfilename"<<endl;
  for(int para=0;para<10;para++){
    fpara<<para<<"\t"<<whole->GetParameter(para)<<"\t"<<whole->GetParError(para);
    if(para<6) {
      string strenergy =sim[para]->GetName();
      int itr = strenergy.find_last_of("/");
      strenergy.erase(0,itr+1);
      fpara<<"\t"<<strenergy;
    }
    fpara<<endl;
  }
  
  // fitlist<<"E0, E1, E2, E3, E4, CS0, CS1, CS2, CS3, CS4, ER0, ER1, ER2, ER3, ER4, Chi-sq"<<endl;
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<energy[i]<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<genevts*whole->GetParameter(i)*CSincl/tot78Ni<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++){gopt[i]==1?
      fitlist<<sqrt(pow(whole->GetParError(i)*CSincl,2.) //Error from fitting
		    //+whole->GetParameter(i)*pow(CSincl,2) //Statistical error for the events (included?
		    //+pow(whole->GetParameter(i)*CSinclerr,2) // Inclusive cross section error
		    )*genevts/tot78Ni<<", " 
      :fitlist<<"0, ";
      }
  fitlist<<whole->GetChisquare()<<endl;

  //RT end


  TF1 *peak1f= new TF1( "peak1f", resp1,fitmin,fitmax,1);
  peak1f->SetParameter(0,whole->GetParameter(0) );
  peak1f->SetLineColor(2);
  peak1f->SetLineWidth(2);
  peak1f->SetLineStyle(9);
  peak1f->Draw("same");

  TF1 *peak2f= new TF1( "peak2f", resp2,fitmin,fitmax,1);
  peak2f->SetParameter(0,whole->GetParameter(1) );
  peak2f->SetLineColor(2);
  peak2f->SetLineWidth(2);
  peak2f->SetLineStyle(9);
  peak2f->Draw("same");

  //
  TF1 *peak3f= new TF1( "peak3f", resp3,fitmin,fitmax,1);
  peak3f->SetParameter(0,whole->GetParameter(2) );
  peak3f->SetLineColor(2);
  peak3f->SetLineWidth(2);
  peak3f->SetLineStyle(9);
  peak3f->Draw("same");
  
  TF1 *peak4f= new TF1( "peak4f", resp4,fitmin,fitmax,1);
  peak4f->SetParameter(0,whole->GetParameter(3) );
  peak4f->SetLineColor(2);
  peak4f->SetLineWidth(2);
  peak4f->SetLineStyle(9);
  peak4f->Draw("same");
  
  TF1 *peak5f= new TF1( "peak5f", resp5,fitmin,fitmax,1);
  peak5f->SetParameter(0,whole->GetParameter(4) );
  peak5f->SetLineColor(2);
  peak5f->SetLineWidth(2);
  peak5f->SetLineStyle(9);
  peak5f->Draw("same");

  TF1 *peak6f= new TF1( "peak6f", resp6,fitmin,fitmax,1);
  peak6f->SetParameter(0,whole->GetParameter(5) );
  peak6f->SetLineColor(2);
  peak6f->SetLineWidth(2);
  peak6f->SetLineStyle(9);
  peak6f->Draw("same");


  TF1 *expon= new TF1( "expon",expf ,fitmin,fitmax,4);
  //expon->SetParameters(whole->GetParameter(5),whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8));
  expon->SetParameters(whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8),whole->GetParameter(9));
  expon->SetLineColor(4);
  expon->SetLineWidth(2);
  expon->SetLineStyle(7);
  expon->Draw("same");

  //hexp[0]->Draw("same");
  hexp[0]->Draw("EL same");
  
  /*TLatex *tex = new TLatex(2000,setlogy?130:60,Form("^{78}Ni (%s)",histname));
  tex->SetTextFont(132);
  tex->SetTextSize(0.07);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  /*TLatex *tex = new TLatex(2700,setlogy?80:55,Form("Incl: %2.1f mbarn for %d cnts", CSincl, (int)tot78Ni));
  tex->SetTextFont(132);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  for(int i =0; i<6; i++){
  if(gopt[i]==1){
    TLatex *tex = new TLatex(labelx[i],labely[i],
			     //Form("#splitline{%d keV }{%2.2f mbarn (%3.1f cnts)}",energy[i], genevts*whole->GetParameter(i)*CSincl/tot78Ni, genevts*whole->GetParameter(i)));
			     Form("%d keV",energy[i]));
    tex->SetTextFont(132);
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    }
  }
    
  fCanvas->Print(Form("%s.C",outname));
  fCanvas->Print(Form("%s.png",outname));
  fCanvas->Print(Form("%s.pdf",outname));
  
  fCanvas->Write();
  hexp[0]->Write();
  fout->Write();
  fout->Close();

}
//===============================
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);

}
Exemple #21
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;
}
Exemple #22
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 #23
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();
  
}
Exemple #24
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;
}
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;
    
}
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 #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;
}
Exemple #28
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;
}
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
/** 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");
}