#!/usr/bin/env python3
"""
Fitting example: fit with masks
"""

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


def get_masked_simulation(P, add_masks=True):
    simulation = model.get_simulation(P)
    if add_masks:
        add_mask_to_simulation(simulation)
    return simulation


def add_mask_to_simulation(simulation):
    """
    Here we demonstrate how to add masks to the simulation.
    Only unmasked areas will be simulated and then used during the fit.

    Masks can have different geometrical shapes (ba.Rectangle, ba.Ellipse, Line)
    with the mask value either "True" (detector bin is excluded from the simulation)
    or False (will be simulated).

    Every subsequent mask overrides previously defined mask in this area.

    In the code below we put masks in such way that simulated image will look like
    a Pac-Man from ancient arcade game.
    """
    # mask all detector (put mask=True to all detector channels)
    simulation.detector().maskAll()

    w2 = 0.7*deg # half width of detector frame in ??

    # set mask to simulate pacman's head
    simulation.detector().addMask(ba.Ellipse(1*w2, 1*w2, 0.5*w2, 0.5*w2), False)

    # set mask for pacman's eye
    simulation.detector().addMask(ba.Ellipse(1.11*w2, 1.25*w2, 0.05*w2, 0.05*w2),
                                  True)

    # set mask for pacman's mouth
    points = [[1*w2, 1*w2], [1.5*w2, 1.2*w2], [1.5*w2, 0.8*w2], [1*w2, 1*w2]]
    simulation.detector().addMask(ba.Polygon(points), True)

    # giving pacman something to eat
    simulation.detector().addMask(
        ba.Rectangle(1.45*w2, 0.95*w2, 1.55*w2, 1.05*w2), False)
    simulation.detector().addMask(
        ba.Rectangle(1.61*w2, 0.95*w2, 1.71*w2, 1.05*w2), False)
    simulation.detector().addMask(
        ba.Rectangle(1.75*w2, 0.95*w2, 1.85*w2, 1.05*w2), False)


if __name__ == '__main__':
    data = model.fake_data().noisy(0.1, 0.1)

    fit_objective = ba.FitObjective()
    fit_objective.addFitPair(get_masked_simulation, data, 1)
    fit_objective.initPrint(10)
    observer = ba_fitmonitor.PlotterGISAS()
    fit_objective.initPlot(10, observer)

    P = lmfit.Parameters()
    P.add("radius", 6.*nm, min=4, max=8)
    P.add("height", 9.*nm, min=8, max=12)

    result = lmfit.minimize(fit_objective.evaluate_residuals, P)
    print(lmfit.fit_report(result))
    ba.showSample3D(model.get_sample(result.params), sample_size=120*nm, seed=0)

    plt.show()
