#!/usr/bin/env python3
"""
Specular reflectometry with hand-averaged SLD layers (no particles).

Instead of explicit particles with setNumberOfSlices, N homogeneous SLD
layers with the volume-averaged scattering length density replace the
sliced-particle layer. Results must agree with SpecularWithSlicing2.py.
"""
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)

    # Effective volume fraction of cylinders in each slice
    eff_vol = SURF_DENSITY * pi * RADIUS**2
    avr_re = eff_vol * par_re
    avr_im = eff_vol * par_im

    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.SLDMaterial("Substrate", substrate_color, sub_re, sub_im)
    avr_color = (0.05, 0.62, 0.55)
    avr_mat = ba.SLDMaterial("Avr", avr_color, avr_re, avr_im)

    sample = ba.Sample()
    sample.addLayer(ba.Layer(vacuum))
    for _ in range(N_SLICES):
        sample.addLayer(ba.Layer(avr_mat, HEIGHT / N_SLICES))
    sample.addLayer(ba.Layer(substrate_mat))
    return sample


def get_simulation(sample):
    n = <%= test_mode ? 50 : 500 %>
    scan = ba.AlphaScan(n, 5*deg/n, 5*deg)
    scan.setWavelength(WAVELENGTH)
    return ba.SpecularSimulation(scan, sample)


<%= include_partial("template/main/runsim.py",
    "ba.showSample3D(sample, sample_size=120*nm, seed=0)") -%>
