#!/usr/bin/env python3
"""
Simple example demonstrating how polarized SANS experiments can be
simulated with BornAgain.
"""
import bornagain as ba
from bornagain import ba_plot as bp, deg, nm, nm2, R3


def get_sample():
    """
    A sample with a magnetic core-shell particle in a solvent.
    """

    # Materials
    B = R3(0, 1e7, 0)
    core_color = (0.86, 0.24, 0.18)
    core_mat = ba.RefractiveMaterial("Core", core_color, 6e-06, 2e-08, B)
    shell_color = (0.25, 0.65, 0.35)
    shell_mat = ba.RefractiveMaterial("Shell", shell_color, 1e-07, 2e-08)
    solvent_color = (0.90, 0.93, 0.97)
    solvent_mat = ba.RefractiveMaterial("Solvent", solvent_color, 5e-06, 0)

    # Form factors
    ff_1 = ba.Sphere(10*nm)
    ff_2 = ba.Sphere(12*nm)

    # Particles
    particle_1 = ba.Particle(core_mat, ff_1)
    particle_1_position = R3(0, 0, 2*nm)
    particle_1.translate(particle_1_position)
    particle_2 = ba.Particle(shell_mat, ff_2)

    # Core shell particles
    particle = ba.CoreAndShell(particle_1, particle_2)

    # Layers: two solvent layers, particles deposited at their interface
    layer_top = ba.Layer(solvent_mat)
    layer_bottom = ba.Layer(solvent_mat)
    layer_top.deposit2D(ba.Dilute2D(0.001/nm2, particle))

    # Sample
    sample = ba.Sample()
    sample.addLayer(layer_top)
    sample.addLayer(layer_bottom)

    return sample


def get_simulation(sample):
    """
    A polarized SANS simulation
    """
    n = 200

    # Beam from above (perpendicular to sample):
    beam = ba.Beam(1e9, 0.4*nm, 0.001*deg)

    # Detector opposite to source:
    detector = ba.SphericalDetector(n, -7*deg, 7*deg, n, -7*deg, 7*deg)

    beam.setPolarization(R3(0, 1, 0))
    detector.setAnalyzer(R3(0, -1, 0))

    simulation = ba.ScatteringSimulation(beam, sample, detector)
    simulation.options().setUseAvgMaterials(False)
    return simulation


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    plotargs = bp.parse_commandline()
    bp.plot_datafield(result, unit_aspect=1, **plotargs)
    bp.export(**plotargs)
