How to use the hyperspy.defaults_parser.preferences.General function in hyperspy

To help you get started, we’ve selected a few hyperspy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hyperspy / hyperspy / hyperspy / model.py View on Github external
spectrum : An instance of the same class as `spectrum`.

        Examples
        --------
        >>> s = hs.signals.Signal1D(np.random.random((10,100)))
        >>> m = s.create_model()
        >>> l1 = hs.model.components1D.Lorentzian()
        >>> l2 = hs.model.components1D.Lorentzian()
        >>> m.append(l1)
        >>> m.append(l2)
        >>> s1 = m.as_signal()
        >>> s2 = m.as_signal(component_list=[l1])

        """
        if parallel is None:
            parallel = preferences.General.parallel
        if out is None:
            data = np.empty(self.signal.data.shape, dtype='float')
            data.fill(np.nan)
            signal = self.signal.__class__(
                data,
                axes=self.signal.axes_manager._get_axes_dicts())
            signal.metadata.General.title = (
                self.signal.metadata.General.title + " from fitted model")
            signal.metadata.Signal.binned = self.signal.metadata.Signal.binned
        else:
            signal = out
            data = signal.data

        if parallel is True:
            from os import cpu_count
            parallel = cpu_count()
github hyperspy / hyperspy / hyperspy / _signals / eds_sem.py View on Github external
are defined in metadata. If not, in interactive mode
        raises an UI item to fill the values

        """
        import hyperspy.gui.messages as messagesui
        must_exist = (
            'Acquisition_instrument.SEM.beam_energy',
            'Acquisition_instrument.SEM.Detector.EDS.live_time', )

        missing_parameters = []
        for item in must_exist:
            exists = self.metadata.has_item(item)
            if exists is False:
                missing_parameters.append(item)
        if missing_parameters:
            if preferences.General.interactive is True:
                par_str = "The following parameters are missing:\n"
                for par in missing_parameters:
                    par_str += '%s\n' % par
                par_str += 'Please set them in the following wizard'
                is_ok = messagesui.information(par_str)
                if is_ok:
                    self._set_microscope_parameters()
                else:
                    return True
            else:
                return True
        else:
            return False
github hyperspy / hyperspy / hyperspy / _signals / signal1d.py View on Github external
%s

        Returns
        -------
        An array with the result of the estimation in the axis units. \
        Although the computation is performed in batches if the signal is \
        lazy, the result is computed in memory because it depends on the \
        current state of the axes that could change later on in the workflow.

        Raises
        ------
        SignalDimensionError
            If the signal dimension is not 1.
        """
        if show_progressbar is None:
            show_progressbar = preferences.General.show_progressbar
        self._check_signal_dimension_equals_one()
        ip = number_of_interpolation_points + 1
        axis = self.axes_manager.signal_axes[0]
        self._check_navigation_mask(mask)
        # we compute for now
        if isinstance(start, da.Array):
            start = start.compute()
        if isinstance(end, da.Array):
            end = end.compute()
        i1, i2 = axis._get_index(start), axis._get_index(end)
        if reference_indices is None:
            reference_indices = self.axes_manager.indices
        ref = self.inav[reference_indices].data[i1:i2]

        if interpolate is True:
            ref = interpolate1D(ip, ref)
github hyperspy / hyperspy / hyperspy / misc / hyperspy_magics.py View on Github external
"""
        warnings.warn(
            "This magic is deprecated and will be removed in HyperSpy 0.9."
            "The reccomended way to start HyperSpy is:\n\n"
            ">>> import hyperspy.api as hs\n"
            ">>> %matplotlib\n\n"
            "See the online documentation for more details.",
            VisibleDeprecationWarning)
        sh = self.shell

        gui = False
        args = parse_argstring(self.hyperspy, line)
        overwrite = args.replace is not None
        toolkit = args.toolkit
        if toolkit is None:
            toolkit = preferences.General.default_toolkit

        if toolkit not in ['qt4', 'gtk', 'wx', 'tk', 'None']:
            raise ValueError("The '%s' toolkit is not supported.\n" % toolkit +
                             "Supported toolkits: {qt4, gtk, wx, tk, None}")

        mpl_code = ""
        if toolkit == "None":
            mpl_code = ("import matplotlib\n"
                        "matplotlib.use('Agg')\n")
        else:
            gui = True

        exec(mpl_code, sh.user_ns)
        if gui:
            sh.enable_matplotlib(toolkit)
        to_import = ("import numpy as np\n"
github hyperspy / hyperspy / hyperspy / _signals / eels.py View on Github external
If True, display a progress bar. If None the default is set in
            `preferences`.
        parallel : {None,bool,int}
            if True, the deconvolution will be performed in a threaded (parallel)
            manner.

        Notes:
        -----
        For details on the algorithm see Gloter, A., A. Douiri,
        M. Tence, and C. Colliex. “Improving Energy Resolution of
        EELS Spectra: An Alternative to the Monochromator Solution.”
        Ultramicroscopy 96, no. 34 (September 2003): 385400.

        """
        if show_progressbar is None:
            show_progressbar = preferences.General.show_progressbar
        self._check_signal_dimension_equals_one()
        psf_size = psf.axes_manager.signal_axes[0].size
        kernel = psf()
        imax = kernel.argmax()
        maxval = self.axes_manager.navigation_size
        show_progressbar = show_progressbar and (maxval > 0)

        def deconv_function(signal, kernel=None,
                            iterations=15, psf_size=None):
            imax = kernel.argmax()
            result = np.array(signal).copy()
            mimax = psf_size - 1 - imax
            for _ in range(iterations):
                first = np.convolve(kernel, result)[imax: imax + psf_size]
                result *= np.convolve(kernel[::-1], signal /
                                      first)[mimax:mimax + psf_size]
github hyperspy / hyperspy / hyperspy / _signals / eels.py View on Github external
Returns
        -------
        I0: Signal1D
            The elastic scattering intensity.

        See Also
        --------
        estimate_elastic_scattering_threshold

        """
        # TODO: Write units tests
        self._check_signal_dimension_equals_one()

        if show_progressbar is None:
            show_progressbar = preferences.General.show_progressbar

        if isinstance(threshold, numbers.Number):
            I0 = self.isig[:threshold].integrate1D(-1)
        else:
            ax = self.axes_manager.signal_axes[0]
            # I0 = self._get_navigation_signal()
            # I0.axes_manager.set_signal_dimension(0)
            threshold.axes_manager.set_signal_dimension(0)
            binned = self.metadata.Signal.binned

            def estimating_function(data, threshold=None):
                if np.isnan(threshold):
                    return np.nan
                else:
                    # the object is just an array, so have to reimplement
                    # integrate1D. However can make certain assumptions, for
github hyperspy / hyperspy / hyperspy / _signals / signal2d.py View on Github external
-------
        list of applied shifts
        Notes
        -----
        The statistical analysis approach to the translation estimation
        when using `reference`='stat' roughly follows [1]_ . If you use
        it please cite their article.
        References
        ----------
        .. [1] Schaffer, Bernhard, Werner Grogger, and Gerald
        Kothleitner. “Automated Spatial Drift Correction for EFTEM
        Signal2D Series.”
        Ultramicroscopy 102, no. 1 (December 2004): 2736.
        """
        if show_progressbar is None:
            show_progressbar = preferences.General.show_progressbar
        self._check_signal_dimension_equals_two()
        if roi is not None:
            # Get the indices of the roi
            yaxis = self.axes_manager.signal_axes[1]
            xaxis = self.axes_manager.signal_axes[0]
            roi = tuple([xaxis._get_index(i) for i in roi[2:]] +
                        [yaxis._get_index(i) for i in roi[:2]])

        ref = None if reference == 'cascade' else \
            self.__call__().copy()
        shifts = []
        nrows = None
        images_number = self.axes_manager._max_index + 1
        if plot == 'reuse':
            # Reuse figure for plots
            plot = plt.figure()
github hyperspy / hyperspy / hyperspy / model.py View on Github external
def _as_signal_iter(self, component_list=None, out_of_range_to_nan=True,
                        show_progressbar=None, data=None):
        # Note that show_progressbar can be an int to determine the progressbar
        # position for a thread-friendly bars. Otherwise race conditions are
        # ugly...
        if data is None:
            raise ValueError('No data supplied')
        if show_progressbar is None:
            show_progressbar = preferences.General.show_progressbar

        with stash_active_state(self if component_list else []):
            if component_list:
                component_list = [self._get_component(x)
                                  for x in component_list]
                for component_ in self:
                    active = component_ in component_list
                    if component_.active_is_multidimensional:
                        if active:
                            continue    # Keep active_map
                        component_.active_is_multidimensional = False
                    component_.active = active
            if out_of_range_to_nan is True:
                channel_switches_backup = copy.copy(self.channel_switches)
                self.channel_switches[:] = True
            maxval = self.axes_manager.navigation_size
github hyperspy / hyperspy / hyperspy / misc / eels / tools.py View on Github external
results0 = _estimate_gain(
            ns, cs, weighted=weighted, higher_than=higher_than,
            plot_results=plot_results, binning=0, pol_order=pol_order)

        results2 = _estimate_gain(
            ns, cs, weighted=weighted, higher_than=higher_than,
            plot_results=False, binning=2, pol_order=pol_order)

        c = _estimate_correlation_factor(results0['fit'][0],
                                         results2['fit'][0], 4)

        message = ("Gain factor: %.2f\n" % results0['fit'][0] +
                   "Gain offset: %.2f\n" % results0['fit'][1] +
                   "Correlation factor: %.2f\n" % c)
        is_ok = True
        if hyperspy.defaults_parser.preferences.General.interactive is True:
            is_ok = messagesui.information(
                message + "Would you like to store the results?")
        else:
            _logger.info(message)
        if is_ok:
            noisy_signal.metadata.set_item(
                "Signal.Noise_properties.Variance_linear_model.gain_factor",
                results0['fit'][0])
            noisy_signal.metadata.set_item(
                "Signal.Noise_properties.Variance_linear_model.gain_offset",
                results0['fit'][1])
            noisy_signal.metadata.set_item(
                "Signal.Noise_properties.Variance_linear_model."
                "correlation_factor",
                c)
            noisy_signal.metadata.set_item(