Reflectometry: Fit honeycomb lattice

In this example, we want to demonstrate how to fit a more complex sample. For this purpose, we utilize the reflectometry data of an artificial magnetic honeycomb lattice published by A. Glavic et al., in this paper

The experiment was performed with polarized neutrons, but without polarization analysis. Since the magnetization of the sample was parallel to the neutron spin, there is no spin flip and we apply the scalar theory to this problem. This is primarily done to speed up computations: when the polarized computational engine is utilized the fitting procedure takes roughly three times as long.

Experimental data

The experimental data consists of four datasets that should be fitted simultaneously. These datasets arise from the two polarization channels for up and down polarization of the incoming beam and both of these channels are measured at two temperatures (300K and 150K).

All of this is measured on the same sample, so all parameters are assumed to be the same, except the magnetization being temperature dependent. Therefore, we introduce a scaling parameter for the magnetization as the ratio of the magnetizations at 150K and 300K: $M_{s150} = M_{150K} / M_{300K}$.

The fifth column of each exported GenX dataset contains the pointwise standard deviation of $q$. The simulation uses these values directly rather than replacing them with a constant relative resolution. This interpretation is consistent with the Gaussian varying-resolution convolution implemented by GenX.

Magnetization model

To model a magnetic material, one can assign a magnetization vector to any material, as is demonstrated in the magnetic material tutorial. When a non-vanishing magnetization vector is specified for at least one layer in a sample, BornAgain will automatically utilize the polarized computational engine. This leads to lower performance as the computations are more invovled.

In this example, the magnetization is (anti)parallel to the neutron spin and hence we instead parametrize the magnetic layers with an effective SLD that is the sum/difference of the nuclear and their magnetic SLD:

$$\rho_\pm = \rho_{\text{N}} \pm \rho_{\text{M}}$$

Here the $+$ is chosen for incoming neutrons with spin up and $-$ is chosen for spin down neutrons.

Computational model

We simulate this experiment by bulding a 6 layer model: As usual the top layer is the vacuum and the bottom layer is a silicon substrate. On top of the silicon substrate, we simulate a thin oxide layer, where we fit its roughness and thickness The SLDs of these three layers are taken from the literature and kept constant.

Then we model the lattice structure with a three-layer model: two layers to account for density fluctuations in $z$-direction and another oxide layer on top. This lattice structure is assumed to be magnetic and we fit all of their SLDs, magnetic SLDs, thicknesses and roughnesses. The magnetic SLD depends on the temperature of the dataset, according to the scaling described above, where the $M_{s150}$ parameter is fitted.

All layers are modeled without absorption, i.e. no imaginary part of the SLD. We apply the pointwise resolution correction with QzScan.setVectorResolution. The experimental data is normalized to unity, but we still fit the intensity.

Running a computation

The common simulation function receives both the $q$ values and their pointwise resolutions:

def run_simulation(q_axis, q_resolution, P, *, spin_sign, temperature):
    resolution_profile = ba.DistributionGaussian(0., 1., 25, 3.)
    scan = ba.QzScan(q_axis)
    scan.setVectorResolution(resolution_profile, q_resolution)
    scan.setIntensity(P["intensity"])

    sample = get_sample(P, spin_sign, temperature)
    simulation = ba.SpecularSimulation(scan, sample)
    simulation.setBackground(ba.ConstantBackground(5e-7))

    return simulation.simulate().intensities()

Each dataset stores its spin sign and temperature alongside the measured values. During the fit, all matching values are read from that one record:

for dataset in datasets:
    simulated = run_simulation(
        dataset["q"], dataset["q_resolution"], parameters,
        spin_sign=dataset["spin_sign"],
        temperature=dataset["temperature"])

We choose some sensible initial parameters and these yield the following simulation result

Reflectivity with the initial parameters

SLD profile with the initial parameters

We have chosen the initial magnetization to be zero, hence there is only a single SLD curve for both spin directions.

Fitting

We fit this example with the differential evolution algorithm exposed by lmfit. As a measure for the goodness of the fit, we use the relative difference:

$$\Delta = \sum_{j = 1}^4 \frac{1}{N_j} \sum_{i = 1}^N \left( \frac{d_{ji} - s_{ji}}{d_{ji} + s_{ji}} \right)^2$$

Here the sum over $i$ sums up the fitting error at every data point as usual and the sum over $j$ adds the contributions from all four datasets. This is implemented directly in the Python objective function. The function loops over the four NumPy datasets, runs the matching simulation for each channel, and returns one weighted residual vector. lmfit minimizes its sum of squares.

The given uncercainty of the experimental data is not taken into account.

Fit Result

As usual, the fit can be run with the following command:

python3 Honeycomb_fit.py fit

On a four-core workstation, the fitting procedure takes roughly 45 minutes to complete and we obtain the following result:

Reflectivity with the fit result

SLD profile with the fit result

As can be seen from the plot of the SLDs, the magnetization is indeed larger for the measurement at lower temperature, exactly as expected.

  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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["bornagain>=25,<26", "lmfit"]
# ///
"""
This example demonstrates how to fit a complex experimental setup using BornAgain.
It is based on real data published in  https://doi.org/10.1002/advs.201700856
by A. Glavic et al.
In this example we utilize the scalar reflectometry engine to fit polarized
data without spin-flip for performance reasons.
"""

from itertools import count
import os

import bornagain as ba
ba.require_versions("bornagain>=25,<26")
import lmfit
import matplotlib.pyplot as plt
import numpy as np
from bornagain import ba_io, nm, sample_tools as st


datadir = ba_io.data_dir()

####################################################################
#  Sample and simulation model
####################################################################

def get_sample(P, spin_sign, temperature):

    if temperature < 200:
        ms150 = P["ms150"]
    else:
        ms150 = 1

    air_color = (0.90, 0.93, 0.97)
    air_mat = ba.SLDMaterial("Air", air_color, 0, 0)

    pyox_color = (0.62, 0.68, 0.72)
    pyox_sld_real = (P["sld_PyOx_real"] + spin_sign*ms150*P["msld_PyOx"])*1e-6
    pyox_mat = ba.SLDMaterial("PyOx", pyox_color, pyox_sld_real, 0)

    py2_color = (0.58, 0.40, 0.74)
    py2_sld_real = (P["sld_Py2_real"] + spin_sign*ms150*P["msld_Py2"])*1e-6
    py2_mat = ba.SLDMaterial("Py2", py2_color, py2_sld_real, 0)

    py1_color = (0.05, 0.62, 0.55)
    py1_sld_real = (P["sld_Py1_real"] + spin_sign*ms150*P["msld_Py1"])*1e-6
    py1_mat = ba.SLDMaterial("Py1", py1_color, py1_sld_real, 0)

    sio2_color = (0.25, 0.74, 0.42)
    sio2_sld_real = P["sld_SiO2_real"]*1e-6
    sio2_mat = ba.SLDMaterial("SiO2", sio2_color, sio2_sld_real, 0)

    si_color = (0.28, 0.57, 0.82)
    si_sld_real = P["sld_Si_real"]*1e-6
    si_mat = ba.SLDMaterial("Substrate", si_color, si_sld_real, 0)

    transient_model = ba.ErfTransient()

    rPyOx_autocorr = ba.SelfAffineFractalModel(P["rPyOx"]*nm, 0.7, 25*nm)
    rPy2_autocorr = ba.SelfAffineFractalModel(P["rPy2"]*nm, 0.7, 25*nm)
    rPy1_autocorr = ba.SelfAffineFractalModel(P["rPy1"]*nm, 0.7, 25*nm)
    rSiO2_autocorr = ba.SelfAffineFractalModel(P["rSiO2"]*nm, 0.7, 25*nm)
    rSi_autocorr = ba.SelfAffineFractalModel(P["rSi"]*nm, 0.7, 25*nm)

    rPyOx = ba.Roughness(rPyOx_autocorr, transient_model)
    rPy2 = ba.Roughness(rPy2_autocorr, transient_model)
    rPy1 = ba.Roughness(rPy1_autocorr, transient_model)
    rSiO2 = ba.Roughness(rSiO2_autocorr, transient_model)
    rSi = ba.Roughness(rSi_autocorr, transient_model)

    l_Air = ba.Layer(air_mat)
    l_PyOx = ba.Layer(pyox_mat, P["t_PyOx"]*nm, rPyOx)
    l_Py2 = ba.Layer(py2_mat, P["t_Py2"]*nm, rPy2)
    l_Py1 = ba.Layer(py1_mat, P["t_Py1"]*nm, rPy1)
    l_SiO2 = ba.Layer(sio2_mat, P["t_SiO2"]*nm, rSiO2)
    l_Si = ba.Layer(si_mat, rSi)

    sample = ba.Sample()

    sample.addLayer(l_Air)
    sample.addLayer(l_PyOx)
    sample.addLayer(l_Py2)
    sample.addLayer(l_Py1)
    sample.addLayer(l_SiO2)
    sample.addLayer(l_Si)

    return sample


def run_simulation(q_axis, q_resolution, P, *, spin_sign, temperature):

    resolution_profile = ba.DistributionGaussian(0., 1., 25, 3.)

    scan = ba.QzScan(q_axis)
    scan.setVectorResolution(resolution_profile, q_resolution)
    scan.setIntensity(P["intensity"])

    sample = get_sample(P, spin_sign, temperature)

    simulation = ba.SpecularSimulation(scan, sample)
    simulation.setBackground(ba.ConstantBackground(5e-7))

    return simulation.simulate().intensities()

####################################################################
#  Experimental data
####################################################################

def load_dataset(fname, q_min, q_max, *, spin_sign, temperature, plot_offset):
    fpath = os.path.join(datadir, fname)
    q_angstrom, intensity, sigma, q_resolution_angstrom = (
        ba_io.read_columns(fpath, usecols=(0, 2, 3, 4)))
    q = 10*q_angstrom
    q_resolution = 10*q_resolution_angstrom
    scale = np.amax(intensity)
    intensity = intensity/scale
    sigma = sigma/scale
    in_range = (q >= q_min) & (q <= q_max)
    spin_label = "+" if spin_sign > 0 else "-"
    return {
        "q": q[in_range],
        "r": intensity[in_range],
        "sigma": sigma[in_range],
        "q_resolution": q_resolution[in_range],
        "spin_sign": spin_sign,
        "temperature": temperature,
        "plot_offset": plot_offset,
        "label": f"{temperature}K ${spin_label}$",
    }

####################################################################
#  Plotting
####################################################################

def plot(q, simulations, datasets):
    """
    Plot the simulated result together with the experimental data.
    """
    fig = plt.figure()
    ax = fig.add_subplot(111)

    for simulated, dataset in zip(simulations, datasets):
        plot_offset = dataset["plot_offset"]

        ax.errorbar(dataset["q"],
                    dataset["r"] / plot_offset,
                    yerr=dataset["sigma"] / plot_offset,
                    fmt='.',
                    markersize=0.75,
                    linewidth=0.5)

        ax.plot(q, simulated/plot_offset, label=dataset["label"])

    ax.set_yscale('log')
    plt.legend()

    plt.xlabel(r"$q\; $(nm$^{-1}$)")
    plt.ylabel("$R$")
    plt.tight_layout()


def plot_sld_profile(P):

    z_300p, sld_300p = st.materialProfile(get_sample(P, +1, 300))
    z_300m, sld_300m = st.materialProfile(get_sample(P, -1, 300))
    z_150p, sld_150p = st.materialProfile(get_sample(P, +1, 150))
    z_150m, sld_150m = st.materialProfile(get_sample(P, -1, 150))

    plt.figure()
    plt.plot(z_300p, np.real(sld_300p)*1e6, label=r"300K $+$")
    plt.plot(z_300m, np.real(sld_300m)*1e6, label=r"300K $-$")
    plt.plot(z_150p, np.real(sld_150p)*1e6, label=r"150K $+$")
    plt.plot(z_150m, np.real(sld_150m)*1e6, label=r"150K $-$")

    plt.xlabel(r"$z\;$(Å)")
    plt.ylabel(r"$\delta(z) \cdot 10^6$")

    plt.legend()
    plt.tight_layout()

####################################################################
#  Main
####################################################################

if __name__ == '__main__':

    parameters = lmfit.Parameters()

    # Fitted parameters with good starting values.

    # (dimensionless)
    parameters.add("intensity", value=0.5, min=0.4, max=0.6)

    # (nm)
    parameters.add("t_PyOx", value=7.7, min=6.0, max=10.0)
    parameters.add("t_Py2", value=5.6, min=4.6, max=6.6)
    parameters.add("t_Py1", value=5.6, min=4.6, max=6.6)
    parameters.add("t_SiO2", value=2.2, min=1.5, max=2.9)

    # The remaining parameters are fixed to keep this multi-dataset fit fast.
    # Set vary=True for selected parameters to perform a more extensive fit.

    # (1e-6 Å⁻²)
    parameters.add("sld_SiO2_real", value=3.47, min=3, max=4, vary=False)
    parameters.add("sld_Si_real", value=2.0704, min=2, max=3, vary=False)
    parameters.add("sld_PyOx_real", value=1.995, min=1.92, max=2.07, vary=False)
    parameters.add("sld_Py2_real", value=5, min=4.7, max=5.3, vary=False)
    parameters.add("sld_Py1_real", value=4.62, min=4.32, max=4.92, vary=False)

    # (nm)
    parameters.add("rPyOx", value=2.7, min=1.5, max=3.5, vary=False)
    parameters.add("rPy2", value=1.2, min=0.2, max=2.0, vary=False)
    parameters.add("rPy1", value=1.2, min=0.2, max=2.0, vary=False)
    parameters.add("rSiO2", value=1.5, min=0.5, max=2.5, vary=False)
    parameters.add("rSi", value=1.5, min=0.5, max=2.5, vary=False)

    # (1e-6 Å⁻²)
    parameters.add("msld_PyOx", value=0.25, min=0, max=1, vary=False)
    parameters.add("msld_Py2", value=0.63, min=0, max=1, vary=False)
    parameters.add("msld_Py1", value=0.64, min=0, max=1, vary=False)

    # (dimensionless)
    parameters.add("ms150", value=1.05, min=1.0, max=1.1, vary=False)

    # Restrict the q range for fitting and plotting
    q_min = 0.08/nm
    q_max = 1.4/nm

    datasets = [
        load_dataset("specular/honeycomb300p.dat", q_min, q_max,
                     spin_sign=+1, temperature=300, plot_offset=1),
        load_dataset("specular/honeycomb300m.dat", q_min, q_max,
                     spin_sign=-1, temperature=300, plot_offset=1),
        load_dataset("specular/honeycomb150p.dat", q_min, q_max,
                     spin_sign=+1, temperature=150, plot_offset=10),
        load_dataset("specular/honeycomb150m.dat", q_min, q_max,
                     spin_sign=-1, temperature=150, plot_offset=10),
    ]

    qzs = np.linspace(q_min, q_max, 1500) # x-axis for plot R vs q

    # Plot data with initial model

    P = parameters.valuesdict()

    sim_results = [
        run_simulation(
            qzs,
            np.interp(qzs, dataset["q"], dataset["q_resolution"]), P,
            spin_sign=dataset["spin_sign"],
            temperature=dataset["temperature"])
        for dataset in datasets
    ]
    plot(qzs, sim_results, datasets)
    plot_sld_profile(P)

    # Fit

    def residuals(P):
        """
        Returns relative-difference residuals with equal dataset weights.
        """
        fullP = P.valuesdict()
        result = []
        for dataset in datasets:
            r = dataset["r"]
            t = run_simulation(
                dataset["q"], dataset["q_resolution"], fullP,
                spin_sign=dataset["spin_sign"],
                temperature=dataset["temperature"])
            reldiff = (r - t) / (r + t)
            result.append(reldiff/np.sqrt(len(t)))
        return np.concatenate(result)

    n_generations = 5 # use 500 for a serious fit
    generations = count(1)

    def stop_callback(*_args, **_kwargs):
        return next(generations) >= n_generations

    result = lmfit.minimize(
        residuals,
        parameters,
        method="differential_evolution",
        callback=stop_callback,  # stops the search after n_generations
        popsize=3, # for a serious DE fit, choose 10
        max_nfev=100000,  # also covers the suggested serious-fit settings
        tol=1e-2,
        mutation=(0.5, 1.5),
        seed=0,
        disp=True,
        polish=True
    )

    print(lmfit.fit_report(result))

    # Plot data with fit result

    P = result.params.valuesdict()
    ba.showSample3D(get_sample(P, 1, 300), sample_size=120*nm, seed=0)

    sim_results = [
        run_simulation(
            qzs,
            np.interp(qzs, dataset["q"], dataset["q_resolution"]), P,
            spin_sign=dataset["spin_sign"],
            temperature=dataset["temperature"])
        for dataset in datasets
    ]
    plot(qzs, sim_results, datasets)
    plot_sld_profile(P)

    plt.show()
auto/Examples/fit/specular/Honeycomb_fit.py

Data to be fitted: honeycomb150m.dat , honeycomb150p.dat , honeycomb300m.dat , honeycomb300p.dat