#!/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 nm
import numpy as np
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.flatSimData()))
        exp = np.sqrt(np.asarray(self.flatExpData()))

        # return vector of residuals
        return sim - exp


if __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)
