#!/usr/bin/env python3
"""
Off-specular simulation showing a prominent Yoneda peak.

Sample: vacuum V | mixed M | substrate S.

Layer M contains a polydisperse 2D random assembly of cylindrical
particles P in vacuum.

Critical angle between vacuum and layer M: 2 deg.

The refractive index of substrate S equals the effective medium
index of layer M (linear mixing rule) so that we get no reflection
from the M/S interface. This leaves the V/M Yoneda peak as the
dominant feature.
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm

# Target critical angle V->M: alpha_c = 2 deg
# delta_eff = alpha_c**2 / 2 = (2*pi/180)**2 / 2 = 6.09e-4
# Ambient = vacuum (delta_A=0); linear mixing at f=0.5:
#   delta_eff = f*delta_P  =>  delta_P = 2*delta_eff
DELTA_P   = 1.218e-3          # 2*DELTA_EFF
DELTA_EFF = 0.5*DELTA_P       # = 6.09e-4
H         = 3*nm               # layer thickness = cylinder height


def get_sample():
    particle_mat  = ba.RefractiveMaterial("Particle",  (0.86, 0.24, 0.18),
                                          DELTA_P, 0)
    substrate_mat = ba.RefractiveMaterial("Substrate", (0.28, 0.57, 0.82),
                                          DELTA_EFF, 0)

    # R = 5±1 nm cylinders, H=2 nm; polydispersity smears F(q_z) oscillations
    vacuum_layer    = ba.Layer(ba.Vacuum())
    mixed_layer     = ba.Layer(ba.Vacuum(), H)
    ff = ba.Cylinder(5*nm, H)
    particle = ba.Particle(particle_mat, ff)
    mixed_layer.deposit2D(ba.Dense2D(0.006, particle))
    substrate_layer = ba.Layer(substrate_mat)

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


def get_simulation(sample):
    nscan = <%= test_mode ? 50 : 200 %>
    scan = ba.AlphaScan(nscan, 1.6*deg, 3.4*deg)
    scan.setIntensity(1e8)
    scan.setWavelength(0.1*nm)
    detector = ba.OffspecDetector(nscan, 1.6*deg, 3.4*deg, -.2*deg, +.2*deg)
    return ba.OffspecSimulation(scan, sample, detector)


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    <%- if test_mode -%>
    from bornagain import ba_check
    ba_check.persistence_test(result)
    <%- elsif figure_mode -%>
    plotargs = bp.parse_commandline()
    bp.plot_datafield(result, intensity_min=1, **plotargs)
    bp.export(**plotargs)
    <%- else -%>
    ba.showSample3D(sample, sample_size=200*nm, seed=0)
    bp.plot_datafield(result)
    bp.plt.show()
    <%- end -%>
