#!/usr/bin/env python3

import bornagain as ba
from bornagain import ba_plot as bp, deg, nm, R3

r = 3*nm  # particle radius
a = 25*nm  # lattice constant


def get_sample():
    """
    Square lattice of cylinders, with two particles per unit cell
    """

    # 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
    ff = ba.Cylinder(r, r)
    particle_1 = ba.Particle(particle_mat, ff)
    particle_2 = ba.Particle(particle_mat, ff)
    particle_2.translate(R3(a/2, a/2, 0))

    # Lattice basis as compound particle
    basis = ba.Compound()
    basis.addComponent(particle_1)
    basis.addComponent(particle_2)

    # 2D lattice
    lattice = ba.SquareLattice2D(a, 0*deg)
    layout = ba.Crystal2D(basis, lattice)
    profile = ba.Profile2DCauchy(480*nm, 1600*nm, 0)
    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):
    beam = ba.Beam(1e9, 0.1*nm, 0.2*deg)
    n = 11
    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()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    from bornagain import ba_check
    ba_check.persistence_test(result)
