#!/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.MultiLayer()
    sample.addLayer(layer)

    n = 11
    beam = ba.Beam(1, 0.1*nm, 0.2*deg)
    detector = ba.Detector2D(2*deg, 2*deg, n, n, 0, 1*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)
