#!/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
from sys import argv
import numpy
import matplotlib.pyplot as plt
import bornagain as ba
from bornagain import deg, angstrom

import PolarizedSpinAsymmetry as psa


def run_simulation(q_axis, fitParams, *, polarizer_dir, analyzer_dir):
    """
    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_dir,
                                    analyzer_dir)

    return simulation.simulate()


####################################################################
#                          Fit Function                            #
####################################################################


def run_fit_ba(q_axis, r_data, r_uncertainty, simulationFactory,
               startParams):

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

    fit_objective.addSimulationAndData(
        lambda P: simulationFactory[0](q_axis[0], P), r_data[0],
        r_uncertainty[0], 1)
    fit_objective.addSimulationAndData(
        lambda P: simulationFactory[1](q_axis[1], P), r_data[1],
        r_uncertainty[1], 1)

    fit_objective.initPrint(10)

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

    minimizer = ba.Minimizer()

    result = minimizer.minimize(fit_objective.evaluate, P)
    fit_objective.finalize(result)

    return {r.name(): r.value for r in result.parameters()}


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

if __name__ == '__main__':

    datadir = os.getenv('BA_DATA_DIR', '')
    fname_stem = os.path.join(datadir, "MAFO_Saturated_")

    expdata_pp = psa.load_exp(fname_stem + "pp.tab")
    expdata_mm = psa.load_exp(fname_stem + "mm.tab")

    if len(argv) > 1 and argv[1] == "fit":
        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": (150, 60, 180),
            "r_Mao": (1, 0, 12),
            "r_Mafo": (1, 0, 12),
        }
        fit = True

    else:
        startParams = {}
        fixedParams = {
            # parameters from our own fit run
            'q_res': 0.010542945012551425,
            'q_offset': 7.971243487467318e-05,
            'rho_Mafo': 6.370140108715461,
            'rhoM_Mafo': 0.27399566816062926,
            't_Mafo': 137.46913056084736,
            'r_Mao': 8.60487712674644,
            'r_Mafo': 3.7844265311293483
        }

        fit = False

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

    def run_Simulation_pp(qzs, P):
        return run_simulation(qzs,
                              P,
                              polarizer_dir=R3(0, 1, 0),
                              analyzer_dir=R3(0, 1, 0))

    def run_Simulation_mm(qzs, P):
        return run_simulation(qzs,
                              P,
                              polarizer_dir=R3(0, -1, 0),
                              analyzer_dir=R3(0, -1, 0))

    qzs = numpy.linspace(psa.qmin, psa.qmax, psa.scan_size)
    q_pp, r_pp = psa.qr(run_Simulation_pp(qzs, PInitial))
    q_mm, r_mm = psa.qr(run_Simulation_mm(qzs, PInitial))

    data_pp = psa.filterData(expdata_pp, psa.qmin, psa.qmax)
    data_mm = psa.filterData(expdata_mm, psa.qmin, psa.qmax)

    psa.plot([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
             ["$++$", "$--$"], "MAFO_Saturated_initial.pdf")

    psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm,
                          "MAFO_Saturated_spin_asymmetry_initial.pdf")

    if fit:
        fitResult = run_fit_ba([data_pp[0], data_mm[0]],
                               [data_pp[1], data_mm[1]],
                               [data_pp[2], data_mm[2]],
                               [run_Simulation_pp, run_Simulation_mm],
                               startParams)
        print("Fit Result:")
        print(fitResult)

        q_pp, r_pp = psa.qr(run_Simulation_pp(qzs, fitResult))
        q_mm, r_mm = psa.qr(run_Simulation_mm(qzs, fitResult))

        psa.plot([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
                 ["$++$", "$--$"], "MAFO_Saturated_fit.pdf")
        plt.draw()

        psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm,
                              "MAFO_Saturated_spin_asymmetry_fit.pdf")
        plt.draw()

    plt.show()
