External minimizer

In this example we are demonstrating how to run a typical fitting task in BornAgain using a third party minimizer.

The BornAgain fit parameters and minimizer interface were developed with the idea to simplify the switch between our own minimization engines and other, possibly more advanced minimization libraries. Particularly, we have been inspired by the lmfit Python package.

This makes the switch between the BornAgain and lmfit minimizers very easy.

Using the BornAgain default minimizer

import bornagain as ba

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

result = ba.Minimizer().minimize(fit_objective.evaluate_residuals, params)
fit_objective.finalize(result)

Using the lmfit minimizer

import lmfit

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

result = lmfit.minimize(fit_objective.evaluate_residuals, params)
fit_objective.finalize(result)

print(result.params.pretty_print())

The complete script for the lmfit based fitting is shown below.

 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
#!/usr/bin/env python3
"""
External minimize: using lmfit minimizers for BornAgain fits.
"""
import bornagain as ba
from bornagain import ba_plot as bp, nm
import lmfit
from matplotlib import pyplot as plt
import model2_hexlattice as model


if __name__ == '__main__':
    bp.parse_args(sim_n=100)

    real_data = model.create_real_data()

    fit_objective = ba.FitObjective()
    fit_objective.addSimulationAndData(model.get_simulation, real_data, 1)
    fit_objective.initPrint(10)

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

    result = lmfit.minimize(fit_objective.evaluate_residuals, params)
    fit_objective.finalize(result)

    print(result.params.pretty_print())
    print(lmfit.fit_report(result))
Examples/fit/scatter2d/lmfit_basics.py