#!/usr/bin/env python3
"""
Basic offspec example.
Sample is a grating on a substrate, modelled by a 1d lattice of long boxes
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm


def get_sample():
    # 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 = 1000*nm
    ff = ba.Box(box_length, 20*nm, 10*nm)
    particle = ba.Particle(particle_mat, ff)
    particle_rotation = ba.RotationZ(90*deg)
    particle.rotate(particle_rotation)

    # Interference functions
    layout = ba.Crystal1D(particle, 100*nm, 0, 1/box_length)
    profile = ba.Profile1DCauchy(1e6*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):
    nla = 573
    naf = 200
    lambda_max = 0.5*nm
    scan = ba.LambdaScan(nla, lambda_max/nla, lambda_max)
    scan.setGrazingAngle(1.5 * deg)
    scan.setIntensity(1e12)
    detector = ba.OffspecDetector(naf, 0*deg, 4*deg, -1*deg, +1*deg)
    simulation = ba.OffspecSimulation(scan, sample, detector)
    return simulation


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    simulation.options().setOffspecIntegratorOptions(
        "AdaptiveGaussKronrod",
        {
        "max_subintervals" : 200,
        "abs_tolerance" : 1e-5,
        "rel_tolerance" : 1e-3,
        "GK_rule" : 3
        });
    result = simulation.simulate()
    ba.showSample3D(sample, sample_size=1000*nm, seed=0)
    bp.plot_datafield(result, intensity_min=1)
    bp.plt.show()
