Fitting along slices

Here we demonstrate how to fit along slices. The idea is that the user defines the positions of vertical and horizontal lines crossing the detector plane in regions of most interest (Yoneda wings, Bragg peaks, etc.) and then finds the sample parameters which fits those regions best.

Such an approach uses much less CPU while still giving a chance to find the optimal sample parameters. In general, however, it is arguable whether fitting along slices makes more sense than fitting using the whole detector image.

Technically, the idea is to pass a boolean bitmap mask to SphericalDetector, with the whole detector excluded except thin lines, one vertical and one horizontal, representing slices. This makes the scattering simulation calculate only along these indicated slices.

  • In the given script we simulate a dilute random assembly of cylinders on a substrate. The fitting procedure looks for the cylinder’s height and radius.
  • Function get_masked_simulation masks the entire detector except for a horizontal and a vertical stripe.
  • The custom PlotObserver class, which plots the fit along the slices at every 10th fit iteration.

Fit window

  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
#!/usr/bin/env python3
"""
Fitting example: fit along slices
"""

from matplotlib.colors import ListedColormap
from matplotlib import pyplot as plt
import bornagain as ba
from bornagain import ba_fit, ba_plot, deg, nm, nm2
import lmfit
import numpy as np


def get_sample(P):
    """
    Uncorrelated cylinders on a substrate, parameterized for fitting.
    """
    substrate_mat = ba.RefractiveMaterial(
        "Substrate", (0.28, 0.57, 0.82), 6e-6, 2e-8)
    particle_mat = ba.RefractiveMaterial(
        "Particle", (0.86, 0.24, 0.18), 6e-4, 2e-8)
    particle = ba.Particle(
        particle_mat, ba.Cylinder(P["radius"], P["height"]))

    particle_layer = ba.Layer(ba.Vacuum())
    particle_layer.deposit2D(ba.Dilute2D(0.01/nm2, particle))

    sample = ba.Sample()
    sample.addLayer(particle_layer)
    sample.addLayer(ba.Layer(substrate_mat))
    return sample


def get_simulation(P):
    """
    GISAS simulation for the parameterized cylinder sample.
    """
    n = 100
    beam = ba.Beam(1e8, 0.1*nm, 0.2*deg)
    detector = ba.SphericalDetector(n, -1*deg, 1*deg, n, 0, 2*deg)
    simulation = ba.ScatteringSimulation(beam, get_sample(P), detector)
    simulation.options().setUseAvgMaterials(False)
    return simulation


phi_slice_value = 0.0  # position of vertical slice in deg
alpha_slice_value = 0.2  # position of horizontal slice in deg

def closest_axis_index(axis, value):
    width = (axis.max() - axis.min()) / axis.size()
    centers = axis.min() + width*(np.arange(axis.size()) + 0.5)
    return int(np.argmin(np.abs(centers - value)))


def get_masked_simulation(P):
    """
    GISAS simulation with only one horizontal and one vertical slice active.
    """
    n = 100
    beam = ba.Beam(1e8, 0.1*nm, 0.2*deg)
    sample = get_sample(P)
    detector = ba.SphericalDetector(n, -1*deg, 1*deg, n, 0, 2*deg)
    n_phi = detector.axis(0).size()
    n_alpha = detector.axis(1).size()

    mask = np.ones((n_alpha, n_phi), dtype=bool)
    i_phi = closest_axis_index(detector.axis(0), phi_slice_value*deg)
    i_alpha = closest_axis_index(detector.axis(1), alpha_slice_value*deg)
    mask[:, i_phi] = False
    mask[i_alpha, :] = False
    detector.setMask(mask)

    simulation = ba.ScatteringSimulation(beam, sample, detector)
    simulation.options().setUseAvgMaterials(False)
    return simulation


def fake_data():
    """
    Generating "real" data by adding noise to the simulated data.
    """
    # initial values which we will have to find later during the fit
    P = {'radius': 5*nm, 'height': 10*nm}

    simulation = get_simulation(P)
    simulation.setBackground(ba.PoissonBackground(seed=0))
    result = simulation.simulate()

    return result.noisy(0.1, 0.1)


class PlotObserver:
    """
    Draws fit progress every nth iteration. Here we plot slices along real
    and simulated images to see fit progress.
    """

    def __init__(self):
        self.fig = plt.figure(figsize=(10.25, 7.69))
        self.fig.canvas.draw()

    @staticmethod
    def slice_indices(data):
        """
        Returns detector bin indices that correspond to the requested slices.
        """
        i_phi = closest_axis_index(data.xAxis(), phi_slice_value*deg)
        i_alpha = closest_axis_index(data.yAxis(), alpha_slice_value*deg)
        return i_phi, i_alpha

    @staticmethod
    def x_slice(data, i_alpha):
        """
        Returns horizontal slice values from plottable 2D data.
        """
        return (np.asarray(data.xCenters()),
                np.asarray(data.intensities()[i_alpha, :]))

    @staticmethod
    def y_slice(data, i_phi):
        """
        Returns vertical slice values from plottable 2D data.
        """
        return (np.asarray(data.yCenters()),
                np.asarray(data.intensities()[:, i_phi]))

    @staticmethod
    def plot_data(data, mask_source, i_phi, i_alpha):
        """
        Plot experimental data with the inactive mask area dimmed.
        """
        data.setTitle("Experimental data")
        ax = plt.gca()
        image = ba_plot.plot_heatmap(data, with_cb=False)

        masked = ~np.isfinite(mask_source.intensities())
        overlay = np.ma.masked_where(~masked,
                                     np.ones_like(masked, dtype=float))
        base_image = ax.images[0]
        ax.imshow(overlay,
                  origin='lower',
                  cmap=ListedColormap([(0.86, 0.86, 0.86, 0.58)]),
                  extent=base_image.get_extent(),
                  aspect=ax.get_aspect(),
                  interpolation='nearest',
                  zorder=2)

        # line representing vertical slice
        x_slice = data.xCenters()[i_phi]
        y_slice = data.yCenters()[i_alpha]
        plt.plot([x_slice, x_slice],
                 [data.yAxis().min(), data.yAxis().max()],
                 color='gray',
                 linestyle='-',
                 linewidth=1,
                 zorder=3)
        # line representing horizontal slice
        plt.plot([data.xAxis().min(), data.xAxis().max()],
                 [y_slice, y_slice],
                 color='gray',
                 linestyle='-',
                 linewidth=1,
                 zorder=3)
        return image

    @staticmethod
    def plot_slices(slices, title):
        """
        Plots vertical and horizontal projections.
        """
        plt.yscale('log')
        ymax = 1.0
        for label, x_values, y_values in slices:
            visible = np.isfinite(y_values) & (y_values > 0)
            plt.plot(x_values[visible], y_values[visible], label=label)
            plt.xlim(np.amin(x_values), np.amax(x_values))
            if np.any(visible):
                ymax = max(ymax, np.amax(y_values[visible]))
        plt.ylim(1, max(10, ymax*10))
        plt.legend(loc='upper right')
        plt.title(title)

    @staticmethod
    def display_fit_parameters(P, iteration, chi2):
        """
        Displays fit parameters, chi and iteration number.
        """
        plt.title('Parameters')
        plt.axis('off')

        plt.text(
            0.01, 0.85, "Iterations  " +
            '{:d}'.format(iteration))
        plt.text(0.01, 0.75,
                 "Chi2       " + '{:8.4f}'.format(chi2))
        for index, (name, val) in enumerate(P.valuesdict().items()):
            plt.text(
                0.01, 0.55 - index*0.1,
                '{:30.30s}: {:6.3f}'.format(name, val))

    def update(self, raw_data, simul_data, P, iteration, chi2):
        """
        Callback to plot every n'th iteration.
        """
        self.fig.clf()

        i_phi, i_alpha = self.slice_indices(simul_data)

        data = raw_data.plottableField()
        masked_data = ba_plot.masked_datafield(raw_data, simul_data).plottableField()
        simul_data = simul_data.plottableField()
        phi_slice = data.xCenters()[i_phi]
        alpha_slice = data.yCenters()[i_alpha]

        canvas = self.fig.add_gridspec(2, 2)
        canvas.update(left=0.07, right=0.96, bottom=0.08, top=0.93,
                      wspace=0.45, hspace=0.35)

        # plot real data
        plt.sca(self.fig.add_subplot(canvas[0, 0]))
        data_image = self.plot_data(data, simul_data, i_phi, i_alpha)

        # horizontal slices
        slices = [("real", *self.x_slice(masked_data, i_alpha)),
                  ("simul", *self.x_slice(simul_data, i_alpha))]
        title = ("Horizontal slice at alpha =" +
                 '{:4.2f}'.format(alpha_slice))
        plt.sca(self.fig.add_subplot(canvas[0, 1]))
        self.plot_slices(slices, title)

        # vertical slices
        slices = [("real", *self.y_slice(masked_data, i_phi)),
                  ("simul", *self.y_slice(simul_data, i_phi))]
        title = "Vertical slice at phi =" + '{:4.2f}'.format(phi_slice)
        plt.sca(self.fig.add_subplot(canvas[1, 0]))
        self.plot_slices(slices, title)

        # display fit parameters
        plt.sca(self.fig.add_subplot(canvas[1, 1]))
        self.display_fit_parameters(P, iteration, chi2)
        ba_plot.add_colorbar(data_image, fig=self.fig, pad=0.012,
                             width=0.014, fontsize=12)
        plt.draw()
        plt.pause(0.01)


def run_fitting():
    """
    main function to run fitting
    """

    data = fake_data()
    exp_values = data.intensities()
    sim_result = None  # latest simulation, shared with the plot callback

    def residuals(P):
        """
        Runs a simulation for given parameters P, and returns residuals
        vector; masked (NaN) pixels contribute zero.
        """
        nonlocal sim_result
        sim_result = get_masked_simulation(P.valuesdict()).simulate()
        return ba_fit.valid_pixel_residual(exp_values,
                                           sim_result.intensities())

    # creating custom observer which will draw fit progress
    plotter = PlotObserver()
    def plot_iteration(P, iteration, resid):
        if iteration % 10 == 0 and sim_result is not None:
            plotter.update(data, sim_result, P, iteration,
                           float(np.sum(resid*resid)))

    P = lmfit.Parameters()
    P.add("radius", 6.*nm, min=4, max=8)
    P.add("height", 9.*nm, min=8, max=12)

    result = lmfit.minimize(residuals, P, iter_cb=plot_iteration)
    print(lmfit.fit_report(result))
    finalP = result.params.valuesdict()
    ba.showSample3D(get_sample(finalP), sample_size=120*nm, seed=0)


if __name__ == '__main__':
    run_fitting()
    plt.show()
auto/Examples/fit/scatter2d/fit_along_slices.py