Debian Codegraph @

hugo/content/ref/fit/ex/custom-objective-function.md

raw
1 +++
2 title = "Custom objective function"
3 weight = 20
4 +++
5
6 ## Custom objective function
7
8 The BornAgain fitting API allows users to define a custom objective function to for the minimization engine.
9
10 In this example we are going to construct a vector of residuals calculated between the
11 experimental and simulated intensity values after applying an additional $sqrt$ function to the amplitudes.
12
13 $$
14 residuals = [r\_{0}, r_{1}, ... , r\_{n-1}], ~~~ r\_{i} = \sqrt{e\_{i}} - \sqrt{s\_{i}}
15 $$
16
17 The length of vector `n` corresponds to the total number of *non-masked* detector channels.
18
19 This is done by defining a custom residual function `my_residuals`.
20 It calls `fit_objective.evaluate(P)` to run the simulation and
21 store the intensity arrays, then retrieves them via
22 `fit_objective.flatSimData()` and `fit_objective.flatExpData()`
23 and applies `sqrt` before differencing.
24 The custom function is then passed directly to `lmfit.minimize`.
25
26 {{< show-ex file="fit/scatter2d/custom_objective_function.py" >}}