3## Fitting histograms in Python
5One-dimensional histograms can be
fit in [Python](https:
6To
fit a 1D histogram to one of the
ROOT standard functions (
e.g.
a Gaussian):
10myTH1D =
ROOT.
TH1D(
"th1d",
"Histogram for fitting", 200, 0, 10)
17The list of standard functions in
ROOT can be accessed with the
TROOT::GetListOfFunctions.
18In Python, the standard functions
for TF1 can be printed
as follows:
23#
Print a list of available functions and their definitions
27## Accessing results of the
fit in Python
30documentation
for a list of possible options).
31This will return
a TFitResult which can be examined with the corresponding
TFitResult methods, with the same names in Python
as in
C++.
36# Re-using the
TH1D defined in the earlier example code
37myResult = myTH1D.
Fit(
"gaus",
"s")
39# Get the fitted parameters
as a vector
42# Get the error of the first parameter
47##
Fitting to user-defined functions in Python
481D histograms can also be
fit to any user-defined
function expressed
as a TF1 (see the
TF1 documentation
for examples
on how to do this).
50For example,
a TF1 can be defined and initialized with its
ROOT constructor:
54myTF1 =
ROOT.
TF1(
"myFunction",
"[0] * pow(x, [1])", 0, 10)
60myTH1D =
ROOT.
TH1D(
"th1d",
"My histogram to fit", 200, 0, 10)
62myTH1D.
Fit(
"myFunction")
68def myGaussian(
x, pars):
70 Defines a Gaussian function
72 return pars[0]*
np.
exp(-0.5*
pow(
x[0] - pars[1], 2))
75myTF1 =
ROOT.
TF1(
"myFunction", myGaussian, -5, 5, npar=2, ndim=1)
78myTH1D =
ROOT.
TH1D(
"th1d",
"Test", 200, -5, 5)
82myTH1D.
Fit(
"myFunction")
86The
TH1 class has several additions
for its use from Python, which are also available in its subclasses (
e.
g.,
TH1F,
TH1D).
88### In-Place Multiplication
90TH1 instances support in-place multiplication with
a scalar
value using the `*=` operator:
98# Multiply histogram contents by 2
102This operation is equivalent to calling `
h.Scale(2)`.
104### Filling with NumPy Arrays
106The Fill method has been pythonized to accept NumPy arrays
as input. This allows
for efficient filling of histograms with large datasets:
116data =
np.random.normal(0, 2, 10000)
118# Fill histogram with
data
122weights =
np.ones_like(
data) * 0.5
126The Fill method accepts the following arguments
when used with NumPy arrays:
127- First argument: NumPy array containing the
data to
fill
128- Second argument (optional): NumPy array containing the weights
for each entry
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:
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)"
139The original Fill method functionality is preserved for non-NumPy arguments:
142# Traditional filling still works
143h.Fill(1.0) # Fill single value
144h.Fill(1.0, 2.0) # Fill single value with weight
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.
void SetParameters(TFitEditor::FuncParams_t &pars, TF1 *func)
Restore the parameters from pars into the function.
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(GNN_Data &d, std::string txt="")
Extends the ROOT::Fit::Result class with a TNamed inheritance providing easy possibility for I/O.
1-D histogram with a double per channel (see TH1 documentation)
1-D histogram with a float per channel (see TH1 documentation)
TH1 is the base class of all histogram classes in ROOT.
ROOT top level object description.
RooCmdArg Parameters(const RooArgSet ¶ms)
RVec< PromoteTypes< T0, T1 > > pow(const T0 &x, const RVec< T1 > &v)
RVec< PromoteType< T > > exp(const RVec< T > &v)
h1 FillRandom("gaus", 30000)
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fit(model, train_loader, val_loader, num_epochs, batch_size, optimizer, criterion, save_best, scheduler)
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
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.
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
void Initialize(Bool_t useTMVAStyle=kTRUE)
constexpr Double_t C()
Velocity of light in .