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 our own MyObjective class at line 14. It is derived from the parent FitObjective class and contains our own definition of the evaluate_residual function. At line 26 we call the parent’s evaluate method to run the simulation and prepare the intensity arrays. At lines 30-34 we calculate the vector of residuals as described above.

Later in the code, the MyObjective.evaluate_residual function is used to setup a custom objective function for the minimizer (line 116).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python3
"""
Using custom objective function to fit GISAS data.

In this example objective function returns vector of residuals computed from
the data and simulation after applying sqrt() to intensity values.
"""
import bornagain as ba
from bornagain import ba_plot as bp, nm
import numpy as np
from matplotlib import pyplot as plt
import model2_hexlattice as model

class MyObjective(ba.FitObjective):
    """
    FitObjective extension for custom fitting metric.
    """

    def evaluate_residuals(self, P):
        """
        Provides custom calculation of vector of residuals
        """
        # calling parent's evaluate functions to run simulations
        super().evaluate(P)

        # accessing simulated and experimental data as flat numpy arrays
        # applying sqrt to every element
        sim = np.sqrt(np.asarray(self.simulation_array()))
        exp = np.sqrt(np.asarray(self.experimental_array()))

        # return vector of residuals
        return sim - exp


if __name__ == '__main__':
    real_data = model.create_real_data()

    objective = MyObjective()
    objective.addSimulationAndData(model.get_simulation, real_data, 1)
    objective.initPrint(10)

    P = ba.Parameters()
    P.add('radius', value=7*nm, min=5*nm, max=8*nm)
    P.add('length', value=10*nm, min=8*nm, max=14*nm)

    minimizer = ba.Minimizer()
    result = minimizer.minimize(objective.evaluate_residuals, P)
    objective.finalize(result)

    plt.show()
auto/Examples/fit/scatter2d/custom_objective_function.py