#!/usr/bin/env python3
"""
Simulation of grating using very long boxes and 1D lattice.
Monte-carlo integration is used to get rid of
large-particle form factor oscillations.
"""
import bornagain as ba
from bornagain import angstrom, ba_plot as bp, deg, nm


def get_sample():
    """
    A sample with a grating on a substrate,
    modelled by very long boxes forming a 1D lattice with Cauchy correlations.
    """

    # Materials
    particle_color = (0.86, 0.24, 0.18)
    particle_mat = ba.RefractiveMaterial("Particle", particle_color, 6e-5, 2e-08)
    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.RefractiveMaterial("Substrate", substrate_color, 6e-06, 2e-08)
    vacuum = ba.Vacuum()

    # Particles
    box_length = 10000*nm
    ff = ba.Box(10*nm, box_length, 10*nm)
    particle = ba.Particle(particle_mat, ff)
    particle_rotation = ba.RotationZ(45*deg)
    particle.rotate(particle_rotation)

    # Interference functions
    layout = ba.Crystal1D(particle, 30*nm, 45*deg, 1/box_length)
    profile = ba.Profile1DCauchy(1000*nm)
    layout.setDecayFunction(profile)

    # Layers
    layer_1 = ba.Layer(vacuum)
    layer_1.deposit2D(layout)
    layer_2 = ba.Layer(substrate_mat)

    # Sample
    sample = ba.Sample()
    sample.addLayer(layer_1)
    sample.addLayer(layer_2)

    return sample


def get_simulation(sample):
    beam = ba.Beam(1e10, 1*angstrom, 0.2*deg)
    n = <%= test_mode ? 21 : 101 %>
    det = ba.SphericalDetector(n, -1*deg, 1*deg, n, 0, 2*deg)
    simulation = ba.ScatteringSimulation(beam, sample, det)
    simulation.options().setMonteCarloIntegration(True, <%= test_mode ? 1000 : 100 %>)
    if not "__no_terminal__" in globals():
        simulation.setTerminalProgressMonitor()
    return simulation


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    <%- if test_mode -%>
    from bornagain import ba_check
    ba_check.persistence_test(result)
    <%- elsif figure_mode -%>
    plotargs = bp.parse_commandline()
    bp.plot_datafield(result, intensity_min=1e-03, unit_aspect=1, **plotargs)
    bp.export(**plotargs)
    <%- else -%>
    ba.showSample3D(sample, sample_size=300*nm, seed=0)
    bp.plot_datafield(result, intensity_min=1e-3, unit_aspect=1)
    bp.plt.show()
    <%- end -%>
