#!/usr/bin/env python3
"""
Minimal working fit examples: finds radius of sphere in Born approximation.
"""
import bornagain as ba
from bornagain import deg, nm


def get_simulation(P):
    """
    Returns GISAS simulation for given set of parameters.
    """
    radius = P["radius"]

    sphere = ba.Particle(ba.RefractiveMaterial("Particle", 6e-4, 2e-8),
                         ba.Sphere(radius))

    layer = ba.Layer(ba.RefractiveMaterial("Vacuum", 0, 0))
    layer.addLayout(ba.ParticleLayout(sphere))
    sample = ba.Sample()
    sample.addLayer(layer)

    n = 100
    beam = ba.Beam(1, 0.1*nm, 0.2*deg)
    detector = ba.SphericalDetector(n, -1*deg, 1*deg, n, 0., 2*deg)
    simulation = ba.ScatteringSimulation(beam, sample, detector)

    return simulation


def fake_data():
    """
    Generating "experimental" data by running simulation with default parameters.
    """
    simulation = get_simulation({'radius': 5 * nm})
    result = simulation.simulate()
    return result


if __name__ == '__main__':
    data = fake_data()
    fit_objective = ba.FitObjective()
    fit_objective.addFitPair(get_simulation, data)
    fit_objective.initPrint(10)

    P = ba.Parameters()
    P.add("radius", 4. * nm, min=0.01)

    minimizer = ba.Minimizer()
    result = minimizer.minimize(fit_objective.evaluate, P)
    fit_objective.finalize(result)
