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
|
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["bornagain>=25,<26", "lmfit"]
# ///
"""
Fitting example: simultaneous fit of two datasets
"""
import numpy as np
import bornagain as ba
ba.require_versions("bornagain>=25,<26")
from bornagain import deg, nm, nm2
import lmfit
def get_sample(P):
"""
A sample with uncorrelated cylinders and pyramids.
"""
substrate_color = (0.28, 0.57, 0.82)
particle_color = (0.86, 0.24, 0.18)
substrate_mat = ba.RefractiveMaterial("Substrate", substrate_color, 6e-6, 2e-8)
particle_mat = ba.RefractiveMaterial("Particle", particle_color, 6e-4, 2e-8)
ff = ba.EllipsoidalSegment(
P["radius_a"], P["radius_b"], P["radius_c"], 0, P["radius_c"])
particle = ba.Particle(particle_mat, ff)
vacuum_layer = ba.Layer(ba.Vacuum())
vacuum_layer.deposit2D(ba.Dilute2D(0.01/nm2, particle))
substrate_layer = ba.Layer(substrate_mat)
sample = ba.Sample()
sample.addLayer(vacuum_layer)
sample.addLayer(substrate_layer)
return sample
def get_simulation(P):
"""
A GISAXS simulation with beam and detector defined.
"""
incident_angle = P["incident_angle"]
beam = ba.Beam(1e8, 0.1*nm, incident_angle)
n = 100
detector = ba.SphericalDetector(n, -1.5*deg, 1.5*deg, n, 0, 2*deg)
return ba.ScatteringSimulation(beam, get_sample(P), detector)
def simulation1(P):
return get_simulation(P | {"incident_angle": 0.1*deg})
def simulation2(P):
return get_simulation(P | {"incident_angle": 0.4*deg})
def fake_data(incident_alpha):
"""
Generating "real" data by adding noise to the simulated data.
"""
P = {
'radius_a': 5*nm,
'radius_b': 6*nm,
'radius_c': 8*nm,
"incident_angle": incident_alpha
}
simulation = get_simulation(P)
result = simulation.simulate()
return result.noisy(0.1, 0.1)
def get_plotters(exp_data, index):
"""
Creates the three fit-progress plotters for one dataset.
"""
norm = ba.intensity_norm(exp_data)
suffix = f" {index + 1}"
def plot_selected_simulation(simulations, ax=None, **plot_args):
"""
Plots this dataset's simulation from the shared result tuple.
"""
return ba.plot_heatmap(simulations[index], ax=ax, **plot_args)
def plot_selected_difference(simulations, ax=None, **plot_args):
"""
Plots this dataset's relative difference from the result tuple.
"""
return ba.plot_difference(
simulations[index], ax=ax, context_data=exp_data, **plot_args)
experiment_plotter = ba.FitPlotter(
ba.plot_experimental,
context_data=exp_data,
norm=norm,
with_cb=True,
title="Experimental" + suffix,
)
simulation_plotter = ba.FitPlotter(
plot_selected_simulation,
norm=norm,
with_cb=True,
title="Simulation" + suffix,
)
difference_plotter = ba.FitPlotter(
plot_selected_difference,
with_cb=True,
title="Relative difference" + suffix,
)
return [
experiment_plotter,
simulation_plotter,
difference_plotter,
]
if __name__ == '__main__':
exp_data1 = fake_data(0.1*deg)
exp_data2 = fake_data(0.4*deg)
flat_exp_values1 = exp_data1.intensities().ravel()
flat_exp_values2 = exp_data2.intensities().ravel()
# Fit progress display
monitor = ba.FitMonitor(
get_plotters(exp_data1, 0) + get_plotters(exp_data2, 1),
ncols=3,
show_best=True,
max_fps=1,
printer=ba.Printer(every_nth=10),
live=True)
def residuals(P):
"""
Simulates, reports, and returns both datasets' residuals.
"""
values = P.valuesdict()
sim1 = simulation1(values).simulate()
sim2 = simulation2(values).simulate()
flat_sim_values1 = sim1.intensities().ravel()
flat_sim_values2 = sim2.intensities().ravel()
residuals = np.concatenate([
flat_exp_values1 - flat_sim_values1,
flat_exp_values2 - flat_sim_values2,
])
monitor.update((sim1, sim2), P, residuals)
return residuals
P = lmfit.Parameters()
P.add("radius_a", value=4*nm, min=2*nm, max=10*nm)
P.add("radius_b", value=6*nm, vary=False)
P.add("radius_c", value=4*nm, min=2*nm, max=10*nm)
result = lmfit.minimize(residuals, P, method="leastsq")
finalP = result.params.valuesdict()
# Recompute and report the simulations 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()
|