Fitting the spin-asymmetry example from NIST

This example shows how to fit the parameters in the spin-asymmetry example.

For this demonstration, we choose initial parameters that are not too far from the fitting results. In particular, the magnetization is initially set to zero, such that the spin asymmetry identically vanishes.

With the initial parameters, we obtain the following reflectivity and spin-asymmetry curves:

Reflectivity

Spin Asymmetry

Setup of the Fit

For fitting of reflectometry data covering several orders of magnitude we use the $\chi^2$ metric

$$\chi^2 = \sum_{i = 1}^N \frac{\left( d_i - s_i \right)^2}{\sigma_i^2}$$

Here $d_i$ is the $i$-thexperimental data point, $\sigma_i$ is its uncertainty and $s_i$ is the corresponding simulation result.

This is supported in BornAgain by setting

fit_objective.setObjectiveMetric("chi2")

Note that in order to obtain good results, one needs to provide the uncertainties of the reflectivity. If no uncertainties are available, using the relative difference fit_objective.setObjectiveMetric("reldiff") yields better results. If the relative difference is selected and uncertainties are provided, BornAgain automatically falls back to the above $\chi^2$ metric.

The fitting of polarized reflectometry data proceeds similar to the lines presented in the tutorial on multiple datasets. We need to add the reflectivity curves for the up-up and down-down channel to the fit objective:

fit_objective.addSimulationAndData( SimulationFunctionPlusplus,
                                    r_data_pp, r_uncertainty_pp, 1.0)
fit_objective.addSimulationAndData( SimulationFunctionMinusMinus,
                                    r_data_mm, r_uncertainty_mm, 1.0)

SimulationFunctionPlusplus and SimulationFunctionMinusMinus are two function objects that return a simulation result for the up-up and down-down channels, respectively.

The fit parameters are defined in the dictionary startParams, where they are defined as a triple of values (start, min, max). If no fit is performed the values obtained from our own fit are stored in fixedParams and are subsequently used to simulate the system.

We want to fit the following parameters:

  • q_res: Relative $Q$-resolution
  • q_offset: Shift of the $Q$-axis.
  • t_Mafo: The thickness of the layer
  • rho_Mafo: The SLD of the layer
  • rhoM_Mafo: The magnetic SLD of the layer
  • r_Mao: The roughness on top of the substrate
  • r_Mafo: The roughness on top of the magnetic layer

Fit Result

After running the fit using

python3 PolarizedSpinAsymmetryFit.py

we get the result

Reflectivity

Spin Asymmetry

This result was already presented in the spin-asymmetry tutorial and can also be plotted by runnning

python3 PolarizedSpinAsymmetry.py

Here is the complete example:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python3
"""
This fitting and simulation example demonstrates how to replicate
the fitting example "Magnetically Dead Layers in Spinel Films"
given at the Nist website:
https://www.nist.gov/ncnr/magnetically-dead-layers-spinel-films

For simplicity, here we only reproduce the first part of that
demonstration without the magnetically dead layer.
"""

import os
import numpy
import matplotlib.pyplot as plt
import bornagain as ba
from bornagain import R3
from bornagain.numpyutil import Arrayf64Converter as dac

import PolarizedSpinAsymmetry as psa


def get_simulation(q_axis, fitParams, *, polarizer_vec, analyzer_vec):
    """
    Run a simulation on the given q-axis, where the sample is
    constructed with the given parameters.
    Vectors for polarization and analyzer need to be provided
    """
    parameters = dict(fitParams, **fixedParams)

    sample = psa.get_sample(parameters)
    simulation = psa.get_simulation(sample, q_axis, parameters, polarizer_vec,
                                    analyzer_vec)

    return simulation

####################################################################
#                          Main Function                           #
####################################################################

if __name__ == '__main__':

    datadir = os.getenv('BA_DATA_DIR', '')
    fname_stem = os.path.join(datadir, "specular/MAFO_Saturated_")

    data_pp = psa.load_data(fname_stem + "pp.tab")
    data_mm = psa.load_data(fname_stem + "mm.tab")

    fixedParams = {
        # parameters can be moved here to keep them fixed
    }
    fixedParams = {d: v[0] for d, v in fixedParams.items()}

    startParams = {
        # own starting values
        "q_res": (0, 0, 0.1),
        "q_offset": (0, -0.002, 0.002),
        "rho_Mafo": (6.3649, 2, 7),
        "rhoM_Mafo": (0, 0, 2),
        "t_Mafo": (150, 60, 180),
        "r_Mao": (1, 0, 12),
        "r_Mafo": (1, 0, 12),
    }

    PInitial = {d: v[0] for d, v in startParams.items()}

    def get_Simulation_pp(qzs, P):
        return get_simulation(qzs,
                              P,
                              polarizer_vec=(0, 1, 0),
                              analyzer_vec=R3(0, 1, 0))

    def get_Simulation_mm(qzs, P):
        return get_simulation(qzs,
                              P,
                              polarizer_vec=(0, -1, 0),
                              analyzer_vec=R3(0, -1, 0))

    qzs = numpy.linspace(psa.qmin, psa.qmax, psa.scan_size)
    q_pp, r_pp = psa.qr(get_Simulation_pp(qzs, PInitial).simulate())
    q_mm, r_mm = psa.qr(get_Simulation_mm(qzs, PInitial).simulate())

    color_pp = ['orange','red']
    color_mm = ['green','blue']

    legend_pp = "$++$"
    legend_mm = "$--$"

    psa.plotData([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
             [legend_pp, legend_mm], [color_pp, color_mm])

    psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm)
    data_pp_Xcenters = dac.npArray(data_pp.xCenters())
    data_mm_Xcenters = dac.npArray(data_mm.xCenters())

    fit_objective = ba.FitObjective()
    fit_objective.setObjectiveMetric("chi2")
    fit_objective.initPrint(10)

    fit_objective.addFitPair(
        lambda P: get_Simulation_pp(data_pp_Xcenters, P), data_pp, 1)
    fit_objective.addFitPair(
        lambda P: get_Simulation_mm(data_mm_Xcenters, P), data_mm, 1)

    P = ba.Parameters()
    for name, p in startParams.items():
        P.add(name, p[0], min=p[1], max=p[2])

    minimizer = ba.Minimizer()

    result = minimizer.minimize(fit_objective.evaluate, P)
    fit_objective.finalize(result)

    fitResult = {r.name(): r.value for r in result.parameters()}

    print("Fit Result:")
    print(fitResult)

    q_pp, r_pp = psa.qr(get_Simulation_pp(qzs, fitResult).simulate())
    q_mm, r_mm = psa.qr(get_Simulation_mm(qzs, fitResult).simulate())

    psa.plotData([q_pp, q_mm], [r_pp, r_mm], [data_pp, data_mm],
             [legend_pp, legend_mm], [color_pp, color_mm])
    plt.draw()

    psa.plotSpinAsymmetry(data_pp, data_mm, qzs, r_pp, r_mm)
    plt.draw()
    plt.show()
auto/Examples/fit/specular/PolarizedSpinAsymmetryFit.py

Data to be fitted: MAFO_Saturated_mm.tab , MAFO_Saturated_pp.tab