#!/usr/bin/env python3
"""
Multilayer with correlated roughness
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm


def get_sample():
    """
    A sample with two layers on a substrate, with correlated roughnesses.
    """
    # defining materials
    vacuum_color = (0.90, 0.93, 0.97)
    vacuum = ba.RefractiveMaterial("ambience", vacuum_color, 0, 0)
    material_part_a_color = (0.86, 0.24, 0.18)
    material_part_a = ba.RefractiveMaterial("PartA", material_part_a_color, 5e-6, 0)
    material_part_b_color = (0.25, 0.65, 0.35)
    material_part_b = ba.RefractiveMaterial("PartB", material_part_b_color, 10e-6, 0)
    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.RefractiveMaterial("substrate", substrate_color, 15e-6, 0)

    # defining roughenss
    sigma, hurst, corrLength = 1*nm, 0.3, 5*nm
    autocorr = ba.SelfAffineFractalModel(sigma, hurst, corrLength)
    transient = ba.TanhTransient()
    crosscorrelation = ba.CommonDepthCrosscorrelation(10*nm)
    roughness = ba.Roughness(autocorr, transient, crosscorrelation)

    # defining layers
    l_ambience = ba.Layer(vacuum)
    l_part_a = ba.Layer(material_part_a, 2.5*nm, roughness)
    l_part_b = ba.Layer(material_part_b, 5*nm, roughness)
    l_substrate = ba.Layer(substrate_mat, roughness)

    # defining periodic stack
    n_repetitions = 5
    stack = ba.LayerStack(n_repetitions)
    stack.addLayer(l_part_a)
    stack.addLayer(l_part_b)

    # defining sample
    my_sample = ba.Sample()
    my_sample.addLayer(l_ambience)
    my_sample.addStack(stack)
    my_sample.addLayer(l_substrate)

    return my_sample


def get_simulation(sample):
    beam = ba.Beam(5e11, 0.1*nm, 0.2*deg)
    n = 200
    detector = ba.SphericalDetector(n, -0.5*deg, 0.5*deg, n, 0., 1*deg)
    simulation = ba.ScatteringSimulation(beam, sample, detector)
    return simulation


if __name__ == '__main__':
    sample = get_sample()
    ba.showSample3D(sample, sample_size=500*nm, seed=0)
    simulation = get_simulation(sample)
    result = simulation.simulate()
    bp.plot_datafield(result, unit_aspect=1)
    bp.plt.show()
