#!/usr/bin/env python3
"""
Specular reflectometry with sliced cylinders (Q-scan variant).

Same sample as SpecularWithSlicing2.py but the scan axis is q_z
instead of incident angle.
"""
from math import pi, sin
import numpy as np
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 = 50
    lam = WAVELENGTH
    qs = [4*pi*sin(a)/lam for a in np.linspace(5*deg/n, 5*deg, n)]
    scan = ba.QzScan(qs)
    return ba.SpecularSimulation(scan, sample)


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    from bornagain import ba_check
    ba_check.persistence_test(result)
