Ejemplo n.º 1
0
    def get_distortion_residuals(self, mask_radius, spread):
        """Obtain residuals for experimental data and distortion corrected data
        with respect to a simulated symmetric ring pattern.

        Parameters
        ----------
        mask_radius : int
            Radius, in pixels, for a mask over the direct beam disc.
        spread : float
            Gaussian spread of each ring in the simulated pattern.

        Returns
        -------
        diff_init : ElectronDiffraction2D
            Difference between experimental data and simulated symmetric ring
            pattern.
        diff_end : ElectronDiffraction2D
            Difference between distortion corrected data and simulated symmetric
            ring pattern.
        """
        # Check all required parameters are defined as attributes
        if self.diffraction_pattern is None:
            raise ValueError(
                "This method requires an Au X-grating diffraction "
                "pattern to be provided. Please update the "
                "CalibrationDataLibrary.")
        if self.affine_matrix is None:
            raise ValueError(
                "This method requires a distortion matrix to have "
                "been determined. Use get_elliptical_distortion "
                "to determine this matrix.")
        # Set name for experimental data pattern
        dpeg = self.diffraction_pattern
        ringP = self.ring_params
        size = dpeg.data.shape[0]
        dpref = generate_ring_pattern(
            image_size=size,
            mask=True,
            mask_radius=mask_radius,
            scale=ringP[0],
            amplitude=ringP[1],
            spread=spread,
            direct_beam_amplitude=ringP[3],
            asymmetry=1,
            rotation=ringP[5],
        )
        # Apply distortion corrections to experimental data
        dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
        dpegs = ElectronDiffraction2D(dpegs.data.reshape((2, 2, size, size)))
        dpegs.apply_affine_transformation(self.affine_matrix,
                                          preserve_range=True,
                                          inplace=True)
        # Calculate residuals to be returned
        diff_init = ElectronDiffraction2D(dpeg.data - dpref.data)
        diff_end = ElectronDiffraction2D(dpegs.inav[0, 0].data - dpref.data)
        residuals = stack_method([diff_init, diff_end])

        return ElectronDiffraction2D(residuals)
Ejemplo n.º 2
0
def diffraction_pattern(z):
    """A simple, multiuse diffraction pattern, with dimensions:
    ElectronDiffraction2D <2,2|8,8>
    """
    dp = ElectronDiffraction2D(z)
    dp.metadata.Signal.found_from = "conftest"  # dummy metadata
    return dp
Ejemplo n.º 3
0
    def test_set_data_type(self):
        # set 8 bit data type which will result in an incorrect mean square
        # pattern if not changed.

        dp_array = np.array([
            [[[10, 10], [50, 30]], [[8, 20], [50, 30]]],
            [[[12, 30], [0, 30]], [[10, 10], [50, 30]]],
        ]).astype(np.uint8)

        variance_test_diffraction_pattern = ElectronDiffraction2D(dp_array)
        vargen = VarianceGenerator(variance_test_diffraction_pattern)

        vardps_8 = vargen.get_diffraction_variance(dqe=1)
        assert isinstance(vardps_8, DiffractionVariance2D)
        corr_var_dp_8 = np.array([[-0.08, -0.66857143],
                                  [-0.92213333, -0.88666667]])
        assert np.allclose(vardps_8.data[1, 1],
                           corr_var_dp_8,
                           atol=1e-6,
                           equal_nan=True)

        vardps_16 = vargen.get_diffraction_variance(dqe=1,
                                                    set_data_type=np.uint16)
        assert isinstance(vardps_16, DiffractionVariance2D)
        corr_var_dp_16 = np.array([[-0.08, 0.16734694],
                                   [0.30666667, -0.0333333]])

        assert np.allclose(vardps_16.data[1, 1],
                           corr_var_dp_16,
                           atol=1e-6,
                           equal_nan=True)
Ejemplo n.º 4
0
    def test_out_of_range_vectors_DiffractionVectors(self):
        """Test that putting vectors that lie outside of the
        diffraction patterns raises a ValueError"""
        vectors = DiffractionVectors(np.array([[1, -100]]))
        dp = ElectronDiffraction2D(np.ones((20, 20)))

        with pytest.raises(ValueError):
            _ = SubpixelrefinementGenerator(dp, vectors)
    def test_out_of_range_vectors_numpy(self):
        """Test that putting vectors that lie outside of the
        diffraction patterns raises a ValueError"""
        vector = np.array([[1, -100]])
        dp = ElectronDiffraction2D(np.ones((20, 20)))

        with pytest.raises(
            ValueError,
            match="Some of your vectors do not lie within your diffraction pattern",
        ):
            _ = SubpixelrefinementGenerator(dp, vector)
Ejemplo n.º 6
0
def test_AcceleratedIndexationGenerator(good_library):
    signal = ElectronDiffraction2D((np.ones((2, 2, 256, 256)))).as_lazy()
    library = generate_library(good_library=good_library)

    if good_library:
        acgen = AcceleratedIndexationGenerator(signal, library)
        d = acgen.correlate(n_largest=2)

    elif not good_library:
        with pytest.raises(ValueError):
            acgen = AcceleratedIndexationGenerator(signal, library)

    return None
    def test_wrong_navigation_dimensions(self):
        """Tests that navigation dimensions must be appropriate too."""
        dp = ElectronDiffraction2D(np.zeros((2, 2, 8, 8)))
        vectors = DiffractionVectors(np.zeros((1, 2)))
        dp.axes_manager.set_signal_dimension(2)
        vectors.axes_manager.set_signal_dimension(0)

        # Note - uses regex via re.search()
        with pytest.raises(
            ValueError,
            match=r"Vectors with shape .* must have the same navigation shape as .*",
        ):
            _ = SubpixelrefinementGenerator(dp, vectors)
Ejemplo n.º 8
0
 def test_2d_data_as_lazy(self):
     data = np.random.random((100, 150))
     s = ElectronDiffraction2D(data)
     scale0, scale1, metadata_string = 0.5, 1.5, "test"
     s.axes_manager[0].scale = scale0
     s.axes_manager[1].scale = scale1
     s.metadata.Test = metadata_string
     s_lazy = s.as_lazy()
     assert isinstance(s_lazy, LazyElectronDiffraction2D)
     assert hasattr(s_lazy.data, "compute")
     assert s_lazy.axes_manager[0].scale == scale0
     assert s_lazy.axes_manager[1].scale == scale1
     assert s_lazy.metadata.Test == metadata_string
     assert data.shape == s_lazy.data.shape
Ejemplo n.º 9
0
def variance_generator():
    diffraction_pattern = ElectronDiffraction2D(
        np.array([
            [
                [
                    [0.66, 0.5, 0.01, 0.54, 0.83, 0.23, 0.92, 0.14],
                    [0.61, 0.45, 0.01, 0.42, 0.33, 0.48, 0.35, 0.19],
                    [0.87, 0.98, 0.58, 0.51, 0.75, 0.95, 0.22, 0.52],
                    [0.29, 0.13, 0.22, 0.98, 0.04, 0.12, 0.26, 0.67],
                    [0.59, 0.55, 0.63, 0.57, 0.89, 0.39, 0.81, 0.43],
                    [0.9, 0.54, 0.24, 0.92, 0.77, 0.33, 0.22, 0.7],
                    [0.7, 0.3, 0.76, 0.27, 0.93, 0.28, 0.73, 0.22],
                    [0.33, 0.7, 0.32, 0.54, 0.27, 0.87, 0.97, 0.7],
                ],
                [
                    [0.68, 0.33, 0.11, 0.26, 0.88, 0.02, 0.71, 0.98],
                    [0.62, 0.55, 0.22, 0.43, 0.17, 0.77, 0.42, 0.52],
                    [0.45, 0.2, 0.21, 0.53, 0.38, 0.64, 0.32, 0.38],
                    [0.5, 0.23, 0.25, 0.91, 0.64, 1.0, 0.69, 0.16],
                    [0.11, 0.82, 0.23, 0.91, 0.46, 0.08, 0.55, 0.86],
                    [0.95, 0.68, 0.74, 0.44, 0.65, 0.92, 0.04, 0.62],
                    [0.59, 0.08, 0.2, 0.33, 0.94, 0.67, 0.31, 0.62],
                    [0.77, 0.01, 0.46, 0.81, 0.92, 0.72, 0.38, 0.25],
                ],
            ],
            [
                [
                    [0.07, 0.63, 0.89, 0.71, 0.65, 0.1, 0.58, 0.78],
                    [0.05, 0.35, 0.02, 0.87, 0.06, 0.06, 0.23, 0.52],
                    [0.44, 0.77, 0.93, 0.94, 0.22, 0.29, 0.22, 0.03],
                    [0.9, 0.79, 0.82, 0.61, 0.6, 0.96, 0.13, 0.63],
                    [0.57, 0.63, 0.53, 0.81, 0.38, 0.92, 0.92, 0.07],
                    [0.01, 0.33, 0.69, 0.36, 0.91, 0.24, 0.05, 0.85],
                    [0.81, 0.38, 0.74, 0.12, 0.33, 0.29, 0.25, 0.06],
                    [0.28, 0.61, 0.37, 0.17, 0.38, 0.52, 0.36, 0.69],
                ],
                [
                    [0.77, 0.68, 0.76, 0.62, 0.52, 0.69, 0.63, 0.11],
                    [0.6, 0.96, 0.17, 0.58, 0.12, 0.23, 0.1, 0.2],
                    [0.4, 0.24, 0.25, 0.61, 0.27, 0.02, 0.03, 0.12],
                    [0.83, 0.66, 0.15, 0.74, 0.91, 0.19, 0.97, 0.58],
                    [0.5, 0.27, 0.93, 0.1, 0.78, 0.73, 0.56, 0.82],
                    [0.49, 0.35, 0.9, 0.48, 0.04, 0.46, 0.16, 0.1],
                    [1.0, 0.13, 0.56, 0.12, 0.16, 0.49, 0.63, 0.5],
                    [0.97, 0.71, 0.78, 0.38, 0.08, 0.79, 0.41, 0.07],
                ],
            ],
        ]))
    return VarianceGenerator(diffraction_pattern)
Ejemplo n.º 10
0
def ring_pattern(input_parameters):
    x0 = input_parameters
    ring_data = generate_ring_pattern(
        image_size=256,
        mask=True,
        mask_radius=10,
        scale=x0[0],
        amplitude=x0[1],
        spread=x0[2],
        direct_beam_amplitude=x0[3],
        asymmetry=x0[4],
        rotation=x0[5],
    )

    return ElectronDiffraction2D(ring_data)
def test_xy_errors_in_conventional_xc_method_as_per_issue_490():
    """ This was the MWE example code for the issue """
    dp = get_simulated_disc(100, 20)
    # translate y by +4
    shifted = np.pad(dp, ((0, 4), (0, 0)), "constant")[4:].reshape(1, 1, *dp.shape)
    signal = ElectronDiffraction2D(shifted)
    spg = SubpixelrefinementGenerator(signal, np.array([[0, 0]]))
    peaks = spg.conventional_xc(100, 20, 1).data[0, 0, 0]  # as quoted in the issue
    np.testing.assert_allclose([0, -4], peaks)
    """ we also test com method for clarity """
    peaks = spg.center_of_mass_method(60).data[0, 0, 0]
    np.testing.assert_allclose([0, -4], peaks, atol=1.5)
    """ we also test reference_xc """
    peaks = spg.reference_xc(100, dp, 1).data[0, 0, 0]  # as quoted in the issue
    np.testing.assert_allclose([0, -4], peaks)
Ejemplo n.º 12
0
def test_integration_generator(radius, offset):
    pixel_positions = np.array([[0, 0], [15, -15], [-15, 15]])
    pattern = np.zeros((50, 50))
    center = np.array(pattern.shape) / 2
    i, j = (pixel_positions + center + offset).T.astype(int)
    pattern[i, j] = 1

    dv = DiffractionVectors(pixel_positions)
    dp = ElectronDiffraction2D(pattern)
    ig = IntegrationGenerator(dp, dv)
    assert isinstance(ig, IntegrationGenerator)

    inties = ig.extract_intensities(radius=radius)
    assert isinstance(inties, BaseSignal)

    assert np.allclose(inties.data, [1, 1, 1])
Ejemplo n.º 13
0
    def test_apply_affine_transformation_with_casting(self, diffraction_pattern):
        diffraction_pattern.change_dtype("uint8")

        with pytest.warns(
            UserWarning,
            match="Bi-quadratic interpolation behavior has changed due to a bug in the implementation of scikit-image",
        ):
            transformed_dp = ElectronDiffraction2D(
                diffraction_pattern
            ).apply_affine_transformation(
                D=np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.2]]),
                order=2,
                keep_dtype=True,
                inplace=False,
            )

        assert transformed_dp.data.dtype == "uint8"
Ejemplo n.º 14
0
    def plot_corrected_diffraction_pattern(self,
                                           reference_circle=True,
                                           *args,
                                           **kwargs):
        """Plot the distortion corrected diffraction pattern with an optional
        reference circle.

        Parameters
        ----------
        reference_circle : bool
            If True a CircleROI widget is added to the plot for reference.
        *args : arguments
            Arguments to be passed to the plot method.
        **kwargs : keyword arguments
            Keyword arguments to be passed to the plot method.

        """
        # Check all required parameters are defined as attributes
        if self.diffraction_pattern is None:
            raise ValueError(
                "This method requires an Au X-grating diffraction "
                "pattern to be provided. Please update the "
                "CalibrationDataLibrary.")
        if self.affine_matrix is None:
            raise ValueError(
                "This method requires a distortion matrix to have "
                "been determined. Use get_elliptical_distortion "
                "to determine this matrix.")
        # Set name for experimental data pattern
        dpeg = self.diffraction_pattern
        # Apply distortion corrections to experimental data
        size = dpeg.data.shape[0]
        dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
        dpegs = ElectronDiffraction2D(dpegs.data.reshape((2, 2, size, size)))
        dpegs.apply_affine_transformation(self.affine_matrix,
                                          preserve_range=True,
                                          inplace=True)
        dpegm = dpegs.mean((0, 1))
        # Plot distortion corrected data
        dpegm.plot(*args, **kwargs)
        # add reference circle if specified
        if reference_circle is True:
            circ = CircleROI(cx=size / 2, cy=size / 2, r=size / 5, r_inner=0)
            circ.add_widget(dpegm)
Ejemplo n.º 15
0
    def create_spot(self):
        z1, z1a = np.zeros((128, 128)), np.zeros((128, 128))
        z2, z2a = np.zeros((128, 128)), np.zeros((128, 128))

        rr, cc = draw.disk((30, 90), radius=4, shape=z1.shape)  # 30 is y!
        z1[rr, cc], z2[rr, cc] = 1, 1
        rr2, cc2 = draw.disk((100, 60), radius=4, shape=z2.shape)
        z2[rr2, cc2] = 1
        rr, cc = draw.disk((30, 90 + 3), radius=4, shape=z1.shape)  # 30 is y!
        z1a[rr, cc], z2a[rr, cc] = 1, 1
        rr2, cc2 = draw.disk((100 - 2, 60), radius=4, shape=z2.shape)
        z2a[rr2, cc2] = 1

        # marks centers for local com and local_gaussian_method
        z1[30, 90], z2[30, 90], z2[100, 60] = 2, 2, 2
        z1a[30, 93], z2a[30, 93], z2a[98, 60] = 10, 10, 10

        dp = ElectronDiffraction2D(np.asarray([[z1, z1a], [z2, z2a]
                                               ]))  # this needs to be in 2x2
        return dp
Ejemplo n.º 16
0
def test_integration_generator_summation_method():
    pixel_positions = np.array([[0, 0], [25, -25], [-25, 25]])
    pattern = np.zeros((100, 100))
    center = np.array(pattern.shape) / 2
    i, j = (pixel_positions + center).T.astype(int)
    pattern[i, j] = 1.0
    pattern = gaussian_filter(pattern, 2)

    dv = DiffractionVectors(pixel_positions)
    dp = ElectronDiffraction2D(pattern)
    ig = IntegrationGenerator(dp, dv)

    assert isinstance(ig, IntegrationGenerator)

    vectors = ig.extract_intensities_summation_method()

    assert np.allclose(pixel_positions, vectors.data, atol=0.05)
    assert np.allclose(vectors.data, pixel_positions, atol=0.05)
    assert np.allclose(vectors.intensities.data[0], 1.0, atol=0.05)
    assert np.allclose(vectors.sigma.data[0], 0.0, atol=0.05)
    assert isinstance(vectors, DiffractionVectors)
Ejemplo n.º 17
0
def test_TemplateIndexationGenerator(default_structure, method):
    identifiers = ["a", "b"]
    structures = [default_structure, default_structure]
    orientations = [
        [(0, 0, 0), (0, 1, 0), (1, 0, 0)],
        [(0, 0, 1), (0, 0, 2), (0, 0, 3)],
    ]
    structure_library = StructureLibrary(identifiers, structures, orientations)
    libgen = DiffractionLibraryGenerator(DiffractionGenerator(300))
    library = libgen.get_diffraction_library(structure_library, 0.017, 0.02,
                                             (100, 100), False)

    edp = ElectronDiffraction2D(np.random.rand(2, 2, 200, 200))
    indexer = TemplateIndexationGenerator(edp, library)

    mask_signal = hs.signals.Signal2D(np.array([[1, 0], [1, 1]])).T
    z = indexer.correlate(method=method, n_largest=2, mask=mask_signal)
    assert isinstance(z, TemplateMatchingResults)
    assert isinstance(z.data, Signal2D)
    assert z.data.data.shape[0:2] == edp.data.shape[0:2]
    assert z.data.data.shape[3] == 5
Ejemplo n.º 18
0
def signal_data():
    s = ElectronDiffraction2D(np.zeros((4, 5, 6, 6)))
    s.inav[:2, :2].data[..., 0, 0] = 2
    s.inav[:2, :2].data[..., 0, 3] = 2
    s.inav[:2, :2].data[..., 3, 5] = 2

    s.inav[2:, :3].data[..., 3, 3] = 2
    s.inav[2:, :3].data[..., 3, 0] = 2

    s.inav[2, :2].data[..., 0, 0] = 1
    s.inav[2, :2].data[..., 0, 3] = 1
    s.inav[2, :2].data[..., 3, 5] = 1
    s.inav[2, :2].data[..., 3, 3] = 1
    s.inav[2, :2].data[..., 3, 0] = 1

    s.inav[:2, 2:].data[..., 5, 5] = 3
    s.inav[:2, 2:].data[..., 5, 0] = 3
    s.inav[:2, 2:].data[..., 5, 3] = 3

    s.inav[3:, 2:].data[..., 5, 5] = 3
    s.inav[3:, 2:].data[..., 5, 0] = 3
    return s
Ejemplo n.º 19
0
 def ones(self):
     ones_diff = ElectronDiffraction2D(data=np.ones(shape=(5, 5)))
     ones_diff.axes_manager.signal_axes[0].name = "kx"
     ones_diff.axes_manager.signal_axes[1].name = "ky"
     ones_diff.unit = "2th_rad"
     return ones_diff
Ejemplo n.º 20
0
    def plot_calibrated_data(self,
                             data_to_plot,
                             line=None,
                             unwrap=False,
                             *args,
                             **kwargs):  # pragma: no cover
        """Plot calibrated data for visual inspection.

        Parameters
        ----------
        data_to_plot : str
            Specify the calibrated data to be plotted. Valid options are:
            {'au_x_grating_dp', 'au_x_grating_im', 'moo3_dp', 'moo3_im',
            'rotation_overlay'}
        line : :obj:`hyperspy.roi.Line2DROI`
            An optional Line2DROI object, as detailed in HyperSpy, to be added
            as a widget to the calibration data plot and the trace plotted
            interactively.
        *args : arguments
            Arguments to be passed to the plot method.
        **kwargs : keyword arguments
            Keyword arguments to be passed to the plot method.
        """
        # Construct object containing user defined data to plot and set the
        # calibration checking that it is defined.
        if data_to_plot == "au_x_grating_dp":
            dpeg = self.diffraction_pattern
            size = dpeg.data.shape[0]
            if self.correction_matrix is None:
                self.get_correction_matrix()
            dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
            dpegs = ElectronDiffraction2D(
                dpegs.data.reshape((2, 2, size, size)))
            dpegs.apply_affine_transformation(self.correction_matrix,
                                              preserve_range=True,
                                              inplace=True)
            data = dpegs.mean((0, 1))
            data.set_diffraction_calibration(self.diffraction_calibration)
            # Plot the calibrated diffraction data
            data.plot(*args, **kwargs)
        elif data_to_plot == "au_x_grating_im":
            data = self.diffraction_pattern
            # Plot the calibrated image data
            data.plot(*args, **kwargs)
        elif data_to_plot == "moo3_dp":
            dpeg = self.calibration_data.moo3_dp
            size = dpeg.data.shape[0]
            if self.correction_matrix is None:
                self.get_correction_matrix()
            dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
            dpegs = ElectronDiffraction2D(
                dpegs.data.reshape((2, 2, size, size)))
            dpegs.apply_affine_transformation(self.correction_matrix,
                                              preserve_range=True,
                                              inplace=True)
            data = dpegs.mean((0, 1))
            data.set_diffraction_calibration(self.diffraction_calibration)
            # Plot the calibrated diffraction data
            data.plot(*args, **kwargs)
        elif data_to_plot == "moo3_im":
            data = self.calibration_data.moo3_im
            # Plot the calibrated image data
            data.plot(*args, **kwargs)
        elif data_to_plot == "rotation_overlay":
            dpeg = self.calibration_data.moo3_dp
            size = dpeg.data.shape[0]
            if self.correction_matrix is None:
                self.get_correction_matrix()
            dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
            dpegs = ElectronDiffraction2D(
                dpegs.data.reshape((2, 2, size, size)))
            dpegs.apply_affine_transformation(self.correction_matrix,
                                              preserve_range=True,
                                              inplace=True)
            dp = dpegs.mean((0, 1))
            im = self.calibration_data.moo3_im.rebin(dp.data.shape)
            stack1 = np.zeros((dp.data.shape[0], dp.data.shape[1], 3))
            stack1[:, :, 0] = dp.data / (0.05 * dp.data.max())
            stack1[:, :, 2] = im.data / im.data.max()
            plt.figure(1)
            plt.imshow(stack1)
        if line:
            line.add_widget(data, axes=data.axes_manager.signal_axes)
            trace = line.interactive(data, navigation_signal="same")
            trace.plot()
            return trace
Ejemplo n.º 21
0
    def get_diffraction_calibration(self, mask_length, linewidth):
        """Determine the diffraction pattern pixel size calibration in units of
        reciprocal Angstroms per pixel.

        Parameters
        ----------
        mask_length : float
            Halfwidth of the region excluded from peak finding around the
            diffraction pattern center.
        linewidth : float
            Width of Line2DROI used to obtain line trace from distortion
            corrected diffraction pattern.

        Returns
        -------
        diff_cal : float
            Diffraction calibration in reciprocal Angstroms per pixel.

        """
        # Check that necessary calibration data is provided
        if self.diffraction_pattern is None:
            raise ValueError(
                "This method requires an Au X-grating diffraction "
                "pattern to be provided. Please update the "
                "CalibrationDataLibrary.")
        if self.affine_matrix is None:
            raise ValueError(
                "This method requires a distortion matrix to have "
                "been determined. Use get_elliptical_distortion "
                "to determine this matrix.")
        dpeg = self.diffraction_pattern
        size = dpeg.data.shape[0]
        dpegs = stack_method([dpeg, dpeg, dpeg, dpeg])
        dpegs = ElectronDiffraction2D(dpegs.data.reshape((2, 2, size, size)))
        dpegs.apply_affine_transformation(self.affine_matrix,
                                          preserve_range=True,
                                          inplace=True)
        dpegm = dpegs.mean((0, 1))
        # Define line roi along which to take trace for calibration
        line = Line2DROI(x1=5,
                         y1=5,
                         x2=size - 6,
                         y2=size - 6,
                         linewidth=linewidth)
        # Obtain line trace
        trace = line(dpegm)
        trace = trace.as_signal1D(0)
        # Find peaks in line trace either side of direct beam
        db = (np.sqrt(2) * (size / 2)) - (5 * np.sqrt(2))
        pka = trace.isig[db +
                         mask_length:].find_peaks1D_ohaver()[0]["position"]
        pkb = trace.isig[:db -
                         mask_length].find_peaks1D_ohaver()[0]["position"]
        # Define Au 220 interplanar spacing (in Angstroms)
        d220 = 1.442
        # Determine predicted position of Au 220 peak
        au_pre = db - (self.ring_params[0] / d220)
        au_post = db + (self.ring_params[0] / d220)
        # Calculate differences between predicted and measured positions
        prediff = np.abs(pkb - au_pre)
        postdiff = np.abs(pka - au_post)
        # Calculate new calibration value based on most accurate peak positions
        dc = (2 / d220) / (pka[postdiff == min(postdiff)] -
                           pkb[prediff == min(prediff)])
        # Store diffraction calibration value as attribute
        self.diffraction_calibration = dc[0]

        return dc[0]
Ejemplo n.º 22
0
def test_init():
    z = np.zeros((2, 2, 2, 2))
    _ = ElectronDiffraction2D(
        z, metadata={"Acquisition_instrument": {
            "SEM": "Expensive-SEM"
        }})
Ejemplo n.º 23
0
 def test_4d_data_as_lazy(self):
     data = np.random.random((4, 10, 15))
     s = ElectronDiffraction2D(data)
     s_lazy = s.as_lazy()
     assert isinstance(s_lazy, LazyElectronDiffraction2D)
     assert data.shape == s_lazy.data.shape
Ejemplo n.º 24
0
    def get_virtual_electron_diffraction(self, calibration, shape, sigma):
        """Obtain a virtual electron diffraction signal that consists
        of one virtual diffraction pattern for each segment. The virtual
        diffraction pattern is composed of Gaussians centered at each
        vector position. If given, the integrated intensities of each
        vector will be taken into account by multiplication with the
        Gaussians.

        Parameters
        ----------
        calibration : float
            Reciprocal space calibration in inverse Angstrom per pixel.
        shape : tuple
            Shape of the signal, (shape_x, shape_y) in pixels, where
            shape_x and shape_y are integers.
        sigma : float
            The standard deviation of the Gaussians in inverse Angstrom
            per pixel. 'calibration' is a decent starting value.

        Returns
        -------
        virtual_ed : ElectronDiffraction2D
            Virtual electron diffraction signal consisting of one
            virtual diffraction pattern for each segment.
        """
        vectors = self.vectors_of_segments.data
        segments = self.segments.data
        num_segments = np.shape(segments)[0]

        if self.intensities is None:
            raise ValueError("The VDFSegment does not have the attribute "
                             "intensities, required for this method.")
        else:
            intensities = self.intensities

        # TODO: Refactor this to use the diffsims simulation to plot functionality
        size_x, size_y = shape[0], shape[1]
        cx, cy = -size_x / 2 * calibration, -size_y / 2 * calibration
        x, y = np.indices((size_x, size_y))
        x, y = x * calibration + cx, y * calibration + cy
        virtual_ed = np.zeros((size_x, size_y, num_segments))

        for i in range(num_segments):
            # Allow plotting for segments that are only associated with
            # one vector.
            if np.shape(np.shape(vectors[i]))[0] <= 1:
                virtual_ed[..., i] = get_gaussian2d(
                    intensities[i],
                    vectors[i][..., 0],
                    vectors[i][..., 1],
                    x=x,
                    y=y,
                    sigma=sigma,
                )
            # Allow plotting for segments associated with several vectors.
            else:
                virtual_ed[..., i] = sum(
                    list(
                        map(
                            lambda a, xo, yo: get_gaussian2d(
                                a, xo, yo, x=x, y=y, sigma=sigma),
                            intensities[i],
                            vectors[i][..., 0],
                            vectors[i][..., 1],
                        )))

        virtual_ed = ElectronDiffraction2D(virtual_ed.T)

        return virtual_ed
Ejemplo n.º 25
0
def dp_single(request):
    """
    1D (in navigation space) diffraction pattern <1|8,8>
    """
    return ElectronDiffraction2D(request.param)
Ejemplo n.º 26
0
 def test_set_diffraction_calibration(self):
     ones = ElectronDiffraction2D(data=np.ones((3, 3, 3, 3)))
     ones.diffraction_calibration = 0.9
     assert ones.axes_manager.signal_axes[0].scale == 0.9
     assert ones.axes_manager.signal_axes[1].scale == 0.9
     assert ones.diffraction_calibration == 0.9