#!/usr/bin/env python3
"""
Fitting example: looking for background.

Real data contains some "unknown" background.
In the fit we are trying to find cylinder radius and height and background.
"""

from matplotlib import pyplot as plt
import bornagain as ba
from bornagain import nm, ba_fitmonitor
import model1_cylinders as model


def get_simulation(P):
    """
    Create and return GISAXS simulation with beam and detector defined
    """
    background = P["background"]

    simulation = model.get_simulation(P)
    simulation.setBackground(ba.ConstantBackground(background))

    return simulation


def fake_data():
    """
    Generating "real" data by adding noise, background and scale
    to the simulated data.
    Cylinder radius is set to 5nm, cylinder height to 10nm.
    During the fit we will try to find cylinder height and radius and
    scale, background factors.
    """

    P = {
        'radius': 5*nm,
        'height': 10*nm,
        'background': 1000
    }

    simulation = get_simulation(P)
    result = simulation.simulate()

    return result


if __name__ == '__main__':
    data = fake_data()

    fit_objective = ba.FitObjective()
    fit_objective.addFitPair(get_simulation, data, 1)

    fit_objective.initPrint(10)
    observer = ba_fitmonitor.PlotterGISAS()
    fit_objective.initPlot(10, observer)
    P = ba.Parameters()
    P.add("radius", 5.*nm, vary=False)
    P.add("height", 9.*nm, min=8.*nm, max=12.*nm)
    P.add("background", 200, min=100, max=2000, step=100)

    minimizer = ba.Minimizer()
    minimizer.setMinimizer("Minuit2", "Migrad", "MaxFunctionCalls=0")
    result = minimizer.minimize(fit_objective.evaluate, P)
    fit_objective.finalize(result)

    plt.show()
