Esempio n. 1
0
    def get_direct_beam_position(self, method, **kwargs):
        """Estimate the direct beam position in each experimentally acquired
        electron diffraction pattern.

        Parameters
        ----------
        method : str,
            Must be one of "cross_correlate", "blur", "interpolate"
        **kwargs:
            Keyword arguments to be passed to map().

        Returns
        -------
        shifts : ndarray
            Array containing the shifts for each SED pattern.

        """
        signal_shape = self.axes_manager.signal_shape
        origin_coordinates = np.array(signal_shape) / 2

        method_dict = {'cross_correlate': find_beam_offset_cross_correlation,
                       'blur': find_beam_center_blur,
                       'interpolate': find_beam_center_interpolate}

        method_function = select_method_from_method_dict(method, method_dict, **kwargs)

        if method == 'cross_correlate':
            shifts = self.map(method_function, inplace=False, **kwargs)
        elif method == 'blur' or method == 'interpolate':
            centers = self.map(method_function, inplace=False, **kwargs)
            shifts = origin_coordinates - centers

        return shifts
Esempio n. 2
0
    def remove_background(self, method, **kwargs):
        """Perform background subtraction via multiple methods.

        Parameters
        ----------
        method : str
            Specifies the method, from:
            {'h-dome','gaussian_difference','median','reference_pattern'}
        **kwargs:
            Keyword arguments to be passed to map(), including method specific ones,
            running a method with no kwargs will return help

        Returns
        -------
        bg_subtracted : :obj:`ElectronDiffraction2D`
            A copy of the data with the background subtracted. Be aware that
            this function will only return inplace.
        """
        method_dict = {
            'h-dome': regional_filter,
            'gaussian_difference': subtract_background_dog,
            'median': subtract_background_median,
            'reference_pattern': subtract_reference,
        }

        method_function = select_method_from_method_dict(
            method, method_dict, **kwargs)

        if method != 'h-dome':
            bg_subtracted = self.map(method_function, inplace=False, **kwargs)
        elif method == 'h-dome':
            scale = self.data.max()
            self.data = self.data / scale
            bg_subtracted = self.map(method_function, inplace=False, **kwargs)
            bg_subtracted.map(filters.rank.mean, selem=square(3))
            bg_subtracted.data = bg_subtracted.data / bg_subtracted.data.max()

        return bg_subtracted
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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