Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
_th1.pyzdoc
Go to the documentation of this file.
2
3## Fitting histograms in Python
4
5One-dimensional histograms can be fit in [Python](https://root.cern/manual/python) with a similar syntax as in C++.
6To fit a 1D histogram to one of the ROOT standard functions (e.g. a Gaussian):
7
8\code{.py}
9# Create and initialize a test histogram to fit
10myTH1D = ROOT.TH1D("th1d", "Histogram for fitting", 200, 0, 10)
11myTH1D.FillRandom("gaus", 1000)
12
14myTH1D.Fit("gaus")
16
17The list of standard functions in ROOT can be accessed with the TROOT::GetListOfFunctions.
19
20\code{.py}
21ROOT.TF1.InitStandardFunctions()
22
24ROOT.gROOT.GetListOfFunctions().Print()
26
27## Accessing results of the fit in Python
28
30documentation for a list of possible options).
32
34
35\code{.py}
37myResult = myTH1D.Fit("gaus", "s")
38
39# Get the fitted parameters as a vector
41
42# Get the error of the first parameter
43myResult.ParError(0)
45
46
47## Fitting to user-defined functions in Python
49
51
52\code{.py}
53# Define the function, e.g. a polynomial with two parameters: y(x) = a * x^b
54myTF1 = ROOT.TF1("myFunction", "[0] * pow(x, [1])", 0, 10)
55
56# Set parameters
57myTF1.SetParameters(10.0, 4.0)
58
59# Initialize a test histogram to fit, and fit it
60myTH1D = ROOT.TH1D("th1d", "My histogram to fit", 200, 0, 10)
61myTH1D.FillRandom("myFunction", 1000)
62myTH1D.Fit("myFunction")
64
66
67\code{.py}
68def myGaussian(x, pars):
69 '''
70 Defines a Gaussian function
71 '''
72 return pars[0]*np.exp(-0.5* pow(x[0] - pars[1], 2))
73
74# Initialize from the Python function with the range -5 to +5, with two parameters to fit, and a one-dimensional input x
75myTF1 = ROOT.TF1("myFunction", myGaussian, -5, 5, npar=2, ndim=1)
76
77# Create a 1D histogram and initialize it with the built-in ROOT Gaussian "gaus"
78myTH1D = ROOT.TH1D("th1d", "Test", 200, -5, 5)
79myTH1D.FillRandom("gaus", 1000)
80
82myTH1D.Fit("myFunction")
84
85## Pythonizations
87
89
91
92\code{.py}
93import ROOT
94
95h = ROOT.TH1D("h", "h", 100, -10, 10)
96h.FillRandom("gaus", 1000)
97
98# Multiply histogram contents by 2
99h *= 2
100\endcode
101
102This operation is equivalent to calling `h.Scale(2)`.
103
105
107
108\code{.py}
109import ROOT
110import numpy as np
111
112# Create a histogram
113h = ROOT.TH1D("h", "h", 100, -10, 10)
114
115# Create sample data
116data = np.random.normal(0, 2, 10000)
117
118# Fill histogram with data
119h.Fill(data)
120
121# Fill with weights
122weights = np.ones_like(data) * 0.5
123h.Fill(data, weights)
124\endcode
125
127- First fill
128- Second argument (optional): NumPy array containing the weights for each entry
129
130<em>Please note</em> that when providing weights, the length of the weights array must match the length of the data array. If weights are not provided, all entries will have a weight of 1. A ValueError will be raised if the lengths don't match:
131
132\code{.py}
133# This will raise ValueError
134data = np.array([1.0, 2.0, 3.0])
135weights = np.array([0.5, 1.0]) # Wrong length!
136h.Fill(data, weights) # Raises ValueError: "Length mismatch: data length (3) != weights length (2)"
137\endcode
138
139The original Fill method functionality is preserved for non-NumPy arguments:
140
141\code{.py}
142# Traditional filling still works
143h.Fill(1.0) # Fill single value
144h.Fill(1.0, 2.0) # Fill single value with weight
145\endcode
146
147## Further Python fitting examples
148Further examples can be found in the tutorials:
149- [combinedFit.py](combinedFit_8py.html) performs a combined (simultaneous) fit of two 1D histograms with separate functions and some common parameters.
150- [fit1.py](fit1_8py.html) reads a `TF1` and 1D histogram (created and saved in an earlier example [fillrandom.py](fillrandom__8py.html)), and fits the histogram.
151- [fitConvolution.py](fitConvolution_8py.html) fits a 1D histogram to a convolution of two functions.
152- [fitNormSum.py](fitNormSum_8py.html) fits a 1D histogram to the normalized sum of two functions (here, a background exponential and a crystal ball function).
153- [multifit.py](multifit_8py.html) fits multiple functions to different ranges of a 1D histogram.
154
155\endpythondoc
#define b(i)
Definition RSha256.hxx:100
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
double Double_t
Definition RtypesCore.h:59
const char Option_t
Definition RtypesCore.h:66
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
void SetParameters(TFitEditor::FuncParams_t &pars, TF1 *func)
Restore the parameters from pars into the function.
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t np
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void on
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void when
void Print(Option_t *option="") const override
#define gROOT
Definition TROOT.h:414
1-Dim function class
Definition TF1.h:234
Extends the ROOT::Fit::Result class with a TNamed inheritance providing easy possibility for I/O.
Definition TFitResult.h:34
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:925
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:877
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:108
ROOT top level object description.
Definition TROOT.h:102
RooCmdArg Parameters(const RooArgSet &params)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
h1 FillRandom("gaus", 30000)
for(Int_t i=0;i< n;i++)
Definition legend1.C:18
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
Definition HFitImpl.cxx:133
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition RExports.h:167
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
TString as(SEXP s)
Definition RExports.h:86
double polynomial(double const *coeffs, int nCoeffs, int lowestOrder, double x)
In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
Definition MathFuncs.h:129
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
Definition Functions.h:282
void Initialize(Bool_t useTMVAStyle=kTRUE)
Definition tmvaglob.cxx:176
constexpr Double_t C()
Velocity of light in .
Definition TMath.h:114