Skip to content

Commit

Permalink
Image export: allow adding scalebar when scale are almost equal (1E-1…
Browse files Browse the repository at this point in the history
…0 relative difference)
  • Loading branch information
ericpre committed Jan 9, 2025
1 parent 85a2d9d commit a6b287a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
12 changes: 9 additions & 3 deletions rsciio/image/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# along with RosettaSciIO. If not, see <https://www.gnu.org/licenses/#GPL>.

import logging
import math
import os
from collections.abc import Iterable

Expand Down Expand Up @@ -167,10 +168,15 @@ def file_writer(
# Sanity check of the axes
# This plugin doesn't support non-uniform axes, we don't need to check
# if the axes have a scale attribute
if axes[0]["scale"] != axes[1]["scale"] or axes[0]["units"] != axes[1]["units"]:
# Use 1E-10 precision to avoid error when scale are almost equal
if (
not math.isclose(axes[0]["scale"], axes[1]["scale"], rel_tol=1e-10)
or axes[0]["units"] != axes[1]["units"]
):
raise ValueError(
"Scale and units must be the same for each axes "
"to export images with a scale bar."
f"Scale ({axes[0]["scale"]} and {axes[1]["scale"]}) and "
f"units ({axes[0]["units"]} and {axes[1]["units"]}) must "
"be the same for each axes to export images with a scale bar."
)

if scalebar or output_size:
Expand Down
21 changes: 19 additions & 2 deletions rsciio/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,31 @@ def test_export_scalebar_different_scale_units(tmp_path):
s = hs.signals.Signal2D(np.arange(pixels**2).reshape((pixels, pixels)))
s.axes_manager[0].scale = 2

filename = tmp_path / "test_export_size.jpg"
filename = tmp_path / "test_export_different_scale.jpg"
with pytest.raises(ValueError):
s.save(filename, scalebar=True)

s = hs.signals.Signal2D(np.arange(pixels**2).reshape((pixels, pixels)))
s.axes_manager[0].units = "nm"

filename = tmp_path / "test_export_size.jpg"
filename = tmp_path / "test_export_different_units.jpg"
with pytest.raises(ValueError):
s.save(filename, scalebar=True)


def test_export_scalebar_different_scale_precision(tmp_path):
hs = pytest.importorskip("hyperspy.api", reason="hyperspy not installed")
pixels = 16
s = hs.signals.Signal2D(np.arange(pixels**2).reshape((pixels, pixels)))
s.axes_manager[0].scale = 1.9999999999
s.axes_manager[1].scale = 2.0
filename = tmp_path / "test_export_scale_1e-11_difference.jpg"
# pass with 1E-11 relative difference
s.save(filename, scalebar=True)

filename = tmp_path / "test_export_scale_1e-10_difference.jpg"
s.axes_manager[0].scale = 1.999999999
# fails with 1E-10 relative difference
with pytest.raises(ValueError):
s.save(filename, scalebar=True)

Expand Down

0 comments on commit a6b287a

Please sign in to comment.