#!/usr/bin/env python3
"""
This fitting and simulation example demonstrates how to replicate
the fitting example "Magnetically Dead Layers in Spinel Films"
given at the Nist website:
https://www.nist.gov/ncnr/magnetically-dead-layers-spinel-films

For simplicity, here we only reproduce the first part of that
demonstration without the magnetically dead layer.
"""

import os
import numpy
import matplotlib.pyplot as plt
import bornagain as ba
from bornagain import R3, nm
import lmfit

import PolarizedSpinAsymmetry as psa


def get_simulation(q_axis, fitParams, *, polarizer_vec, analyzer_vec):
    """
    Run a simulation on the given q-axis, where the sample is
    constructed with the given parameters.
    Vectors for polarization and analyzer need to be provided
    """
    parameters = dict(fitParams, **fixedParams)

    sample = psa.get_sample(parameters)
    simulation = psa.get_simulation(sample, q_axis, parameters, polarizer_vec,
                                    analyzer_vec)

    return simulation

####################################################################
#                          Main Function                           #
####################################################################

if __name__ == '__main__':

    datadir = os.getenv('BA_DATA_DIR', '')
    if not datadir:
        raise Exception("Environment variable BA_DATA_DIR not set")
    fname_stem = os.path.join(datadir, "specular/MAFO_Saturated_")

    data_pp = psa.load_data(fname_stem + "pp.tab")
    data_mm = psa.load_data(fname_stem + "mm.tab")

    fixedParams = {
        # parameters can be moved here to keep them fixed
    }
    fixedParams = {d: v[0] for d, v in fixedParams.items()}

    startParams = {
        # own starting values
        "q_res": (0, 0, 0.1),
        "q_offset": (0, -0.002, 0.002),
        "rho_Mafo": (6.3649, 2, 7),
        "rhoM_Mafo": (0, 0, 2),
        "t_Mafo": (15, 6, 18),
        "r_Mao": (0.1, 0, 1.2),
        "r_Mafo": (0.1, 0, 1.2),
    }

    PInitial = {d: v[0] for d, v in startParams.items()}

    def get_Simulation_pp(qzs, P):
        return get_simulation(qzs,
                              P,
                              polarizer_vec=R3(0, 1, 0),
                              analyzer_vec=R3(0, 1, 0))

    def get_Simulation_mm(qzs, P):
        return get_simulation(qzs,
                              P,
                              polarizer_vec=R3(0, -1, 0),
                              analyzer_vec=R3(0, -1, 0))

    qzs = numpy.linspace(psa.qmin, psa.qmax, psa.scan_size)
    q_pp, r_pp = psa.qr(get_Simulation_pp(qzs, PInitial).simulate())
    q_mm, r_mm = psa.qr(get_Simulation_mm(qzs, PInitial).simulate())

    color_pp = ['orange','red']
    color_mm = ['green','blue']

    legend_pp = "$++$"
    legend_mm = "$--$"

    psa.plotData([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
             [legend_pp, legend_mm], [color_pp, color_mm])

    psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm)
    data_pp_Xcenters = data_pp.xCenters()
    data_mm_Xcenters = data_mm.xCenters()

    fit_objective = ba.FitObjective()
    fit_objective.setObjectiveMetric("chi2")
    fit_objective.initPrint(10)

    fit_objective.addFitPair(
        lambda P: get_Simulation_pp(data_pp_Xcenters, P), data_pp, 1)
    fit_objective.addFitPair(
        lambda P: get_Simulation_mm(data_mm_Xcenters, P), data_mm, 1)

    P = lmfit.Parameters()
    for name, p in startParams.items():
        P.add(name, p[0], min=p[1], max=p[2])

    result = lmfit.minimize(fit_objective.evaluate_residuals, P)
    print(lmfit.fit_report(result))

    fitResult = {name: result.params[name].value for name in result.params}
    <%- unless test_mode || figure_mode -%>
    sample = psa.get_sample(fitResult | fixedParams)
    ba.showSample3D(sample, sample_size=120*nm, seed=0)
    <%- end -%>

    print("Fit Result:")
    print(fitResult)

    q_pp, r_pp = psa.qr(get_Simulation_pp(qzs, fitResult).simulate())
    q_mm, r_mm = psa.qr(get_Simulation_mm(qzs, fitResult).simulate())

    psa.plotData([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
             [legend_pp, legend_mm], [color_pp, color_mm])
    <%- if test_mode or figure_mode -%>
    <%- else -%>
    plt.draw()
    <%- end -%>

    psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm)
    <%- if test_mode or figure_mode -%>
    <%- else -%>
    plt.draw()
    plt.show()
    <%- end -%>
