#!/usr/bin/env python3
"""
Basic GISAS 2D fitting example.
The model is in gisas_model1.
Fake experimental data are generated by gisas_fake1.
"""

import gisas_model1 as model
import bornagain as ba
import ba_fitmonitor
import numpy as np
from matplotlib import pyplot as plt


def run_fitting():
    real_data = np.loadtxt("../data/faked-gisas1.txt.gz", dtype=float)

    fit_objective = ba.FitObjective()
    fit_objective.addSimulationAndData(model.get_simulation, real_data)

    fit_objective.initPrint(10)  # Print on every 10th iteration.
    observer = ba_fitmonitor.PlotterGISAS()
    fit_objective.initPlot(10, observer)  # Plot every 10th, slow!

    minimizer = ba.Minimizer()
    params = model.start_parameters_1()
    result = minimizer.minimize(fit_objective.evaluate, params)

    fit_objective.finalize(result)

    print("Fit completed.")
    print("chi2:", result.minValue())
    for fitPar in result.parameters():
        print(fitPar.name(), fitPar.value, fitPar.error)

    # Save simulation image corresponding to the best fit parameters
    np.savetxt("fit.txt", fit_objective.simulationResult().array())


if __name__ == '__main__':
    run_fitting()
    plt.show()
