#!/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.Sample()
    sample.addLayer(layer_1)
    sample.addLayer(layer_2)

    return sample


def get_simulation(sample):
    beam = ba.Beam(1e9, 1*angstrom, 0.2*deg)
    n = 101
    det = ba.SphericalDetector(n, -1*deg, 1*deg, n, 0, 2*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__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    plotargs = bp.parse_commandline()
    plotargs['intensity_min'] = 1e-03
    bp.plot_simulation_result(result, **plotargs)
    bp.export(**plotargs)
