Reflectometry: Fit Pt layer

In this example, we want to demonstrate how to fit experimental reflectivity data that was obtained by a time-of-flight experiment with unpolarized neutrons. Experimental data is available for a sample of a roughly 50 nm thick platinum layer on top of a silicon substrate that is published in this repository.

The mesaurements were made by Timothy Charlton, Haile Ambaye and Michael Fitzsimmons (ORNL) on a sample provided by Eric Fullerton (UCSD).

The fourth data column is the full width of a logarithmic $q$ bin. The source notebook writes it as the difference between adjacent bin edges for bins with $\Delta q/q=0.01$. It is not a Gaussian instrument resolution and is therefore not passed to QzScan.setVectorResolution.

Fit model

We describe the above experiment by a three-layer model, where as usual the top layer is the vacuum and the substrate layer is the silicon substrate. On top of the silicon substrate, we place the platinum layer. The materials of both layers are described by their SLD, where we use literature values for both silicon as well as platinum and keep them constant throughout the fitting procedure.

The fit uses the following six lmfit parameters:

  • Dimensionless beam-intensity scale: intensity

    We explicitly fit the beam intensity, in order to compensate for possible experimental errors and to circumvent problems with the rather large variance in the reflectivity data at low $Q$-values.

  • Roughness on top of the Pt layer in nm: r_pt

  • Roughness on top of the Si substrate in nm: r_si

  • Thickness of the Pt layer in nm: t_pt

  • The absolute Gaussian $Q$-resolution: q_resolution, in nm$^{-1}$

  • A $Q$-offset in nm$^{-1}$: q_offset

This global offset is introduced to account for uncertainties in the angle at which the measurement is performed.

Due to saturation of the detector it is possible that the intensity at low $Q$-values (i.e. at high count rates) is underestimated. Furthermore, there is a rather large variance in the data that also leads to a rather bad fit in this region. Therefore, we neglect the data in the low $Q$-region by choosing a cutoff at $Q_{\text{min}} = $ 0.18 nm$^{-1}$. This value is selected by hand after performing several fits and visually selecting a good result.

$Q$-offset

The offset is assigned directly to the scan before performing a simulation:

scan = ba.QzScan(q_axis)
scan.setOffset(P["q_offset"])
Initial parameters

The example uses starting values sufficiently close to the measured sample. Run it with:

python3 Pt_layer_fit.py

This performs a simulation with the initial parameters and yields the following result:

Reflectivity with the initial parameters before fitting

Immediately afterwards the fit is performed.

Fit result

The script then performs the fit and should compute the following result:

Reflectivity with the parameters obtained from our fit

  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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["bornagain>=25,<26", "lmfit"]
# ///
"""
Fit example with data by M. Fitzsimmons et al,
https://doi.org/10.5281/zenodo.4072376.
Sample is a ~50 nm Pt film on a Si substrate.
Single event data from Spallation Neutron Source
Beamline-4A (MagRef) with 60 Hz pulses and a wavelength
band of roughly 4-7 Å in 100 steps of 2theta.
"""

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

datadir = ba_io.data_dir()

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

# Use fixed values for the SLD of the substrate and Pt layer
sldPt = (6.3568e-06, 1.8967e-09)
sldSi = (2.0728e-06, 2.3747e-11)

def get_sample(P):

    vacuum = ba.Vacuum()
    layer_color = (0.93, 0.72, 0.25)
    layer_mat = ba.SLDMaterial("Pt", layer_color, *sldPt)
    substrate_color = (0.30, 0.62, 0.86)
    substrate_mat = ba.SLDMaterial("Si", substrate_color, *sldSi)

    transient = ba.TanhTransient()

    si_autocorr = ba.SelfAffineFractalModel(P["r_si"]*nm, 0.7, 25*nm)
    pt_autocorr = ba.SelfAffineFractalModel(P["r_pt"]*nm, 0.7, 25*nm)

    r_si = ba.Roughness(si_autocorr, transient)
    r_pt = ba.Roughness(pt_autocorr, transient)

    ambient_layer = ba.Layer(vacuum)
    layer = ba.Layer(layer_mat, P["t_pt"]*nm, r_pt)
    substrate_layer = ba.Layer(substrate_mat, r_si)

    sample = ba.Sample()
    sample.addLayer(ambient_layer)
    sample.addLayer(layer)
    sample.addLayer(substrate_layer)

    return sample


def get_simulation(q_axis, P):
    sample = get_sample(P)

    scan = ba.QzScan(q_axis)
    scan.setIntensity(P["intensity"])
    scan.setOffset(P["q_offset"])

    distr = ba.DistributionGaussian(0., 1., 25, 4.)
    scan.setAbsoluteQResolution(distr, P["q_resolution"])

    simulation = ba.SpecularSimulation(scan, sample)

    return simulation


def load_data(path):
    """
    Reads q, reflectivity, and its uncertainty.

    The unused fourth column is the width of a logarithmic q bin, not a
    Gaussian instrument resolution.
    """
    q_angstrom, intensity, sigma = ba_io.read_columns(path,
                                                      usecols=(0, 1, 2))
    q = 10*q_angstrom
    return q, intensity, sigma

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

def plot(q, r, q_exp, intensity, sigma, P):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.errorbar(q_exp,
                intensity,
                # xerr=data.xxx, TODO restore
                yerr=sigma,
                label="R",
                fmt='.',
                markersize=1.,
                linewidth=0.6,
                color='r')

    ax.plot(q, r, label="Simulation", color='C0', linewidth=0.5)

    ax.set_yscale('log')

    ax.set_xlabel("$q\;$(nm$^{-1}$)")
    ax.set_ylabel("$R$")

    y = 0.5
    if P is not None:
        for n, v in P.items():
            plt.text(0.7, y, f"{n} = {v:.3g}", transform=ax.transAxes)
            y += 0.05

    plt.tight_layout()

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

if __name__ == '__main__':

    P = lmfit.Parameters()

    P.add("intensity", value=1, min=0.8, max=1.2)  # (dimensionless)
    P.add("q_offset", value=0.01, min=-0.02, max=0.02)  # (1/nm)
    P.add("q_resolution", value=0.01, min=0, max=0.02)  # (1/nm)
    P.add("t_pt", value=50, min=45, max=55)  # (nm)
    P.add("r_si", value=1.22, min=0, max=5)  # (nm)
    P.add("r_pt", value=0.25, min=0, max=5)  # (nm)
    initialP = P.valuesdict()

    # Set q axis, load data:

    qmin = 0.18
    qmax = 2.4
    qzs = np.linspace(qmin, qmax, 1500)

    fpath = os.path.join(datadir, "specular/RvsQ_36563_36662.dat.gz")
    q_exp, exp_values, sigma = load_data(fpath)

    # Initial plot

    res = get_simulation(qzs, initialP).simulate()
    r = res.intensities()
    plot(qzs, r, q_exp, exp_values, sigma, initialP)

    # Restrict data to given q range

    in_range = (q_exp >= qmin) & (q_exp <= qmax)
    q_fit = q_exp[in_range]
    y_fit = exp_values[in_range]

    # Fit:

    def residuals(P):
        sim_values = get_simulation(
            q_fit, P.valuesdict()).simulate().intensities()
        return y_fit - sim_values

    result = lmfit.minimize(residuals, P, method="leastsq")
    print(lmfit.fit_report(result))

    finalP = result.params.valuesdict()

    # Print and plot fit outcome:

    print("Fit Result:")
    print(finalP)
    ba.showSample3D(get_sample(finalP), sample_size=120*nm, seed=0)

    res = get_simulation(qzs, finalP).simulate()
    r = res.intensities()
    plot(qzs, r, q_exp, exp_values, sigma, finalP)

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