コード例 #1
0
ファイル: eds.py プロジェクト: jhemmelg/hyperspy
 def __init__(self, *args, **kwards):
     Signal1D.__init__(self, *args, **kwards)
     if self.metadata.Signal.signal_type == 'EDS':
         warnings.warn('The microscope type is not set. Use '
                       'set_signal_type(\'EDS_TEM\')  '
                       'or set_signal_type(\'EDS_SEM\')')
     self.metadata.Signal.binned = True
     self._xray_markers = {}
コード例 #2
0
    def get_phase_signal(self, rotation=None):
        """Get DPC phase image visualized using continuous color scale.

        Converts the x and y beam shifts into an RGB array, showing the
        direction of the beam shifts.

        Useful for visualizing magnetic domain structures.

        Parameters
        ----------
        rotation : float, optional
            In degrees. Useful for correcting the mismatch between
            scan direction and diffraction pattern rotation.
        autolim : bool, default True
        autolim_sigma : float, default 4

        Returns
        -------
        phase_signal : HyperSpy 2D RGB signal

        Examples
        --------
        >>> s = ps.dummy_data.get_simple_dpc_signal()
        >>> s_color = s.get_phase_signal(rotation=20)
        >>> s_color.plot()

        See Also
        --------
        get_color_signal : Signal showing both phase and magnitude
        get_magnitude_signal : Signal showing the magnitude

        """
        # Rotate the phase by -30 degrees in the color "wheel", to get better
        # visualization in the vertical and horizontal direction.
        if rotation is None:
            rotation = -30
        else:
            rotation = rotation - 30
        phase = np.arctan2(self.inav[0].data, self.inav[1].data) % (2 * np.pi)
        rgb_array = pst._get_rgb_phase_array(phase=phase, rotation=rotation)
        signal_rgb = Signal1D(rgb_array * (2**16 - 1))
        signal_rgb.change_dtype("uint16")
        signal_rgb.change_dtype("rgb16")
        pst._copy_signal2d_axes_manager_metadata(self, signal_rgb)
        return signal_rgb
コード例 #3
0
def test_setting_indices_coordinates():
    s = Signal1D(arange(1000).reshape(10, 10, 10))

    m = mock.Mock()
    s.axes_manager.events.indices_changed.connect(m, [])

    # both indices are changed but the event is triggered only once
    s.axes_manager.indices = (5, 5)
    assert s.axes_manager.indices == (5, 5)
    assert m.call_count == 1

    # indices not changed, so the event is not triggered
    s.axes_manager.indices == (5, 5)
    assert s.axes_manager.indices == (5, 5)
    assert m.call_count == 1

    # both indices changed again, call only once
    s.axes_manager.indices = (2, 3)
    assert s.axes_manager.indices == (2, 3)
    assert m.call_count == 2

    # single index changed, call only once
    s.axes_manager.indices = (2, 2)
    assert s.axes_manager.indices == (2, 2)
    assert m.call_count == 3

    # both coordinates are changed but the event is triggered only once
    s.axes_manager.coordinates = (5, 5)
    assert s.axes_manager.coordinates == (5, 5)
    assert m.call_count == 4

    # coordinates not changed, so the event is not triggered
    s.axes_manager.indices == (5, 5)
    assert s.axes_manager.indices == (5, 5)
    assert m.call_count == 4

    # both coordinates changed again, call only once
    s.axes_manager.coordinates = (2, 3)
    assert s.axes_manager.coordinates == (2, 3)
    assert m.call_count == 5

    # single coordinate changed, call only once
    s.axes_manager.indices = (2, 2)
    assert s.axes_manager.indices == (2, 2)
    assert m.call_count == 6
コード例 #4
0
def _generate_dataset():
    coefficients = np.array([
        350949.04890400 + 0.j, -22003.98742841 + 51494.56650429j,
        37292.52741553 + 38067.97686711j, 37292.52741553 - 38067.97686711j,
        -22003.98742841 - 51494.56650429j
    ])
    coordinates = np.array([[0, 26, 30, 994, 998], [0, 1003, 39, 985, 21]])
    dense = np.zeros((1024, 1024), dtype=complex)
    dense[coordinates[0], coordinates[1]] = coefficients
    dense = Signal2D(np.real(np.fft.ifft2(dense)))
    dense = dense.isig[500:550, 500:550]

    coefficients = np.array([
        10, 5, 86, 221, 6, 95, 70, 12, 255, 5, 255, 3, 23, 24, 77, 255, 11,
        255, 8, 35, 195, 165, 27, 255, 8, 14, 255, 21, 53, 107, 255, 18, 255,
        4, 26, 255, 39, 27, 255, 6, 255, 7, 13, 37, 35, 9, 83
    ])
    coordinates = np.array([[3, 40], [3, 138], [9, 67], [14, 95], [20, 23],
                            [20, 122], [26, 51], [26, 100],
                            [31, 78], [31, 128], [37, 107], [38, 7], [43, 34],
                            [43, 84], [43, 134], [49, 62], [49, 112], [54, 90],
                            [60, 17], [60, 67], [60, 118], [66, 45], [66, 96],
                            [72, 73], [72, 124], [77, 51], [77, 101], [83, 28],
                            [83, 79], [83, 130], [89, 57], [89, 107], [95, 85],
                            [101, 12], [101, 62], [101, 113], [106, 40],
                            [107, 91], [112, 68], [113, 119], [119, 97],
                            [124, 23], [124, 74], [124, 125], [130, 51],
                            [130, 103], [136, 80]])
    sparse = np.zeros((144, 144))
    xs, ys = np.ogrid[:144, :144]
    for (x0, y0), a in zip(coordinates, coefficients):
        sparse += a * norm.pdf(xs, x0) * norm.pdf(ys, y0)
    sparse = sparse[50:100, 50:100]
    sparse_nav0d = Signal2D(sparse)
    sparse_nav1d = Signal2D(np.stack([sparse] * 2))
    sparse_nav2d = Signal2D(np.stack([[sparse] * 2] * 3))
    shifts = np.array(
        [[2 * i, 2 * i]
         for i in range(sparse_nav2d.axes_manager.navigation_size)])
    shifts = shifts.reshape(3, 2, 2)
    shifts = Signal1D(-shifts)
    sparse_nav2d_shifted = sparse_nav2d.deepcopy()
    sparse_nav2d_shifted.align2D(shifts=shifts, fill_value=0)

    return dense, sparse_nav0d, sparse_nav1d, sparse_nav2d, sparse_nav2d_shifted
コード例 #5
0
ファイル: test_powerlaw.py プロジェクト: ytzeng1/hyperspy
def test_estimate_parameters_binned(only_current, binned):
    s = Signal1D(np.empty((100, )))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 0.02
    axis.offset = 1
    g1 = PowerLaw(50015.156, 1.2)
    s.data = g1.function(axis.axis)
    g2 = PowerLaw()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s,
                                  axis.low_value,
                                  axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    # error of the estimate function is rather large, esp. when binned=FALSE
    np.testing.assert_allclose(g1.A.value, g2.A.value * factor, rtol=0.05)
    assert abs(g2.r.value - g1.r.value) <= 2e-2
コード例 #6
0
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((100,)))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 1
    axis.offset = -20
    g1 = Gaussian(50015.156, 10/sigma2fwhm, 10)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = Gaussian()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s, axis.low_value, axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    assert_allclose(g1.A.value, g2.A.value * factor)
    assert abs(g2.centre.value - g1.centre.value) <= 1e-3
    assert abs(g2.sigma.value - g1.sigma.value) <= 0.1
コード例 #7
0
def test_function_nd(binned, lazy):
    s = Signal1D(np.empty((100, )))
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 0.02
    axis.offset = 1
    g1 = PowerLaw(50015.156, 1.2)
    s.data = g1.function(axis.axis)
    s.axes_manager.signal_axes[0].is_binned = binned
    s2 = stack([s] * 2)
    if lazy:
        s = s.as_lazy()
    g2 = PowerLaw()
    factor = axis.scale if binned else 1
    g2.estimate_parameters(s2, axis.low_value, axis.high_value, False)
    assert g2._axes_manager[-1].is_binned == binned
    np.testing.assert_allclose(g2.function_nd(axis.axis) * factor,
                               s2.data,
                               rtol=0.05)
コード例 #8
0
ファイル: test_gaussianhf.py プロジェクト: ytzeng1/hyperspy
def test_function_nd(binned):
    s = Signal1D(np.empty((100, )))
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 2.
    axis.offset = -30
    g1 = GaussianHF(50015.156, 23, 10)
    s.data = g1.function(axis.axis)
    s.metadata.Signal.binned = binned

    s2 = stack([s] * 2)
    g2 = GaussianHF()
    factor = axis.scale if binned else 1
    g2.estimate_parameters(s2, axis.low_value, axis.high_value, False)
    assert g2.binned == binned
    # TODO: sort out while the rtol to be so high...
    np.testing.assert_allclose(g2.function_nd(axis.axis) * factor,
                               s2.data,
                               rtol=0.05)
コード例 #9
0
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((250,)))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = .2
    axis.offset = -15
    g1 = Lorentzian(52342, 2, 10)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = Lorentzian()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s, axis.low_value, axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    np.testing.assert_allclose(g1.A.value, g2.A.value * factor,0.1)
    assert abs(g2.centre.value - g1.centre.value) <= 0.2
    assert abs(g2.gamma.value - g1.gamma.value) <= 0.1
コード例 #10
0
def test_file_reader_options():
    s = Signal1D(np.arange(10))

    with tempfile.TemporaryDirectory() as dirpath:
        f = os.path.join(dirpath, "temp.hspy")
        s.save(f)

        # Test string reader
        t = hs.load(Path(dirpath, "temp.hspy"), reader="hspy")
        assert len(t) == 1
        np.testing.assert_allclose(t.data, np.arange(10))

        # Test object reader
        from hyperspy.io_plugins import hspy

        t = hs.load(Path(dirpath, "temp.hspy"), reader=hspy)
        assert len(t) == 1
        np.testing.assert_allclose(t.data, np.arange(10))
コード例 #11
0
ファイル: test_gaussianhf.py プロジェクト: realxnl/hyperspy
def test_estimate_parameters_binned(only_current, binned):
    s = Signal1D(np.empty((100, )))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 2.
    axis.offset = -30
    g1 = GaussianHF(50015.156, 23, 10)
    s.data = g1.function(axis.axis)
    g2 = GaussianHF()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s,
                                  axis.low_value,
                                  axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    assert_allclose(g1.height.value, g2.height.value * factor)
    assert abs(g2.centre.value - g1.centre.value) <= 1e-3
    assert abs(g2.fwhm.value - g1.fwhm.value) <= 0.1
コード例 #12
0
ファイル: test_rpca.py プロジェクト: zezhong-zhang/hyperspy
    def test_signal(self, poisson):
        # Note that s1.decomposition() operates on the transpose
        # i.e. (n_samples, n_features).
        x = self.X.copy().T.reshape(16, 16, 128)

        if poisson:
            x -= x.min()
            x[x <= 0] = 1e-16

        s1 = Signal1D(x)

        X, E = s1.decomposition(
            normalize_poissonian_noise=poisson,
            algorithm="RPCA",
            output_dimension=self.rank,
            return_info=True,
        )
        compare_norms(X, self.A.T)
コード例 #13
0
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((100,)))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 1
    axis.offset = -20
    g1 = SplitVoigt(A=20001.0, centre=10.0, sigma1=3.0, sigma2=3.0)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = SplitVoigt()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s, axis.low_value, axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    assert_allclose(g1.A.value, g2.A.value * factor, rtol=0.2)
    assert abs(g2.centre.value - g1.centre.value) <= 0.1
    assert abs(g2.sigma1.value - g1.sigma1.value) <= 0.1
    assert abs(g2.sigma2.value - g1.sigma2.value) <= 0.1
コード例 #14
0
def test_function_nd(binned, lazy):
    s = Signal1D(np.empty((100, )))
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 0.2
    axis.offset = 15

    g1 = Exponential(A=10005.7, tau=214.3)
    s.data = g1.function(axis.axis)
    s.metadata.Signal.binned = binned

    s2 = stack([s] * 2)
    if lazy:
        s2 = s2.as_lazy()
    g2 = Exponential()
    factor = axis.scale if binned else 1.
    g2.estimate_parameters(s2, axis.low_value, axis.high_value, False)

    assert g2.binned == binned
    assert_allclose(g2.function_nd(axis.axis) * factor, s2.data, rtol=0.05)
コード例 #15
0
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((300,)))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 0.2
    axis.offset = -10
    g1 = SkewNormal(A=2, x0=2, scale=10, shape=5)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = SkewNormal()
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s, axis.low_value, axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    assert_allclose(g1.A.value, g2.A.value * factor)
    assert abs(g2.x0.value - g1.x0.value) <= 0.002
    assert abs(g2.shape.value - g1.shape.value) <= 0.01
    assert abs(g2.scale.value - g1.scale.value) <= 0.01
コード例 #16
0
ファイル: test_exponential.py プロジェクト: ssomnath/hyperspy
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((100, )))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = 0.2
    axis.offset = 15.
    g1 = Exponential(A=10005.7, tau=214.3)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = Exponential()
    factor = axis.scale if binned else 1.
    assert g2.estimate_parameters(s,
                                  axis.low_value,
                                  axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    np.testing.assert_allclose(g1.A.value, g2.A.value * factor, rtol=0.05)
    np.testing.assert_allclose(g1.tau.value, g2.tau.value)
コード例 #17
0
def RDF(s, rebin_factor=None, bin_size=1.0):
    """
    Calculate the radial profile the FFT of an image.

    Args
    ----------
    s : Hyperspy Signal2D
        Image from which to calculate the RDF
    rebin_factor : int
        If defined, the image is downsampled prior to analysis by this
        factor.
    bin_size : float
        Size of the bins to distribute the azimuthally averaged data. Default
        is 1.0.

    Returns
    ----------
    psd : Numpy array
        Power spectrum of the input image (i.e. the square of the real part of
        the 2D FFT)
    profile : Hyperspy Signal1D
        Radially average of the PSD

    """
    if rebin_factor:
        image = s.rebin(scale=(rebin_factor, rebin_factor))
    else:
        image = s.deepcopy()
    fft = image.fft(shift=True)
    psd = Signal2D(np.abs(fft.real())**2,
                   axes=[
                       fft.axes_manager[0].get_axis_dictionary(),
                       fft.axes_manager[1].get_axis_dictionary()
                   ])
    xaxis, profile = azimuthal_average(psd.data, bin_size)
    scale = fft.axes_manager[0].scale
    profile = Signal1D(profile)
    profile.axes_manager[0].name = 'Frequency'
    profile.axes_manager[0].units = '1/%s' % s.axes_manager[0].units
    profile.axes_manager[0].offset = xaxis[0] * scale
    profile.axes_manager[0].scale = scale
    return psd, profile
コード例 #18
0
def test_fft_signal1d(lazy):
    s = Signal1D(np.random.random((2, 3, 4, 5)))
    if lazy:
        s = s.as_lazy()

    s.axes_manager.signal_axes[0].scale = 6.

    s_fft = s.fft()
    s_fft.axes_manager.signal_axes[0].units = 'mrad'

    assert s_fft.axes_manager.signal_axes[0].scale == 1. / 5. / 6.

    s_ifft = s_fft.ifft()
    assert s_ifft.axes_manager.signal_axes[0].units == '1 / mrad'
    assert s_ifft.axes_manager.signal_axes[0].scale == 6.
    assert isinstance(s_fft, ComplexSignal1D)
    assert isinstance(s_ifft, Signal1D)
    assert_allclose(s.data, s_ifft.data, atol=1e-3)

    s_fft = s.inav[0].fft()
    s_ifft = s_fft.ifft()
    assert_allclose(s.inav[0].data, s_ifft.data, atol=1e-3)

    s_fft = s.inav[0, 0].fft()
    s_ifft = s_fft.ifft()
    assert_allclose(s.inav[0, 0].data, s_ifft.data, atol=1e-3)

    s_fft = s.inav[0, 0, 0].fft()
    s_ifft = s_fft.ifft()
    assert_allclose(s.inav[0, 0, 0].data, s_ifft.data, atol=1e-3)
    assert_allclose(np.fft.fft(s.inav[0, 0, 0].data), s_fft.data)

    s_fft = s.inav[0, 0, 0].fft(shift=True)
    s_ifft = s_fft.ifft(shift=True)
    assert_allclose(s.inav[0, 0, 0].data, s_ifft.data, atol=1e-3)
    assert_allclose(np.fft.fftshift(np.fft.fft(s.inav[0, 0, 0].data)),
                    s_fft.data)

    assert s.fft(apodization=True) == s.apply_apodization().fft()
    for apodization in ['hann', 'hamming', 'tukey']:
        assert s.fft(apodization=apodization) == s.apply_apodization(
            window=apodization).fft()
コード例 #19
0
    def test_signal(self, poisson):
        # Note that s1.decomposition() operates on the transpose
        # i.e. (n_samples, n_features).
        x = self.Y.T.copy().reshape(16, 16, 128)

        if poisson:
            x -= x.min()
            x[x <= 0] = 1e-16

        s1 = Signal1D(x)

        X_out, E_out = s1.decomposition(
            normalize_poissonian_noise=poisson,
            algorithm="ORNMF",
            output_dimension=self.rank,
            return_info=True,
        )

        # Check the low-rank component MSE
        compare_norms(X_out, self.X.T)
コード例 #20
0
ファイル: test_voigt.py プロジェクト: pc494/hyperspy
def test_estimate_parameters_binned(only_current, binned, lazy):
    s = Signal1D(np.empty((200, )))
    s.metadata.Signal.binned = binned
    axis = s.axes_manager.signal_axes[0]
    axis.scale = .05
    axis.offset = -5
    g1 = Voigt(centre=1, area=5, gamma=0.001, sigma=0.5, legacy=False)
    s.data = g1.function(axis.axis)
    if lazy:
        s = s.as_lazy()
    g2 = Voigt(legacy=False)
    factor = axis.scale if binned else 1
    assert g2.estimate_parameters(s,
                                  axis.low_value,
                                  axis.high_value,
                                  only_current=only_current)
    assert g2.binned == binned
    assert_allclose(g2.sigma.value, 0.5, 0.01)
    assert_allclose(g1.area.value, g2.area.value * factor, 0.01)
    assert_allclose(g2.centre.value, 1, 1e-3)
コード例 #21
0
 def test_convert_to_uniform_axis(self):
     scale = (self.axis.high_value - self.axis.low_value) / self.axis.size
     is_binned = self.axis.is_binned
     navigate = self.axis.navigate
     self.axis.name = "parrot"
     self.axis.units = "plumage"
     s = Signal1D(np.arange(10), axes=[self.axis])
     index_in_array = s.axes_manager[0].index_in_array
     s.axes_manager[0].convert_to_uniform_axis()
     assert isinstance(s.axes_manager[0], UniformDataAxis)
     assert s.axes_manager[0].name == "parrot"
     assert s.axes_manager[0].units == "plumage"
     assert s.axes_manager[0].size == 16
     assert s.axes_manager[0].scale == scale
     assert s.axes_manager[0].offset == 0
     assert s.axes_manager[0].low_value == 0
     assert s.axes_manager[0].high_value == 15 * scale
     assert index_in_array == s.axes_manager[0].index_in_array
     assert is_binned == s.axes_manager[0].is_binned
     assert navigate == s.axes_manager[0].navigate
コード例 #22
0
def test_spikes_removal_tool_non_interactive_masking():
    s = Signal1D(np.ones((2, 3, 30)))
    np.random.seed(1)
    s.add_gaussian_noise(1e-5)
    # Add three spikes
    s.data[1, 0, 1] += 2
    s.data[0, 2, 29] += 1
    s.data[1, 2, 14] += 1

    navigation_mask = np.zeros((2, 3), dtype='bool')
    navigation_mask[1, 0] = True
    signal_mask = np.zeros((30, ), dtype='bool')
    signal_mask[28:] = True
    sr = s.spikes_removal_tool(threshold=0.5,
                               interactive=False,
                               add_noise=False,
                               navigation_mask=navigation_mask,
                               signal_mask=signal_mask)
    np.testing.assert_almost_equal(s.data[1, 0, 1], 3, decimal=5)
    np.testing.assert_almost_equal(s.data[0, 2, 29], 2, decimal=5)
    np.testing.assert_almost_equal(s.data[1, 2, 14], 1, decimal=5)
コード例 #23
0
    def setup_method(self, method):
        np.random.seed(0)  # Same random every time, Line2DROi test requires it
        s_s = Signal1D(np.random.rand(50, 60, 4))
        s_s.axes_manager[0].scale = 5
        s_s.axes_manager[0].units = 'nm'
        s_s.axes_manager[1].scale = 5
        s_s.axes_manager[1].units = 'nm'

        # 4D dataset
        s_i = Signal2D(np.random.rand(100, 100, 4, 4))

        # Generate ROI for test of angle measurements
        r = []
        t = np.tan(30. / 180. * np.pi)
        for x in [-1., -t, t, 1]:
            for y in [-1., -t, t, 1]:
                r.append(Line2DROI(x1=0., x2=x, y1=0., y2=y))

        self.s_s = s_s
        self.s_i = s_i
        self.r = r
コード例 #24
0
ファイル: test_linear_model.py プロジェクト: jat255/hyperspy
def test_fit_binned():
    np.random.seed(1)
    s = Signal1D(np.random.normal(scale=2, size=10000)).get_histogram()
    s.axes_manager[-1].binned = True
    g = Gaussian()
    m = s.create_model()
    m.append(g)
    g.sigma.value = 1
    g.centre.value = 0.5
    g.A.value = 1e3
    # model contains free nonlinear parameters
    with pytest.raises(RuntimeError):
        m.fit(optimizer='lstsq')

    g.centre.free = False
    g.sigma.free = False

    m.fit(optimizer='lstsq')
    np.testing.assert_allclose(m[0].A.value, 6132.640632924692, 1)
    np.testing.assert_allclose(m[0].centre.value, 0.5)
    np.testing.assert_allclose(m[0].sigma.value, 1)
コード例 #25
0
    def setup_method(self, method):
        # Define shape etc.
        m = 100  # Dimensionality
        n = 128  # Number of samples
        r = 3

        self.rng = np.random.RandomState(101)
        U = self.rng.randn(m, r)
        V = self.rng.randn(n, r)
        X = U @ V.T
        X = np.exp(0.1 * X / np.linalg.norm(X))

        self.m = m
        self.n = n
        self.rank = r
        self.X = X
        self.s = Signal1D(X.copy().reshape(int(np.sqrt(m)), int(np.sqrt(m)),
                                           n)).as_lazy()

        # Test tolerance
        self.tol = 1e-2 * (self.m * self.n)
コード例 #26
0
ファイル: test_linear_model.py プロジェクト: jat255/hyperspy
    def setup_method(self, method):
        g1 = Gaussian(centre=10)
        g2 = Gaussian(centre=20)
        g3 = Gaussian(centre=30)

        g3.A.twin = g2.A
        g3.A.twin_function_expr = "-0.5*x"
        g2.A.twin = g1.A
        g2.A.twin_function_expr = "-0.5*x"

        g1.A.value = 20
        x = np.linspace(0, 50, 1000)

        y = g1.function(x) + g2.function(x) + g3.function(x)
        s = Signal1D(y)
        s.axes_manager[-1].scale = x[1] - x[0]

        gs = [g1, g2, g3]
        m = s.create_model()
        m.extend(gs)
        self.s, self.m, self.gs = s, m, gs
コード例 #27
0
ファイル: test_plot_markers.py プロジェクト: shogas/hyperspy
 def test_add_several_permanent_markers(self):
     s = Signal1D(np.arange(10))
     m_point = markers.point(x=5, y=5)
     m_line = markers.line_segment(x1=5, x2=10, y1=5, y2=10)
     m_vline = markers.vertical_line(x=5)
     m_vline_segment = markers.vertical_line_segment(x=4, y1=3, y2=6)
     m_hline = markers.horizontal_line(y=5)
     m_hline_segment = markers.horizontal_line_segment(x1=1, x2=9, y=5)
     m_rect = markers.rectangle(x1=1, x2=3, y1=5, y2=10)
     m_text = markers.text(x=1, y=5, text="test")
     s.add_marker(m_point, permanent=True)
     s.add_marker(m_line, permanent=True)
     s.add_marker(m_vline, permanent=True)
     s.add_marker(m_vline_segment, permanent=True)
     s.add_marker(m_hline, permanent=True)
     s.add_marker(m_hline_segment, permanent=True)
     s.add_marker(m_rect, permanent=True)
     s.add_marker(m_text, permanent=True)
     assert len(list(s.metadata.Markers)) == 8
     with pytest.raises(ValueError):
         s.add_marker(m_rect, permanent=True)
コード例 #28
0
def test_fit(A=1, x0=0, shape=1, scale=1, noise=0.01):
    """
    Creates a simulated noisy skew normal distribution based on the input
    parameters and fits a skew normal component to this data.
    """
    # create skew normal signal and add noise
    g = SkewNormal(A=A, x0=x0, scale=scale, shape=shape)
    x = np.arange(x0 - scale * 3, x0 + scale * 3, step=0.01 * scale)
    s = Signal1D(g.function(x))
    s.axes_manager.signal_axes[0].axis = x
    s.add_gaussian_noise(std=noise * A)
    # fit skew normal component to signal
    g2 = SkewNormal()
    m = s.create_model()
    m.append(g2)
    g2.x0.bmin = x0 - scale * 3  # prevent parameters to run away
    g2.x0.bmax = x0 + scale * 3
    g2.x0.bounded = True
    m.fit(bounded=True)
    m.print_current_values()  # print out parameter values
    m.plot()  # plot fit
    return m
コード例 #29
0
    def test_roi_add_widget(self):
        s = Signal1D(np.random.rand(60, 4))
        s.axes_manager[0].name = 'nav axis'
        # Test adding roi to plot
        s.plot(navigator='spectrum')

        # Try using different argument types
        for axes in [0, s.axes_manager[0], 'nav axis', [0], ['nav axis']]:
            r = SpanROI(0, 60)
            r.add_widget(s, axes=axes)
            np.testing.assert_equal(r(s).data, s.data)

        # invalid arguments
        for axes in ['not a DataAxis name', ['not a DataAxis name'], [0, 1]]:
            r2 = SpanROI(0, 60)
            with pytest.raises(ValueError):
                r2.add_widget(s, axes=axes)

        for axes in [2, [2]]:
            r3 = SpanROI(0, 60)
            with pytest.raises(IndexError):
                r3.add_widget(s, axes=axes)
コード例 #30
0
def test_function_nd(lazy):
    s = Signal1D(np.empty((200,)))
    axis = s.axes_manager.signal_axes[0]
    axis.scale = .05
    axis.offset = -5
    A, sigma1, sigma2, fraction, centre = 5, 0.3, 0.75, 0.5, 1
    g1 = SplitVoigt(A=A, sigma1=sigma1, sigma2=sigma2, fraction=fraction,
                    centre=centre)
    s.data = g1.function(axis.axis)
    s2 = stack([s] * 2)
    if lazy:
        s2 = s2.as_lazy()
    g2 = SplitVoigt()
    assert g2.estimate_parameters(s2, axis.low_value, axis.high_value, False)

    g2.A.map['values'] = [A] * 2
    g2.sigma1.map['values'] = [sigma1] * 2
    g2.sigma2.map['values'] = [sigma2] * 2
    g2.fraction.map['values'] = [fraction] * 2
    g2.centre.map['values'] = [centre] * 2

    assert_allclose(g2.function_nd(axis.axis), s2.data)
コード例 #31
0
 def test_convert_to_non_uniform_axis(self):
     axis = np.copy(self.axis.axis)
     is_binned = self.axis.is_binned
     navigate = self.axis.navigate
     self.axis.name = "parrot"
     self.axis.units = "plumage"
     s = Signal1D(np.arange(10), axes=[self.axis])
     index_in_array = s.axes_manager[0].index_in_array
     s.axes_manager[0].convert_to_non_uniform_axis()
     assert isinstance(s.axes_manager[0], DataAxis)
     assert s.axes_manager[0].name == "parrot"
     assert s.axes_manager[0].units == "plumage"
     assert s.axes_manager[0].size == 10
     assert s.axes_manager[0].low_value == 10
     assert s.axes_manager[0].high_value == 10 + 0.1 * 9
     np.testing.assert_allclose(s.axes_manager[0].axis, axis)
     with pytest.raises(AttributeError):
         s.axes_manager[0].offset
     with pytest.raises(AttributeError):
         s.axes_manager[0].scale
     assert index_in_array == s.axes_manager[0].index_in_array
     assert is_binned == s.axes_manager[0].is_binned
     assert navigate == s.axes_manager[0].navigate