Пример #1
0
def test_template_get_crystallographic_map(dp_template_match_result,
                                           sp_template_match_result):
    # Assertion free test, as the tests in test_indexation_utils do the heavy
    # lifting
    match_results = np.array(
        np.vstack((dp_template_match_result[0], sp_template_match_result[0])))
    match_results = TemplateMatchingResults(match_results)
    cryst_map = match_results.get_crystallographic_map()
    assert cryst_map.method == "template_matching"
Пример #2
0
    def correlate(self, n_largest=5, mask=None, *args, **kwargs):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values are returned.
        mask : Array
            Array with the same size as signal (in navigation) or None
        *args : arguments
            Arguments passed to map().
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
            Navigation axes of the electron diffraction signal containing
            correlation results for each diffraction pattern, in the form
            [Library Number , [z, x, z], Correlation Score]

        """
        signal = self.signal
        library = self.library

        if mask is None:
            # Index at all real space pixels
            mask = 1

        # TODO: Add extra methods
        no_extra_methods_yet = True
        if no_extra_methods_yet:
            # adds a normalisation to library
            for phase in library.keys():
                norm_array = np.ones(
                    library[phase]
                    ['intensities'].shape[0])  # will store the norms
                for i, intensity_array in enumerate(
                        library[phase]['intensities']):
                    norm_array[i] = np.linalg.norm(intensity_array)
                library[phase][
                    'pattern_norms'] = norm_array  # puts this normalisation into the library

            matches = signal.map(correlate_library,
                                 library=library,
                                 n_largest=n_largest,
                                 mask=mask,
                                 inplace=False,
                                 **kwargs)

        matching_results = TemplateMatchingResults(matches)
        matching_results = transfer_navigation_axes(matching_results, signal)

        return matching_results
Пример #3
0
    def correlate(self, n_largest=5, keys=[], mask=None, *args, **kwargs):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values are returned.
        keys : list
            If more than one phase present in library it is recommended that
            these are submitted. This allows a mapping from the number to the
            phase.  For example, keys = ['si','ga'] will have an output with 0
            for 'si' and 1 for 'ga'.
        mask : Array
            Array with the same size as signal (in navigation) True False
        *args : arguments
            Arguments passed to map().
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
            Navigation axes of the electron diffraction signal containing
            correlation results for each diffraction pattern, in the form
                [Library Number , [z, x, z], Correlation Score]

        """
        signal = self.signal
        library = self.library
        if mask is None:
            # index at all real space pixels
            sig_shape = signal.axes_manager.navigation_shape
            mask = hs.signals.Signal1D(np.ones(
                (sig_shape[0], sig_shape[1], 1)))

        matches = signal.map(correlate_library,
                             library=library,
                             n_largest=n_largest,
                             keys=keys,
                             mask=mask,
                             inplace=False,
                             **kwargs)
        matching_results = TemplateMatchingResults(matches)

        matching_results = transfer_navigation_axes(matching_results, signal)

        return matching_results
Пример #4
0
    def correlate(
        self,
        n_largest=5,
        method="fast_correlation",
        mask=None,
        print_help=False,
        **kwargs,
    ):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values for each phase are returned.
        method : str
            Name of method used to compute correlation between templates and diffraction patterns. Can be
            'fast_correlation' or 'zero_mean_normalized_correlation'.
        mask : Array
            Array with the same size as signal (in navigation) or None
        print_help : bool
            Display information about the method used.
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
        """
        signal = self.signal
        library = self.library

        method_dict = {
            "fast_correlation": fast_correlation,
            "zero_mean_normalized_correlation":
            zero_mean_normalized_correlation,
        }

        if mask is None:
            # Index at all real space pixels
            mask = 1

        # tests if selected method is valid and can print help for selected method.
        chosen_function = select_method_from_method_dict(
            method, method_dict, print_help)

        # adds a normalisation to library #TODO: Port to diffsims
        for phase in library.keys():
            # initialise a container for the norms
            norm_array = np.ones(library[phase]["intensities"].shape[0])

            for i, intensity_array in enumerate(library[phase]["intensities"]):
                norm_array[i] = np.linalg.norm(intensity_array)
                library[phase]["pattern_norms"] = norm_array

        matches = signal.map(
            _correlate_templates,
            library=library,
            n_largest=n_largest,
            method=method,
            mask=mask,
            inplace=False,
            **kwargs,
        )

        matching_results = TemplateMatchingResults(matches)

        return matching_results
Пример #5
0
def test_TemplateMatchingResults_to_crystal_map():
    t = TemplateMatchingResults(np.empty((10,10,10,5)))
    return t.to_crystal_map()
Пример #6
0
    def correlate(
        self,
        n_largest=5,
        method="fast_correlation",
        mask=None,
        print_help=False,
        *args,
        **kwargs,
    ):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values are returned.
        method : str
            Name of method used to compute correlation between templates and diffraction patterns. Can be
            'fast_correlation', 'full_frame_correlation' or 'zero_mean_normalized_correlation'.
        mask : Array
            Array with the same size as signal (in navigation) or None
        print_help : bool
            Display information about the method used.
        *args : arguments
            Arguments passed to map().
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
            Navigation axes of the electron diffraction signal containing
            correlation results for each diffraction pattern, in the form
            [Library Number , [z, x, z], Correlation Score]

        """
        signal = self.signal
        library = self.library

        method_dict = {
            "fast_correlation": fast_correlation,
            "zero_mean_normalized_correlation":
            zero_mean_normalized_correlation,
            "full_frame_correlation": full_frame_correlation,
        }

        if mask is None:
            # Index at all real space pixels
            mask = 1

        # tests if selected method is a valid argument, and can print help for selected method.
        chosen_function = select_method_from_method_dict(
            method, method_dict, print_help)
        if method in ["fast_correlation", "zero_mean_normalized_correlation"]:
            # adds a normalisation to library
            for phase in library.keys():
                norm_array = np.ones(
                    library[phase]
                    ["intensities"].shape[0])  # will store the norms

                for i, intensity_array in enumerate(
                        library[phase]["intensities"]):
                    norm_array[i] = np.linalg.norm(intensity_array)
                library[phase][
                    "pattern_norms"] = norm_array  # puts this normalisation into the library

            matches = signal.map(
                correlate_library,
                library=library,
                n_largest=n_largest,
                method=method,
                mask=mask,
                inplace=False,
                **kwargs,
            )

        elif method in ["full_frame_correlation"]:
            shape = signal.data.shape[-2:]
            size = 2 * np.array(shape) - 1
            fsize = [optimal_fft_size(a, real=True) for a in (size)]
            if not (np.asarray(size) + 1 == np.asarray(fsize)).all():
                raise ValueError(
                    "Please select input signal and templates of dimensions 2**n X 2**n"
                )

            library_FT_dict = get_library_FT_dict(library, shape, fsize)

            matches = signal.map(
                correlate_library_from_dict,
                template_dict=library_FT_dict,
                n_largest=n_largest,
                method=method,
                mask=mask,
                inplace=False,
                **kwargs,
            )

        matching_results = TemplateMatchingResults(matches)
        matching_results = transfer_navigation_axes(matching_results, signal)

        return matching_results
Пример #7
0
    def correlate(self,
                  n_largest=5,
                  method='fast_correlation',
                  mask=None,
                  print_help=False,
                  *args,
                  **kwargs):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values are returned.
        method : str
            Name of method used to compute correlation between templates and diffraction patterns. Can be
            'fast_correlation' or 'zero_mean_normalized_correlation'.
        mask : Array
            Array with the same size as signal (in navigation) or None
        print_help : bool
            Display information about the method used.
        *args : arguments
            Arguments passed to map().
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
            Navigation axes of the electron diffraction signal containing
            correlation results for each diffraction pattern, in the form
            [Library Number , [z, x, z], Correlation Score]

        """
        signal = self.signal
        library = self.library

        method_dict = {
            'fast_correlation': fast_correlation,
            'zero_mean_normalized_correlation':
            zero_mean_normalized_correlation
        }

        if mask is None:
            # Index at all real space pixels
            mask = 1

        #tests if selected method is a valid argument, and can print help for selected method.
        chosen_function = select_method_from_method_dict(
            method, method_dict, print_help)

        # adds a normalisation to library
        for phase in library.keys():
            norm_array = np.ones(
                library[phase]['intensities'].shape[0])  # will store the norms

            for i, intensity_array in enumerate(library[phase]['intensities']):
                norm_array[i] = np.linalg.norm(intensity_array)
            library[phase][
                'pattern_norms'] = norm_array  # puts this normalisation into the library

        matches = signal.map(correlate_library,
                             library=library,
                             n_largest=n_largest,
                             method=method,
                             mask=mask,
                             inplace=False,
                             **kwargs)

        matching_results = TemplateMatchingResults(matches)
        matching_results = transfer_navigation_axes(matching_results, signal)

        return matching_results
Пример #8
0
    def correlate(self,
                  n_largest=5,
                  mask=None,
                  inplane_rotations=np.arange(0, 360, 1),
                  max_peaks=100,
                  *args,
                  **kwargs):
        """Correlates the library of simulated diffraction patterns with the
        electron diffraction signal.

        Parameters
        ----------
        n_largest : int
            The n orientations with the highest correlation values are returned.
        mask : Array
            Array with the same size as signal (in navigation) True False
        inplane_rotations : ndarray
            Array of inplane rotation angles in degrees. Defaults to 0-360 degrees
            at 1 degree resolution.
        max_peaks : int
            Maximum number of peaks to consider when comparing a template to
            the diffraction pattern. The strongest peaks are kept.
        *args : arguments
            Arguments passed to map().
        **kwargs : arguments
            Keyword arguments passed map().

        Returns
        -------
        matching_results : TemplateMatchingResults
            Navigation axes of the electron diffraction signal containing
            correlation results for each diffraction pattern, in the form
            [Library Number , [z, x, z], Correlation Score]

        """
        signal = self.signal
        library = self.library
        inplane_rotations = np.deg2rad(inplane_rotations)
        num_inplane_rotations = inplane_rotations.shape[0]
        sig_shape = signal.axes_manager.signal_shape
        signal_half_width = sig_shape[0] / 2

        if mask is None:
            # Index at all real space pixels
            mask = 1

        # Create a copy of the library, cropping and padding the peaks to match
        # max_peaks. Also create rotated pixel coordinates according to
        # inplane_rotations
        rotation_matrices_2d = np.array([[[np.cos(t), np.sin(t)],
                                          [-np.sin(t), np.cos(t)]]
                                         for t in inplane_rotations])
        cropped_library = {}

        for phase_name, phase_entry in library.items():
            num_orientations = len(phase_entry['orientations'])
            intensities_jagged = phase_entry['intensities']
            intensities = np.zeros((num_orientations, max_peaks))
            pixel_coords_jagged = phase_entry['pixel_coords']
            pixel_coords = np.zeros(
                (num_inplane_rotations, num_orientations, max_peaks, 2))
            for i in range(num_orientations):
                num_peaks = min(pixel_coords_jagged[i].shape[0], max_peaks)
                highest_intensity_indices = np.argpartition(
                    intensities_jagged[i], -num_peaks)[-num_peaks:]
                intensities[i, :num_peaks] = intensities_jagged[i][
                    highest_intensity_indices]
                # Get and compute pixel coordinates for all rotations about the
                # center, clipped to the detector size and rounded to integer positions.
                pixel_coords[:, i, :num_peaks] = np.clip(
                    (signal_half_width + rotation_matrices_2d
                     @ (pixel_coords_jagged[i][highest_intensity_indices].T -
                        signal_half_width)).transpose(0, 2, 1),
                    a_min=0,
                    a_max=np.array(sig_shape) - 1)

            np.rint(pixel_coords, out=pixel_coords)
            cropped_library[phase_name] = {
                'orientations': phase_entry['orientations'],
                'pixel_coords': pixel_coords.astype('int'),
                'intensities': intensities,
                'pattern_norms': np.linalg.norm(intensities, axis=1),
            }

        matches = signal.map(correlate_library,
                             library=cropped_library,
                             n_largest=n_largest,
                             mask=mask,
                             inplace=False,
                             **kwargs)

        matching_results = TemplateMatchingResults(matches)
        matching_results = transfer_navigation_axes(matching_results, signal)

        return matching_results