#!/usr/bin/env python3
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm


def get_sample():
    # Define materials
    material_HMDSO = ba.RefractiveMaterial("HMDSO", 2.0888e-06, 1.3261e-08)
    material_PTFE = ba.RefractiveMaterial("PTFE", 5.20509e-06, 1.9694e-08)
    material_Si = ba.RefractiveMaterial("Si", 5.7816e-06, 1.0229e-07)
    material_Vacuum = ba.RefractiveMaterial("Vacuum", 0.0, 0.0)

    # Define roughness
    autocorr_1 = ba.SelfAffineFractalModel(1.1, 0.3, 5*nm)
    autocorr_2 = ba.SelfAffineFractalModel(2.3, 0.3, 5*nm)

    transient = ba.TanhTransient()

    roughness_1 = ba.Roughness(autocorr_1, transient)
    roughness_2 = ba.Roughness(autocorr_2, transient)

    # Define layers
    layer_1 = ba.Layer(material_Vacuum)
    layer_2 = ba.Layer(material_HMDSO, 18.5*nm, roughness_1)
    layer_3 = ba.Layer(material_PTFE, 22.1*nm, roughness_2)
    layer_4 = ba.Layer(material_Si)

    # Define sample
    sample = ba.Sample()
    sample.addLayer(layer_1)
    sample.addLayer(layer_2)
    sample.addLayer(layer_3)
    sample.addLayer(layer_4)

    return sample


def get_simulation(sample):
    beam = ba.Beam(1e9, 0.1*nm, 0.4*deg)
    n = 11
    detector = ba.SphericalDetector(n, -2*deg, 2*deg, n, -.6*deg, 1.4*deg)
    detector.setResolutionFunction(
        ba.ResolutionFunction2DGaussian(0.02*deg, 0.02*deg))
    simulation = ba.ScatteringSimulation(beam, sample, detector)
    simulation.options().setUseAvgMaterials(True)
    simulation.options().setIncludeSpecular(True)
    return simulation


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    plotargs = bp.parse_commandline()
    bp.plot_datafield(result, **plotargs)
    bp.export(**plotargs)
