#!/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 lmfit
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()
    <%- if test_mode or figure_mode -%>
    plt.close() # hide plot
    <%- else -%>
    fit_objective.initPlot(10, observer)
    <%- end -%>
    P = lmfit.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)

    result = lmfit.minimize(fit_objective.evaluate_residuals, P)
    print(lmfit.fit_report(result))
    <%- unless test_mode || figure_mode -%>
    ba.showSample3D(model.get_sample(result.params), sample_size=120*nm, seed=0)
    <%- end -%>

    plt.show()
