How to use the hyperspy.signals.BaseSignal 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 pyxem / pyxem / pycrystem / diffraction_vectors.py View on Github external
def __init__(self, *args, **kwargs):
        BaseSignal.__init__(self, *args, **kwargs)
github hyperspy / hyperspy / hyperspy / misc / utils.py View on Github external
inplace,
                            result,
                            ragged,
                            sig_shape=None,
                            lazy=False):
    from hyperspy.signals import BaseSignal
    from hyperspy._lazy_signals import LazySignal
    res = None
    if inplace:
        sig = signal
    else:
        res = sig = signal._deepcopy_with_new_data()
    if ragged:
        sig.data = result
        sig.axes_manager.remove(sig.axes_manager.signal_axes)
        sig.__class__ = LazySignal if lazy else BaseSignal
        sig.__init__(**sig._to_dictionary(add_models=True))

    else:
        if not sig._lazy and sig.data.shape == result.shape and np.can_cast(
                result.dtype, sig.data.dtype):
            sig.data[:] = result
        else:
            sig.data = result

        # remove if too many axes
        sig.axes_manager.remove(sig.axes_manager.signal_axes[len(sig_shape):])
        # add additional required axes
        for ind in range(
                len(sig_shape) - sig.axes_manager.signal_dimension, 0, -1):
            sig.axes_manager._append_axis(sig_shape[-ind], navigate=False)
    sig.get_dimensions_from_data()
github pyxem / pyxem / pycrystem / diffraction_vectors.py View on Github external
from pycrystem.utils.expt_utils import *

"""
Signal class for diffraction vectors.
"""

def _calculate_norms(z):
    norms = []
    #print(z)
    for i in z[0]:
        norms.append(np.linalg.norm(i))
    return np.asarray(norms)


class DiffractionVectors(BaseSignal):
    _signal_type = "diffraction_vectors"

    def __init__(self, *args, **kwargs):
        BaseSignal.__init__(self, *args, **kwargs)

    def plot(self):
        """Plot the diffraction vectors.
        """
        #Find the unique gvectors to plot.
        unique_vectors = self.get_unique_vectors()
        #Plot the gvector positions
        import matplotlib.pyplot as plt
        plt.plot(unique_vectors.T[1], unique_vectors.T[0], 'ro')
        plt.axes().set_aspect('equal')
        plt.show()
github pyxem / pyxem / pyxem / signals / diffraction_vectors.py View on Github external
Returns
        -------
        magnitudes : BaseSignal
            A signal with navigation dimensions as the original diffraction
            vectors containging an array of gvector magnitudes at each
            navigation position.

        """
        # If ragged the signal axes will not be defined
        if len(self.axes_manager.signal_axes) == 0:
            magnitudes = self.map(calculate_norms_ragged,
                                  inplace=False,
                                  *args, **kwargs)
        # Otherwise easier to calculate.
        else:
            magnitudes = BaseSignal(calculate_norms(self))
            magnitudes.axes_manager.set_signal_dimension(0)

        return magnitudes
github hyperspy / hyperspy / hyperspy / io_plugins / emd.py View on Github external
def _read_signal_from_group(self, name, group, lazy=False):
        self._log.debug('Calling _read_signal_from_group')
        from hyperspy import signals
        # Extract essential data:
        data = group.get('data')
        if lazy:
            data = da.from_array(data, chunks=data.chunks)
        else:
            data = np.asanyarray(data)
        # EMD does not have a standard way to describe the signal axis.
        # Therefore we return a BaseSignal
        signal = signals.BaseSignal(data)
        # Set signal properties:
        signal.set_signal_origin = group.attrs.get('signal_origin', '')
        signal.set_signal_type = group.attrs.get('signal_type', '')
        # Iterate over all dimensions:
        for i in range(len(data.shape)):
            dim = group.get('dim{}'.format(i + 1))
            axis = signal.axes_manager._axes[i]
            axis_name = dim.attrs.get('name', '')
            if isinstance(axis_name, bytes):
                axis_name = axis_name.decode('utf-8')
            axis.name = axis_name

            axis_units = dim.attrs.get('units', '')
            if isinstance(axis_units, bytes):
                axis_units = axis_units.decode('utf-8')
            units = re.findall(r'[^_\W]+', axis_units)
github pyxem / pyxem / pycrystem / utils / strain_utils.py View on Github external
def get_strain_maps(component):
    """Gets the strain maps from model fitting results.

    Parameters
    ----------

    Returns
    -------
    """
    D = BaseSignal(np.zeros((component.model.axes_manager.navigation_shape[1],
                             component.model.axes_manager.navigation_shape[0],
                             3, 3)))
    D.axes_manager.set_signal_dimension(2)

    D.data[:, :, 0, 0] = component.d11.map['values']
    D.data[:, :, 1, 0] = component.d12.map['values']
    D.data[:, :, 0, 1] = component.d21.map['values']
    D.data[:, :, 1, 1] = component.d22.map['values']
    D.data[:, :, 2, 2] = 1.

    R, U = _polar_decomposition(D)

    theta = _get_rotation_angle(R)

    e11 = -U.isig[0, 0].T + 1
github pyxem / pyxem / pycrystem / orientation_map.py View on Github external
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyCrystEM.  If not, see .

from __future__ import division

from hyperspy.signals import BaseSignal
import numpy as np

"""
Signal class for crystallographic orientation maps.
"""


class OrientationMap(BaseSignal):
    """
    Signal class for crystallographic orientation maps.
    """
    _signal_type = "tensor_field"

    def __init__(self, *args, **kwargs):
        BaseSignal.__init__(self, *args, **kwargs)
        # Check that the signal dimensions are (3,3) for it to be a valid
        # TensorField

    def get_angle_map(self):
        """Obtain an orientation map specifed by the magnitude of the rotation
        angle at each navigation position.

        Returns
        -------
github pyxem / pyxem / pycrystem / diffraction_signal.py View on Github external
def __init__(self, *args, **kwargs):
        Signal2D.__init__(self, *args, **kwargs)
        # Attributes defaults
        if 'Acquisition_instrument.TEM' not in self.metadata:
            if 'Acquisition_instrument.SEM' in self.metadata:
                self.metadata.set_item(
                    "Acquisition_instrument.TEM",
                    self.metadata.Acquisition_instrument.SEM)
                del self.metadata.Acquisition_instrument.SEM
        self.decomposition.__func__.__doc__ = BaseSignal.decomposition.__doc__
github pyxem / pyxem / pycrystem / utils / strain_utils.py View on Github external
part of the polar decomposition appears. i.e. if 'right' D = RU and
        if 'left' D = UR.

    Returns
    -------

    R : TensorField

        The orthogonal matrix describing

    U : TensorField

        The strain tensor field

    """
    R = BaseSignal(np.ones((D.axes_manager.navigation_shape[1],
                            D.axes_manager.navigation_shape[0],
                            3,3)))
    R.axes_manager.set_signal_dimension(2)
    U = BaseSignal(np.ones((D.axes_manager.navigation_shape[1],
                            D.axes_manager.navigation_shape[0],
                            3,3)))
    U.axes_manager.set_signal_dimension(2)

    for z, indices in zip(D._iterate_signal(),
                          D.axes_manager._array_indices_generator()):
        ru = linalg.polar(z, side=side)
        R.data[indices] = ru[0]
        U.data[indices] = ru[1]

    return R, U
github hyperspy / hyperspy / hyperspy / _signals / hologram_image.py View on Github external
#

        # Parsing sideband size
        if sb_size is None:  # Default value is 1/2 distance between sideband and central band
            if reference is None:
                sb_size = self.estimate_sideband_size(sb_position,
                                                      parallel=parallel)
            else:
                sb_size = reference.estimate_sideband_size(sb_position,
                                                           parallel=parallel)
        else:
            if not isinstance(sb_size, BaseSignal):
                if isinstance(sb_size, np.ndarray) and sb_size.size > 1:  # transpose if np.array of multiple instances
                    sb_size = BaseSignal(sb_size).T
                else:
                    sb_size = BaseSignal(sb_size)

        if sb_size.axes_manager.navigation_size != self.axes_manager.navigation_size:
            if sb_size.axes_manager.navigation_size:
                raise ValueError('Sideband size dimensions do not match neither reference nor hologram dimensions.')

            else:  # sb_position navdim=0, therefore map function should not iterate it:
                sb_size_temp = np.float64(sb_size.data)
        else:
            sb_size_temp = sb_size.deepcopy()
        #

        # Standard edge smoothness of sideband aperture 5% of sb_size
        if sb_smoothness is None:
            sb_smoothness = sb_size * 0.05
        else:
            if not isinstance(sb_smoothness, BaseSignal):