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