#!/usr/bin/env python3
"""
Dilute film of small spheres: scattering intensity for different particle densities.
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm

thickness = 100*nm

def get_sample(density):
    # Materials
    particle_color = (0.86, 0.24, 0.18)
    particle_mat = ba.RefractiveMaterial("Particle", particle_color, 1e-5, 0)
    substrate_color = (0.28, 0.57, 0.82)
    substrate_mat = ba.RefractiveMaterial("Substrate", substrate_color, 1e-6, 0)
    vacuum = ba.Vacuum()

    # Particles
    ff = ba.Sphere(4*nm)
    particle = ba.Particle(particle_mat, ff)

    # Layers
    layer_1 = ba.Layer(vacuum)
    layer_2 = ba.Layer(vacuum, thickness)
    layer_3 = ba.Layer(substrate_mat)
    layer_2.fill3D(ba.Dilute3D(density, particle))

    # Sample
    sample = ba.Sample()
    sample.addLayer(layer_1)
    sample.addLayer(layer_2)
    sample.addLayer(layer_3)

    return sample


def get_simulation(sample):
    beam = ba.Beam(1e9, 0.1*nm, 0.2*deg)
    n = 300
    # Just compute a 1d cut at phi=0
    detector = ba.SphericalDetector(1, -1*deg, 1*deg, n, 0., 2*deg)
    simulation = ba.ScatteringSimulation(beam, sample, detector)
    return simulation


if __name__ == '__main__':
    densities = [1e-9, 3.16e-9, 1e-8, 3.16e-8, 1e-7]
    samples = [get_sample(d) for d in densities]
    results = [get_simulation(sample).simulate() for sample in samples]
    ba.showSample3D(samples[-1], sample_size=80*nm, seed=0)
    for r in results:
        bp.plot_datafield(r, intensity_min=1e-5, intensity_max=1e3)
    bp.plt.legend([f'{d*1e9:.2g}/nm³' for d in densities])
    bp.plt.show()
