+++
title = "Fitting"
weight = 20
+++

## Overview

In fitting, we estimate the optimum parameters in a numerical model,
specifically a scattering simulation,
by minimizing the difference between simulated and reference data.

BornAgain supports
+ a variety of minimization algorithms;
+ choice of fitting parameters, their properties and correlations;
+ full control over objective function calculations, including the use of different normalizations and assignments of different masks and weights to different areas of the reference data;
+ possibility to fit simultaneously an arbitrary number of data sets.

In the following we will show how to fit using the BornAgain Python API.
## Introductory example

In the following, a very simple example shows how to fit a parametric model to given data.

The model is a specular reflectometry scan,
with a sample consisting of 20 alternating Ti and Ni layers on a Si substrate.
Using this model, synthetic data
have been generated with GenX.
These data are part of the BornAgain sources,
{{% ref-src "testdata/specular/genx_alternating_layers.dat.gz" %}}.
To make them findable by the script,
the environment variable `BA_DATA_DIR` must point
to the `testdata/` directory in your local BornAgain repository.

From the build directory, run as:
```bash
BA_DATA_DIR=../testdata python3 ../auto/Examples/fit/...
```

The fit model is identical to the model used for generating the data.
There is just one fit parameter, namely the thickness of the Ti layers.
The resulting fit is indistinguishable from the data:
{{< figscg src="/img/fit/Specular1Par.png">}}

#### Script

{{< show-ex file="fit/specular/Specular1Par.py" >}}

#### Explanations

The arrays (Python lists) `exp_x`, `exp_y` contain the data to be fitted.

The dictionary `P` contains the fit parameter.

An instance of class `FitObjective` defines the objective function
in terms of data $y(x)$ and fit model $f(x;P)$.
By default, it is a $\chi^2$ function, weighted with the inverse standard deviation.

The function call `initPrint(10)` means that values of $\chi^2$ and of all
fit parameters are printed to the terminal every 10 fit iterations.
To suppress the printing, set the function argument to 0.

Similarly, the function call `initPlot(10, ...)` means that
data and fit are replotted every 10 fit iterations.
In the `PlotterSpecular`,
the argument `pause=0.5` means that after refreshing the plot the program
is put to sleep for 0.5 s.
This enables humans to observe the evolution of the plots in real time.
With `pause=0`, the program executes so fast that one only sees the final plot.

The actual fit is controlled by the external minimizer. In the examples this
is `lmfit.minimize(fit_objective.evaluate_residuals, P)`, where `P` is an
`lmfit.Parameters` object.
