TREFF Ni film

Result

TREFF Ni film result

Sample

TREFF Ni film sample

Data files

Place these files next to the Python script.

Python script

  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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["bornagain>=25,<26", "lmfit"]
# ///
"""
Basic real-life example of fitting specular data.
The sample consists of single Ni film on SiO2 substrate.
"""

from itertools import count
import math
import bornagain as ba
ba.require_versions("bornagain>=25,<26")
import os
from bornagain import deg, nm
import lmfit
import numpy as np


def load_data():
    # By default, read data files from the script directory.
    datadir = ba.data_dir(beside=__file__)
    fname = os.path.join(datadir, "MLZ-TREFF-Ni58.txt")

    q_angstrom, intensity = ba.read_columns(fname, usecols=(0, 1))
    q = 10*q_angstrom
    return q, intensity


def get_sample(P):
    # Materials
    material_Ni_58_color = (0.93, 0.48, 0.14)
    material_Ni_58 = ba.SLDMaterial("Ni", material_Ni_58_color, 9.408e-06, 0)
    sio2_color = (0.20, 0.55, 0.72)
    sio2_mat = ba.SLDMaterial("SiO2", sio2_color, 2.0704e-06, 0)

    # Layers and interfaces
    transient = ba.TanhTransient()

    Ni_autocorr = ba.SelfAffineFractalModel(P["sigma_Ni"], 0.7, 25*nm)
    roughness_Ni = ba.Roughness(Ni_autocorr, transient)

    sub_autocorr = ba.SelfAffineFractalModel(P["sigma_Substrate"], 0.7, 25*nm)
    roughness_Substrate = ba.Roughness(sub_autocorr, transient)

    layer_Ni = ba.Layer(material_Ni_58, P["thickness"], roughness_Ni)
    substrate = ba.Layer(sio2_mat, roughness_Substrate)

    sample = ba.Sample()
    sample.addLayer(ba.Layer(ba.Vacuum()))
    sample.addLayer(layer_Ni)
    sample.addLayer(substrate)

    return sample


def get_simulation(q_axis, P):
    scan = ba.QzScan(q_axis)

    # Finite resolution due to beam divergence
    n_samples = 5
    rel_sampling_width = 2.0
    res_distr = ba.DistributionGaussian(0, 1, n_samples, rel_sampling_width)

    wavelength = 0.473*nm
    res_alpha = 0.006*deg
    res_q = 4*math.pi*res_alpha/wavelength
    scan.setAbsoluteQResolution(res_distr, res_q)

    sample = get_sample(P)
    simulation = ba.SpecularSimulation(scan, sample)
    simulation.setBackground(ba.ConstantBackground(1e-4))

    return simulation


if __name__ == '__main__':
    q_axis, exp_values = load_data()
    eps = np.finfo(float).tiny
    log_exp_values = np.log10(np.maximum(eps, exp_values))
    exp_data = ba.Datafield(ba.Frame(ba.ListScan("q_z (1/nm)", q_axis)),
                            exp_values.tolist())

    # Fit progress display
    fit_plotter = ba.FitPlotter(
        ba.plot_specular,
        context_data=exp_data,
        ylabel="Intensity",
    )

    monitor = ba.FitMonitor(
        fit_plotter,
        ncols=1,
        show_best=True,
        max_fps=1,
        printer=ba.Printer(every_nth=10),
        live=True)

    P = lmfit.Parameters()
    P.add("thickness", value=75*nm, min=50*nm, max=100*nm)
    P.add("sigma_Ni", value=1.505*nm, min=0.01*nm, max=3*nm)
    P.add("sigma_Substrate", value=1.505*nm, min=0.01*nm, max=3*nm)

    def residuals(P):
        """
        Simulates, reports, and returns log-intensity residuals.
        """
        sim_result = get_simulation(q_axis, P.valuesdict()).simulate()
        sim_values = sim_result.intensities()
        residuals = np.log10(np.maximum(eps, sim_values)) - log_exp_values
        monitor.update(sim_result, P, residuals)
        return residuals

    # Stage 1: global search with differential evolution
    n_generations = 5
    generations = count(1)

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

    de_result = lmfit.minimize(
        residuals,
        P,
        method="differential_evolution",
        callback=stop_callback,  # stops the search after n_generations
        popsize=15,
        max_nfev=1000,  # emergency evaluation cap
        polish=False,
        seed=42)

    # Stage 2: local refinement seeded from global search result
    result = lmfit.minimize(residuals, de_result.params, method="leastsq")

    finalP = result.params.valuesdict()
    # Recompute and report the simulation at the fitted parameters.
    residuals(result.params)
    # Render the just-reported evaluation as the final fit state.
    monitor.render_final(result.params)
    print(lmfit.fit_report(result))
    ba.showSample3D(get_sample(finalP), sample_size=120*nm, seed=0)
    ba.plt.show()
auto/Examples/fit/specular/TREFF_Ni_film.py