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


def get_sample(P):
    """
    Returns sample for given set of parameters.
    """
    radius = P["radius"]

    particle_color = (0.86, 0.24, 0.18)
    particle_mat = ba.RefractiveMaterial("Particle", particle_color, 6e-4, 2e-8)
    particle = ba.Particle(particle_mat, ba.Sphere(radius))

    layer_top = ba.Layer(ba.Vacuum())
    layer_bottom = ba.Layer(ba.Vacuum())
    layer_top.deposit2D(ba.Dilute2D(0.01/nm2, particle))

    sample = ba.Sample()
    sample.addLayer(layer_top)
    sample.addLayer(layer_bottom)

    return sample


def get_simulation(P):
    """
    Returns GISAS simulation for given set of parameters.
    """
    sample = get_sample(P)

    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 = lmfit.Parameters()
    P.add("radius", 4. * nm, min=0.01)

    result = lmfit.minimize(fit_objective.evaluate_residuals, P)
    print(lmfit.fit_report(result))
    ba.showSample3D(get_sample(result.params), sample_size=120*nm, seed=0)
