Fitting and Minimization
ROOT provides several interfaces for fitting and numerical minimization, including the Minuit2 minimization library.
This chapter focuses on the application of Minuit2 to scientific parameter estimation problems.
Learning objectives
After completing this chapter, you should be able to:
- Perform standard fits using ROOT.
- Use the Minuit2 minimization algorithms.
- Estimate parameter uncertainties.
- Interpret covariance and correlation matrices.
- Evaluate convergence and goodness of fit.
Mathematical functions in ROOT
ROOT provides the TF1 class for
representing one-dimensional mathematical
functions.
#include <TF1.h>
Predefined functions
ROOT provides several predefined mathematical expressions.
| Expression | Function |
|---|---|
"gaus" |
Gaussian function |
"expo" |
Exponential function |
"pol0" |
Constant function |
"pol1" |
Linear polynomial |
"pol2" |
Quadratic polynomial |
For example:
TF1 f("f", "gaus", -5.0, 5.0);
User-defined expressions
A mathematical expression can contain free parameters denoted by square brackets.
TF1 f("f", "[0]*x + [1]", 0.0, 10.0);
User-defined C++ functions
More complicated mathematical models can be implemented using C++ functions.
#include <cmath>
double model(double* x, double* par)
{
double amplitude = par[0];
double lambda = par[1];
return amplitude * std::exp(
-lambda * x[0]
);
}
The function can then be passed to
the TF1 constructor:
TF1 f("f", model, 0.0, 10.0, 2);
The final argument specifies the number of model parameters.
Configuring parameters
f.SetParameter(0, 100.0);
f.SetParameter(1, 0.5);
Multiple parameters can also be initialized simultaneously:
f.SetParameters(100.0, 0.5);
Parameter names improve the readability of fit results.
f.SetParNames("Amplitude", "Lambda");
Parameter constraints
A parameter can be restricted to a specified interval.
f.SetParLimits(1, 0.001, 10.0);
A parameter can also be fixed:
f.FixParameter(1, 0.5);
To release a fixed parameter:
f.ReleaseParameter(1);
Standard fitting in ROOT
ROOT provides convenient fitting interfaces for histograms and graphs.
For example:
h.Fit("gaus");
This fits a predefined Gaussian function to a histogram.
A user-defined function can also be supplied:
TF1 f("f", "[0]*exp(-[1]*x)", 0, 10);
f.SetParameters(100, 0.5);
h.Fit(&f, "R");
The "R" option restricts the fit
to the range specified by the
function.
Common fitting options
| Option | Description |
|---|---|
"R" |
Use the function range |
"S" |
Return the complete fit result |
"Q" |
Reduce printed output |
"V" |
Increase printed output |
"L" |
Use likelihood fitting for histograms |
"WL" |
Weighted likelihood fitting for histograms |
"I" |
Use the function integral over histogram bins |
"E" |
Request improved parameter errors using MINOS |
Options can be combined:
h.Fit(&f, "RSQ");
Histogram fitting conventions
By default, histogram fitting evaluates the model at bin centers.
The "I" option uses the function
integral divided by the bin volume
instead of the bin-center value.
Ensure that the normalization and units of the fitted function are consistent with the histogram bin contents.
Accessing fit results
#include <TFitResult.h> // Provides access to detailed fit results
#include <TFitResultPtr.h> // Provides a smart pointer-like wrapper for fit results
TFitResultPtr result = h.Fit(&f, "RS");
// Retrieve the fit status code through implicit conversion to int
int status = result;
// Check whether the fit succeeded, the result exists and is valid
if (status == 0 && result.Get() && result->IsValid())
{
// Retrieve the fitted value of the first parameter
double parameter = result->Parameter(0);
// Retrieve the estimated uncertainty of the first parameter
double uncertainty = result->ParError(0);
// Retrieve the chi-squared value of the fit
double chi2 = result->Chi2();
// Retrieve the number of degrees of freedom
int ndf = result->Ndf();
}
The fitted parameters can also be obtained directly from the function:
double amplitude = f.GetParameter(0);
double error = f.GetParError(0);
Introduction to Minuit2
Fitting is a statistical parameter estimation problem. Minimization is a mathematical optimization problem. A fitting problem can often be formulated as a minimization problem. The objective of fitting is to determine the parameter values for which the model provides the best description of the observations, according to a specified statistical criterion. A typical objective function has the form \(F(\theta_1,\theta_2,\ldots,\theta_M).\)
Minuit2 is a numerical minimization and uncertainty estimation library included in ROOT.
It attempts to determine:
- The location of a minimum.
- The value of the objective function at the minimum.
- Parameter uncertainties.
- Parameter correlations.
- Numerical convergence information.
Minuit2 is particularly useful when the statistical problem cannot be conveniently expressed using ROOT's standard fitting interfaces.
Minuit2 interfaces
ROOT provides two important ways of accessing Minuit2.
Generic minimizer interface
ROOT::Math::Minimizer
This interface provides a common framework for different numerical minimization libraries. Minuit2 can be selected using the corresponding factory method.
Native Minuit2 interface
ROOT::Minuit2
This namespace contains the underlying Minuit2 classes.
Minuit2 algorithms
Minuit2 provides several algorithms for minimization and uncertainty estimation. MIGRAD and SIMPLEX attempt to locate a minimum. HESSE and MINOS investigate the properties of the objective function around an estimated minimum.
| Algorithm | Purpose |
|---|---|
| MIGRAD | Gradient-based local minimization |
| SIMPLEX | Derivative-free local minimization |
| MINIMIZE | Combined minimization strategy |
| SCAN | Parameter scanning |
| HESSE | Local covariance estimation |
| MINOS | Profile-based parameter uncertainty estimation |
When to use MIGRAD
MIGRAD is generally an appropriate first choice for smooth objective functions. It may become unreliable when the objective function is discontinuous, numerically noisy or poorly scaled.
Using the generic minimizer interface
The following headers provide access to ROOT's generic minimization framework:
#include <Math/Factory.h>
#include <Math/Minimizer.h>
#include <Math/Functor.h>
Creating a minimizer
ROOT::Math::Minimizer* minimizer =
ROOT::Math::Factory::CreateMinimizer(
"Minuit2",
"Migrad"
);
The first argument selects the minimization library. The second argument selects the minimization algorithm. The factory method returns a pointer to a dynamically allocated minimizer. The caller is responsible for managing its lifetime.
A modern C++ implementation can use a smart pointer:
#include <memory>
std::unique_ptr<ROOT::Math::Minimizer> minimizer(
ROOT::Math::Factory::CreateMinimizer(
"Minuit2",
"Migrad"
)
);
Check whether the minimizer was successfully created:
if (!minimizer)
{
std::cerr << "Cannot create minimizer\n";
return;
}
Configuring the minimizer
minimizer->SetMaxFunctionCalls(100000);
minimizer->SetMaxIterations(10000);
minimizer->SetTolerance(0.001);
minimizer->SetPrintLevel(1);
| Method | Description |
|---|---|
SetMaxFunctionCalls() |
Maximum number of objective function evaluations |
SetMaxIterations() |
Requested maximum number of iterations |
SetTolerance() |
Algorithm-dependent convergence tolerance |
SetPrintLevel() |
Amount of printed information |
SetStrategy() |
Balance between numerical reliability and computational cost |
SetErrorDef() |
Objective function increase defining parameter errors |
Configuration parameters
Not every minimization algorithm uses all configuration parameters in the same way. In particular, the function-call limit is an important stopping condition for Minuit2.
Defining the objective function
The objective function passed to the generic minimizer must return a scalar value.
double objective(const double* par)
{
double a = par[0];
double b = par[1];
return
(a - 3.0) * (a - 3.0)
+
(b + 2.0) * (b + 2.0);
}
Each time the minimizer evaluates the function, a potentially different parameter vector is supplied.
Wrapping the objective function
ROOT provides the ROOT::Math::Functor
class for wrapping callable C++
objects.
ROOT::Math::Functor function(
&objective,
2
);
The second argument specifies the number of independent parameters. The wrapped function can then be assigned to the minimizer:
minimizer->SetFunction(function);
Objective function versus model function
A model function evaluates a physical prediction at a specified coordinate. An objective function evaluates the agreement between the model and the entire dataset. The minimizer receives the objective function, not necessarily the physical model itself.
Defining minimization parameters
Each free parameter must be registered with the minimizer.
minimizer->SetVariable(0, "a", 0.0, 0.1);
The arguments specify:
| Argument | Meaning |
|---|---|
0 |
Parameter index |
"a" |
Parameter name |
0.0 |
Initial parameter value |
0.1 |
Initial step size |
Initial values determine the starting point of the minimization. For complicated objective functions, different initial values may lead to different local minima. Initial values should therefore be chosen using physical knowledge, exploratory analysis or preliminary parameter estimates.
The step size provides an initial estimate of the numerical scale associated with a parameter. It is not a fixed increment used throughout the minimization. The algorithm adapts its numerical steps during optimization. The step size is also not necessarily the final statistical uncertainty of the parameter.
Parameter scaling
Choose initial step sizes that reflect the characteristic scales of the corresponding parameters.
Limited parameters
Parameters can be restricted to a finite interval. The final two arguments specify the lower and upper limits.
minimizer->SetLimitedVariable(0, "Amplitude", 100.0, 1.0, 0.0,1000.0);
One-sided limits
minimizer->SetLowerLimitedVariable(1, "Sigma", 1.0, 0.01, 0.0);
An upper limit can be specified
using SetUpperLimitedVariable().
Fixed parameters
minimizer->SetFixedVariable(2, "Background", 5.0);
Fixed parameters remain part of the objective function but are not varied during minimization.
Parameter boundaries
Parameter limits should preferably follow from physical or mathematical constraints. Artificially narrow limits may prevent the algorithm from locating the actual minimum. Uncertainty estimation also becomes more complicated when a fitted parameter lies near a boundary.
Executing the minimization
After configuring the objective function and its parameters, the minimization can be started:
bool success = minimizer->Minimize();
The returned Boolean value indicates whether the minimizer reports a successful minimization. Additional information should be obtained using the minimizer status:
int status = minimizer->Status();
The fitted parameter values are returned by
const double* parameters = minimizer->X();
The minimum objective function value is obtained using
double minimum = minimizer->MinValue();
Parameter uncertainties can be also obtained by using
const double* errors = minimizer->Errors();
These returned pointers refer to data managed by the minimizer. They should not be deleted independently. Copy the values if they are required after the minimizer is destroyed or reconfigured.
Error definition
Minuit2 uses an error definition,
traditionally denoted by UP,
to determine the increase of the
objective function associated with
parameter uncertainties.
| Objective function | Conventional error definition |
|---|---|
| \(\chi^2\) | 1.0 |
| \(-\ln\mathcal{L}\) | 0.5 |
| \(-2\ln\mathcal{L}\) | 1.0 |
For chi-squared fitting:
minimizer->SetErrorDef(1.0);
For negative log-likelihood fitting:
minimizer->SetErrorDef(0.5);
Incorrect error definition
Using an incorrect error definition can produce incorrect parameter uncertainties even when the location of the minimum is correct. Always ensure that the error definition corresponds to the normalization of the objective function.
Confidence level
These conventional values correspond to approximately 68.3% intervals for one parameter of interest under the usual regularity assumptions. Joint confidence regions involving multiple parameters require different objective function thresholds.
HESSE
HESSE estimates the covariance matrix by numerically investigating the local second-order derivatives of the objective function. The Hessian is evaluated near the estimated minimum:
Near the minimum,
In the local quadratic approximation, the parameter covariance matrix is
For a chi-squared objective function,
For a negative log-likelihood,
The parameter uncertainties are obtained from the diagonal elements:
Executing HESSE
bool success = minimizer->Hesse();
After executing HESSE, the updated parameter uncertainties can be obtained using
const double* errors = minimizer->Errors();
MIGRAD and HESSE
MIGRAD maintains an approximation to the local curvature matrix during minimization.
HESSE performs a dedicated numerical calculation of the local Hessian to improve covariance estimation.
Limitations of HESSE
HESSE relies on the local quadratic approximation.
Its symmetric uncertainty estimates may be inappropriate for strongly asymmetric objective functions, poorly constrained parameters or parameters close to boundaries.
Covariance and correlation matrices
For a model with two parameters, the covariance matrix has the form
The diagonal elements represent the parameter variances. The off-diagonal elements describe the statistical dependence between the parameter estimates.
Accessing covariance elements
double covariance =
minimizer->CovMatrix(0, 1);
Correlation coefficients
The correlation coefficient between parameters \(i\) and \(j\) is defined as
In ROOT:
double correlation =
minimizer->Correlation(0, 1);
MINOS
MINOS provides parameter uncertainty estimates without requiring the objective function to be locally symmetric. Instead of relying exclusively on the Hessian matrix, MINOS investigates the shape of the objective function by profiling the remaining parameters.
Profile objective function
Suppose that the objective function depends on two parameters:
The profile objective function for parameter \(a\) is defined as
For every investigated value of \(a\), the remaining parameter \(b\) is reoptimized. The uncertainty boundaries are determined from
The resulting uncertainties may be asymmetric:
Executing MINOS
double lowerError = 0.0;
double upperError = 0.0;
bool success = minimizer->GetMinosError(
0,
lowerError,
upperError
);
The first argument specifies the parameter index. The lower error is conventionally returned as a negative displacement.
HESSE versus MINOS
| HESSE | MINOS |
|---|---|
| Uses local curvature | Profiles the objective function |
| Usually symmetric uncertainties | Allows asymmetric uncertainties |
| Generally computationally cheaper | Generally computationally more expensive |
| Relies on quadratic approximation | Investigates departures from quadratic behavior |
Choosing an uncertainty method
HESSE is often sufficient for well-constrained parameters with approximately quadratic objective functions. MINOS is useful when the objective function is asymmetric or the parameters are strongly correlated. Neither method guarantees correct confidence interval coverage for every statistical problem.
Convergence diagnostics
A minimization result should not be accepted solely because parameter values have been returned. Several numerical diagnostics should be investigated.
Minimizer status
int status = minimizer->Status();
A status of zero generally indicates successful minimization. Nonzero status values indicate warnings or failures. The precise interpretation depends on the selected minimizer and the operations that have been performed.
Estimated distance to minimum
Minuit2 uses the Estimated Distance to Minimum, abbreviated as EDM. EDM estimates how much the objective function could still decrease according to its local numerical approximation. A small EDM indicates that the current point is estimated to be close to a local minimum.
A simplified quadratic interpretation is
In ROOT:
double edm = minimizer->Edm();
EDM is not parameter distance
EDM estimates a remaining decrease in the objective function. It is not the Euclidean distance between the current parameter vector and the optimal parameter vector.
Number of function evaluations
unsigned int calls = minimizer->NCalls();
A large number of function evaluations may indicate:
- Poor initial parameter values.
- Strong parameter correlations.
- Inappropriate parameter scaling.
- Numerical noise.
- A complicated objective function.
Covariance matrix status
int covarianceStatus =
minimizer->CovMatrixStatus();
For the Minuit2 interface, the usual covariance status convention is:
| Status | Meaning |
|---|---|
-1 |
Covariance matrix unavailable |
0 |
Covariance matrix not calculated |
1 |
Approximate covariance matrix |
2 |
Covariance matrix forced positive definite |
3 |
Accurate covariance matrix |
Strategy
The strategy controls the balance between computational cost and numerical reliability.
minimizer->SetStrategy(1);
| Strategy | General interpretation |
|---|---|
0 |
Reduced computational effort |
1 |
Default compromise |
2 |
More thorough numerical investigation |
Increasing the strategy may improve the numerical treatment of difficult objective functions, but does not guarantee convergence.
Goodness of fit
Numerical convergence and statistical goodness of fit are different concepts. A minimizer may successfully locate the minimum of an objective function even when the model provides a poor description of the observations.
Degrees of freedom
For a conventional chi-squared fit with \(N\) independent observations and \(M\) freely estimated parameters,
The quantity \(\nu\) represents the number of degrees of freedom. This expression assumes a regular fitting problem without additional complications such as rank deficiency or parameter-dependent constraints.
Reduced chi-squared
The reduced chi-squared statistic is defined as
Under the usual statistical assumptions, its expected value is approximately one.
| Reduced chi-squared | Possible interpretation |
|---|---|
| \(\chi^2_{\mathrm{red}}\approx1\) | Agreement with the assumed statistical model |
| \(\chi^2_{\mathrm{red}}\gg1\) | Poor model, underestimated errors or unmodeled effects |
| \(\chi^2_{\mathrm{red}}\ll1\) | Overestimated errors, correlations or statistical fluctuations |
These interpretations are qualitative. The expected statistical variation is
Consequently, reduced chi-squared values may fluctuate substantially for small numbers of degrees of freedom.
p-value
The chi-squared goodness-of-fit p-value is defined as
ROOT provides the corresponding
calculation through TMath::Prob().
#include <TMath.h>
double chi2 = minimizer->MinValue();
double pValue = TMath::Prob(chi2, ndf);
This calculation requires a valid chi-squared statistic and a positive number of degrees of freedom.
Interpretation of the p-value
The p-value is not the probability that the model is correct.
It measures how unusual the observed discrepancy would be under the assumed statistical model.
An arbitrary minimized objective function must not automatically be interpreted as a chi-squared statistic.
Common problems
The minimizer does not converge
Investigate:
- Initial parameter values.
- Parameter step sizes.
- Parameter limits.
- Function-call limits.
- Numerical continuity of the objective function.
- Invalid function evaluations.
Consider starting from several different parameter vectors.
The objective function returns NaN
Check for:
- Division by zero.
- Logarithms of non-positive values.
- Square roots of negative values.
- Numerical overflow.
- Invalid parameter combinations.
Define the valid parameter domain before performing minimization.
The fitted parameters depend on the starting point
The objective function may contain multiple local minima.
Investigate the objective function using parameter scans or repeated minimization from different initial values.
Parameter uncertainties are unexpectedly large
Possible reasons include:
- Insufficient experimental information.
- Strong parameter correlations.
- Redundant model parameters.
- Weak dependence on a parameter.
- An incorrect error definition.
The covariance matrix is not positive definite
The local curvature may be poorly determined.
Investigate parameter degeneracy, numerical precision and whether the minimization reached a valid minimum.
The parameter is located at its limit
The actual minimum may lie outside the allowed parameter interval.
Alternatively, the physical problem may genuinely favor a boundary solution.
Reconsider the parameter constraints and the interpretation of symmetric uncertainties.
The fit converged but the model looks incorrect
Numerical convergence does not imply statistical agreement.
Investigate the residuals, goodness-of-fit statistics and physical assumptions of the model.
Exercises
Exercise 1 — Analytical and numerical minimization
Consider the objective function
Determine its minimum analytically.
Implement the objective function using Minuit2 and compare the numerical and analytical results.
Calculate the Hessian matrix analytically and compare the expected covariance matrix with the HESSE result.
Exercise 2 — Initial parameter dependence
Construct the objective function
Perform minimization using several different initial parameter values.
Investigate whether MIGRAD always converges to the same minimum.
Compare the results with SIMPLEX.
Exercise 3 — Custom chi-squared fitting
Generate measurements from a linear model with Gaussian noise.
Construct a custom chi-squared objective function.
Estimate the model parameters using Minuit2.
Compare the results with
TGraphErrors::Fit().
Exercise 4 — Parameter correlations
Fit a linear model to a dataset whose independent variable lies far from zero.
Investigate the covariance and correlation matrices.
Repeat the fit after centering the independent variable.
Explain the change in the parameter correlation.
Exercise 5 — HESSE and MINOS
Construct a non-quadratic objective function with an asymmetric shape around its minimum.
Estimate the parameter uncertainty using HESSE and MINOS.
Visualize the objective function and the resulting uncertainty intervals.
Explain the differences.