Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/RELEASE_next_patch' into RELEA…
Browse files Browse the repository at this point in the history
…SE_next_minor
  • Loading branch information
ericpre committed Sep 26, 2022
2 parents c6a6543 + 953fc8d commit 048028d
Show file tree
Hide file tree
Showing 15 changed files with 91 additions and 71 deletions.
2 changes: 1 addition & 1 deletion doc/dev_guide/writing_docs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ about how it should be used, such as which arguments can be passed to it and
what the syntax should be. The docstrings need to follow the `numpy
specification <https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard>`_,
as shown in `this example
<https://github.com/numpy/numpy/blob/main/doc/example.py>`_.
<https://numpydoc.readthedocs.io/en/latest/example.html>`_.

As a general rule, any code that is part of the public API (i.e. any function
or class that an end-user might access) should have a clear and comprehensive
Expand Down
7 changes: 2 additions & 5 deletions hyperspy/drawing/_markers/arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,10 @@ class Arrow(MarkerBase):
Keyword arguments are passed to
:py:class:`matplotlib.patches.FancyArrowPatch`.
Example
-------
>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> m = hs.plot.markers.arrow(x1=150, y1=100, x2=400, y2=400,
>>> arrowprop={'arrowstyle':'<->', edgecolor='red'})
>>> im.add_marker(m)
Expand Down Expand Up @@ -102,5 +101,3 @@ def _plot_marker(self):
y2 = self.get_data_position('y2')
self.marker = self.ax.add_patch(patches.FancyArrowPatch(
(x1,y1), (x2,y2), **self.marker_properties))


5 changes: 2 additions & 3 deletions hyperspy/drawing/_markers/ellipse.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ class Ellipse(MarkerBase):
Example
-------
>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> m = hs.plot.markers.ellipse(x=150, y=100, width=400, height=400,
>>> edgecolor='red', facecolor='white', fill=True)
>>> im.add_marker(m)
Expand Down Expand Up @@ -105,4 +105,3 @@ def _plot_marker(self):
height = self.get_data_position('y2')
self.marker = self.ax.add_patch(patches.Ellipse(
[x1,y1], width, height, **self.marker_properties))

31 changes: 14 additions & 17 deletions hyperspy/drawing/_markers/point.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,25 @@ class Point(MarkerBase):
Example
-------
>>> im = hs.signals.Signal2D(np.random.random([10, 50, 50]))
>>> m = hs.plot.markers.point(x=range(10), y=range(10)[::-1],
>>> color='red')
>>> im.add_marker(m)
Add a marker with the same position for all navigation positions
>>> im = hs.signals.Signal2D(np.arange(1000).reshape([10, 10, 10]))
>>> m = hs.plot.markers.point(x=1, y=2, color='C0')
>>> s.add_marker(m)
Add a marker, the position of which depends on the navigation positions
Adding a marker permanently to a signal
>>> x_position = np.arange(10)
>>> y_position = np.arange(10) / 2
>>> m = hs.plot.markers.point(x=x_position, y=y_position, color='C1')
>>> s.add_marker(m)
Add a marker permanently; the marker is saved in the metadata
>>> im = hs.signals.Signal2D(np.random.random([10, 50, 50]))
>>> m = hs.plot.markers.point(10, 30, color='blue', size=50)
>>> im.add_marker(m, permanent=True)
Markers on local maxima
>>> from skimage.feature import peak_local_max
>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent()).as_signal2D([2,0])
>>> index = array([peak_local_max(i.data, min_distance=100, num_peaks=4)
>>> for i in im])
>>> for i in range(4):
>>> m = hs.plot.markers.point(x=index[:, i, 1],
>>> y=index[:, i, 0], color='red')
>>> im.add_marker(m)
"""

def __init__(self, x, y, size=20, **kwargs):
Expand Down
6 changes: 2 additions & 4 deletions hyperspy/drawing/_markers/rectangle.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class Rectangle(MarkerBase):
Example
-------
>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> m = hs.plot.markers.rectangle(x1=150, y1=100, x2=400, y2=400,
>>> color='red')
>>> im.add_marker(m)
Expand Down Expand Up @@ -108,5 +108,3 @@ def _plot_marker(self):
self.marker = self.ax.add_patch(patches.Rectangle(
(self.get_data_position('x1'), self.get_data_position('y1')),
width, height, **self.marker_properties))


24 changes: 12 additions & 12 deletions hyperspy/misc/tv_denoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,10 @@ def _tv_denoise_2d(im, weight=50, eps=2.e-4, keep_type=False, n_iter_max=200):
Examples
---------
>>> import scipy
>>> ascent = scipy.ascent().astype(float)
>>> ascent += 0.5 * ascent.std()*np.random.randn(*ascent.shape)
>>> denoised_ascent = tv_denoise(ascent, weight=60.0)
>>> import skimage
>>> camera = skimage.data.camera().astype(float)
>>> camera += 0.5 * camera.std()*np.random.randn(*ascent.shape)
>>> denoised_camera = tv_denoise(camera, weight=60.0)
"""
im_type = im.dtype
if im_type is not float:
Expand Down Expand Up @@ -258,10 +258,10 @@ def _tv_denoise_1d(im, weight=50, eps=2.e-4, keep_type=False, n_iter_max=200):
Examples
---------
>>> import scipy
>>> ascent = scipy.misc.ascent().astype(float)
>>> ascent += 0.5 * ascent.std()*np.random.randn(*ascent.shape)
>>> denoised_ascent = tv_denoise(ascent, weight=60.0)
>>> import skimage
>>> camera = skimage.data.camera().astype(float)
>>> camera += 0.5 * camera.std()*np.random.randn(*camera.shape)
>>> denoised_camera = tv_denoise(camera, weight=60.0)
"""
im_type = im.dtype
if im_type is not float:
Expand Down Expand Up @@ -356,10 +356,10 @@ def tv_denoise(im, weight=50, eps=2.e-4, keep_type=False, n_iter_max=200):
Examples
---------
>>> # 2D example using ascent
>>> import scipy
>>> ascent = scipy.misc.ascent().astype(float)
>>> ascent += 0.5 * ascent.std()*np.random.randn(*ascent.shape)
>>> denoised_ascent = tv_denoise(ascent, weight=60)
>>> import skimage
>>> camera = skimage.data.camera().astype(float)
>>> camera += 0.5 * camera.std()*np.random.randn(*camera.shape)
>>> denoised_camera = tv_denoise(camera, weight=60)
>>> # 3D example on synthetic data
>>> x, y, z = np.ogrid[0:40, 0:40, 0:40]
>>> mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
Expand Down
13 changes: 7 additions & 6 deletions hyperspy/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2507,7 +2507,7 @@ def ragged(self, value):
# and in the future, it will raise an error
data = np.array(self.data.tolist())
except:
_logger.error(error)
raise ValueError(error)

if data.dtype == object:
raise ValueError(error)
Expand Down Expand Up @@ -4292,7 +4292,8 @@ def fft(self, shift=False, apodization=False, real_fft_only=False, **kwargs):
Examples
--------
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> im.fft()
<ComplexSignal2D, title: FFT of , dimensions: (|512, 512)>
Expand Down Expand Up @@ -4387,8 +4388,8 @@ def ifft(self, shift=None, return_real=True, **kwargs):
Examples
--------
>>> import scipy
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> imfft = im.fft()
>>> imfft.ifft()
<Signal2D, title: real(iFFT of FFT of ), dimensions: (|512, 512)>
Expand Down Expand Up @@ -5912,8 +5913,8 @@ def add_marker(
Examples
--------
>>> import scipy.misc
>>> im = hs.signals.Signal2D(scipy.misc.ascent())
>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> m = hs.markers.rectangle(x1=150, y1=100, x2=400,
>>> y2=400, color='red')
>>> im.add_marker(m)
Expand Down
9 changes: 7 additions & 2 deletions hyperspy/tests/drawing/test_plot_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,8 +570,13 @@ def test_plot_add_background_windows():

def test_iterate_markers():
from skimage.feature import peak_local_max
import scipy.misc
ims = BaseSignal(scipy.misc.face()).as_signal2D([1, 2])
try:
# scipy <1.10
from scipy.misc import face
except:
# scipy >=1.10
from scipy.dataset import face
ims = BaseSignal(face()).as_signal2D([1, 2])
index = np.array([peak_local_max(im.data, min_distance=100,
num_peaks=4) for im in ims])
# Add multiple markers
Expand Down
11 changes: 8 additions & 3 deletions hyperspy/tests/drawing/test_plot_signal1d.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@
import matplotlib.pyplot as plt
import numpy as np
import pytest
import scipy.misc
try:
# scipy <1.10
from scipy.misc import ascent, face
except:
# scipy >=1.10
from scipy.dataset import ascent, face

import hyperspy.api as hs
from hyperspy.misc.test_utils import update_close_figure
Expand Down Expand Up @@ -87,7 +92,7 @@ def setup_teardown(request, scope="class"):
@pytest.mark.usefixtures("setup_teardown")
class TestPlotSpectra():

s = hs.signals.Signal1D(scipy.misc.ascent()[100:160:10])
s = hs.signals.Signal1D(ascent()[100:160:10])

# Add a test signal with decreasing axis
s_reverse = s.deepcopy()
Expand Down Expand Up @@ -148,7 +153,7 @@ def test_plot_spectra_rev(self, style, fig, ax):
@pytest.mark.mpl_image_compare(baseline_dir=baseline_dir,
tolerance=default_tol, style=style_pytest_mpl)
def test_plot_spectra_sync(self, figure):
s1 = hs.signals.Signal1D(scipy.misc.face()).as_signal1D(0).inav[:, :3]
s1 = hs.signals.Signal1D(face()).as_signal1D(0).inav[:, :3]
s2 = s1.deepcopy() * -1
hs.plot.plot_signals([s1, s2])
if figure == '1nav':
Expand Down
28 changes: 17 additions & 11 deletions hyperspy/tests/drawing/test_plot_signal2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
import numpy as np
import pytest
import scipy.ndimage
try:
# scipy <1.10
from scipy.misc import ascent, face
except:
# scipy >=1.10
from scipy.dataset import ascent, face
import traits.api as t

import hyperspy.api as hs
Expand All @@ -37,7 +43,7 @@ def _generate_image_stack_signal():
image = hs.signals.Signal2D(np.random.random((2, 3, 512, 512)))
for i in range(2):
for j in range(3):
image.data[i, j, :] = scipy.misc.ascent() * (i + 0.5 + j)
image.data[i, j, :] = ascent() * (i + 0.5 + j)
axes = image.axes_manager
axes[2].name = "x"
axes[3].name = "y"
Expand Down Expand Up @@ -140,7 +146,7 @@ def test_plot_FFT(fft_shift):
baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl)
def test_plot_multiple_images_list(vmin, vmax):
# load red channel of raccoon as an image
image0 = hs.signals.Signal2D(scipy.misc.face()[:, :, 0])
image0 = hs.signals.Signal2D(face()[:, :, 0])
image0.metadata.General.title = 'Rocky Raccoon - R'
axes0 = image0.axes_manager
axes0[0].name = "x"
Expand All @@ -152,7 +158,7 @@ def test_plot_multiple_images_list(vmin, vmax):
image1 = _generate_image_stack_signal()

# load green channel of raccoon as an image
image2 = hs.signals.Signal2D(scipy.misc.face()[:, :, 1])
image2 = hs.signals.Signal2D(face()[:, :, 1])
image2.metadata.General.title = 'Rocky Raccoon - G'
axes2 = image2.axes_manager
axes2[0].name = "x"
Expand All @@ -161,7 +167,7 @@ def test_plot_multiple_images_list(vmin, vmax):
axes2[1].units = "mm"

# load rgb imimagesage
rgb = hs.signals.Signal1D(scipy.misc.face())
rgb = hs.signals.Signal1D(face())
rgb.change_dtype("rgb8")
rgb.metadata.General.title = 'RGB'
axesRGB = rgb.axes_manager
Expand All @@ -178,7 +184,7 @@ def test_plot_multiple_images_list(vmin, vmax):
baseline_dir=baseline_dir, tolerance=default_tol, style=style_pytest_mpl)
def test_plot_rgb_image():
# load rgb imimagesage
rgb = hs.signals.Signal1D(scipy.misc.face())
rgb = hs.signals.Signal1D(face())
rgb.change_dtype("rgb8")
rgb.metadata.General.title = 'RGB'
axesRGB = rgb.axes_manager
Expand All @@ -192,7 +198,7 @@ def test_plot_rgb_image():
class _TestIteratedSignal:

def __init__(self):
s = hs.signals.Signal2D([scipy.misc.ascent()] * 6)
s = hs.signals.Signal2D([ascent()] * 6)
angles = hs.signals.BaseSignal(range(00, 60, 10))
s.map(scipy.ndimage.rotate, angle=angles.T, reshape=False)
# prevent values outside of integer range
Expand Down Expand Up @@ -229,8 +235,8 @@ def _set_signal_axes(self, axes_manager, name=t.Undefined,
return axes_manager


class TestPlotNonLinearAxis:
class TestPlotNonLinearAxis:

def setup_method(self):
dict0 = {'axis': np.arange(10)**0.5, 'name':'Non uniform 0', 'units':'A',
'navigate':True}
Expand Down Expand Up @@ -388,7 +394,7 @@ def test_plot_images_cmap_multi_w_rgb():
test_plot2.signal *= 2 # change scale of second signal
test_plot2.signal.metadata.General.title = 'Ascent-2'

rgb_sig = hs.signals.Signal1D(scipy.misc.face())
rgb_sig = hs.signals.Signal1D(face())
rgb_sig.change_dtype('rgb8')
rgb_sig.metadata.General.title = 'Racoon!'

Expand Down Expand Up @@ -661,7 +667,7 @@ def test_plot_images_overlay_figsize():
hs.plot.plot_images([s, s], overlay=True, scalebar='all', axes_decor='off')
f = plt.gcf()
np.testing.assert_allclose((f.get_figwidth(), f.get_figheight()), (6.4, 3.2))

# aspect_ratio is 0.5
s = hs.signals.Signal2D(np.random.random((20, 10)))
hs.plot.plot_images([s, s], overlay=True, scalebar='all', axes_decor='off')
Expand All @@ -672,7 +678,7 @@ def test_plot_images_overlay_figsize():
def test_plot_images_overlay_vmin_warning(caplog):
s = hs.signals.Signal2D(np.arange(100).reshape(10, 10))
with caplog.at_level(logging.WARNING):
hs.plot.plot_images([s, s], overlay=True, vmin=0)
hs.plot.plot_images([s, s], overlay=True, vmin=0)

assert "`vmin` is ignored when overlaying images." in caplog.text

Expand Down
13 changes: 9 additions & 4 deletions hyperspy/tests/misc/test_tv_denoise.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,33 @@
# You should have received a copy of the GNU General Public License
# along with HyperSpy. If not, see <https://www.gnu.org/licenses/#GPL>.

from packaging.version import Version

import numpy as np
import pytest
import skimage

from hyperspy.misc.tv_denoise import tv_denoise
from scipy.misc import ascent


def test_tv_denoise_error():
with pytest.raises(ValueError, match="may be denoised"):
_ = tv_denoise(np.array([1, 2, 3]))


@pytest.mark.skipif(Version(skimage.__version__) < Version("0.18"),
reason="This test requires scikit-image >= 0.18")
def test_2d_tv_denoise():
rng = np.random.RandomState(123)
data = ascent().astype(float)
data = skimage.data.camera().astype(float)
data_noisy = data + data.std() * rng.randn(*data.shape)
data_clean = tv_denoise(data, weight=60)

norm_noisy = np.linalg.norm(data - data_noisy) / np.linalg.norm(data)
norm_clean = np.linalg.norm(data - data_clean) / np.linalg.norm(data)

np.testing.assert_allclose(norm_noisy, 0.48604971)
np.testing.assert_allclose(norm_clean, 0.10888393)
np.testing.assert_allclose(norm_noisy, 0.49466990)
np.testing.assert_allclose(norm_clean, 0.06453270)


def test_3d_tv_denoise():
Expand Down
7 changes: 6 additions & 1 deletion hyperspy/tests/signals/test_2D_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@
import numpy as np
import numpy.testing as npt
import pytest
from scipy.misc import ascent, face
try:
# scipy <1.10
from scipy.misc import ascent, face
except:
# scipy >=1.10
from scipy.dataset import ascent, face
from scipy.ndimage import fourier_shift

import hyperspy.api as hs
Expand Down

0 comments on commit 048028d

Please sign in to comment.