Ejemplo n.º 1
0
def load_mib(filename, scan_size, sum_length=10):  # pragma: no cover
    """Load a medipix hdr/mib file.

    Parameters
    ----------
    filename : string
        File path and name to .hdr file.
    scan_size : int
        Scan size in pixels, allows the function to reshape the array into
        the right shape.
    sum_length : int
        Number of lines to sum over to determine scan fly back location.

    """
    dpt = load_with_reader(filename=filename, reader=mib_reader)
    dpt = ElectronDiffraction2D(
        dpt.data.reshape((scan_size, scan_size, 256, 256)))
    trace = dpt.inav[:, 0:sum_length].sum((1, 2, 3))
    edge = np.where(trace == max(trace.data))[0][0]
    if edge == scan_size - 1:
        dp = ElectronDiffraction2D(dpt.inav[0:edge, 1:])
    else:
        dp = ElectronDiffraction2D(
            np.concatenate((dpt.inav[edge + 1:, 1:], dpt.inav[0:edge, 1:]),
                           axis=1))

    dp.data = np.flip(dp.data, axis=2)

    return dp
Ejemplo n.º 2
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.calibration_data.au_x_grating_dp 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.calibration_data.au_x_grating_dp
        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.º 3
0
def test_strain_mapping_affine_transform():
    latt = diffpy.structure.lattice.Lattice(3, 3, 3, 90, 90, 90)
    atom = diffpy.structure.atom.Atom(atype='Zn', xyz=[0, 0, 0], lattice=latt)
    structure = diffpy.structure.Structure(atoms=[atom], lattice=latt)
    ediff = DiffractionGenerator(300., 0.025)
    affines = [[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
               [[1.04, 0, 0], [0, 1, 0], [0, 0, 1]],
               [[1.08, 0, 0], [0, 1, 0], [0, 0, 1]],
               [[1.12, 0, 0], [0, 1, 0], [0, 0, 1]]]

    data = []
    for affine in affines:
        # same coords as used for latt above
        latt_rot = diffpy.structure.lattice.Lattice(3, 3, 3, 90, 90, 90, baserot=affine)
        structure.placeInLattice(latt_rot)

        diff_dat = ediff.calculate_ed_data(structure, 2.5)
        dpi = sim_as_signal(diff_dat, 64, 0.02, 2.5)
        data.append(dpi.data)
    data = np.array(data)
    dp = ElectronDiffraction2D(data.reshape((2, 2, 64, 64)))

    m = dp.create_model()
    ref = ScalableReferencePattern(dp.inav[0, 0])
    m.append(ref)
    m.multifit()
    disp_grad = ref.construct_displacement_gradient()

    assert disp_grad.data.shape == np.asarray(affines).reshape(2, 2, 3, 3).shape
Ejemplo n.º 4
0
    def plot_corrected_diffraction_pattern(self, reference_circle=True):
        """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.

        """
        # Check all required parameters are defined as attributes
        if self.calibration_data.au_x_grating_dp 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.calibration_data.au_x_grating_dp
        # 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(cmap='magma', vmax=0.1)
        # add reference circle if specified
        if reference_circle is True:
            circ = CircleROI(cx=128, cy=128, r=53.5, r_inner=0)
            circ.add_widget(dpegm)
Ejemplo n.º 5
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.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.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.º 6
0
    def diffraction_pattern_for_radial(self):
        """
        Two diffraction patterns with easy to see radial profiles, wrapped
        in ElectronDiffraction2D  <2|8,8>
        """
        dp = ElectronDiffraction2D(np.zeros((2, 8, 8)))
        dp.data[0] = np.array([[0., 0., 2., 2., 2., 2., 0., 0.],
                               [0., 2., 3., 3., 3., 3., 2., 0.],
                               [2., 3., 3., 4., 4., 3., 3., 2.],
                               [2., 3., 4., 5., 5., 4., 3., 2.],
                               [2., 3., 4., 5., 5., 4., 3., 2.],
                               [2., 3., 3., 4., 4., 3., 3., 2.],
                               [0., 2., 3., 3., 3., 3., 2., 0.],
                               [0., 0., 2., 2., 2., 2., 0., 0.]])

        dp.data[1] = np.array([[0., 0., 0., 0., 0., 0., 0., 0.],
                               [0., 0., 0., 0., 0., 0., 0., 0.],
                               [0., 0., 0., 0., 0., 0., 0., 0.],
                               [1., 1., 1., 1., 1., 1., 1., 1.],
                               [1., 1., 1., 1., 1., 1., 1., 1.],
                               [0., 0., 0., 0., 0., 0., 0., 0.],
                               [0., 0., 0., 0., 0., 0., 0., 0.],
                               [0., 0., 0., 0., 0., 0., 0., 0.]])

        return dp
Ejemplo n.º 7
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.º 8
0
def test_plot_best_vector_matching_results_on_signal(structure, rot_list, edc):
    library, match_results = get_vector_match_results(structure, rot_list, edc)
    match_results.data = np.vstack((
        match_results.data,
        match_results.data))  # Hyperspy can only add markers to square signals
    dp = ElectronDiffraction2D(2 * [2 * [np.zeros((144, 144))]])
    match_results.plot_best_matching_results_on_signal(dp)
def test_bad_vectors_numpy():
    """ tests that putting bad vectors in causes an error to be thrown when
    you initiate the geneartor
    """
    v = np.array([[1, -100]])
    dp = ElectronDiffraction2D(np.ones((20, 20)))
    sprg = SubpixelrefinementGenerator(dp, v)
Ejemplo n.º 10
0
    def plot_calibrated_data(self, data_to_plot, *args, **kwargs):
        """ Plot calibrated data for visual inspection.

        Parameters
        ----------
        data_to_plot : string
            Specify the calibrated data to be plotted. Valid options are:
            {'au_x_grating_dp', 'au_x_grating_im', 'moo3_dp', 'moo3_im'}
        """
        # 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.calibration_data.au_x_grating_dp
            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)
            data = dpegs.mean((0, 1))
            data.set_diffraction_calibration(self.diffraction_calibration)
        elif data_to_plot == 'au_x_grating_im':
            data = self.calibration_data.au_x_grating_im
        # Plot the data
        data.plot(*args, **kwargs)
Ejemplo n.º 11
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.º 12
0
    def get_diffraction_calibration(self, mask_length, linewidth):
        """Determine the diffraction pattern pixel size calibration in units of
        reciprocal Angsstroms 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.calibration_data.au_x_grating_dp 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.calibration_data.au_x_grating_dp
        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=250, y2=250, 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) * 128) - (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']
        # Determine predicted position of 022 peak of Au pattern d022=1.437
        au_pre = db - (self.ring_params[0] / 1.437)
        au_post = db + (self.ring_params[0] / 1.437)
        # 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 / 1.437) / (pka[postdiff == min(postdiff)] - pkb[prediff == min(prediff)])
        # Store diffraction calibration value as attribute
        self.diffraction_calibration = dc[0]

        return dc[0]
Ejemplo n.º 13
0
def create_spot_gaussian():
    z1 = np.zeros((128, 128))
    x = np.arange(0.0, 10, 1.0)
    y = x[:, np.newaxis]
    z1[20:30, 50:60] = np.exp(-((x - 5.1)**2 + (y - 5.3)**2) / 4)
    dp = ElectronDiffraction2D(np.asarray([[z1, z1],
                                           [z1,
                                            z1]]))  # this needs to be in 2x2
    return dp
Ejemplo n.º 14
0
 def test_apply_affine_transformation_with_casting(self,
                                                   diffraction_pattern):
     diffraction_pattern.change_dtype('uint8')
     transformed_dp = ElectronDiffraction2D(
         diffraction_pattern).apply_affine_transformation(D=np.array(
             [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.2]]),
                                                          order=2,
                                                          keep_dtype=True,
                                                          inplace=False)
     assert transformed_dp.data.dtype == 'uint8'
Ejemplo n.º 15
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,
            match="Some of your vectors do not lie within your diffraction pattern",
        ):
            sprg = SubpixelrefinementGenerator(dp, vectors)
Ejemplo n.º 16
0
 def ragged_peak(self):
     """
     A small selection of peaks in an ElectronDiffraction2D, to allow
     flexibilty of test building here.
     """
     pattern = np.zeros((2, 2, 128, 128))
     pattern[:, :, 40:42, 45] = 1
     pattern[:, :, 110, 30:32] = 1
     pattern[1, 0, 71:73, 21:23] = 1
     dp = ElectronDiffraction2D(pattern)
     dp.set_diffraction_calibration(1)
     return dp
Ejemplo n.º 17
0
    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 .*",
        ):
            sprg = SubpixelrefinementGenerator(dp, vectors)
Ejemplo n.º 18
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)
Ejemplo n.º 20
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 s_lazy.__class__ == 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.º 21
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.º 22
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])
def create_spot():
    z1 = np.zeros((128, 128))
    z2 = np.zeros((128, 128))

    for r in [4, 3, 2]:
        c = 1 / r
        rr, cc = draw.circle(30, 90, radius=r, shape=z1.shape)  # 30 is y!
        z1[rr, cc] = c
        z2[rr, cc] = c
        rr2, cc2 = draw.circle(100, 60, radius=r, shape=z2.shape)
        z2[rr2, cc2] = c

    dp = ElectronDiffraction2D(np.asarray([[z1, z1],
                                           [z2,
                                            z2]]))  # this needs to be in 2x2
    return dp
Ejemplo n.º 24
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.º 25
0
def sim_as_signal(diffsim, size, sigma, max_r):
    """Returns the diffraction data as an ElectronDiffraction signal with
    two-dimensional Gaussians representing each diffracted peak. Should only
    be used for qualitative work.

    Parameters
    ----------
    diffsim : diffsims.DiffractionSimulation
        A DiffractionSimulation object
    size : int
        Side length (in pixels) for the signal to be simulated.
    sigma : float
        Standard deviation of the Gaussian function to be plotted.
    max_r : float
        Half the side length in reciprocal Angstroms. Defines the signal's
        calibration

    Returns
    -------
    dp : ElectronDiffraction
        Simulated electron diffraction pattern.
    """
    l, delta_l = np.linspace(-max_r, max_r, size, retstep=True)

    mask_for_max_r = np.logical_and(
        np.abs(diffsim.coordinates[:, 0]) < max_r,
        np.abs(diffsim.coordinates[:, 1]) < max_r,
    )

    coords = diffsim.coordinates[mask_for_max_r]
    inten = diffsim.intensities[mask_for_max_r]

    dp_dat = np.zeros([size, size])
    x, y = (coords)[:, 0], (coords)[:, 1]
    if len(x) > 0:  # avoiding problems in the peakless case
        num = np.digitize(x, l, right=True), np.digitize(y, l, right=True)
        dp_dat[num] = inten
        # sigma in terms of pixels. transpose for Hyperspy
        dp_dat = point_spread(dp_dat, sigma=sigma / delta_l).T
        dp_dat = dp_dat / np.max(dp_dat)

    dp = ElectronDiffraction2D(dp_dat)
    dp.set_diffraction_calibration(2 * max_r / size)

    return dp
Ejemplo n.º 26
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.circle(30, 90, radius=4, shape=z1.shape)  # 30 is y!
        z1[rr, cc], z2[rr, cc] = 1, 1
        rr2, cc2 = draw.circle(100, 60, radius=4, shape=z2.shape)
        z2[rr2, cc2] = 1
        rr, cc = draw.circle(30, 90 + 3, radius=4, shape=z1.shape)  # 30 is y!
        z1a[rr, cc], z2a[rr, cc] = 1, 1
        rr2, cc2 = draw.circle(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.º 27
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.º 28
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.º 29
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
Ejemplo n.º 30
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