Debian Codegraph @

hugo/content/ref/fit/ex/external-minimizer-with-plotting.md

raw
1 +++
2 title = "External minimizer: plotting"
3 weight = 40
4 +++
5
6 ## External Minimizers: Plotting Fit Progress
7
8 In this example we are demonstrating how to run a typical fitting task in BornAgain using a third party minimizer while plotting the results. As in our [previous example](/ref/fit/ex/external-minimizer), we use lmfit for sake of illustration.
9
10 To plot the fit progress, it is needed to use the lmfit iteration callback function. It will come handy to define the plotting callback function as a specialized class:
11
12 ```python
13 from bornagain import ba_fitmonitor
14
15 class Plotter:
16 """
17 Adapts standard plotter for lmfit minimizer.
18 """
19 def __init__(self, fit_objective, every_nth = 10):
20 self.fit_objective = fit_objective
21 self.plotter_gisas = ba_fitmonitor.PlotterGISAS()
22 self.every_nth = every_nth
23
24 def __call__(self, params, iteration, resid):
25 if iteration % self.every_nth == 0:
26 self.plotter_gisas.plot(self.fit_objective)
27 ```
28
29 An instance of this class is then passed to the lmfit minimization function:
30
31 ```python
32 plotter = Plotter(fit_objective)
33 result = lmfit.minimize(fit_objective.evaluate_residuals, params, iter_cb=plotter)
34 ```
35 The complete script to plot the fitting progress and the image produced by it are shown below.
36
37
38 {{% figure src="/img/draw/ExternalMinimizerWithPlotting.png" command="Resize" options="450x" caption="Plotting the fitting progress of external minimizers" class="center" %}}
39
40
41
42 {{< show-ex file="fit/scatter2d/lmfit_with_plotting.py" >}}