#!/usr/bin/env python3
"""
Specular reflectometry with sliced cylinders (SLD-material variant, canonical).

A layer of cylinders is subdivided into N horizontal slabs. The SLD
profile produced by the slicing algorithm is used for the specular
simulation. Compare SpecularWithSlicing1.py (refractive-index) and
SpecularWithSlicing3.py (hand-averaged layers).
"""
from math import pi
import bornagain as ba
from bornagain import angstrom, ba_plot as bp, deg, nm

HEIGHT = 5 * nm
RADIUS = 5 * nm
SURF_DENSITY = 0.01   # nm^-2
N_SLICES = 3
WAVELENGTH = 1.54 * angstrom


def _sld(delta, beta):
    """Convert refractive index (delta, beta) to SLD (Å⁻²) at WAVELENGTH."""
    f = pi * angstrom**2 / WAVELENGTH**2
    return (2*delta - delta**2 + beta**2) * f, (2*beta - 2*delta*beta) * f


def get_sample():
    vacuum = ba.Vacuum()
    sub_re, sub_im = _sld(6e-6, 2e-8)
    par_re, par_im = _sld(6e-4, 2e-8)

    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.SLDMaterial("Substrate", substrate_color, sub_re, sub_im)
    particle_color = (0.86, 0.24, 0.18)
    particle_mat = ba.SLDMaterial("Particle", particle_color, par_re, par_im)

    cylinder = ba.Cylinder(RADIUS, HEIGHT)
    particle = ba.Particle(particle_mat, cylinder)

    top_layer = ba.Layer(vacuum)
    top_layer.deposit2D(ba.Dilute2D(SURF_DENSITY, particle))
    top_layer.setNumberOfSlices(N_SLICES)

    sample = ba.Sample()
    sample.addLayer(top_layer)
    sample.addLayer(ba.Layer(substrate_mat))
    return sample


def get_simulation(sample):
    n = 500
    scan = ba.AlphaScan(n, 5*deg/n, 5*deg)
    scan.setWavelength(WAVELENGTH)
    return ba.SpecularSimulation(scan, sample)


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)
