#!/usr/bin/env python3
"""
Square lattice of cylinders inside finite layer with usage of average material
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm, R3


def get_sample(cyl_height=5*nm):
    """
    A sample with cylinders on a substrate.
    """
    # defining materials
    vacuum = ba.Vacuum()
    layer_color = (0.93, 0.72, 0.25)
    layer_mat = ba.RefractiveMaterial("Layer", layer_color, 3e-6, 2e-8)
    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.RefractiveMaterial("Substrate", substrate_color, 6e-6, 2e-8)
    particle_color = (0.86, 0.24, 0.18)
    particle_mat = ba.RefractiveMaterial("Particle", particle_color, 3e-5, 2e-8)

    # cylindrical particle
    cylinder_ff = ba.Cylinder(5*nm, cyl_height)
    cylinder = ba.Particle(particle_mat, cylinder_ff)
    cylinder.translate(R3(0, 0, -cyl_height))

    # interference function
    layout = ba.Crystal2D(cylinder, ba.SquareLattice2D(15*nm, 0))
    profile = ba.Profile2DCauchy(300*nm, 300*nm, 0)
    layout.setDecayFunction(profile)

    vacuum_layer = ba.Layer(vacuum)
    intermediate_layer = ba.Layer(layer_mat, 5*nm)
    substrate_layer = ba.Layer(substrate_mat)
    vacuum_layer.deposit2D(layout)

    sample = ba.Sample()
    sample.addLayer(vacuum_layer)
    sample.addLayer(intermediate_layer)
    sample.addLayer(substrate_layer)
    return sample


def get_simulation(sample):
    beam = ba.Beam(1e9, 0.1*nm, 0.2*deg)
    n = 100
    detector = ba.SphericalDetector(n, -2*deg, 2*deg, n, 0, 2*deg)
    simulation = ba.ScatteringSimulation(beam, sample, detector)
    return simulation


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