예제 #1
1
void ratioPlots( TCanvas* c1, TH1* h_r, TH1* h_i, 
		 string xTitle, string yTitle, 	string savePath, 
		 double fitMin=-100000, double fitMax=100000, bool doubleColFit=0 ){

	double xMaximum = h_r->GetXaxis()->GetBinUpEdge(h_r->GetXaxis()->GetLast());
	double xMinimum = h_r->GetXaxis()->GetBinLowEdge(h_r->GetXaxis()->GetFirst());
	double yMaximum;
	double yMinimum;

	h_i->Sumw2();
	h_r->Sumw2();

	TLine* line1 = new TLine(xMinimum,1,xMaximum,1);
	line1->SetLineColor(1);
	line1->SetLineWidth(2);
	line1->SetLineStyle(7);
	
	TF1* fpol1  = new TF1("fpol1", "pol1", fitMin, fitMax);	
	fpol1->SetLineColor(2);
	fpol1->SetLineWidth(3);
	fpol1->SetLineStyle(7);
	
	TH1* hRatio = (TH1*)h_r->Clone("clone_record");
	hRatio->Divide(h_i);
	yMaximum = hRatio->GetMaximum();
	yMinimum = hRatio->GetMinimum(0);
	hRatio->GetYaxis()->SetRangeUser(yMinimum/2.5,yMaximum+yMaximum/5);
	hRatio->SetXTitle(xTitle.c_str());
	hRatio->SetYTitle(yTitle.c_str());
	hRatio->SetLineColor(9); 
	hRatio->SetLineWidth(2); 
	hRatio->SetMarkerStyle(8); 
	hRatio->Draw("e");
	hRatio->Fit("fpol1", "L");
	line1->Draw("SAME");
	
	if(doubleColFit){
		double p0=fpol1->GetParameter(0);
		double p1=fpol1->GetParameter(1);
		double endPoint=double(fitMax*p1)+p0;
		double p1new=(endPoint-1)/(fitMax-fitMin);
		char fun[100], text[100];
		sprintf(fun,"x*(%f)+1",p1new);	
		sprintf(text,"Tangent: %f",p1new);	
		TF1* fnew = new TF1("fnew", fun, fitMin, fitMax);
		fnew->SetLineColor(2);
		fnew->SetLineWidth(3);
		fnew->Draw("SAME");
	
			
		TText* Title = new TText( fitMax/12, yMinimum, text);
		Title->SetTextColor(2);
		Title->SetTextSize(0.035);
		Title->Draw("SAME");
	}

	c1->SaveAs(savePath.c_str());
	c1->cd();
}
예제 #2
0
/*============================================================================*/
void gaus1peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[5],epar[5],x[4],y[4];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  setcanvas(1);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

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

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

  //--**-- Final Peak Fit with Background --**--//
  TF1 *func = new TF1("FGAUS","gaus(0)+pol1(3)",x1,x4);
  func->SetParameters(par);
  hist->Fit(func,"R+QN");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  Double_t fwhm = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N0 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r0 = epar[0]/par[0];
  Double_t r2 = epar[2]/par[2];
  Double_t eN0= N0*TMath::Sqrt(r0*r0+r2*r2);
  printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
          par[1],epar[1],fwhm,efwhm,N0,eN0);
  //printf("%11.4f %11.4f %11.0f %11.0f\n",
  //        par[1],epar[1],N0,eN0);
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
}
예제 #3
0
//------------------------------------------------------------------------------
std::pair<double,double> fitskwlin( char* hs, double xl=-0.1, double xr=0.1 ) {
  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ) {
    cout << hs << " does not exist\n";
    return std::make_pair(0.,0.);
  }

  int nb = h->GetNbinsX();
  double x1 = h->GetBinCenter(1); // first
  double x9 = h->GetBinCenter(nb); // last

  if( xl > x1 && xl < x9 ) x1 = xl; // left
  if( xr > x1 && xr < x9 ) x9 = xr; // right

  // create a TF1 with the range from x1 to x9 and 3 parameters
  TF1 *tanhFcn = new TF1( "tanhFcn", fitSkw, x1, x9, 2 );
  tanhFcn->SetParName( 0, "dyoff" );
  tanhFcn->SetParName( 1, "dyslp" );

  // set start values:
  tanhFcn->SetParameter( 0, 0 ); // dy off [um]
  tanhFcn->SetParameter( 1, 99 ); // dy slope [um/skw]

  h->Fit( "tanhFcn", "R Q", "p" );// R = range from tanhFcn

  return std::make_pair(tanhFcn->GetParameter(0),tanhFcn->GetParameter(1));
}
예제 #4
0
void fadc_fit_heights(std::string fadc_id,std::string hist_type)
{
  /*****************************************************************/
  // Prepare the canvas
  gStyle->SetOptFit(1111);
  TCanvas *AlCapCanvas = (TCanvas *) gROOT->GetListOfCanvases()->At(0);
  AlCapCanvas->Clear();
  AlCapCanvas->Divide(4,2);

  //  gROOT->ProcessLine(".L common/get_histogram.C"); // get_histogram() is called here
  /*****************************************************************/
  const int n_channels = 8;
  std::string bank_names[n_channels] = {"Na", "Nb", "Nc", "Nd", "Ne", "Nf", "Ng", "Nh"};
  std::string name;

  double mean = 0;
  double rms = 0;

  for (int iChn = 0; iChn < n_channels; iChn++) {
    name=bank_names[iChn]+fadc_id;
    TH1* hist = get_histogram(name, hist_type);
    mean = hist->GetMean();
    rms = hist->GetRMS();

      AlCapCanvas->cd(iChn+1);

    if (hist->Integral()!=0) {
      TF1* gaus = new TF1("gaus","gaus",mean-rms,mean+rms);
      hist->Fit("gaus","Q");
      hist->GetXaxis()->SetRange(mean-2*rms,mean+2*rms);
      hist->Draw();
    }
  }
}
예제 #5
0
// show the histogram in first slot, try a Gaussian fit with given parameters
void PRadHistCanvas::UpdateHist(int index, TObject *tob, int range_min, int range_max)
{
    --index;
    if(index < 0 || index >= canvases.size())
        return;

    canvases[index]->cd();
    canvases[index]->SetGrid();
    gPad->SetLogy();

    TH1 *hist = (TH1*)tob;

    hist->GetXaxis()->SetRangeUser(hist->FindFirstBinAbove(0,1) - 10,
                                   hist->FindLastBinAbove(0,1) + 10);

    hist->GetXaxis()->SetLabelSize(HIST_LABEL_SIZE);
    hist->GetYaxis()->SetLabelSize(HIST_LABEL_SIZE);

    // try to fit gaussian in certain range
    if(range_max > range_min
       && hist->Integral(range_min, range_max + 1) > 0)
    {
        TF1 *fit = new TF1("", "gaus", range_min, range_max);
        fit->SetLineColor(kRed);
        fit->SetLineWidth(2);
        hist->Fit(fit,"qlR");
    }

    hist->SetFillColor(fillColors[index]);
    hist->Draw();
    canvases[index]->Refresh();
}
예제 #6
0
TCanvas* DrawNP(int np, TObjArray* harr, TCanvas* cnv)
{
  if (!harr) harr = &histoArr;
  if (!cnv) cnv = new TCanvas(Form("cnv%d",np),Form("cnv%d",np),900,700);
  cnv->Clear();
  cnv->Divide(2,1);
  cnv->cd(1);
  //
  TH1* dxodd = (TH1*)harr->At(np*10+kDTXodd);
  TH1* dxevn = (TH1*)harr->At(np*10+kDTXeven);
  TH1* dxoddS =(TH1*)harr->At(np*10+kDTXoddSPL);
  TH1* dxevnS =(TH1*)harr->At(np*10+kDTXevenSPL);
  double max = TMath::Max(dxodd->GetMaximum(),dxevn->GetMaximum());
  dxodd->SetMaximum(1.1*max);
  dxodd->GetXaxis()->SetTitle("#DeltaX, #mum");
  dxodd->SetTitle(Form("#DeltaX for clSize=%d",np));
  dxodd->Fit("gaus","","");
  dxevn->Fit("gaus","","sames");
  //
  dxoddS->Draw("sames");
  dxevnS->Draw("sames");
  //
  gPad->Modified();
  gPad->Update();
  SetStPadPos(dxodd,0.75,0.97,0.8,1., -1,dxodd->GetLineColor());
  SetStPadPos(dxevn,0.75,0.97,0.6,0.8, -1,dxevn->GetLineColor());
  SetStPadPos(dxoddS,0.75,0.97,0.4,0.6, -1,dxoddS->GetLineColor());
  SetStPadPos(dxevnS,0.75,0.97,0.2,0.4, -1,dxevnS->GetLineColor());
  //
  cnv->cd(2);
  TH1* dz  = (TH1*)harr->At(np*10+kDTZ);
  dz->SetTitle(Form("#DeltaZ for clSize=%d",np));
  dz->GetXaxis()->SetTitle("#DeltaZ, #mum");
  dz->Fit("gaus");
  TH1* dzS = (TH1*)harr->At(np*10+kDTZSPL);
  dz->Draw("sames");
  gPad->Modified();
  gPad->Update();
  SetStPadPos(dz,0.75,0.97,0.8,1., -1, dz->GetLineColor());
  SetStPadPos(dzS,0.75,0.97,0.5,0.7, -1, dzS->GetLineColor());
  gPad->Modified();
  gPad->Update();
  //
  cnv->cd();
  return cnv;
}
예제 #7
0
Double_t fitgp0( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){
    cout << hs << " does not exist\n";
    return 0;
  }

  h->SetMarkerStyle(21);
  h->SetMarkerSize(0.8);
  h->SetStats(1);
  gStyle->SetOptFit(101);

  gROOT->ForceStyle();

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1 = h->GetBinCenter(1);
  double x9 = h->GetBinCenter(nb);

  // create a TF1 with the range from x1 to x9 and 4 parameters
  TF1 *gp0Fcn = new TF1( "gp0Fcn", gp0Fit, x1, x9, 4 );

  gp0Fcn->SetParName( 0, "mean" );
  gp0Fcn->SetParName( 1, "sigma" );
  gp0Fcn->SetParName( 2, "area" );
  gp0Fcn->SetParName( 3, "BG" );

  gp0Fcn->SetNpx(500);
  gp0Fcn->SetLineWidth(4);
  gp0Fcn->SetLineColor(kMagenta);
  gp0Fcn->SetLineColor(kGreen);

  // set start values for some parameters:
  gp0Fcn->SetParameter( 0, xmax ); // peak position
  gp0Fcn->SetParameter( 1, 4*dx ); // width
  gp0Fcn->SetParameter( 2, nn ); // N
  gp0Fcn->SetParameter( 3, bg );

  // N: not drawing
  // Q: quiet
  // R: use specified range
  h->Fit( "gp0Fcn", "NQR", "ep" );

  return gp0Fcn->GetParameter(1);

}
예제 #8
0
double Fit511Photopeak(TH1* h, double* error=0)
{
  TSpectrum spec(1);
  spec.Search(h);
  h->GetXaxis()->SetTitle("Energy [photoelectrons]");
  h->Draw("e");
  TH1* bg = spec.Background(h);
  TH1* sig = (TH1*)(h->Clone());
  sig->SetLineColor(kGreen);
  
  sig->Add(bg,-1);
  sig->Draw("same e");
  sig->Fit("gaus","m","same e");
  TF1* gaus = sig->GetFunction("gaus");
  if(gaus)
    gaus->SetLineColor(kGreen);
  
  bg->SetLineColor(kRed);
  bg->Draw("same e");
  
  TLine* line = new TLine(gaus->GetParameter(1),0,
			  gaus->GetParameter(1),h->GetMaximum());
  line->SetLineColor(kBlue);
  line->SetLineWidth(2);
  line->Draw();
  

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

  if(error) *error = err;
  return yield;
}
예제 #9
0
Double_t fitfulllang( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){
    cout << hs << " does not exist\n";
    return 0;
  }

  double aa = h->GetEntries();//normalization

  // find peak:
  int ipk = h->GetMaximumBin();
  double xpk = h->GetBinCenter(ipk);
  double sm = xpk / 9; // sigma
  double ns = sm; // noise

  // fit range:
  int ib0 = ipk/2;
  int ib9 = h->GetNbinsX() - 1;

  double x0 = h->GetBinLowEdge(ib0);
  double x9 = h->GetBinLowEdge(ib9) + h->GetBinWidth(ib9);

  // create a TF1 with the range from x0 to x9 and 4 parameters
  TF1 *fitFcn = new TF1( "fitFcn", fitLandauGauss, x0, x9, 4 );

  fitFcn->SetParName( 0, "peak" );
  fitFcn->SetParName( 1, "sigma" );
  fitFcn->SetParName( 2, "area" );
  fitFcn->SetParName( 3, "smear" );

  fitFcn->SetNpx(500);
  fitFcn->SetLineWidth(4);
  fitFcn->SetLineColor(kMagenta);

  // set start values:
  fitFcn->SetParameter( 0, xpk ); // peak position, defined above
  fitFcn->SetParameter( 1, sm ); // width
  fitFcn->SetParameter( 2, aa ); // area
  fitFcn->SetParameter( 3, ns ); // noise

  h->Fit("fitFcn", "NQR", "ep" );// R = range from fitFcn
  return fitFcn->GetParameter(0);
}
예제 #10
0
Double_t fitep0sigma( char* hs, int binlow=-999, int binhigh=999) {

  TH1 *h = (TH1*)gDirectory->Get(hs);
  if( h == NULL ){ cout << hs << " does not exist\n"; return 0; }

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1, x9;
  if(binlow < -900 && binhigh > 900) {
    x1 = h->GetBinCenter(1);
    x9 = h->GetBinCenter(nb);
  }
  else {
    x1 = binlow;
    x9 = binhigh;
  }

  // create a TF1 with the range from x1 to x9 and 5 parameters
  TF1 *ep0Fcn = new TF1( "ep0Fcn", ep0Fit, x1, x9, 5 );

  ep0Fcn->SetParName( 0, "mean" );
  ep0Fcn->SetParName( 1, "sigma" );
  ep0Fcn->SetParName( 2, "pow" );
  ep0Fcn->SetParName( 3, "area" );
  ep0Fcn->SetParName( 4, "BG" );

  // Start values for some parameters:
  ep0Fcn->SetParameter( 0, xmax ); // peak position
  ep0Fcn->SetParameter( 1, 4*dx ); // width
  ep0Fcn->SetParameter( 2, 3.3 ); // pow
  ep0Fcn->SetParameter( 3, nn ); // N
  ep0Fcn->SetParameter( 4, bg );
    
  h->Fit("ep0Fcn", "Q R", "ep" );
  TF1 *fit = h->GetFunction("ep0Fcn");
  return fit->GetParameter(1);
}
예제 #11
0
double fittp0sigma( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){ cout << hs << " does not exist\n"; return 0; }

  double dx = h->GetBinWidth(1);
  double nmax = h->GetBinContent(h->GetMaximumBin());
  double xmax = h->GetBinCenter(h->GetMaximumBin());
  double nn = 7*nmax;

  int nb = h->GetNbinsX();
  double n1 = h->GetBinContent(1);
  double n9 = h->GetBinContent(nb);
  double bg = 0.5*(n1+n9);

  double x1 = h->GetBinCenter(1);
  double x9 = h->GetBinCenter(nb);

  // create a TF1 with the range from x1 to x9 and 5 parameters
  TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 );

  tp0Fcn->SetParName( 0, "mean" );
  tp0Fcn->SetParName( 1, "sigma" );
  tp0Fcn->SetParName( 2, "nu" );
  tp0Fcn->SetParName( 3, "area" );
  tp0Fcn->SetParName( 4, "BG" );
   
  // set start values for some parameters:
  tp0Fcn->SetParameter( 0, xmax ); // peak position
  tp0Fcn->SetParameter( 1, 4*dx ); // width
  tp0Fcn->SetParameter( 2, 2.2 ); // nu
  tp0Fcn->SetParameter( 3, nn ); // N
  tp0Fcn->SetParameter( 4, bg );
    
  h->Fit( "tp0Fcn", "Q R", "ep" );
  // h->Fit("tp0Fcn","V+","ep");
  TF1 *fit = h->GetFunction("tp0Fcn");
  return fit->GetParameter(1);
}
예제 #12
0
void fitmmp(TH1 *hmmp, bool verbose = false) {
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,2,true);
  hmmp->Fit(fbg,options.Data(),"",0.42,2);
  //printf("%s\n",gMinuit->fCstatu.Data());
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,2,false);
    fbg2->SetParameters(fbg->GetParameters());
    //fbg2->Draw("same");
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    //htmp->Draw();
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,2);
    htmp->Fit(fgaus,options.Data(),"",0.74,0.85);
    TF1 *f = f_pol4gaus("f",0.4,2,fbg2,fgaus);
    f->SetNpx(500);
    hmmp->Fit(f,options.Data(),"",0.42,2);
    fgaus->SetRange(0.4,2);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
예제 #13
0
std::vector<double> fitskwpol( char* hs, double xl=-0.1, double xr=0.1) {
  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ) {
    cout << hs << " does not exist\n";
    return std::vector<double>();
  }

  int nb = h->GetNbinsX();
  double x1 = h->GetBinCenter(1); // first
  double x9 = h->GetBinCenter(nb); // last

  if( xl > x1 && xl < x9 ) x1 = xl; // left
  if( xr > x1 && xr < x9 ) x9 = xr; // right

  // create a TF1 with the range from x1 to x9 and 3 parameters
  TF1 *tanhFcn = new TF1( "tanhFcn", fitSkwPol, x1, x9, 4 );
  tanhFcn->SetParName( 0, "dyoff" );
  tanhFcn->SetParName( 1, "dyslp" );
  tanhFcn->SetParName( 2, "dypar" );
  tanhFcn->SetParName( 3, "dyhyp" );

  // set start values:
  tanhFcn->SetParameter( 0, 0 ); // dy off [um]
  tanhFcn->SetParameter( 1, 99 ); // dy slope [um/skw]
  tanhFcn->SetParameter( 2, 0 ); // dy parabola
  tanhFcn->SetParameter( 3, 0 ); // dy hyperbola


  h->Fit( "tanhFcn", "R Q", "p" );// R = range from tanhFcn

  std::vector<double> result;
  for(size_t i = 0; i < 4; i++) {
    result.push_back(tanhFcn->GetParameter(i));
  }
  return result;
}
void fitmmp(TH1 *hmmp, float step_x0 = 2, float step_x1 = 2.1, float wval = 0, bool verbose = false) {
  float fnrangemax = 1.1;
  float mmplow = 0.4;
  //float bgp2 = 2.1e8;
  float gsig = -0.0065+0.013*wval;
  float pol2cutoff = 4; //wval under which to use pol2
  float fitcutoff = 1.1;
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,fnrangemax,true);
  fbg->FixParameter(7,step_x0);
  fbg->FixParameter(8,step_x1);
  if (wval<pol2cutoff) {
    fitcutoff = 1.1;
    fbg->FixParameter(3,0);
    fbg->FixParameter(4,0);
  } else fitcutoff = 2;
  hmmp->Fit(fbg,options.Data(),"",mmplow,fitcutoff);
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,fnrangemax,false);
    fbg2->SetParameters(fbg->GetParameters());
    fbg2->FixParameter(7,step_x0);
    fbg2->FixParameter(8,step_x1);
    if (wval<pol2cutoff) {
      fbg2->FixParameter(3,0);
      fbg2->FixParameter(4,0);
    }
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,fnrangemax);
    fgaus->FixParameter(2,gsig);
    fgaus->FixParameter(1,0.783);
    float gmax = 0.85;
    if (gmax > step_x0) gmax = step_x0;
    htmp->Fit(fgaus,options.Data(),"",0.74,gmax);
    TF1 *f = f_pol4gaus("f",0.4,fnrangemax,fbg2,fgaus);
    f->FixParameter(8,step_x0);
    f->FixParameter(9,step_x1);
    if (wval<pol2cutoff) {
      f->FixParameter(3,0);
      f->FixParameter(4,0);
    }
    f->SetNpx(500);
    f->FixParameter(6,0.783);
    f->FixParameter(7,gsig);
    hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    //f->FixParameter(2,0.9*f->GetParameter(2));
    //hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    fgaus->SetRange(0.4,fnrangemax);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    float ymax = 1.1*hmmp->GetMaximum();
    hmmp->GetYaxis()->SetRangeUser(0,ymax);
    TLine *l1 = new TLine(step_x0,0,step_x0,ymax);
    TLine *l2 = new TLine(step_x1,0,step_x1,ymax);
    l1->SetLineColor(kBlue+1);
    l2->SetLineColor(kBlue+1);
    hmmp->GetListOfFunctions()->Add(l1);
    hmmp->GetListOfFunctions()->Add(l2);
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
예제 #15
0
TH1D *
GetTOFRatio(TFile *file, Int_t num, Int_t den, Int_t cent, Bool_t cutSpectrum = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin_[9] = {
    0.5, 0.5, 0.5, 
    0.45, 0.45, 0.45, 
    0.5, 0.5, 0.5
  };
  Double_t ptMax_[9] = {
    3.0, 3.0, 3.0, 
    3.0, 3.0, 3.0, 
    4.5, 4.5, 4.5
  };

  Double_t ptMin = TMath::Max(ptMin_[num], ptMin_[den]);
  Double_t ptMax = TMath::Min(ptMax_[num], ptMax_[den]);
  
  TH1D *hin = (TH1D *)file->Get(Form("hRatio_cent%d_%s_%s", cent, ratioName[num], ratioName[den]));
  if (!hin) return NULL;


#if 0
  /* get matching systematics */
  TFile *fsys = TFile::Open(Form("MATCHSYS_TOF_%s.root", TOFChargeName[charge]));
  TH1 *hsys = fsys->Get(Form("hErr%sMatch", ITSsaPartName[part]));
  TF1 *ffsys = new TF1("fsys", "[0] + [1] * x + [2] * TMath::Exp(-[3] * x)");
  ffsys->SetParameter(0, 0.02);
  ffsys->FixParameter(1, 0.);
  ffsys->SetParameter(2, 0.5);
  ffsys->SetParameter(3, 10.);
  hsys->Fit(ffsys, "W");
  ffsys->ReleaseParameter(1);
  hsys->Fit(ffsys, "W");
  hsys->Fit(ffsys, "W");
  hsys->Fit(ffsys, "W");
  hsys->Draw();
#endif
			
  TH1D *h = new TH1D(Form("hTOF_cent%d_%s_%s", cent, ratioName[num], ratioName[den]), "TOF", NptBins, ptBin);
  Double_t pt, width, value, error, sys;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin || pt > ptMax)) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    /*** TEMP ADD SYS ***/
    //    sys = ffsys->Eval(pt) * value;
    //    error = TMath::Sqrt(error * error + sys * sys);
    //    h->SetBinContent(ipt + 1, value);
    //    h->SetBinError(ipt + 1, error);

    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
  h->SetTitle("TOF");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(23);
  h->SetMarkerColor(4);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  return h;
}
void EMCDistribution_PeakSample_Fast(bool full_gain = false)
{
  const TString gain = "RAW";

  TString hname = "EMCDistribution_" + gain + TString(full_gain ? "_FullGain" : "") + cuts;

  TH2 *h2 = NULL;
  {
    if (full_gain)
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 100,
                    .05 * 100, 25 * 100, 64, -.5, 63.5);
      QAHistManagerDef::useLogBins(h2->GetXaxis());
    }
    else
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 260,
                    -.2 * 100, 5 * 100, 64, -.5, 63.5);
    }
    T->Draw(
        "TOWER_" + gain + "_CEMC[].get_bineta() + 8* TOWER_" + gain + "_CEMC[].get_binphi():(TOWER_RAW_CEMC[].signal_samples[10] - TOWER_RAW_CEMC[].signal_samples[0])*(-1)>>" + hname, "", "goff");
  }

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts,
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts, 1800, 950);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      if (full_gain)
      {
        p->SetLogx();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(full_gain ? "_FullGain" : "");

      TH1 *h = h2->ProjectionX(hname, ieta + 8 * iphi + 1,
                               ieta + 8 * iphi + 1);  // axis bin number is encoded as ieta+8*iphi+1

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);

      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      h->Draw();

      if (full_gain)
        h->Fit("x*gaus", "M");
      else
        h->Fit("landau", "M");

      double peak = -1;

      TF1 *fit = ((TF1 *) (h->GetListOfFunctions()->At(0)));
      if (fit)
      {
        fit->SetLineColor(kRed);
        peak = fit->GetParameter(1);
      }

      cout << Form("Finished <Col%d Row%d> = %.1f", ieta, iphi, peak)
           << endl;

      TText *t = new TText(.9, .9,
                           Form("<Col%d Row%d> = %.1f", ieta, iphi, peak));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
void EMCDistribution_SUM_RawADC(TString sTOWER = "Energy_Sum_col1_row2_5x5",
                                TString CherenkovSignal = "C2_Inner")
{
  TH1 *EnergySum_LG_full = new TH1F("EnergySum_LG_full",
                                    ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  TH1 *EnergySum_LG = new TH1F("EnergySum_LG",
                               ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  //  TH1 * EnergySum_HG = new TH1F("EnergySum_HG",
  //      ";Low range Tower Energy Sum (ADC);Count / bin", 50, 0, 500);

  TH1 *C2_Inner_full = new TH1F("C2_Inner_full",
                                CherenkovSignal + ";Cherenkov Signal (ADC);Count / bin", 1000, 0, 2000);
  TH1 *C2_Inner = new TH1F("C2_Inner",
                           CherenkovSignal + ";Cherenkov Inner Signal (ADC);Count / bin", 1000, 0, 2000);

  EnergySum_LG_full->SetLineColor(kBlue + 3);
  EnergySum_LG_full->SetLineWidth(2);

  EnergySum_LG->SetLineColor(kGreen + 3);
  EnergySum_LG->SetLineWidth(3);
  EnergySum_LG->SetMarkerColor(kGreen + 3);

  C2_Inner_full->SetLineColor(kBlue + 3);
  C2_Inner_full->SetLineWidth(2);

  C2_Inner->SetLineColor(kGreen + 3);
  C2_Inner->SetLineWidth(3);
  C2_Inner->SetMarkerColor(kGreen + 3);

  TCut c2 = CherenkovSignal + ">240";

  T->Draw(sTOWER + ">>EnergySum_LG_full", "", "goff");
  T->Draw(sTOWER + ">>EnergySum_LG", c2, "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner_full", "", "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner", c2, "goff");

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts,
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts, 1800,
      600);
  c1->Divide(3, 1);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  C2_Inner_full->DrawClone();
  C2_Inner->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  (TH1 *) EnergySum_LG->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h_full = (TH1 *) EnergySum_LG_full->DrawClone();
  TH1 *h = (TH1 *) EnergySum_LG->DrawClone("same");

  TF1 *fgaus_g = new TF1("fgaus_LG_g", "gaus", h->GetMean() - 1 * h->GetRMS(),
                         h->GetMean() + 4 * h->GetRMS());
  fgaus_g->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
                         h->GetMean() + 2 * h->GetRMS());
  h->Fit(fgaus_g, "MR0N");

  TF1 *fgaus = new TF1("fgaus_LG", "gaus",
                       fgaus_g->GetParameter(1) - 1 * fgaus_g->GetParameter(2),
                       fgaus_g->GetParameter(1) + 4 * fgaus_g->GetParameter(2));
  fgaus->SetParameters(fgaus_g->GetParameter(0), fgaus_g->GetParameter(1),
                       fgaus_g->GetParameter(2));
  h->Fit(fgaus, "MR");

  h->Sumw2();
  h_full->Sumw2();
  h_full->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
                                   h->GetMean() + 4 * h->GetRMS());

  h->SetLineWidth(2);
  h->SetMarkerStyle(kFullCircle);

  h_full->SetTitle(
      Form("#DeltaE/<E> = %.1f%%",
           100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //  h->SetLineWidth(2);
  //  h->SetLineColor(kBlue + 3);
  ////  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  //
  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  ////  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //
  //  TF1 * fgaus = new TF1("fgaus_HG", "gaus", 0, 100);
  //  fgaus->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
  //      h->GetMean() + 2 * h->GetRMS());
  //  h->Fit(fgaus, "M");
  //
  //  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
  //      h->GetMean() + 4 * h->GetRMS());
  //
  //  h->SetLineWidth(2);
  //  h->SetMarkerStyle(kFullCircle);
  //
  //  h->SetTitle(
  //      Form("#DeltaE/<E> = %.1f%%",
  //          100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
예제 #18
0
TObjArray* ProcessSummary(TObjArray* arrs, int icl, const char* pref)
{
  // Process TObjArray (e.g. for set of pt bins) of TObjArray of KMCTrackSummary objects:
  // pick the KMCTrackSummary for "summary class" icl (definition of acceptable track) and create
  // graphs vs bin.
  // These graphs are returned in new TObjArray
  //
  TString prefs = pref;
  if (!gs) gs = new TF1("gs","gaus",-1,1);
  //
  int nb = arrs->GetEntriesFast();
  TObjArray* sums = (TObjArray*) arrs->At(0);
  int nclass = sums->GetEntriesFast();
  if (icl>=nclass) {printf("summary set has %d classes only, %d requested\n",nclass,icl);return 0;}
  //
  KMCTrackSummary* sm = (KMCTrackSummary*)sums->At(icl);
  //
  TH1* h;
  //
  h = sm->GetHMCSigDCARPhi();  // MC resolution in transverse DCA 
  TGraphErrors * grSigD = 0;
  if (h) {
    grSigD = new TGraphErrors(nb);
    grSigD->SetName(Form("%s%s",prefs.Data(),h->GetName()));
    grSigD->SetTitle(Form("%s%s",prefs.Data(),h->GetTitle()));
  }
  //
  TGraphErrors * grSigZ = 0;
  h = sm->GetHMCSigDCAZ();    // MC resolution in Z DCA
  if (h) {
    grSigZ = new TGraphErrors(nb);
    grSigZ->SetName(Form("%s%s",prefs.Data(),h->GetName()));
    grSigZ->SetTitle(Form("%s%s",prefs.Data(),h->GetTitle()));
  }
  //
  TGraphErrors * grSigAD = 0; // anaitical estimate for resolution in transverse DCA 
  {
    grSigAD = new TGraphErrors(nb);
    grSigAD->SetName(Form("%s%s",prefs.Data(),"sigmaDan"));
    grSigAD->SetTitle(Form("%s%s",prefs.Data(),"#sigmaD an"));
  }
  //
  TGraphErrors * grSigAZ = 0; // anaitical estimate for resolution in Z DCA 
  {
    grSigAZ = new TGraphErrors(nb);
    grSigAZ->SetName(Form("%s%s",prefs.Data(),"sigmaZan"));
    grSigAZ->SetTitle(Form("%s%s",prefs.Data(),"#sigmaZ an"));
  }
  //
  //
  TGraphErrors * grSigPt = 0; // MC res. in pt
  {
    grSigPt = new TGraphErrors(nb);
    grSigPt->SetName(Form("%s%s",prefs.Data(),"sigmaPt"));
    grSigPt->SetTitle(Form("%s%s",prefs.Data(),"#sigmaPt"));
  }
  //
  TGraphErrors * grSigAPt = 0; // analitycal res. in pt
  {
    grSigAPt = new TGraphErrors(nb);
    grSigAPt->SetName(Form("%s%s",prefs.Data(),"sigmaPtan"));
    grSigAPt->SetTitle(Form("%s%s",prefs.Data(),"#sigmaPt an"));
  }

  //
  TGraphErrors * grEff = 0; // MC efficiency
  {
    grEff = new TGraphErrors(nb);
    grEff->SetName(Form("%s_rate",prefs.Data()));
    grEff->SetTitle(Form("%s Rate",prefs.Data()));
  }
  //
  TGraphErrors * grUpd = 0; // number of Kalman track updates
  {
    grUpd = new TGraphErrors(nb);
    grUpd->SetName(Form("%s_updCalls",prefs.Data()));
    grUpd->SetTitle(Form("%s Updates",prefs.Data()));
  }
  //
  for (int ib=0;ib<nb;ib++) {
    sums = (TObjArray*) arrs->At(ib);
    sm = (KMCTrackSummary*)sums->At(icl);
    KMCProbe& prbRef = sm->GetRefProbe();
    KMCProbe& prbAn  = sm->GetAnProbe();
  
    double pt = prbRef.Pt();
    //
    if (grSigAD) {
      grSigAD->SetPoint(ib, pt,prbAn.GetSigmaY2()>0 ? TMath::Sqrt(prbAn.GetSigmaY2()) : 0.);
    }
    //
    if (grSigAZ) {
      grSigAZ->SetPoint(ib, pt,prbAn.GetSigmaZ2()>0 ? TMath::Sqrt(prbAn.GetSigmaZ2()) : 0.);
    }
    //
    if (grSigAPt) {
      double pts = TMath::Sqrt(prbAn.GetSigma1Pt2());
      grSigAPt->SetPoint(ib, pt,pts>0 ? pts*pt : 0.);
    }
    //
    if (grSigPt) {
      h = sm->GetHMCSigPt();
      h->Fit(gs,"0q");
      grSigPt->SetPoint(ib, pt, gs->GetParameter(2));
      grSigPt->SetPointError(ib, 0, gs->GetParError(2));
    }
    //
     if (grSigD) {
      h = sm->GetHMCSigDCARPhi();
      h->Fit(gs,"0q");
      grSigD->SetPoint(ib, pt,gs->GetParameter(2));
      grSigD->SetPointError(ib, 0,gs->GetParError(2));      
    }
    //
    if (grSigZ) {
      h = sm->GetHMCSigDCAZ();
      h->Fit(gs,"0q");
      grSigZ->SetPoint(ib, pt,gs->GetParameter(2));
      grSigZ->SetPointError(ib, 0,gs->GetParError(2));      
    }
    //
    if (grEff) {
      grEff->SetPoint(ib, pt,sm->GetEff());
      grEff->SetPointError(ib, 0,sm->GetEffErr());
    }
    //
    if (grUpd) {
      grUpd->SetPoint(ib, pt,sm->GetUpdCalls());
      grUpd->SetPointError(ib, 0, 0);
    }
  }
  //
  TObjArray* dest = new TObjArray();
  dest->AddAtAndExpand(grSigAD,kSigAD);
  dest->AddAtAndExpand(grSigAZ,kSigAZ);  
  dest->AddAtAndExpand(grSigAPt,kSigAPt);  
  dest->AddAtAndExpand(grSigD,kSigD);
  dest->AddAtAndExpand(grSigZ,kSigZ);  
  dest->AddAtAndExpand(grSigPt,kSigPt);  
  dest->AddAtAndExpand(grEff,kEff);
  dest->AddAtAndExpand(grUpd,kUpd);
  //
  if (!prefs.IsNull()) dest->SetName(pref);
  return dest;
}
예제 #19
0
void CalibrateData(Int_t nevt,Int_t startEv = 1, char *PedFile = "drs4_20100311_t_ped.root") {

	// create progress bar
	TGHProgressBar *gProgress = ProgressBar("Calibrazione dati");

	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// create list of histograms for pedestals
	TList *grPedList = new TList();
	TGraphErrors *grPed;

	// create list of histograms for channels
	TList *hCellCalibList = new TList();
	TH1F *hCellCalib;

	TList *grCellCalibList = new TList();
	TGraphErrors *grCellCalib;

	int mV[NCALIBFILES] = {-500,-400,-300,-200,-100,0,100,200,300,400,500};

	/*for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		mV[iFile] = mVStart;
		mVStart += mVStep;
	}*/

	char *calibrationFile;
	char *calibrationFileArray[NCALIBFILES];
	calibrationFileArray[0] = "drs4_1000ev_dcm500mv.dat";
	calibrationFileArray[1] = "drs4_1000ev_dcm400mv.dat";
	calibrationFileArray[2] = "drs4_1000ev_dcm300mv.dat";
	calibrationFileArray[3] = "drs4_1000ev_dcm200mv.dat";
	calibrationFileArray[4] = "drs4_1000ev_dcm100mv.dat";
	calibrationFileArray[5] = "drs4_1000ev_dc1mv.dat";
	calibrationFileArray[6] = "drs4_1000ev_dc100mv.dat";
	calibrationFileArray[7] = "drs4_1000ev_dc200mv.dat";
	calibrationFileArray[8] = "drs4_1000ev_dc300mv.dat";
	calibrationFileArray[9] = "drs4_1000ev_dc400mv.dat";
	calibrationFileArray[10] = "drs4_1000ev_dc500mv.dat";

	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			//
			TString title = "Calibration signal file:";
			title += iFile;
			title += " ch:";
			title += ch;
			hCellCalib = new TH1F(title,title, DominoDepthADC, -DominoDepthADC, DominoDepthADC);
			hCellCalibList->Add(hCellCalib);
		}
	}


	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = new TGraphErrors(NCALIBFILES);
		grCellCalibList->Add(grCellCalib);
	}


	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);
	grPedData = (TGraphErrors *) grPedList->At(anaChannel);
	grPedTrig = (TGraphErrors *) grPedList->At(trigChannel);

	// create gauss function
	TF1 *fgauss = new TF1("fgauss", "TMath::Gaus(x,[0],[1],0)", -DOMINO_NCELL, DOMINO_NCELL);
	fgauss->SetParameter(0,0.);
	fgauss->SetParameter(1,1.);
	fgauss->SetParLimits(0, 0., DominoDepthADC);
	fgauss->SetParLimits(1, 0.1, 20.);

	TCanvas *ctest = new TCanvas("ChannelTest", "ChannelTest", 800, 600);
	ctest->Divide(3, 4);

	gProgress->Reset();
	gProgress->SetMax(nevt*NCALIBFILES);

	gSystem->ProcessEvents();


	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {

		// open file

		calibrationFile = calibrationFileArray[iFile];
		FILE *fdata = OpenDataFile(calibrationFile);
		struct channel_struct *p;
		struct channel_struct *dep;

		Double_t refval=0, reftmp = 0;
		Double_t PedVal, itmp;

		// Count number of events in data file
		int nevtDataMax = 0;
		while (!feof(fdata)) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			nevtDataMax++;
		}
		printf("nevtDataMax: %d\n", nevtDataMax);

		if (nevt > (nevtDataMax - startEv) || nevt == 0)
			nevt = nevtDataMax - startEv;
		cout << endl << "==>> Processing " << nevt << " events from file "
				<< calibrationFile << endl;

		rewind(fdata);

		for (int j = 0; j < 1; j++) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			p += anaChannel;
			for (ch = 0; ch < DOMINO_NCELL; ch++) {
				grPedData->GetPoint(ch, itmp, PedVal);
				reftmp = TMath::Abs((Double_t)(p->data[ch])-PedVal);
				if (reftmp > 0.8* refval)
					refval = 0.2*reftmp+0.8*refval;
				//					cout << ch << " " <<p->data[ch] << " " <<reftmp << " " << refval <<endl ;
			}
		}
		cout << "refval="<< refval<<endl;
		rewind(fdata);

		Int_t ievt = 1;
		// go to first event (startEv)
		while (ievt < startEv) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				break;
			ievt++;
		}

		ievt = 1;
		Int_t iTrig = 0;
		Int_t flagEnd = 0;
		Double_t chtmp, chtrig;
		Double_t ratio;
		Double_t mean, rms;

		// loop on events

		while (ievt <= nevt && !flagEnd) {

			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				flagEnd = 1;

			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

			//now anaChannel analysis

			p += anaChannel;

			// read data, subtract pedestals values and fill hCellCalibList.

			for (int ch = 0; ch < DOMINO_NCELL; ch++) {
				// Read pedestal value for this cell
				grPedData->GetPoint(ch, itmp, PedVal);
				chtmp = (Double_t)(p->data[ch]); // data value
				chtmp = chtmp - PedVal;
				//if (TMath::Abs(chtmp) > 0.9 * refval)
				((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch))->Fill(chtmp);
				//cout << ch << " " << iFile << " " << chtmp << endl;
			}

			gProgress->Increment(1);
			gSystem->DispatchOneEvent(kTRUE);
			ievt++; // next event
		}


		TH1 *hCellTmp;
		for(ch = 0; ch < DOMINO_NCELL;ch++) {
			hCellTmp = ((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch));
			//hCellTmp->Fit("gaus", "Q");
			//mean = (hCellTmp->GetFunction("gaus"))->GetParameter(1);
			//rms = (hCellTmp->GetFunction("gaus"))->GetParameter(2);
			mean = hCellTmp->GetMean();
			rms = hCellTmp->GetRMS();
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPoint(iFile, (Double_t) mV[iFile], mean);
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPointError(iFile, 0., rms);
		}


		ctest->cd(iFile + 1);
		hCellTmp = ((TH1 *) hCellCalibList->At(567 + iFile*DOMINO_NCELL));
		hCellTmp->Fit("gaus","Q");
		hCellTmp->DrawCopy();
	}

	TString OutFile = "CalibrationDataNew";
	OutFile += nevt;
	OutFile += "events.root";
	TFile *f = new TFile(OutFile, "RECREATE");
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		TString key = "CalibDataCell";
		key += ch;
		((TGraphErrors*) grCellCalibList->At(ch))->Write(key);
	}
	f->Close();

	hCellCalibList->Delete();

	((TGMainFrame *) gProgress->GetParent())->CloseWindow();
	fclose(fdata);
}
예제 #20
0
파일: Sparse_MC.C 프로젝트: musinsky/bordel
void AnalysisSparse(Bool_t save_output = kFALSE)
{
  gStyle->SetGridColor(kGray);
  //  TString tmpstr(fname);
  //  if (tmpstr.Contains("data")) {
  //    Printf("!!! Real Data !!!");
  //    mc = kFALSE;
  //  }
  TString gtitle = Form("Monte Carlo, %s", graph_name.Data());
  grapht = graph_name.Data();
  Double_t grx[999], gry[999], gry2[999], gry3[999], gry4[999],
    gry_eff[999], gry_fix[999], grxE[999];
  Double_t gry22[999], gry22E[999], grx22E[999];
  Double_t gry_true[999], gry_true_eff[999], gry_true_effE[999];
  TH1::AddDirectory(kFALSE);
  TFile::SetCacheFileDir(gSystem->HomeDirectory());
  TFile *f = TFile::Open(fname.Data(), "CACHEREAD");
  if (!f) return;
  TList *l; f->GetObject(lname.Data(), l);
  if (!l) return;
  Int_t bf[999], bl[999];
  Int_t nn = FindExactRange(((THnSparse *)(l->FindObject(s1name.Data())))->
                            Projection(1), del_step, bf, bl);
  //  Int_t nn = FindRange5(bf, bl);
  Bool_t binhaluska = kFALSE;
  if (binAnders) {
    nn = 8;
    bf[0] = 6;bf[1] =  9;bf[2] = 11;bf[3] = 16;bf[4] = 21;bf[5] = 26;
    bl[0] = 8;bl[1] = 10;bl[2] = 15;bl[3] = 20;bl[4] = 25;bl[5] = 30;

    bf[6] = 31;bf[7] = 41;
    bl[6] = 40;bl[7] = 50;
  }
  Printf("number of intervals = %d =>", nn);

  Int_t count = 0;
  Double_t ptmean = 0, value = 0;
  Int_t fitStatus = -1;
  gStyle->SetOptStat(0);
  TCanvas *c = new TCanvas("c", "Signal & Background");
  c->Divide(5, 5); c->Modified(); c->Draw();
  TCanvas *c2 = (TCanvas *)c->DrawClone("c2");
  c2->SetTitle("Phi mesons (raw)"); c2->Modified(); c2->Draw();
  TCanvas *c3, *c4;
  if (mc) {
    c3 = (TCanvas *)c->DrawClone("c3");
    c3->SetTitle("Phi mesons (gen)"); c3->Modified(); c3->Draw();
    c4 = (TCanvas *)c->DrawClone("c4");
    c4->SetTitle("Phi mesons (true)"); c4->Modified(); c4->Draw();
  }

  for (Int_t i = 0; i < nn; i++) {
    c->cd(count + 1)->SetGrid();
    h1 = (TH1D *)PullHisto(l, s1name.Data(), bf[i], bl[i], ptmean);
    h1->SetLineColor(kRed);
    h1->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
    h1->Draw("hist");

    h3_p = (TH1D *)PullHisto(l, s3name_p.Data(), bf[i], bl[i], ptmean);
    h3_m = (TH1D *)PullHisto(l, s3name_m.Data(), bf[i], bl[i], ptmean);
    // !!!!!!!!!!!!!!!!!!!!!!!!
    if (count==0) h3_p = h1;
    // !!!!!!!!!!!!!!!!!!!!!!!!
    else {
      h3_p->Add(h3_m);
      //      h3_p->Add((TH1D *)PullHisto(l, smix.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixpp.Data(), bf[i], bl[i], ptmean));
      //      h3_p->Add((TH1D *)PullHisto(l, smixmm.Data(), bf[i], bl[i], ptmean));
      Norm(h1, h3_p, norm[0], norm[1]);
    }
    h3_p->SetLineColor(kBlue);
    h3_p->Draw("hist, same");

    if (mc) {
      c3->cd(count + 1)->SetGrid();
      Printf("%s", s1namegen.Data());
      hg = (TH1D *)PullHisto(l, s1namegen.Data(), bf[i], bl[i], ptmean);
      hg->SetLineColor(kMagenta);
      hg->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      hg->Draw("hist");
      c4->cd(count + 1)->SetGrid();
      ht = (TH1D *)PullHisto(l, s1nametrue.Data(), bf[i], bl[i], ptmean);
      ht->SetLineColor(kMagenta-5);
      ht->GetXaxis()->SetTitle("inv. mass, GeV/c^2");
      ht->Draw("hist");
    }
    c2->cd(count + 1)->SetGrid();
    TH1 *hh = (TH1 *)h1->Clone("hh");
    hh->SetLineColor(kRed+1);
    hh->Add(h3_p, -1);
    /// !!!!!!!!!!!!!!!!!!!!!!
    //////////    if ((ilist == 3) && (count < 2)) hh->Reset();
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    hh->Draw("hist");

    // !!!!!!!!!!!!!!!!!!
    ff->SetParameters(0.1, 1.02, 0.004, -25000., 0., 0., 0.);
    ff->SetLineColor(hh->GetLineColor());
    ff->SetLineWidth(1);
    //    ff->SetLineStyle(kDashed);
    // where fit
    Double_t fmin = 1.02-2*0.004;
    Double_t fmax = 1.02+2*0.004;
    //    Double_t fmin = 0.995;
    //    Double_t fmax = 1.185;
    // !!!!!!!!!!!!!!!!!!
    Bool_t hisfun = kFALSE; // kFALSE = integral from function
    Double_t   hisfun_k = 1.0/hh->GetBinWidth(10);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    if (binhaluska)
      if (i > 9) hisfun_k = 0.5/hh->GetBinWidth(10);
    Printf("======= %f", hisfun_k);
    // !!!!!!!!!!!!!!!!!!
    // wehere integral (his or fun)
    Double_t fmini = 1.02-2*0.004;
    Double_t fmaxi = 1.02+2*0.004;
    hh->Fit(ff, "Q", "", fmin, fmax);
    hh->Fit(ff, "Q", "", fmin, fmax);
    fitStatus = hh->Fit(ff, "Q", "", fmin, fmax);
    TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
    pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
                       ff->GetParameter(5), ff->GetParameter(6));
    pp3->SetLineWidth(1);
    pp3->SetLineColor(h3_p->GetLineColor());
    pp3->Draw("same");
    // ff->SetRange(fmin, fmax);
    // ff->DrawCopy("same");

    value              = hh->Integral(hh->FindBin(fmini), hh->FindBin(fmaxi));
    if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k -
                   pp3->Integral(fmini, fmaxi)*hisfun_k;
    if (value < 0) value = 0;

    if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
      printf(" SKIP Data");
      value = 0;
    }
    grx[count] = ptmean;
    if (binhaluska) {
      if (count < 10) grxE[count] = 0.25; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      else            grxE[count] = 0.50; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }
    else
      //      grxE[count] = (1.30-1.10)/2.0; // !!!!!!!!!!!!!!!!!!!!!!!!!!
      grxE[count] = 0.05;
    gry[count] = value;

    Double_t tmp1 = h1->Integral(h1->FindBin(fmini), h1->FindBin(fmaxi));
    Double_t tmp2 = h3_p->Integral(h3_p->FindBin(fmini), h3_p->FindBin(fmaxi));
    Double_t tmp_sg = tmp1 - tmp2;
    Double_t tmp_bg = tmp2;

    // if ((tmp_sg <= -tmp_bg) || (tmp_bg < 33.0)) {
    //   gry3[count] = 0.0;
    //   gry4[count] = 0.0;
    // }
    // else {
    gry3[count] = tmp_sg/tmp_bg;
    gry4[count] = tmp_sg/TMath::Sqrt(tmp_sg + tmp_bg);
    // }

    //    Printf("%4.2f, %10f, %10f, %10f", ptmean, tmp1, tmp2, gry3[count]);


    if (mc) {
      c3->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      hg->Fit(ff, "Q", "", fmin, fmax);
      hg->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = hg->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = hg->Integral(hg->FindBin(fmini), hg->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP MC");
        value = -1;
      }
      gry2[count]    = value;
      Double_t superfactor = CalculateFactor(l, 0.1);
      if (useCF) {
        gry22E[i] = TMath::Sqrt(gry2[i])*superfactor;
        //        gry22E[i] = 0.0001;
        gry22[i]  = gry2[i]*superfactor;
        grx22E[i] = 0.05;
      }
      gry_eff[count] = gry[count]/gry2[count];

      c4->cd(count + 1);
      // !!!!!!!!!!!!!!!!
      ff->SetParameters(1, 1.02, 0.004, 0., 0., 0., 0.);
      ht->Fit(ff, "Q", "", fmin, fmax);
      ht->Fit(ff, "Q", "", fmin, fmax);
      fitStatus = ht->Fit(ff, "Q", "", fmin, fmax);
      /*      TF1 *pp3 = new TF1("pp3", "[0]+x*[1]+x*x*[2]+x*x*x*[3]", fmin, fmax);
              pp3->SetParameters(ff->GetParameter(3), ff->GetParameter(4),
              ff->GetParameter(5), ff->GetParameter(6));
              pp3->SetLineWidth(1);
              pp3->SetLineColor(h3_p->GetLineColor());
              pp3->Draw("same");
      */

      value              = ht->Integral(ht->FindBin(fmini), ht->FindBin(fmaxi));
      if (!hisfun) value = ff->Integral(fmini, fmaxi)*hisfun_k;
      //!!!!!!!!!!!!!!!!!!!pp3->Integral(fmini, fmaxi)*hisfun_k;
      if (value <= 0) value = -1;

      if ((fitStatus != 0) || (ff->GetParameter(2) > 0.1)) {
        printf(" SKIP true");
        value = -1;
      }
      gry_true[count]     = value;
      gry_true_eff[count] = gry_true[count]/gry2[count];
      // Propagation of uncertainty (A/B)
      Double_t AAA  = gry_true[count];
      Double_t AAAE = TMath::Sqrt(AAA);
      Double_t BBB  = gry2[count];
      Double_t BBBE = TMath::Sqrt(BBB);
      Double_t EEE  = TMath::Sqrt((AAAE/AAA)*(AAAE/AAA)+(BBBE/BBB)*(BBBE/BBB));
      EEE = EEE*gry_true_eff[count];
      gry_true_effE[count] = EEE;
    }

    Printf("=> %6.4f", ptmean);
    count++;
  }

  new TCanvas();
  TGraph *gr = new TGraph(count, grx, gry);
  gr->SetMarkerStyle(8);
  gr->SetMarkerColor(hh->GetLineColor());
  gr->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr->SetTitle(Form("raw phi, %s", gtitle.Data()));
  gr->Draw("AP");

  cc3 = new TCanvas();
  TGraph *gr3 = new TGraph(count, grx, gry3);
  gr3->SetMarkerStyle(22);
  gr3->SetMarkerColor(kBlue+1);
  gr3->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr3->SetTitle(Form("SIG / BKG, %s", gtitle.Data()));
  gr3->SetMinimum(0);
  gr3->Draw("AP");

  cc4 = new TCanvas();
  TGraph *gr4 = new TGraph(count, grx, gry4);
  gr4->SetMarkerStyle(23);
  gr4->SetMarkerColor(kBlue-1);
  gr4->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr4->SetTitle(Form("Significance, %s", gtitle.Data()));
  gr4->SetMinimum(0);
  gr4->Draw("AP");

  ccc = new TCanvas("ccc","ccc",0,0,900,300);
  ccc->Divide(2, 1, 0.001, 0.001);
  ccc->cd(1); gr3->Draw("AP");
  ccc->cd(2); gr4->Draw("AP");

  TString blabla = "mc";
  if (!mc) blabla = "data";
  // gr3->SaveAs(Form("SB_%s_%s.C", blabla.Data(), grapht.Data()));
  // gr4->SaveAs(Form("Sig_%s_%s.C", blabla.Data(), grapht.Data()));
  // ccc->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  // c->SaveAs(Form("%s_%s_0.eps", blabla.Data(), grapht.Data()));
  // c2->SaveAs(Form("%s_%s_1.eps", blabla.Data(), grapht.Data()));

  //  cc3->SaveAs(Form("%s_%s_2.eps", blabla.Data(), grapht.Data()));
  //  gr3->SaveAs(Form("sig_bck_%s_%s.C", blabla.Data(), grapht.Data()));

  if (mc) {
    new TCanvas();
    TGraph *gr2 = new TGraph(count, grx, gry2);
    gr2->SetMarkerStyle(8);
    gr2->SetMarkerColor(hg->GetLineColor());
    gr2->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr2->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr2->Draw("AP");

    new TCanvas();
    TGraphErrors *gr22 = new TGraphErrors(count, grx, gry22, grx22E, gry22E);
    gr22->SetMarkerStyle(8);
    gr22->SetMarkerColor(kCyan);
    gr22->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr22->SetTitle(Form("gen phi, %s", gtitle.Data()));
    gr22->Draw("AP");


    c = new TCanvas();
    c->SetGrid();
    TGraph *gr_e = new TGraph(count, grx, gry_eff);
    gr_e->SetMarkerStyle(22);
    gr_e->SetMarkerColor(kBlack);
    gr_e->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_e->SetTitle(Form("efficiency (raw), %s", grapht.Data()));
    gr_e->Draw("AP");
    Printf("Save as '\033[1meffi_raw_%s\033[0m' file", grapht.Data());
    for (Int_t i = 0; i < gr_e->GetN(); i++)
      Printf("%f %f", gr_e->GetX()[i], gr_e->GetY()[i]);

    cvb = new TCanvas();
    cvb->cd();
    TGraph *gr_true = new TGraph(count, grx, gry_true);
    gr_true->SetMarkerStyle(8);
    gr_true->SetMarkerColor(ht->GetLineColor());
    gr_true->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true->SetTitle(Form("true phi, %s", gtitle.Data()));
    gr_true->Draw("AP");
    c = new TCanvas();
    c->cd();
    c->SetGrid();
    TGraphErrors *gr_true_eff = new TGraphErrors(count, grx, gry_true_eff,
                                                 grxE, gry_true_effE);
    gr_true_eff->SetMarkerStyle(20);
    //    gr_true_eff->SetMarkerSize(0.75);
    gr_true_eff->SetMarkerColor(kBlack);
    gr_true_eff->GetXaxis()->SetTitle("p_{t}, GeV/c");
    gr_true_eff->SetTitle(Form("efficiency (true), %s", grapht.Data()));
    gr_true_eff->Draw("AEP");
    m_gr->Add(gr_true_eff);
    Printf("Save as '\033[1meffi_true_%s\033[0m' file", grapht.Data());
    TString tout;
    Double_t oux, ouy, ouxe, ouye;
    for (Int_t i = 0; i < gr_true_eff->GetN(); i++) {
      oux = gr_true_eff->GetX()[i];
      ouy = gr_true_eff->GetY()[i];
      ouy = MinusCheck(ouy);
      ouxe = gr_true_eff->GetErrorX(i);
      ouye = gr_true_eff->GetErrorY(i);
      ouye = NanCheck(ouye);
      Printf("%f %f %f %f", gr_true_eff->GetX()[i], gr_true_eff->GetY()[i],
             gr_true_eff->GetErrorX(i), gr_true_eff->GetErrorY(i));
      if (!save_output) continue;
      gSystem->mkdir(dir_prefix.Data());
      tout = Form("%f %f %f %f", oux, ouy, ouxe, ouye);
      if (i == 0)
        tout = Form("Printf(\"%s\"); > %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      else
        tout = Form("Printf(\"%s\"); >> %s/effi_%s", tout.Data(),
                    dir_prefix.Data(), grapht.Data());
      //      Printf(":::::: %s", tout.Data());
      gROOT->ProcessLine(tout.Data());
    }
    // ------------------
    c = new TCanvas("cfinal", "mc_effi", 1200, 450);
    c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
    c->cd(1);
    gr_true->SetMinimum(0);
    gr_true->SetTitle(Form("phi (true & raw), %s", gtitle.Data()));
    gr_true->SetMarkerColor(kGreen+1);
    gr_true->Draw("AP");
    gr->SetMarkerColor(kRed+1);
    gr->Draw("P");
    c->cd(2)->SetGrid();
    gr_true_eff->SetMinimum(0);
    gr_true_eff->SetTitle(Form("efficiency, %s", grapht.Data()));
    gr_true_eff->SetMarkerColor(kGreen+1);
    gr_true_eff->Draw("AP");
    gr_e->SetMarkerColor(kRed+1);
    gr_e->Draw("P");
    //    c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
    return;
  }

  //  TGraph *geff = new TGraph(Form("effi_raw_%s", grapht.Data()));
  //  TGraph *geff = new TGraph(Form("effi_true_%s", grapht.Data()));
  //  TGraph *geff = new TGraph("effi_true_Phi2010_qualityonly");
  TGraph *geff = new TGraph("effi_true_PhiNsigma_qualityonly");
  if (geff->IsZombie()) return;
  geff->SetMarkerStyle(22);
  geff->SetMarkerColor(kBlack);
  geff->GetXaxis()->SetTitle("p_{t}, GeV/c");
  geff->SetTitle(Form("efficiency, %s", grapht.Data()));
  c = new TCanvas();
  c->SetGrid();
  geff->Draw("AP");
  Double_t tpcsigma = 9999.9;
  if (ilist == 1) tpcsigma = 1.0;
  if (ilist == 2) tpcsigma = 1.5;
  if (ilist == 3) tpcsigma = 2.0;
  if (ilist == 4) tpcsigma = 2.5;
  if (ilist == 5) tpcsigma = 3.0;
  Double_t sss = TMath::Erf(tpcsigma/TMath::Sqrt(2.0));
  if (noSigma) sss = 1.0;
  Printf("sigma = %10f", sss);

  // for (Int_t i = 0; i < count; i++)
  //   geff->GetY()[i] = (sss*sss)/(geff->GetY()[i]);
  // geff->SetMaximum(1.0);
  // geff->Draw("AP");

  for (Int_t i = 0; i < count; i++) {
    Double_t deno = geff->Eval(grx[i])*sss*sss;
    if (deno < 0.00001) deno = 1;
    gry_fix[i] = gry[i]/deno;
  }
  new TCanvas;
  TGraph *gr_fix = new TGraph(count, grx, gry_fix);
  gr_fix->SetMarkerStyle(21);
  gr_fix->SetMarkerColor(hh->GetLineColor());
  gr_fix->GetXaxis()->SetTitle("p_{t}, GeV/c");
  gr_fix->SetTitle(Form("corrected phi * #sigma^{2}, %s", gtitle.Data()));
  if (noSigma)
    gr_fix->SetTitle(Form("corrected phi (no #sigma), %s", gtitle.Data()));
  gr_fix->Draw("AP");

  //---------------------
  c = new TCanvas("cfinald", "data_correct", 1200, 450);
  c->Divide(2, 1, 0.001, 0.001); c->Modified(); c->Draw();
  c->cd(1);
  gr->SetMinimum(0);
  gr->SetMarkerColor(kBlack);
  gr->Draw("AP");
  c->cd(2);
  gr_fix->SetMinimum(0);
  gr_fix->SetMarkerColor(kGreen+3);
  gr_fix->Draw("AP");
  TString bla9 = Form("qualityonly_PID2_%s", grapht.Data());
  if (noSigma) bla9 = Form("%s_noSig.C", bla9.Data());
  else         bla9 = Form("%s.C", bla9.Data());
  //  gr_fix->SaveAs(bla9.Data());
  //  TPad *cp = new TPad("cpf", "", 0.45,0.45,0.99,0.92);
  TPad *cp = new TPad("cpf", "", 0.60,0.55,0.99,0.93);
  cp->SetLogy(); cp->Draw(); cp->cd();
  TGraph *cloneg = ((TGraph *)gr_fix->Clone());
  cloneg->SetTitle(); cloneg->SetMarkerSize(0.8);
  cloneg->Draw("AP");
  //  c->SaveAs(Form("%s_%s.eps", blabla.Data(), grapht.Data()));
  f->Close();
}
예제 #21
0
void FitOmegaPeak(const bool fixOmegaMass=false, const double r_min=650.0, const double r_max=900.0) {

	const char*  hist_name = "ggg_IM";
	const int    npx   = 500;
	const double omega_mass     = 782.0;
	const double expected_width =  15.0;


	TH1* h = NULL;
	gDirectory->GetObject(hist_name, h);

	if(!h) {
		cerr << "Can't find histogram" << endl;
		return;
	}



	TF1* sig = new TF1("sig", "gaus", r_min, r_max);
	sig->SetLineColor(kGreen);
	sig->SetNpx(npx);

	// height
	sig->SetParameter(0, 0.5 * h->GetMaximum());

	// position
	if(fixOmegaMass)
		sig->FixParameter(1, omega_mass);
	else
		sig->SetParameter(1, omega_mass);

	// width
	sig->SetParameter(2, expected_width);



	TF1* bg = new TF1("bg", "pol2", r_min, r_max);
	bg->SetLineColor(kBlue);

	bg->SetParameter(0,0);
	bg->SetParName(0, "BG p_{0}");
	bg->SetParameter(1,0);
	bg->SetParName(1, "BG p_{1}");
	bg->SetParameter(2,0);
	bg->SetParName(2, "BG p_{2}");

	TFSum::FitRanged(h, bg, 650, 730, 830, 900);
	//bg->FixParameter(0, bg->GetParameter(0));
	//bg->FixParameter(1, bg->GetParameter(1));
	//bg->FixParameter(2, bg->GetParameter(2));


	TFSum* sum = new TFSum("sum", sig, bg, r_min, r_max);
	sum->SetNpx(npx);


	TCanvas* c = new TCanvas();
	c->SetTitle(Form("Fit to %s", hist_name));
	h->SetStats(true);
	gStyle->SetOptFit(1);
	h->Draw();
	h->Fit(sum->Function(), "REM0NB");

	sum->SyncToFcts();

	sum->Draw();


	const double total_area = sum->Function()->Integral(r_min, r_max);
	const double bg_area    =  bg->Integral(r_min, r_max);
	const double sig_area   = total_area - bg_area;

	const double sig_to_bg = sig_area / bg_area;
	const double peak_pos  = sig->GetParameter(1);

	cout << "Mass offset = " << peak_pos - omega_mass << " MeV\n";
	cout << "Sig/BG      = " << sig_to_bg << "\n";
	cout << "Sig         = " << sig_area << endl;

	// TODO: choose a position. Positions for TLatex are histogram coordinates.
	TLatex* label = new TLatex(r_min, h->GetMaximum(),Form("Signal content = %lf", sig_area));
	label->Draw();

}
예제 #22
0
float PurityFit::fit_specific( const TH1* h_, const TH1* sig_, const TH1* bkg_, 
        string name, // unique name of the result
        string outname , // output file name, where to save results
        map<string,float> *pars	 // to gather additional params
        )
{

    // 1) perform preliminary checks
    if ( h_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no target histogram"<<endl; return -1;}
    if ( sig_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no sig histogram"<<endl; return -1;}
    if ( bkg_ == NULL ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] no bkg histogram"<<endl; return -1;}

    if (sig_ -> Integral() == 0 ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] sig integrall is NULL"<<endl; return -2;}
    if (bkg_ -> Integral() == 0 ) { cout<<"[PurityFit]::[fit_specific]::[ERROR] bkg integrall is NULL"<<endl; return -2;}

    if (verbose_ >0) cout <<"[PurityFit]::[fit_specific]::[INFO] fitting "<<h_->GetName() << " " << sig_->GetName()<<" "<<bkg_->GetName()<<endl;
    // 1.5) Clone
    TH1 * sig = (TH1*)sig_ -> Clone(Form("%s_fitspecific_clone",sig_->GetName()));
    TH1 * bkg = (TH1*)bkg_ -> Clone(Form("%s_fitspecific_clone",bkg_->GetName()));
    TH1 * h = (TH1*)h_ -> Clone(Form("%s_fitspecific_clone",h_->GetName()));
    // 1.6) check no negative entries otherwise 0
    for(int i=1;i<=sig->GetNbinsX();++i)
        if(sig->GetBinContent(i) <0) sig->SetBinContent(i,0);
    for(int i=1;i<=bkg->GetNbinsX();++i)
        if(bkg->GetBinContent(i) <0) bkg->SetBinContent(i,0);

    // 2) scale templates: template normalization is meaningless
    sig->Sumw2();	
    bkg->Sumw2();

    if (bkg->Integral() <=0)
    {
    for(int i=1;i<=bkg->GetNbinsX();++i)
        bkg->SetBinContent(i,1.0);
    }

    // 2.5) fit background with exponential
    int   nbins = h->GetNbinsX();
    float xmin = h->GetBinLowEdge(1);
    float xmax = h->GetBinLowEdge(nbins+1);

    double prevChi2=-1;

    vector<TCanvas*> cbkgs;
    vector<TF1> expos;

    double cached_pars[50]; //cache
    for(int i=0;i< sizeof(cached_pars)/sizeof(double); ++i) cached_pars[i]=0;

    int poln=0;
    for( poln=0;poln<5; ++poln)
    {
        string formula = "TMath::Exp(-[0]*x) * ( ";
        for(int i=0;i<=poln;++i)
                {
                    if (i>0 ) formula += " + ";
                    formula += Form("[%d]",i+1);
                    if (i>0) formula += Form("*TMath::Power(x,%d)",i);
                }
        formula += ")";
        cout <<"Considering Formula"<<formula<<endl;
        TF1 expo(Form("expo%d",poln),formula.c_str(),xmin,xmax);
        expo.SetParameter(0,0.01);
        expo.SetParameter(1,0.05);

        expo.SetParLimits(0,TMath::Min(bkg->Integral()*.1,0.001), bkg->Integral()*10);
        expo.SetParLimits(1,1e-9, 1.);

        if (poln>0)for(int k=0;k < poln+1;++k) expo.SetParameter(k, cached_pars[k]);

        bkg->Fit( &expo ,"QN") ;
        bkg->Fit( &expo ,"QNM") ;
        expos.push_back(expo);

        //cache parameters
        for(int k=0;k < poln+1;++k) cached_pars[k]=expo.GetParameter(k);

        double chi2=expo.GetChisquare();
        double prob = 0 ; 
        if (poln > 0)
        {
            int n = 0;
            for(int i=1;i<=bkg->GetNbinsX();++i) if ( bkg->GetBinContent(i)> 0 ) ++n;
            int dof = n - (poln+2) + 1;
            double f = (prevChi2 - chi2) / ( chi2 /dof) ;
            prob= 1.- TMath::FDistI (f , 1, dof  ) ;
        }
        prevChi2 = chi2;

        cout<<"----------- BKG PARAMETERS ARE -------"<<endl;
        cout << "Prob = "<<prob<<endl;
        cout << "chi2 = "<<chi2<<endl;
        cout<<" 0 : "<< expo.GetParameter(0) <<endl;
        for(int i=0; i<=poln;++i)
            cout<<" "<< i+1 <<" : "<< expo.GetParameter(i+1) <<endl;
        cout<<"--------------------------------------"<<endl;
        TCanvas *cbkg=new TCanvas( (string(name)+"_bkgfit"+ Form("pol%d",poln)).c_str(),"Canvas"); cbkgs.push_back(cbkg);
        bkg->Clone("bkgForDraw")->Draw("P E"); // FIXME, memory leak
        expo.DrawClone("L SAME");

        if (prob >0.05 and poln> 0) break; // ---------------------- EXIT BEFORE UPDATING
    }
    
    poln -= 1;  // the last has a negligible improvement

    for(int i=1;i<=bkg->GetNbinsX() ;++i)
            bkg->SetBinContent(i,expos[poln].Integral( bkg->GetBinLowEdge(i),bkg->GetBinLowEdge(i+1) ) ) ;

    if (sig->Integral() >0)
        sig -> Scale( 1./sig->Integral() );
    if (bkg->Integral() >0)
        bkg -> Scale( 1./bkg->Integral() );


    // 3) estimate paramaters
    // float fracEstimator=0.5;
    //     {
    //          // 3.1) compute frac as around the max of sig 
    //          float sigMax= sig->GetMaximum();
    //          int sigBinMax= sig->GetMaximumBin();
    //          float sigInt= sig->Integral();
    //          float bkgUnderMax=bkg->GetBinContent(sigBinMax);
    //          float targetMax = h->GetMaximum();
    //          float targetInt = h->Integral();
    //          float frac1=(targetMax/targetInt)/( (sigMax-bkgUnderMax)/sigInt);
    //          // 3.2) compute frac as tail
    //          float bkgInt= bkg->Integral();
    //          int bkgN=bkg->GetNbinsX();
    //          int nTailSum= bkgN/10;
    //          float bkgTail=0;for(int i=0;i<nTailSum;i++) bkgTail+= bkg->GetBinContent(bkgN-i);
    //          int targetN=h->GetNbinsX();
    //          float targetTail=0;for(int i=0;i<nTailSum;i++) targetTail+= h->GetBinContent(targetN-i);
    //          float frac2=1.- (targetTail/targetInt)/(bkgTail/bkgInt);
    //          // 3.3) set estimator 
    //          fracEstimator = frac1;
    //          if(fracEstimator<0.05 or fracEstimator>0.95) fracEstimator=frac2;
    //          if(fracEstimator<0.05 or fracEstimator>0.95) fracEstimator=0.8;
    //     }
    // 4) create roofit variables
    RooRealVar f("f","fraction",0.95,0.3,1.0);
    //if ( TMath::IsNaN( fracEstimator ) )
    //    f.setVal(0.05);
    //else
    //    f.setVal(fracEstimator);
    f.setRange(0.3,1.0);
    f.setConstant(false);

    RooRealVar x("x","EtMiss",xmin,xmax);
    // 5) create roo data hist
    RooDataHist HistSig("sig","hist sig",x,sig);
    RooDataHist HistBkg("bkg","hist bkg",x,bkg);
    RooDataHist HistToFit("target","hist target",x,h);
    // 6) create roo hist pdf
    RooHistPdf PdfSig("pdfsig","pdfsig",x,HistSig,0);
    RooHistPdf PdfBkg("pdfbkg","pdfbkg",x,HistBkg,10); //last number is interpolation
    // 7) create model
    RooAddPdf PdfModel("model","model",RooArgList(PdfSig,PdfBkg),f);
    // 8) fit
    RooFitResult *r;
    RooPlot *frame=x.frame();
    RooMsgService::instance().setSilentMode(true);

    PdfModel.fitTo(HistToFit,
            SumW2Error(kTRUE),
            Save(), 
            PrintEvalErrors(-1),
            PrintLevel(-1),
            //Minos(kTRUE),
            Warnings(0)
            );
    r = PdfModel.fitTo(HistToFit,
            SumW2Error(kTRUE),
            Save(), 
            PrintEvalErrors(-1),
            PrintLevel(-1),
            Minos(kTRUE),
            Warnings(0)
            );
    cout <<" -------------- FLOATING -------------"<<endl;
    r-> floatParsInit() . Print("V");
    cout <<" -------------- FINAL ----------------"<<endl;
    r-> floatParsFinal() . Print("V");
    cout <<" -------------------------------------"<<endl;
    // 8.5) save additional results
    if (pars != NULL ) {
        (*pars)["fracErrorHigh"] = f.getAsymErrorHi(); 
        (*pars)["fracErrorLow" ] = f.getAsymErrorLo(); 
    }
    // 9) plot
    HistToFit.plotOn(frame,DataError(RooAbsData::SumW2));
    PdfModel.plotOn(frame, LineColor(kBlack));
    PdfModel.plotOn(frame, Components(PdfBkg),LineColor(kRed)); 
    PdfModel.plotOn(frame, Components(PdfSig),LineColor(kBlue),LineStyle(kDashed));

    TCanvas *c=new TCanvas((string(name)+"_canvas").c_str(),"Canvas");
    c->cd();
    c->Draw();
    frame->Draw();

    TLatex* txt = new TLatex();//Form("Fraction=%.1f\%",f.getVal()*100) ;
    txt->SetTextSize(0.03) ;
    txt->SetTextColor(kBlack) ;
    txt->SetNDC();
    txt->SetTextAlign(22);
    //txt->AddText(Form("Fraction=%.1f\%",f.getVal()*100) );
    txt->DrawLatex(.3,.85,Form("Fraction=%.1f%%",float(f.getVal()*100)));

    // get pt from name
    {
        size_t n = name.find("pt");
        float ptmin = -1;
        float ptmax = -1;
        if (n != string::npos)
        {
            string pts = "";	
            //name[n+0] == 'p'
            //name[n+1] =='t'
            n +=2;

            //all string are null terminated in C/C++
            while (	name[n] != '_' and name[n] != '\0' ) { pts+=name[n]; ++n;}
            ptmin = atof( pts.c_str() ) ;

            pts="";
            ++n;
            while (	name[n] != '_' and name[n] != '\0' ) { pts+=name[n]; ++n;}
            ptmax = atof( pts.c_str() ) ;
            txt->DrawLatex(.3,.82,Form("%.1f<P_{T}<%.1f",ptmin,ptmax));	
        }
    } // end get pt from name

    if ( outname != "")
    {
        TFile *fOut=TFile::Open(outname.c_str(),"UPDATE");
        fOut->cd();
        c->Write();
        for( auto c : cbkgs ) c->Write();
        r->Write(Form("%s_roofit",name.c_str() ) );
        fOut->Close();
    }

    // delete the clone
    for( auto c : cbkgs ) c->Delete();
    cbkgs.clear();
    sig -> Delete();
    bkg -> Delete();
    h   -> Delete();

    return f.getVal();
}
예제 #23
0
파일: YieldMean.C 프로젝트: ktf/AliPhysics
TH1 *
YieldMean(TH1 *hstat, TH1 *hsys, TF1 *f = NULL, Double_t min = 0., Double_t max = 10., Double_t loprecision = 0.01, Double_t hiprecision = 0.1, Option_t *opt = "0q",TString logfilename="log.root",Double_t minfit=0.0,Double_t maxfit=10.0)
{
	if(maxfit>max)
		max=maxfit;	
	if(minfit<min)
		min=minfit;	


  /* set many iterations when fitting the data so we don't
     stop minimization with MAX_CALLS */
  TVirtualFitter::SetMaxIterations(1000000);

  /* create output histo */
  Double_t integral, mean, extra;
  TH1 *hout = new TH1D("hout", "", 9, 0, 9);
  TH1 *hlo, *hhi;
  
  /* create histo with stat+sys errors */
  TH1 *htot = (TH1 *)hstat->Clone(Form("%sfittedwith%s",hstat->GetName(),f->GetName()));
  for (Int_t ibin = 0; ibin < htot->GetNbinsX(); ibin++) {
    htot->SetBinError(ibin + 1, TMath::Sqrt(hsys->GetBinError(ibin + 1) * hsys->GetBinError(ibin + 1) + hstat->GetBinError(ibin + 1) * hstat->GetBinError(ibin + 1)));
  }

  /*
   *   measure the central value 
   */
  Int_t fitres;
  Int_t trials = 0;
  trials = 0;
  do {
    fitres = htot->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  TFile* filewithfits=TFile::Open(logfilename.Data(),"UPDATE");
  htot->Write();
  filewithfits->Close();		
  delete filewithfits;	 
	
  cout<<" Fit sys+stat for " <<f->GetName()<<endl;		
  cout<<"NDF="<<f->GetNDF()<<" Chi^2="<<f->GetChisquare()<<" Chi^2/NDF="<<f->GetChisquare()/f->GetNDF()<<endl;

  hlo = YieldMean_LowExtrapolationHisto(htot, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(htot, f, max, hiprecision);
  YieldMean_IntegralMean(htot, hlo, hhi, integral, mean, extra, kTRUE);
  hout->SetBinContent(kYield, integral);
  hout->SetBinContent(kMean, mean);
  hout->SetBinContent(kExtra, extra);

  /*
   * STATISTICS
   */
  
  TCanvas *cCanvasStat = new TCanvas("cCanvasStat");
  cCanvasStat->Divide(2, 1);
  
  /*
   * measure statistical error
   */

  /* fit with stat error */
  trials = 0;
  do {
    fitres = hstat->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  hlo = YieldMean_LowExtrapolationHisto(hstat, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(hstat, f, max, hiprecision);
  
  /* random generation with integration (coarse) */
  TH1 *hIntegral_tmp = new TH1F("hIntegral_tmp", "", 1000, 0.75 * integral, 1.25 * integral);
  TH1 *hMean_tmp = new TH1F("hMean_tmp", "", 1000, 0.75 * mean, 1.25 * mean);
  for (Int_t irnd = 0; irnd < 100; irnd++) {
    /* get random histogram */
    TH1 *hrnd = YieldMean_ReturnRandom(hstat);
    /* fit */
    TH1 *hrndlo = YieldMean_ReturnCoherentRandom(hlo);
    TH1 *hrndhi = YieldMean_ReturnCoherentRandom(hhi);
    /* integrate */
    YieldMean_IntegralMean(hrnd, hrndlo, hrndhi, integral, mean, extra);
    hIntegral_tmp->Fill(integral);
    hMean_tmp->Fill(mean);
    delete hrnd;
    delete hrndlo;
    delete hrndhi;
   }
  /* random generation with integration (fine) */
  TH1 *hIntegral = new TH1F("hIntegral", "", 100, 
                            hIntegral_tmp->GetMean() - 10. * hIntegral_tmp->GetRMS(),
                            hIntegral_tmp->GetMean() + 10. * hIntegral_tmp->GetRMS());
  TH1 *hMean = new TH1F("hMean", "", 100,
                        hMean_tmp->GetMean() - 10. * hMean_tmp->GetRMS(),
                        hMean_tmp->GetMean() + 10. * hMean_tmp->GetRMS());
  for (Int_t irnd = 0; irnd < 1000; irnd++) {
    /* get random histogram */
    TH1 *hrnd = YieldMean_ReturnRandom(hstat);
    /* fit */
    TH1 *hrndlo = YieldMean_ReturnCoherentRandom(hlo);
    TH1 *hrndhi = YieldMean_ReturnCoherentRandom(hhi);
    /* integrate */
    YieldMean_IntegralMean(hrnd, hrndlo, hrndhi, integral, mean, extra);
    hIntegral->Fill(integral);
    hMean->Fill(mean);
    delete hrnd;
    delete hrndlo;
    delete hrndhi;
  }
  TF1 *gaus = (TF1 *)gROOT->GetFunction("gaus");
  
  cCanvasStat->cd(1);
  hIntegral->Fit(gaus, "q");
  integral = hout->GetBinContent(kYield) * gaus->GetParameter(2) / gaus->GetParameter(1);
  hout->SetBinContent(kYieldStat, integral);
  
  cCanvasStat->cd(2);
  hMean->Fit(gaus, "q");
  mean = hout->GetBinContent(kMean) * gaus->GetParameter(2) / gaus->GetParameter(1);
  hout->SetBinContent(kMeanStat, mean);
  
  /*
   * SYSTEMATICS
   */

  TCanvas *cCanvasSys = new TCanvas("cCanvasYieldSys");
  cCanvasSys->Divide(2, 1);
  cCanvasSys->cd(1)->DrawFrame(min, 1.e-3, max, 1.e3);
  hsys->SetMarkerStyle(20);
  hsys->SetMarkerColor(1);
  hsys->SetMarkerSize(1);
  hsys->Draw("same");
  cCanvasSys->cd(2)->DrawFrame(min, 1.e-3, max, 1.e3);
  hsys->Draw("same");
  
  /*
   * systematic error high
   */

  TH1 *hhigh = YieldMean_ReturnExtremeHighHisto(hsys);
  trials = 0;
  do {
    fitres = hhigh->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  hlo = YieldMean_LowExtrapolationHisto(hhigh, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(hhigh, f, max, hiprecision);
  YieldMean_IntegralMean(hhigh, hlo, hhi, integral, mean, extra);
  integral = TMath::Abs(integral - hout->GetBinContent(kYield));
  hout->SetBinContent(kYieldSysHi, integral);

  cCanvasSys->cd(1);
  f->SetLineColor(2);
  f->DrawCopy("same");
  
  /*
   * systematic error hard
   */

  TH1 *hhard = YieldMean_ReturnExtremeHardHisto(hsys);
  trials = 0;
  do {
    fitres = hhard->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  hlo = YieldMean_LowExtrapolationHisto(hhard, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(hhard, f, max, hiprecision);
  YieldMean_IntegralMean(hhard, hlo, hhi, integral, mean, extra);
  mean = TMath::Abs(mean - hout->GetBinContent(kMean));
  hout->SetBinContent(kMeanSysHi, mean);

  cCanvasSys->cd(2);
  f->SetLineColor(2);
  f->DrawCopy("same");
  
  /*
   * systematic error low
   */

  TH1 *hlow = YieldMean_ReturnExtremeLowHisto(hsys);
  trials = 0;
  do {
    fitres = hlow->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  hlo = YieldMean_LowExtrapolationHisto(hlow, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(hlow, f, max, hiprecision);
  YieldMean_IntegralMean(hlow, hlo, hhi, integral, mean, extra);
  integral = TMath::Abs(integral - hout->GetBinContent(kYield));
  hout->SetBinContent(kYieldSysLo, integral);

  cCanvasSys->cd(1);
  f->SetLineColor(4);
  f->DrawCopy("same");

  /*
   * systematic error soft
   */

  TH1 *hsoft = YieldMean_ReturnExtremeSoftHisto(hsys);
  trials = 0;
  do {
    fitres = hsoft->Fit(f, opt,"",minfit,maxfit);
    Printf("Trial: %d", trials++);
    if(trials > 10) {
      Printf("FIT DOES NOT CONVERGE IN LINE %d",__LINE__);
      break;
    }
  }
  while (fitres != 0);
  hlo = YieldMean_LowExtrapolationHisto(hsoft, f, min, loprecision);
  hhi = YieldMean_HighExtrapolationHisto(hsoft, f, max, hiprecision);
  YieldMean_IntegralMean(hsoft, hlo, hhi, integral, mean, extra);
  mean = TMath::Abs(mean - hout->GetBinContent(kMean));
  hout->SetBinContent(kMeanSysLo, mean);

  cCanvasSys->cd(2);
  f->SetLineColor(4);
  f->DrawCopy("same");

  return hout;
}
예제 #24
0
//______________________________________________________________________________
void CalibrateFit(Int_t nPar, Double_t time_limit, Double_t bad_frac)
{
    // Calibrate using iterative fitting.

    const Double_t convergence_factor = 0.05;

    // iterate calibrations
    for (Int_t i = 0; i >= 0; i++)
    {
        // create new histogram
        TH2* h = CreateHisto("fit_histo", nPar, gOff);

        // user info
        printf("Calibration iteration %d\n", i+1);

        // loop over elements
        Int_t n = 0;
        Int_t outside_n = 0;
        for (Int_t j = 0; j < nPar; j++)
        {
            // create projection
            TH1* hProj = (TH1*) h->ProjectionX(TString::Format("Proj_%d", j).Data(), j+1, j+1, "e");

            // check for filled histograms
            if (hProj->GetEntries())
            {
                // create fitting function
                TF1* func = new TF1(TString::Format("Func_%d", j).Data(), "gaus", -5, 5);
                func->SetParameter(0, 1);
                func->SetParameter(1, hProj->GetXaxis()->GetBinCenter(hProj->GetMaximumBin()));
                func->SetParameter(2, 0.1);

                // fit histogram
                hProj->GetXaxis()->SetRangeUser(-5, 5);
                hProj->Fit(func, "0Q");
                Double_t mean = func->GetParameter(1);

                // update offset
                gOff[j] = gOff[j] + convergence_factor * mean / gGain[j];
                n++;
                if (TMath::Abs(mean) > time_limit)
                    outside_n++;

                // clean-up
                delete func;
            }

            // clean-up
            delete hProj;
        }

        // clean-up
        delete h;

        // user info
        Double_t outside_frac = (Double_t)outside_n/(Double_t)n;
        printf("Element outside limits: %.1f%%\n", outside_frac*100.);
        if (outside_frac < bad_frac)
            break;
    }
}
예제 #25
0
//______________________________________________________________________________
void CheckTime(const Char_t* loc)
{
    // Check time.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // create arrays
    const Int_t nCh = 352;
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d", i);
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();
        
        TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time");

        // loop over channels
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d", j);
            fROOTout->cd(t);
            sprintf(t, "%d_%d", i, j);
            TH1* h = h2->ProjectionX(t, j+1, j+1);
            h->Rebin(2);
            
            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            TLine* tline = 0;
            
            // check entries
            if (h->GetEntries())
            {
                // fit gaussian to peak
                Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
                func->SetParameters(1, maxPos, 0.5, 1, 0.1);
                func->SetRange(maxPos - 2, maxPos + 2);
                func->SetParLimits(0, 0, 1000);
                for (Int_t k = 0; k < 10; k++)
                    if (!h->Fit(func, "RBQ")) break;

                // save position in file and memory
                maxPos = func->GetParameter(1);
                pedPos[j][i] = maxPos;

                h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10);
                h->Draw();
                
                tline = new TLine(maxPos, 0, maxPos, 10000);
                tline->SetLineColor(kRed);
                tline->SetLineWidth(2);
                tline->Draw();
            }
            else
            {
                h->Draw();
            }

            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            if (tline) delete tline;
        }
        
        delete h2;
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating time graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d", j);
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
예제 #26
0
void AnalyzeData(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt,
		Int_t startEv = 1, char *PedFile, Int_t DrawExtraGraphs = 0) {


	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// open file

	FILE *fdata = OpenDataFile(DataFile);
	struct channel_struct *p;
	struct channel_struct *dep;

	// create histograms
	// create list of histograms for channels and distribution

	TList *DistChList = new TList();
	TH1F *distch; // histo with distribution of cell-charge, for each channel

	TList *DistChSubList = new TList();
	TH1F *distchsub; // histo with distribution of cell-charge, pedestals subtracted, for each channel

	TList *DistCh0SubList = new TList();
	TH1F *distch0sub; // histo with distribution of cell-charge, pedestals subtracted,
	// channel 0 subtracted for each channel

	TList *grPedList = new TList();
	TGraphErrors *grPed; // for each channel, pedestal value and RMS for each cell is plotted

	TList *hCellList = new TList();
	TH1F *hCell; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos)
	TList *hCellSubList = new TList();
	TH1F *hCellSub; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos), pedestal subtracted

	TList *hRMSList = new TList();
	TH1F *hRMSdist; // histo with RMS distribution (statistical RMS of distribution)
	TList *hRMSFitList = new TList();
	TH1F *hRMSFitdist; // histo with RMS distribution (RMS of Gaussian fit)

	TList *grDataList = new TList();
	TGraphErrors *grData; // charge-cell and RMS for each cell is plotted

	TList *grDataSubList = new TList();
	TGraphErrors *grDataSub; // pedestal subtracted charge-cell and RMS for each cell is plotted


	for (int h = 0; h < DOMINO_NCH; h++) {
		//
		TString title = "Data Dist channel";
		title += h;
		distch = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
		DistChList->Add(distch);
		//
		TString title = "Data Dist Ped Sub channel";
		title += h;
		distchsub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistChSubList->Add(distchsub);
		//
		TString title = "Data Dist Ped Ch0 Sub channel";
		title += h;
		distch0sub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistCh0SubList->Add(distch0sub);
		//
		TString title = "Pedestal ch";
		title += h;
		grPed = new TGraphErrors(DOMINO_NCELL);
		grPed->SetTitle(title);
		grPedList->Add(grPed);
		//
		TString title = "Data ch";
		title += h;
		grData = new TGraphErrors(DOMINO_NCELL);
		grData->SetTitle(title);
		grDataList->Add(grData);
		//
		// Mean data and RMS for each channel and cell
		TString title = "Data PedSubtracted ch";
		title += h;
		grDataSub = new TGraphErrors(DOMINO_NCELL);
		grDataSub->SetTitle(title);
		grDataSubList->Add(grDataSub);
		//
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			TString title = "Data ch";
			title += h;
			title += " cell";
			title += ch;
			hCell = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
			hCellList->Add(hCell);
			// data (ped subtracted) distribution histos
			TString title = "Data PedSub ch";
			title += h;
			title += " cell ";
			title += ch;
			hCellSub = new TH1F(title, title, 2 * DominoDepthADC, -1
					* DominoDepthADC, DominoDepthADC);
			hCellSubList->Add(hCellSub);
		}
		// Data-RMS distribution histos
		TString title = "RMSDist channel";
		title += h;
		hRMSdist = new TH1F(title, title, 100, 0, 20.);
		hRMSList->Add(hRMSdist);
		// Data-RMS (calculated through a fit) distribution histos
		TString title = "RMSFitDist channel";
		title += h;
		hRMSFitdist = new TH1F(title, title, 100, 0, 20.);
		hRMSFitList->Add(hRMSFitdist);
	}
	//--------------
	//
	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);

	//    return;
	//
	// ====== Read data file and subtract the pedestals
	//
	// Count number of events in data file
	int nevtDataMax = 0;
	while (!feof(fdata)) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		nevtDataMax++;
	}
	printf("nevtDataMax: %d\n", nevtDataMax);

	if (nevt > (nevtDataMax - startEv) || nevt == 0)
		nevt = nevtDataMax - startEv;
	cout << endl << "==>> Processing " << nevt << " events from file "
			<< DataFile << endl;

	rewind(fdata);

	Int_t ievt = 1;
	// go to first event (startEv)
	while (ievt < startEv) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			break;
		ievt++;
	}
	// filling
	ievt = 1;
	Int_t flagEnd = 0;
	Double_t chtmp;
	Double_t PedVal, itmp, Ch0Val;
	// loop on events
	cout << endl << " --- read DATA file:" << fdata << endl;
	while (ievt <= nevt && !flagEnd) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			flagEnd = 1;
		if (ievt % (nevt / 10 + 1) == 0)
			cout << "*" << endl;
		p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
		dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

		TGraphErrors *grCh0 = new TGraphErrors(DOMINO_NCELL);

		// loop on channels
		for (int h = 0; h < DOMINO_NCH; h++) {
			// loop on cells
			distch = (TH1F *) DistChList->At(h);
			distchsub = (TH1F *) DistChSubList->At(h);
			grPed = (TGraphErrors *) grPedList->At(h);
			distch0sub = (TH1F *) DistCh0SubList->At(h);
			if(h==0) {
				for(i = 0; i < DOMINO_NCELL;i++) {
					grPed->GetPoint(i, itmp, PedVal);
					chtmp = (Double_t)(p->data[i]);
					chtmp = chtmp - PedVal;
					grCh0->SetPoint(i,itmp, chtmp);
				}
			}
			for (int i = 0; i < DOMINO_NCELL; i++) {
				// Read pedestal value for this cell
				grPed->GetPoint(i, itmp, PedVal);
				grCh0->GetPoint(i, itmp, Ch0Val);
				//                cout << itmp << ", " << PedVal << endl;
				// Read calibration correction for this cell
				//                CalFact =

				//charge distribution for each cell, pedestal subtracted
				chtmp = (Double_t)(p->data[i]); // data value
				//                cout  << "tcell, tcell, depth: " << chtmp << ","  << p->data[i] << "," << deptmp << endl;
				distch->Fill(chtmp);
				// Check data value: must be within DOMINO Depth
				//                if(chtmp > DominoDepthADC)
				//                    cout << " === WARNING!!! Channel " << h << " Cell " << i << " has value " << chtmp << endl;
				//                cout << "Charge: " << p->data[i] << endl;
				((TH1 *) hCellList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				// Now the pedestal is subtracted
				chtmp = chtmp - PedVal;
				distchsub->Fill(chtmp);
				((TH1 *) hCellSubList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				chtmp = chtmp - Ch0Val;
				distch0sub->Fill(chtmp);
			}
			p++; // next channel
		}
		ievt++; // next event
	}
	cout << endl;

	// now mean and RMS for each cell are computed and save in histos and graphs
	cout << " --- filling data histos and grphs " << endl;
	TF1 *fgauss = new TF1("fgauss", Gauss, -10., 10., 3);
	fgauss->SetParLimits(0, 0.1, 10000.);
	fgauss->SetParLimits(1, 0., 4096.);
	fgauss->SetParLimits(2, 0.1, 20.);
	Float_t mean, rms, meansub, rmssub;
	for (int h = 0; h < DOMINO_NCH; h++) {
		//        for (int h=5; h<6; h++){
		cout << " Channel:" << h << endl;
		hRMSdist = (TH1F *) hRMSList->At(h);
		hRMSFitdist = (TH1F *) hRMSFitList->At(h);
		grData = (TGraphErrors *) grDataList->At(h);
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			//            cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<<hCell->GetMean()<< "," << hCell->GetRMS()<<endl;
			hCell = (TH1F *) hCellList->At(h * DOMINO_NCELL + ch);
			mean = hCell->GetMean();
			rms = hCell->GetRMS();
			hCellSub = (TH1F *) hCellSubList->At(h * DOMINO_NCELL + ch);
			meansub = hCellSub->GetMean();
			rmssub = hCellSub->GetRMS();
			fgauss->SetParameter(0, (Double_t) nevt / 4.);
			fgauss->SetParameter(1, mean);
			fgauss->SetParameter(2, rms);
			//            hCell->Fit("fgauss","QN0");
			grData->SetPoint(ch, ch, mean);
			grData->SetPointError(ch, 0, rms);
			grDataSub->SetPoint(ch, ch, meansub);
			//            grDataSub->SetPointError(ch,0.5,rmssub);
			grDataSub->SetPointError(ch, 0.5, 2.1);
			hRMSdist->Fill(rms);
			hRMSFitdist->Fill(fgauss->GetParameter(2));
			//           cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<< mean << "," << rms<<endl;
		}
	}

	Double_t x, y, chtmp, x1, x2, y1, y2;

	/*TList *grCellCalibList = OpenCalibFile("CalibrationData1000events.root");

	TGraphErrors *grCellCalib;
	TGraphErrors *grDataSubCalib = new TGraphErrors(DOMINO_NCELL);
	grDataSubCalib->SetTitle("Data after calibration correction");
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);


	for(ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = ((TGraphErrors *) grCellCalibList->At(ch));
		grCellCalib->Fit("pol3", "Q");
		TF1 *pol3fit = ((TF1 *) grCellCalib->GetFunction("pol3"));
		grDataSub->GetPoint(ch, x, y);
		chtmp = y - (Double_t)(pol3fit->Eval(y/3.25));
		grDataSubCalib->SetPoint(ch, x, chtmp);
	}

	TCanvas *cGrTest = new TCanvas("grTest", "test per vedere i dati", 1000,1000);

	grDataSubCalib->Draw("APEL");*/


	TString Title = "Charge Distribution per channel";
	gStyle->SetOptFit(111);
	TCanvas *cdistch = new TCanvas("cdistch", Title, 1000, 1000);
	cdistch->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch->cd(i + 1);
		TH1 *dhist = (TH1 *) DistChList->At(i);
		dhist->DrawCopy();
		dhist->SetLineWidth(1);
		dhist->Fit("gaus", "Q");
		dhist->GetFunction("gaus")->SetLineColor(4);
		dhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals Subtracted per channel";
	TCanvas *cdistchsub = new TCanvas("cdistchsub", Title, 1000, 1000);
	cdistchsub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistchsub->cd(i + 1);
		TH1 *dsubhist = (TH1 *) DistChSubList->At(i);
		dsubhist->DrawCopy();
		dsubhist->SetLineWidth(1);
		dsubhist->Fit("gaus", "Q");
		dsubhist->GetFunction("gaus")->SetLineColor(4);
		dsubhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals and Ch0 Subtracted per channel";
	TCanvas *cdistch0sub = new TCanvas("cdistch0sub", Title, 1000, 1000);
	cdistch0sub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch0sub->cd(i + 1);
		TH1 *dch0subhist = (TH1 *) DistCh0SubList->At(i);
		dch0subhist->DrawCopy();
		dch0subhist->SetLineWidth(1);
		dch0subhist->Fit("gaus", "Q");
		dch0subhist->GetFunction("gaus")->SetLineColor(4);
		dch0subhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TCanvas *cDataSubTest = new TCanvas("cDataSubTest", "Data after pedestal subtraction", 1000, 1000);
	cDataSubTest->Divide(1,8);
	for (h = 0; h< DOMINO_NCH; h++) {
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		cDataSubTest->cd(h+1);
		grDataSub->GetYaxis()->SetLabelSize(0.06);
		grDataSub->GetXaxis()->SetLabelSize(0.06);
		grDataSub->Draw("APE");
	}

	TCanvas *cDataSubTestCh5 = new TCanvas("cDataSubTestCh5", "Data after pedestal subtraction Ch5", 1200, 800);
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);
	grDataSub->GetYaxis()->SetLabelSize(0.06);
	grDataSub->GetYaxis()->SetTitle("ADC Counts");
	grDataSub->GetXaxis()->SetTitle("Cell");
	grDataSub->GetXaxis()->SetLabelSize(0.06);
	TLine *refval = new TLine(0,350,1024,350);
	refval->SetLineWidth(3);
	refval->SetLineStyle(2);
	refval->SetLineColor(2);
	TLine *i1 = new TLine(121,-50,121,800);
	i1->SetLineStyle(2);
	TLine *i2 = new TLine(291,-50,291,800);
	i2->SetLineStyle(2);
	TLine *i3 = new TLine(461,-50,461,800);
	i3->SetLineStyle(2);
	TLine *i4 = new TLine(632,-50,632,800);
	i4->SetLineStyle(2);
	TLine *i5 = new TLine(803,-50,803,800);
	i5->SetLineStyle(2);
	TLine *i6 = new TLine(975,-50,975,800);
	i6->SetLineStyle(2);
	TLine *ireal1 = new TLine(121+20,600,121+20,800);
	ireal1->SetLineWidth(3);
	ireal1->SetLineColor(4);
	TLine *ireal2 = new TLine(291-20,600,291-20,800);
	ireal2->SetLineWidth(3);
	ireal2->SetLineColor(4);
	TLine *ireal3 = new TLine(461+20,600,461+20,800);
	ireal3->SetLineWidth(3);
	ireal3->SetLineColor(4);
	TLine *ireal4 = new TLine(632-20,600,632-20,800);
	ireal4->SetLineWidth(3);
	ireal4->SetLineColor(4);
	TLine *ireal5 = new TLine(803+20,600,803+20,800);
	ireal5->SetLineWidth(3);
	ireal5->SetLineColor(4);
	TLine *ireal6 = new TLine(975-20,600,975-20,800);
	ireal6->SetLineWidth(3);
	ireal6->SetLineColor(4);
	grDataSub->Draw("APE");
	refval->Draw("SAME");
	i1->Draw("SAME");
	i2->Draw("SAME");
	i3->Draw("SAME");
	i4->Draw("SAME");
	i5->Draw("SAME");
	i6->Draw("SAME");
	ireal1->Draw("SAME");
	ireal2->Draw("SAME");
	ireal3->Draw("SAME");
	ireal4->Draw("SAME");
	ireal5->Draw("SAME");
	ireal6->Draw("SAME");


	TCanvas *cDataTest = new TCanvas("cDataTest", "Raw Data", 1000,1000);
	cDataTest->Divide(1,8);
	for(h = 0; h < DOMINO_NCH; h++) {
		cDataTest->cd(h+1);
		grData = (TGraphErrors *) grDataList->At(h);
		grData->SetMarkerStyle(20);
		grData->SetMarkerSize(0.5);
		grData->Draw("APE");

	}

	// save root file with graph containing channel 5 data after pedestals subtraction.
	/*
	cout << "test" << endl;

	TString OutFile = DataSubFile;
	TFile *f = new TFile(OutFile,"RECREATE");
	int h = anaChannel;
	TString key="DataSubGraph";
	key += h;
	((TGraphErrors*)grDataSubList->At(h))->Write(key);
	f->Close();
	cout << " ---- Write data on file " << endl;
	 */

	// =======================================================//
	// =====================Matteo's Code=====================//
	// =======================================================//
	/*
	Int_t cht, incCht, decCht, xflag, nPeriods, iMax, iMin;
	Double_t xdiff, incDiff, decDiff, incDiffTemp, decDiffTemp, incXDiff, decXDiff;
	Double_t fitMax, fitMin, fitPeriod, chisquare;
	Double_t DominoXval[DOMINO_NCELL];
	Double_t DominoYval[DOMINO_NCELL];
	Double_t FitXval[DOMINO_NCELL];
	Double_t FitYval[DOMINO_NCELL];


        // opens grDataSub.root

        TString FileName = DataSubFile;
        TGraphErrors *grDataSub;
        int h = anaChannel;
        TFile *f = new TFile(FileName);
        TString key = "DataSubGraph";
        key += h;
        grDataSub = (TGraphErrors *) f->Get(key);
        f->Close();


	// Create a new graph with channel 5 data
	TGraphErrors *grDataSubAnaCh;
	int h = anaChannel;
	grDataSubAnaCh = (TGraphErrors *) grDataSubList->At(h);

	TGraphErrors *grDataSubFix = grDataSubAnaCh->Clone();
	TGraphErrors *grRes = new TGraphErrors(DOMINO_NCELL);
	TList *grResPeriodList = new TList();



	Double_t xtemp, ytemp, DominoMax, DominoMin;

	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		// get domino-output point and save in array
		grDataSubAnaCh->GetPoint(ch, DominoXval[ch], DominoYval[ch]);
	}

	// find the domino point with max y-value
	iMax = 0;
	for(int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] > DominoYval[iMax]) {
			DominoMax = DominoYval[ch];
			iMax = ch;
		}
	}

	cout << "DominoMax e': " << DominoMax << endl;

	// find the domino point with min y-value
	iMin = 0;
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] < DominoYval[iMin]) {
			DominoMin = DominoYval[ch];
			iMin = ch;
		}
	}

	cout << "DominoMin e': " << DominoMin << endl;

	// remove points from the graph that will be used for fit
	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		grDataSubFix->GetPoint(ch, xtemp, ytemp);
		if(ytemp > 0.8*DominoMax || ytemp < 0.2*DominoMin)
			grDataSubFix->RemovePoint(ch);
	}


	TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
	fsin->SetParameters(600., DOMINO_NCELL / 4., 150., 150.);
	fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	grDataSubFix->Fit("fsin");
	TF1 *fsinFit = grDataSubFix->GetFunction("fsin");
	fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	chisquare = grDataSub->Chisquare(fsinFit);
	cout << "il chi quadro della funzione di fit e' : " << chisquare << endl;

	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		// get Fit-value and save in array
		FitXval[ch] = DominoXval[ch];
		FitYval[ch] = fsinFit->Eval(FitXval[ch]);
	}

	fitPeriod = fsinFit->GetParameter("Period");
	cout << "il periodo della funzione e': " << fitPeriod << endl;

	nPeriods = (Int_t) (DOMINO_NCELL/fitPeriod);
	cout << "il numero di periodi della funzione e': " << nPeriods << endl;

	fitMax = fsinFit->GetMaximum();
	cout << "il massimo della funzione e': " << fitMax << endl;

	fitMin = fsinFit->GetMinimum();
	cout << "il minimo della funzione e': " << fitMin << endl;




	// computes the y difference between the ch-domino point and the i-fit point
	// and stops when the difference changes sign
	//
	// first and last points are not included in the cicle
	//
	// if the fit point y-value is bigger or smaller than the fit function max*0.8 or min*0.2
	// the point is removed

	for (int ch = 1; ch < DOMINO_NCELL - 1; ch++) {

		if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
			grRes->RemovePoint(ch);
			continue;
		}

		incDiff = DominoYval[ch] - FitYval[ch];
		incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

		decDiff = DominoYval[ch] - FitYval[ch];
		decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

		if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
			for (int i = ch; i < DOMINO_NCELL; i++, incDiff = incDiffTemp) {
				incDiffTemp = DominoYval[ch] - FitYval[i];

				if (sign(incDiff) != sign(incDiffTemp)) {
					if(abs(incDiffTemp) < abs(incDiff))
						incCht = i;
					else
						incCht = i - 1;
					break;
				}
			}
			xflag = 1;
		}
		else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
			for (int j = ch; j >= 0 ; j--, decDiff = decDiffTemp) {
				decDiffTemp = DominoYval[ch] - FitYval[j];

				if (sign(decDiff) != sign(decDiffTemp)) {
					if(abs(decDiffTemp) < abs(decDiff))
						decCht = j;
					else
						decCht = j + 1;
					break;
				}
			}
			xflag = -1;
		}

		if(xflag == 1)
			xdiff = FitXval[incCht] - DominoXval[ch];
		else
			xdiff = FitXval[decCht] - DominoXval[ch];

		grRes->SetPoint(ch, (Double_t) ch, xdiff);
	}

	cout << "Draw Time Residuals" << endl;
	TString Title = "Time Residuals";
	TCanvas *timeres = new TCanvas("timeres", Title, 1200, 780);
	grRes->SetMarkerStyle(20);
	grRes->SetMarkerSize(0.3);
	grRes->GetYaxis()->SetLabelSize(0.12);
	grRes->GetXaxis()->SetLabelSize(0.12);
	grRes->Draw("APE");


	// The previous graph is now split in N graphs, where N is the number of fit periods

	// this will be needed to set the function phase
	//
    //    iMax = 0;
	//
    //    for(ch = 0; ch < fitPeriod - 1; ch++) {
    //            if(FitYval[ch] > FitYval[iMax]) iMax = ch;
    //    }

	cout << "il primo massimo ha l'indice : " << iMax << endl;

	for (i = 0; i < nPeriods; i++) {
		TGraphErrors *grResPeriod = new TGraphErrors((Int_t) fitPeriod);
		grResPeriodList->Add(grResPeriod);

		for(ch = i*fitPeriod + 1; ch < fitPeriod + (i*fitPeriod); ch++) {

			if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
				grResPeriod->RemovePoint(ch);
				continue;
			}

			incDiff = DominoYval[ch] - FitYval[ch];
			incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

			decDiff = DominoYval[ch] - FitYval[ch];
			decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

			if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
				for (int k = ch; k < k*fitPeriod + fitPeriod; k++, incDiff = incDiffTemp) {
					incDiffTemp = DominoYval[ch] - FitYval[k];

					if (sign(incDiff) != sign(incDiffTemp)) {
						if(abs(incDiffTemp) < abs(incDiff))
							incCht = k;
						else
							incCht = k - 1;
						break;
					}
				}
				xflag = 1;
			}
			else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
				for (int j = ch; j > i*fitPeriod; j--, decDiff = decDiffTemp) {
					decDiffTemp = DominoYval[ch] - FitYval[j];

					if (sign(decDiff) != sign(decDiffTemp)) {
						if(abs(decDiffTemp) < abs(decDiff))
							decCht = j;
						else
							decCht = j + 1;
						break;
					}
				}
				xflag = -1;
			}

			if(xflag == 1)
				xdiff = FitXval[incCht] - DominoXval[ch];
			else
				xdiff = FitXval[decCht] - DominoXval[ch];

			grResPeriod->SetPoint(ch - i*fitPeriod, (Double_t) (ch - i*fitPeriod), xdiff);
		}
	}

	TCanvas *timeresperiod = new TCanvas("timeresperiod", "Time Residuals Period", 1200, 780);
	for(i = 0; i < nPeriods; i++) {
		grResPeriod = ((TGraphErrors *) grResPeriodList->At(i));
		grResPeriod->SetMarkerStyle(20);
		grResPeriod->SetMarkerSize(0.3);
		grResPeriod->GetYaxis()->SetLabelSize(0.12);
		grResPeriod->GetXaxis()->SetLabelSize(0.12);
		grResPeriod->Draw("APEsame");
	}

	cout << "Draw Data - Pedestals Subtracted" << endl;
	TString Title = "Average Charge - Pedestal subtracted";
	TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
	grDataSubAnaCh->SetMarkerStyle(20);
	grDataSubAnaCh->SetMarkerSize(0.3);
	grDataSubAnaCh->GetYaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->GetXaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->Draw("APE");
	fsinFit->Draw("same");
	 */
	// draw extra graphs
	if (DrawExtraGraphs == 1) {
		cout << " ----- DRAW Results ------" << endl;
		//================ DRAW Results ==================

		TCanvas *c = new TCanvas("ctmp", "test", 800, 800);
		c->Divide(3, 3);
		for (int pad = 1; pad < 10; pad++) {
			c->cd(pad);
			((TH1 *) hCellList->At(pad * 512 + 219))->DrawCopy();
			hCellSub = (TH1F *) hCellSubList->At(pad * 512 + 219);
			hCellSub->SetLineColor(2);
			hCellSub->DrawCopy("same");
		}

		cout << "Draw RMS distributions" << endl;
		TString Title = "RMS distributions per channel";
		TCanvas *c4 = new TCanvas("c4", Title, 700, 700);
		c4->Divide(3, 3);
		for (int i = 0; i < DOMINO_NCH; i++) {
			c4->cd(i + 2);
			hRMSdist = (TH1F *) hRMSList->At(i);
			hRMSFitdist = (TH1F *) hRMSFitList->At(i);
			hRMSFitdist->SetLineColor(2);
			hRMSFitdist->DrawCopy();
			hRMSdist->DrawCopy("same");
		}


		TList *grDataCh0SubList = new TList();
		TGraphErrors *grDataCh0Sub;
		for(h = 0; h< DOMINO_NCELL; h++) {
			grDataCh0Sub = new TGraphErrors(DOMINO_NCELL);
			grDataCh0SubList->Add(grDataCh0Sub);
		}

		TGraphErrors *grDataSubCh0 = (TGraphErrors *) grDataSubList->At(6);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSubCh0->GetPoint(ch, x1, y1);
				grDataSub->GetPoint(ch, x2, y2);
				grDataCh0Sub->SetPoint(ch, x1 , y2 - y1);
			}
		}

		TCanvas *cDataCH0Sub = new TCanvas("cDataCH0Sub","cDataCH0Sub", 1000,1000);
		cDataCH0Sub->Divide(1,8);
		for(h = 0; h < DOMINO_NCH; h++) {
			cDataCH0Sub->cd(h+1);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			grDataCh0Sub->GetYaxis()->SetLabelSize(0.12);
			grDataCh0Sub->GetXaxis()->SetLabelSize(0.12);
			grDataCh0Sub->Draw("APEL");
		}



		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1000, 1000);
		csubdata->Divide(3,3);

		for(h = 0; h < DOMINO_NCH; h++) {
			csubdata->cd(h+1);
			TString title = "DataSub channel ";
			title += h;
			TH1F *hCellDataSub = new TH1F(title, title, 100, -20, 20);
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellDataSub->Fill(y);
			}
			hCellDataSub->Fit("gaus", "Q");
			hCellDataSub->GetXaxis()->SetTitle("ADC Counts");
			hCellDataSub->GetFunction("gaus")->SetLineColor(4);
			hCellDataSub->DrawCopy();
		}

		cout << "breakpoint" << endl;
		TCanvas *csubdata2 = new TCanvas("csubdata2", "DataSub for every channel", 1000, 1000);
		TString title = "DataSub every channel ";
		TH1F *hCellChDataSubTot = new TH1F(title, title, 100, -20, 20);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellChDataSubTot->Fill(y);
			}
			hCellChDataSubTot->Fit("gaus", "Q");
			hCellChDataSubTot->GetXaxis()->SetTitle("ADC Counts");
			hCellChDataSubTot->GetFunction("gaus")->SetLineColor(4);
			hCellChDataSubTot->Draw();
		}

		cout << "Draw Pedestals" << endl;
		TString Title = "Pedestals";
		TCanvas *c2 = new TCanvas("c2", Title, 1050, 780);
		c2->SetBorderMode(0);
		c2->SetBorderSize(0.);
		c2->Divide(1, 8);
		//    gStyle->SetCanvasBorderMode(0.);
		//    gStyle->SetCanvasBorderSize(0.);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			c2->cd(h + 1);
			grPed = ((TGraphErrors *) grPedList->At(h));
			grPed->SetMarkerStyle(20);
			grPed->SetMarkerSize(0.5);
			grPed->GetYaxis()->SetLabelSize(0.12);
			grPed->GetXaxis()->SetLabelSize(0.12);
			//        cout <<  " err:" << grPed->GetErrorY(102) << " " ;
			//        cout << x << "--" << y << endl;
			grPed->Draw("APE");
		}

		cout << "Draw Data - Average charge" << endl;
		TString Title = "Average_Charge";
		TCanvas *cdata = new TCanvas("cdata", Title, 1050, 780);
		cdata->Divide(1, 8);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			cdata->cd(h + 1);
			grData = ((TGraphErrors *) grDataList->At(h));
			grData->SetMarkerStyle(20);
			grData->SetMarkerSize(0.3);
			grData->GetYaxis()->SetLabelSize(0.12);
			grData->GetXaxis()->SetLabelSize(0.12);
			grData->GetPoint(10, x, y);
			//        cout << x << "-" << y << endl;
			grData->Draw("APE");
		}

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
		csubdata->Divide(1, 8);
		TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
		TH1D *resDist = new TH1D("resDist", "Residuals Signal", 100, -100., 100.);

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Residuals";
		TCanvas *residuals = new TCanvas("residuals", Title, 1200, 780);
		resDist->DrawCopy();

	}

	fclose(fdata);

	hCellList->Delete();
	hCellSubList->Delete();
	hRMSList->Delete();
	hRMSFitList->Delete();
}
예제 #27
0
파일: Outliers.C 프로젝트: ktf/AliPhysics
void
TestSPD(const TString& which, Double_t nVar=2)
{
  TFile* file = TFile::Open("forward.root", "READ");
  if (!file) return;

  Bool_t spd = which.EqualTo("spd", TString::kIgnoreCase);
  
  TList* l = 0;
  if (spd) l = static_cast<TList*>(file->Get("CentralSums"));
  else     l = static_cast<TList*>(file->Get("ForwardSums"));
  if (!l) { 
    Warning("", "%sSums not found", spd ? "Central" : "Forward");
    return;
  }

  TList* ei = static_cast<TList*>(l->FindObject("fmdEventInspector"));
  if (!l) { 
    Warning("", "fmdEventInspector not found");
    return;
  }
  
  TObject* run = ei->FindObject("runNo");
  if (!run) 
    Warning("", "No run number found");
  ULong_t runNo = run ? run->GetUniqueID() : 0;

  TH2* h = 0;
  if (spd) h = static_cast<TH2*>(l->FindObject("nClusterVsnTracklet"));
  else { 
    TList* den = static_cast<TList*>(l->FindObject("fmdDensityCalculator"));
    if (!den) { 
      Error("", "fmdDensityCalculator not found");
      return;
    }
    TList* rng = static_cast<TList*>(den->FindObject(which));
    if (!rng) { 
      Error("", "%s not found", which.Data());
      return;
    }
    h = static_cast<TH2*>(rng->FindObject("elossVsPoisson"));
  }
  if (!h) { 
    Warning("", "%s not found", spd ? nClusterVsnTracklet : "elossVsPoisson");
    return;
  }

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  TCanvas* c = new TCanvas("c", Form("Run %u", runNo));
  c->Divide(2,2);
  
  TVirtualPad* p = c->cd(1);
  if (spd) {
    p->SetLogx();
    p->SetLogy();
  }
  p->SetLogz();
  h->Draw("colz");

  TObjArray* fits = new TObjArray;
  h->FitSlicesY(0, 1, -1, 0, "QN", fits);

  TF1* mean = new TF1("mean", "pol1");
  TF1* var  = new TF1("var", "pol1");
  // mean->FixParameter(0, 0);
  // var->FixParameter(0, 0);
  for (Int_t i = 0; i < 3; i++) { 
    p = c->cd(2+i);
    if (spd) { 
      p->SetLogx();
      p->SetLogy();
    }
    TH1* hh = static_cast<TH1*>(fits->At(i));
    hh->Draw();

    if (i == 0) continue;
    
    hh->Fit((i == 1? mean : var), "+Q");
    
  }

  TGraphErrors* g1 = new TGraphErrors(h->GetNbinsX());
  g1->SetFillColor(kBlue-10);
  g1->SetFillStyle(3001);
  g1->SetLineStyle(1);
  TGraph* u1 = new TGraph(h->GetNbinsX());
  TGraph* l1 = new TGraph(h->GetNbinsX());
  u1->SetLineColor(kBlue+1);
  l1->SetLineColor(kBlue+1);
  u1->SetName("u1");
  l1->SetName("l1");
  TGraphErrors* g2 = new TGraphErrors(h->GetNbinsX());
  g2->SetFillColor(kRed-10);
  g2->SetFillStyle(3001);
  g2->SetLineStyle(2);
  TGraph* u2 = new TGraph(h->GetNbinsX());
  TGraph* l2 = new TGraph(h->GetNbinsX());
  u2->SetLineColor(kRed+1);
  l2->SetLineColor(kRed+1);
  u2->SetName("u2");
  l2->SetName("l2");
  for (Int_t i = 1; i <= h->GetNbinsX(); i++) {
    Double_t x  = hh->GetXaxis()->GetBinCenter(i);
    Double_t y  = mean->Eval(x);
    Double_t e  = var->Eval(y);
    Double_t e1 = nVar * e;
    if (spd) e1 *= TMath::Log10(e);
    // Printf("%10e -> %10e +/- %10e", x, y, ee);
    g1->SetPoint(i-1, x, y);
    g1->SetPointError(i-1, 0, e1);
    u1->SetPoint(i-1, x, y+e1);
    l1->SetPoint(i-1, x, y-e1);
    // Printf("%3d: %f -> %f +/- %f", i, x, y, ee);

    Double_t e2 = nVar*0.05*x;
    g2->SetPoint(i-1, x, x);
    g2->SetPointError(i-1, 0, e2);
    u2->SetPoint(i-1, x, x+e2);
    l2->SetPoint(i-1, x, x-e2);
  }

  p = c->cd(1);
  c->Clear();
  c->cd();
  c->SetLogz();
  h->Draw("colz");
  g1->Draw("3 same");
  u1->Draw("l same");
  l1->Draw("l same");
  g2->Draw("3 same");
  u2->Draw("l same");
  l2->Draw("l same");

  Double_t ly = 0.9;
  Double_t dy = 0.06;
  TLatex* ltx = new TLatex(0.15, ly, Form("#LTy#GT = %f + %f x",
					   mean->GetParameter(0),
					   mean->GetParameter(1)));
  ltx->SetNDC();
  ltx->SetTextSize(dy);
  ltx->SetTextAlign(13);
  ltx->Draw();

  ly -= dy + 0.01;
  ltx->DrawLatex(0.15, ly, Form("#sigma_{y} = %f + %f x", 
				var->GetParameter(0),
				var->GetParameter(1)));
  
  ly -= dy + 0.01;
  ltx->DrawLatex(0.15, ly, Form("#delta = %f #sigma %s", 
				nVar, (spd ? "log_{10}(#sigma" : "")));
	    
					   
}
예제 #28
0
/*============================================================================*/
void gaus2peakfit(Char_t *s, Float_t x1, Float_t x2, Float_t x3, Float_t x4)
{
  Double_t par[8],epar[8],x[2],y[2];
  TH1 *hist;
  hist = (TH1 *) gROOT->FindObject(s);
  TCanvas *c1=(TCanvas*) gROOT->FindObject("c1");
  if(c1==NULL)setcanvas(1);
  c1->Clear();
  hist->SetAxisRange(x1-30,x4+30);
  hist->Draw();

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

  //--**-- Two Gaussian Peak estimation without background --**--//
  fgaus1 = new TF1("m1","gaus",x1,x2);
  fgaus2 = new TF1("m2","gaus",x3,x4);
  hist->Fit(fgaus1,"R+QN");
  hist->Fit(fgaus2,"R+QN");
  fgaus1->GetParameters(&par[0]);
  fgaus2->GetParameters(&par[3]);

  //--**-- Final Peak Fit with Background --**--//
  func = new TF1("m","gaus(0)+gaus(3)+pol1(6)",x1,x4);
  func->SetParameters(par);

  
  hist->Fit(func,"R+QN");
  func->SetLineWidth(0.5);
  func->SetLineStyle(1);
  func->SetLineColor(4);
  func->SetFillColor(4);
  func->Draw("same");
  func->GetParameters(par);
  epar[0]=func->GetParError(0);
  epar[1]=func->GetParError(1);
  epar[2]=func->GetParError(2);
  epar[3]=func->GetParError(3);
  epar[4]=func->GetParError(4);
  epar[5]=func->GetParError(5);
 
  Double_t fwhm1 = par[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm1 = epar[2]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N10 = par[0]*(TMath::Sqrt(TMath::TwoPi())*par[2]);
  Double_t r10 = epar[0]/par[0];
  Double_t r12 = epar[2]/par[2];
  Double_t eN10= N10*TMath::Sqrt(r10*r10+r12*r12);

  Double_t fwhm2 = par[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t efwhm2 = epar[5]*TMath::Sqrt(8*TMath::Log(2));
  Double_t N20 = par[3]*(TMath::Sqrt(TMath::TwoPi())*par[5]);
  Double_t r20 = epar[3]/par[3];
  Double_t r22 = epar[5]/par[5];
  Double_t eN20= N20*TMath::Sqrt(r20*r20+r22*r22);

  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[1],epar[1],fwhm1,efwhm1,N10,eN10);
  //printf("Peak = %f +- %f; FFHM = %f +- %f; Area = %f +- %f\n",
  //        par[4],epar[4],fwhm2,efwhm2,N20,eN20);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[1],epar[1],N10,eN10);
  printf("%11.4f %11.4f %11.0f %11.0f\n",
          par[4],epar[4],N20,eN20);
}
예제 #29
0
파일: playV0M.C 프로젝트: ktf/AliPhysics
TH2 *
ReturnCorrFromFit(TH2 *hcorr)
{

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

  TObjArray *oa = new TObjArray();
  hcorr->FitSlicesX(0, 0, -1, 0, "QNR", oa);

  TCanvas *cFit = new TCanvas("cFit", "cFit");
  cFit->Divide(2, 2);

  TF1 *fMean = new TF1("fMean", "[0] + [1] * TMath::Power(x, [2])", 1., 100.);
  fMean->SetParameter(0, 0.);
  fMean->SetParameter(1, 1.);
  fMean->SetParameter(2, 1.);
  TH1 *hMean = (TH1 *)oa->At(1);
  hMean->Fit(fMean, "0q", "I", 1., 100.);
  cFit->cd(1)->SetLogx();
  cFit->cd(1)->SetLogy();
  hMean->Draw();
  fMean->Draw("same");

  TF1 *fSigma = new TF1("fSigma", "[0] + [1] * TMath::Power(x, [2])", 1., 100.);
  fSigma->SetParameter(0, 0.);
  fSigma->SetParameter(1, 1.);
  fSigma->SetParameter(2, 0.5);
  TH1 *hSigma = (TH1 *)oa->At(2);
  hSigma->Fit(fSigma, "0q", "", 1., 100.);
  cFit->cd(3)->SetLogx();
  cFit->cd(3)->SetLogy();
  hSigma->Draw();
  fSigma->Draw("same");

  cFit->cd(2)->SetLogx();
  cFit->cd(2)->SetLogy();
  cFit->cd(2)->SetLogz();
  hcorr->Draw("colz");

  TH2 *hcorrfit = (TH2 *)hcorr->Clone("hcorrfit");
  //  hcorrfit->Reset();
  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    Float_t cent = hcorr->GetXaxis()->GetBinCenter(i + 1);
    Float_t mean = fMean->Eval(cent);
    Float_t sigma = fSigma->Eval(cent);
    if (cent < 25 || cent > 100) continue;
    for (Int_t j = 0; j < 10000; j++) {
      Float_t val = gRandom->Gaus(mean, sigma);
      if (val <= 0.) continue;
      hcorrfit->Fill(val, cent);
    }
  }

  cFit->cd(4)->SetLogx();
  cFit->cd(4)->SetLogy();
  cFit->cd(4)->SetLogz();
  hcorrfit->Draw("colz");

  return hcorrfit;
}
예제 #30
0
//
//----------------------------------------------------------------------
//
int fittp0( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){

    cout << hs << " does not exist\n";

  }

  else{
   
    h->SetMarkerStyle(21);
    h->SetMarkerSize(0.8);
    h->SetStats(1);
    gStyle->SetOptFit(101);

    gROOT->ForceStyle();

    double dx = h->GetBinWidth(1);
    double nmax = h->GetBinContent(h->GetMaximumBin());
    double xmax = h->GetBinCenter(h->GetMaximumBin());
    double nn = 7*nmax;

    int nb = h->GetNbinsX();
    double n1 = h->GetBinContent(1);
    double n9 = h->GetBinContent(nb);
    double bg = 0.5*(n1+n9);

    double x1 = h->GetBinCenter(1);
    double x9 = h->GetBinCenter(nb);
    cout << hs << ": " << x1 << " - " << x9 << endl;

    // create a TF1 with the range from x1 to x9 and 5 parameters

    TF1 *tp0Fcn = new TF1( "tp0Fcn", tp0Fit, x1, x9, 5 );

    tp0Fcn->SetParName( 0, "mean" );
    tp0Fcn->SetParName( 1, "sigma" );
    tp0Fcn->SetParName( 2, "nu" );
    tp0Fcn->SetParName( 3, "area" );
    tp0Fcn->SetParName( 4, "BG" );

    tp0Fcn->SetNpx(500);
    tp0Fcn->SetLineWidth(4);
    tp0Fcn->SetLineColor(kMagenta);
    tp0Fcn->SetLineColor(kGreen);
   
    // set start values for some parameters:

    cout << hs << " " << dx << ", " << nn << ", " << xmax << endl;

    tp0Fcn->SetParameter( 0, xmax ); // peak position
    tp0Fcn->SetParameter( 1, 4*dx ); // width
    tp0Fcn->SetParameter( 2, 2.2 ); // nu
    tp0Fcn->SetParameter( 3, nn ); // N
    tp0Fcn->SetParameter( 4, bg );
    
    h->Fit( "tp0Fcn", "R", "ep" );
    // h->Fit("tp0Fcn","V+","ep");

    h->Draw("histepsame");  // data again on top
  }
}