#!/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, R3


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

    # Materials
    B = R3(0, 1e7, 0)
    material_Core = ba.RefractiveMaterial("Core", 6e-06, 2e-08, B)
    material_Shell = ba.RefractiveMaterial("Shell", 1e-07, 2e-08)
    material_Solvent = ba.RefractiveMaterial("Solvent", 5e-06, 0)

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

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

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

    # Particle layouts
    layout = ba.ParticleLayout()
    layout.addParticle(particle)
    layout.setTotalParticleSurfaceDensity(0.01)

    # Layers
    layer = ba.Layer(material_Solvent)
    layer.addLayout(layout)

    # Sample
    sample = ba.MultiLayer()
    sample.addLayer(layer)

    return sample


def get_simulation(sample):
    """
    A polarized SANS simulation
    """
    n = <%= sm ? 11 : 200 %>

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

    # Detector opposite to source:
    detector = ba.Detector2D(14*deg, 14*deg, n, n, 0, 0)

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

    return ba.ScatteringSimulation(beam, sample, detector)


if __name__ == '__main__':
    sample = get_sample()
    simulation = get_simulation(sample)
    result = simulation.simulate()
    bp.plot_simulation_result(result)
    bp.show_or_export()
