Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
fitter.C
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file fitter.C
1 #include "TCanvas.h"
2 #include "TH1.h"
3 #include "TF1.h"
4 #include "TRandom.h"
5 #include "TSpectrum.h"
6 #include "TVirtualFitter.h"
7 
8 Int_t npeaks = 30;
9 Double_t fpeaks(Double_t *x, Double_t *par) {
10  Double_t result = par[0] + par[1]*x[0];
11  for (Int_t p=0;p<npeaks;p++) {
12  Double_t norm = par[3*p+2];
13  Double_t mean = par[3*p+3];
14  Double_t sigma = par[3*p+4];
15  result += norm*TMath::Gaus(x[0],mean,sigma);
16  }
17  return result;
18 }
19 void peaks(Int_t np=10) {
20  npeaks = np;
21  // create histogram with x[0,1000] with randomly positioned np peaks each sigma of 4
22  // total number of parameters to fit are 2(linear backgrownd) +3*np
23  TH1F *h = new TH1F("h","test",500,0,1000);
24  //generate n peaks at random
25  Double_t par[3000];
26  par[0] = 0.8;
27  par[1] = -0.6/1000;
28  Int_t p;
29  for (p=0;p<npeaks;p++) {
30  par[3*p+2] = 1;
31  par[3*p+3] = 10+gRandom->Rndm()*980;
32  par[3*p+4] = 3+2*gRandom->Rndm();
33  }
34  TF1 *f = new TF1("f",fpeaks,0,1000,2+3*npeaks);
35  f->SetNpx(1000);
36  f->SetParameters(par);
37  TCanvas *c1 = new TCanvas("c1","c1",10,10,1000,900);
38  c1->Divide(1,2);
39  c1->cd(1);
40  h->FillRandom("f",200000);
41  h->Draw();
42  // now extracting those pareameters from MC generated histogram
43  TH1F *h2 = (TH1F*)h->Clone("h2");
44  //Use TSpectrum to find the peak candidates
45  TSpectrum *s = new TSpectrum(2*npeaks);
46  Int_t nfound = s->Search(h,1,"new");
47  printf("Found %d candidate peaks to fitn",nfound);
48  c1->Update();
49  c1->cd(2);
50 
51  //estimate linear background
52  TF1 *fline = new TF1("fline","pol1",0,1000);
53  h->Fit("fline","qn");
54  //Loop on all found peaks. Eliminate peaks at the background level
55  par[0] = fline->GetParameter(0);
56  par[1] = fline->GetParameter(1);
57  npeaks = 0;
58  Float_t *xpeaks = s->GetPositionX();
59  for (p=0;p<nfound;p++) {
60  Float_t xp = xpeaks[p];
61  Int_t bin = h->GetXaxis()->FindBin(xp);
62  Float_t yp = h->GetBinContent(bin);
63  if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue;
64  par[3*npeaks+2] = yp;
65  par[3*npeaks+3] = xp;
66  par[3*npeaks+4] = 3;
67  npeaks++;
68  }
69 
70  printf("Found %d useful peaks to fitn",npeaks);
71  printf("Now fitting: Be patientn");
72  TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks);
73  TVirtualFitter::Fitter(h2,10+3*npeaks); //we may have more than the default 25 parameters
74  fit->SetParameters(par);
75  fit->SetNpx(1000);
76  h2->Fit("fit");
77 }
78