#!/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
    material_particle = ba.RefractiveMaterial("Particle", 0.0006, 2e-08)
    material_substrate = ba.RefractiveMaterial("Substrate", 6e-06, 2e-08)
    vacuum = ba.RefractiveMaterial("Vacuum", 0, 0)

    # Form factors
    ff = ba.Box(10*nm, 10000*nm, 10*nm)

    # Particles
    particle = ba.Particle(material_particle, ff)
    particle_rotation = ba.RotationZ(45*deg)
    particle.rotate(particle_rotation)

    # Interference functions
    iff = ba.Interference1DLattice(30*nm, 45*deg)
    iff_pdf = ba.Profile1DCauchy(1000*nm)
    iff.setDecayFunction(iff_pdf)

    # Particle layouts
    layout = ba.ParticleLayout()
    layout.addParticle(particle)
    layout.setInterference(iff)
    layout.setTotalParticleSurfaceDensity(0.01)

    # Layers
    layer_1 = ba.Layer(vacuum)
    layer_1.addLayout(layout)
    layer_2 = ba.Layer(material_substrate)

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

    return sample


def get_simulation(sample):
    beam = ba.Beam(1e9, 1*angstrom, 0.2*deg)
    n = 11
    det = ba.Detector2D(2*deg, 2*deg, n, n, 0, 1*deg)
    simulation = ba.ScatteringSimulation(beam, sample, det)
    simulation.options().setMonteCarloIntegration(True, 100)
    if not "__no_terminal__" in globals():
        simulation.setTerminalProgressMonitor()
    return simulation


if __name__ == '__main__':
    bp.parse_args(intensity_min=1e-03)
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    bp.plot_simulation_result(result)
    bp.show_or_export()
