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.
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).
#!/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.
"""importbornagainasbafrombornagainimportnmimportnumpyasnpimportmodel2_hexlatticeasmodelclassMyObjective(ba.FitObjective):"""
FitObjective extension for custom fitting metric.
"""defevaluate_residuals(self,P):"""
Provides custom calculation of vector of residuals
"""# calling parent's evaluate functions to run simulationssuper().evaluate(P)# accessing simulated and experimental data as flat numpy arrays# applying sqrt to every elementsim=np.sqrt(np.asarray(self.flatSimData()))exp=np.sqrt(np.asarray(self.flatExpData()))# return vector of residualsreturnsim-expif__name__=='__main__':data=model.fake_data()objective=MyObjective()objective.addFitPair(model.get_simulation,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)