Skip to content

Commit

Permalink
Merge pull request #677 from hakonanes/minor-improvements-ebsd-detector
Browse files Browse the repository at this point in the history
Improve EBSD detector string representation, force float data type
  • Loading branch information
hakonanes authored Jun 2, 2024
2 parents 0480dd3 + 4f1c686 commit f4946c7
Show file tree
Hide file tree
Showing 14 changed files with 711 additions and 685 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ Changed
(`#674 <https://github.com/pyxem/kikuchipy/pull/674>`_)
- Minimum scikit-image version is now 0.22.0.
(`#674 <https://github.com/pyxem/kikuchipy/pull/674>`_)
- Upon creation of an ``EBSDDetector``, the following attributes are forced to be
floats: sample tilt, tilt, azimuthal angle, binning, pixel size, and the projection
centers (PCs). (`#677 <https://github.com/pyxem/kikuchipy/pull/677>`_)
- Simpler string representation of an ``EBSDDetector``, also showing the sample tilt.
(`#677 <https://github.com/pyxem/kikuchipy/pull/677>`_)

Deprecated
----------
Expand Down
258 changes: 133 additions & 125 deletions doc/tutorials/esteem2022_diffraction_workshop.ipynb

Large diffs are not rendered by default.

329 changes: 160 additions & 169 deletions doc/tutorials/hybrid_indexing.ipynb

Large diffs are not rendered by default.

88 changes: 44 additions & 44 deletions doc/tutorials/mandm2021_sunday_short_course.ipynb

Large diffs are not rendered by default.

111 changes: 56 additions & 55 deletions doc/tutorials/pattern_matching.ipynb

Large diffs are not rendered by default.

171 changes: 85 additions & 86 deletions doc/tutorials/pc_extrapolate_plane.ipynb

Large diffs are not rendered by default.

148 changes: 73 additions & 75 deletions doc/tutorials/pc_fit_plane.ipynb

Large diffs are not rendered by default.

176 changes: 88 additions & 88 deletions doc/tutorials/pc_orientation_dependence.ipynb

Large diffs are not rendered by default.

62 changes: 37 additions & 25 deletions kikuchipy/detectors/ebsd_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import logging
from pathlib import Path
import re
from typing import List, Optional, Tuple, Union
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

from matplotlib.figure import Figure
from matplotlib.markers import MarkerStyle
Expand All @@ -40,6 +40,11 @@
from kikuchipy import __version__
from kikuchipy.indexing._hough_indexing import _get_indexer_from_detector

if TYPE_CHECKING: # pragma: no cover
from diffsims.crystallography import ReciprocalLatticeVector
from pyebsdindex import EBSDIndexer


_logger = logging.getLogger(__name__)

CONVENTION_ALIAS = {
Expand Down Expand Up @@ -172,7 +177,7 @@ class EBSDDetector:
... sample_tilt=70,
... )
>>> det
EBSDDetector (60, 60), px_size 70 um, binning 8, tilt 5, azimuthal 0, pc (0.421, 0.221, 0.505)
EBSDDetector(shape=(60, 60), pc=(0.421, 0.221, 0.505), sample_tilt=70.0, tilt=5.0, azimuthal=0.0, binning=8.0, px_size=70.0 um)
>>> det.navigation_shape
(10, 20)
>>> det.bounds
Expand Down Expand Up @@ -204,22 +209,32 @@ def __init__(
projection/pattern centers (PCs).
"""
self.shape = shape
self.px_size = px_size
self.binning = binning
self.tilt = tilt
self.azimuthal = azimuthal
self.sample_tilt = sample_tilt
self.px_size = float(px_size)
self.binning = float(binning)
self.tilt = float(tilt)
self.azimuthal = float(azimuthal)
self.sample_tilt = float(sample_tilt)
self.pc = pc
if convention is None:
convention = "bruker"
self._set_pc_in_bruker_convention(convention)

def __repr__(self) -> str:
pc_average = tuple(self.pc_average.round(3))
decimals = 3
pc_average = tuple(self.pc_average.round(decimals))
sample_tilt = np.round(self.sample_tilt, decimals)
tilt = np.round(self.tilt, decimals)
azimuthal = np.round(self.azimuthal, decimals)
px_size = np.round(self.px_size, decimals)
return (
f"{type(self).__name__} {self.shape}, "
f"px_size {self.px_size} um, binning {self.binning}, "
f"tilt {self.tilt}, azimuthal {self.azimuthal}, pc {pc_average}"
f"{type(self).__name__}"
f"(shape={self.shape}, "
f"pc={pc_average!r}, "
f"sample_tilt={sample_tilt}, "
f"tilt={tilt}, "
f"azimuthal={azimuthal}, "
f"binning={self.binning}, "
f"px_size={px_size} um)"
)

@property
Expand Down Expand Up @@ -287,7 +302,7 @@ def pc(self, value: Union[np.ndarray, List, Tuple]):
"""Set all projection center coordinates, assuming Bruker's
convention.
"""
self._pc = np.atleast_2d(value)
self._pc = np.atleast_2d(value).astype(float)

@property
def pc_flattened(self) -> np.ndarray:
Expand All @@ -312,7 +327,7 @@ def pcx(self) -> np.ndarray:
@pcx.setter
def pcx(self, value: Union[np.ndarray, list, tuple, float]):
"""Set the x projection center coordinates."""
self._pc[..., 0] = np.atleast_2d(value)
self._pc[..., 0] = np.atleast_2d(value).astype(float)

@property
def pcy(self) -> np.ndarray:
Expand All @@ -330,7 +345,7 @@ def pcy(self) -> np.ndarray:
@pcy.setter
def pcy(self, value: Union[np.ndarray, list, tuple, float]):
"""Set y projection center coordinates."""
self._pc[..., 1] = np.atleast_2d(value)
self._pc[..., 1] = np.atleast_2d(value).astype(float)

@property
def pcz(self) -> np.ndarray:
Expand All @@ -348,7 +363,7 @@ def pcz(self) -> np.ndarray:
@pcz.setter
def pcz(self, value: Union[np.ndarray, list, tuple, float]):
"""Set z projection center coordinates."""
self._pc[..., 2] = np.atleast_2d(value)
self._pc[..., 2] = np.atleast_2d(value).astype(float)

@property
def pc_average(self) -> np.ndarray:
Expand Down Expand Up @@ -524,13 +539,10 @@ def load(cls, fname: Union[Path, str]) -> EBSDDetector:
detector_kw[k] = tuple(int(i) for i in shape[1:-1].split(","))
except ValueError: # pragma: no cover
detector_kw[k] = None
for k, dtype in zip(
["px_size", "binning", "tilt", "azimuthal", "sample_tilt"],
[float, int, float, float, float],
):
for k in ["px_size", "binning", "tilt", "azimuthal", "sample_tilt"]:
value = detector_kw[k].rstrip(" deg")
try:
detector_kw[k] = dtype(value)
detector_kw[k] = float(value)
except (): # pragma: no cover
detector_kw[k] = None

Expand Down Expand Up @@ -559,9 +571,9 @@ def crop(self, extent: Union[Tuple[int, int, int, int], List[int]]) -> EBSDDetec
>>> import kikuchipy as kp
>>> det = kp.detectors.EBSDDetector((6, 6), pc=[3 / 6, 2 / 6, 0.5])
>>> det
EBSDDetector (6, 6), px_size 1 um, binning 1, tilt 0, azimuthal 0, pc (0.5, 0.333, 0.5)
EBSDDetector(shape=(6, 6), pc=(0.5, 0.333, 0.5), sample_tilt=70.0, tilt=0.0, azimuthal=0.0, binning=1.0, px_size=1.0 um)
>>> det.crop((1, 5, 2, 6))
EBSDDetector (4, 4), px_size 1 um, binning 1, tilt 0, azimuthal 0, pc (0.25, 0.25, 0.75)
EBSDDetector(shape=(4, 4), pc=(0.25, 0.25, 0.75), sample_tilt=70.0, tilt=0.0, azimuthal=0.0, binning=1.0, px_size=1.0 um)
Plot a cropped detector with the PC on a cropped pattern
Expand Down Expand Up @@ -1262,7 +1274,7 @@ def pc_tsl(self) -> np.ndarray:
... convention="bruker",
... )
>>> det.pc_tsl()
array([[0.4 , 0.6 , 0.45]])
array([[0.4, 0.8, 0.6]])
"""
return self._pc_bruker2tsl()

Expand Down Expand Up @@ -1498,12 +1510,12 @@ def plot_pc(
... shape=(480, 640), pc=(0.4, 0.3, 0.5), px_size=70, sample_tilt=70
... )
>>> det0
EBSDDetector (480, 640), px_size 70 um, binning 1, tilt 0, azimuthal 0, pc (0.4, 0.3, 0.5)
EBSDDetector(shape=(480, 640), pc=(0.4, 0.3, 0.5), sample_tilt=70.0, tilt=0.0, azimuthal=0.0, binning=1.0, px_size=70.0 um)
>>> det = det0.extrapolate_pc(
... pc_indices=[0, 0], navigation_shape=(5, 10), step_sizes=(20, 20)
... )
>>> det
EBSDDetector (480, 640), px_size 70 um, binning 1, tilt 0, azimuthal 0, pc (0.398, 0.299, 0.5)
EBSDDetector(shape=(480, 640), pc=(0.398, 0.299, 0.5), sample_tilt=70.0, tilt=0.0, azimuthal=0.0, binning=1.0, px_size=70.0 um)
Plot PC values in maps
Expand Down
22 changes: 13 additions & 9 deletions kikuchipy/detectors/tests/test_ebsd_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ def test_init(self, pc1):
)
assert det.shape == shape
assert det.aspect_ratio == 2
assert np.issubdtype(det.pc.dtype, np.floating)
for attr in [det.sample_tilt, det.tilt, det.azimuthal, det.px_size]:
assert type(attr) is float

@pytest.mark.parametrize(
"nav_shape, desired_nav_shape, desired_nav_dim",
Expand Down Expand Up @@ -97,24 +100,25 @@ def test_detector_dimensions(
px_size_binned,
):
"""Initialization yields expected derived values."""
detector = kp.detectors.EBSDDetector(
det = kp.detectors.EBSDDetector(
shape=shape, px_size=px_size, binning=binning, pc=pc
)
assert detector.specimen_scintillator_distance == ssd
assert detector.width == width
assert detector.height == height
assert detector.size == size
assert detector.unbinned_shape == shape_unbinned
assert detector.px_size_binned == px_size_binned
print(det)
assert det.specimen_scintillator_distance == ssd
assert det.width == width
assert det.height == height
assert det.size == size
assert det.unbinned_shape == shape_unbinned
assert det.px_size_binned == px_size_binned

def test_repr(self, pc1):
"""Expected string representation."""
det = kp.detectors.EBSDDetector(
shape=(1, 2), px_size=3, binning=4, tilt=5, azimuthal=2, pc=pc1
)
assert repr(det) == (
"EBSDDetector (1, 2), px_size 3 um, binning 4, tilt 5, azimuthal 2, pc "
"(0.421, 0.779, 0.505)"
"EBSDDetector(shape=(1, 2), pc=(0.421, 0.779, 0.505), sample_tilt=70.0, "
"tilt=5.0, azimuthal=2.0, binning=4.0, px_size=3.0 um)"
)

def test_deepcopy(self, pc1):
Expand Down
8 changes: 6 additions & 2 deletions kikuchipy/signals/_kikuchi_master_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from copy import deepcopy
import logging
from typing import Any, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
from warnings import warn

import hyperspy.api as hs
Expand All @@ -32,6 +32,10 @@
from kikuchipy.signals.util._master_pattern import _lambert2vector
from kikuchipy.signals.util._overwrite_hyperspy_methods import insert_doc_disclaimer

if TYPE_CHECKING: # pragma: no cover
from pyvista import Plotter


_logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -206,7 +210,7 @@ def plot_spherical(
style: str = "surface",
plotter_kwargs: Union[dict] = None,
show_kwargs: Union[dict] = None,
) -> "pyvista.Plotter":
) -> "Plotter":
"""Plot the master pattern sphere.
This requires the master pattern to be in the stereographic
Expand Down
2 changes: 1 addition & 1 deletion kikuchipy/signals/_kikuchipy_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def normalize_intensity(
146.0670987654321
>>> s.normalize_intensity(dtype_out=np.float32)
>>> np.mean(s.data)
2.6373216e-08
0.0
"""
if lazy_output and inplace:
raise ValueError("`lazy_output=True` requires `inplace=False`")
Expand Down
10 changes: 5 additions & 5 deletions kikuchipy/signals/ebsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ class EBSD(KikuchipySignal2D):
>>> s
<EBSD, title: patterns Scan 1, dimensions: (3, 3|60, 60)>
>>> s.detector
EBSDDetector (60, 60), px_size 1 um, binning 8, tilt 0, azimuthal 0, pc (0.425, 0.213, 0.501)
EBSDDetector(shape=(60, 60), pc=(0.425, 0.213, 0.501), sample_tilt=70.0, tilt=0.0, azimuthal=0.0, binning=8.0, px_size=1.0 um)
>>> s.static_background
array([[84, 87, 90, ..., 27, 29, 30],
[87, 90, 93, ..., 27, 28, 30],
Expand All @@ -160,7 +160,7 @@ class EBSD(KikuchipySignal2D):
>>> s.xmap
Phase Orientations Name Space group Point group Proper point group Color
0 9 (100.0%) ni Fm-3m m-3m 432 tab:blue
Properties: scores
Properties: scores, z
Scan unit: px
"""

Expand Down Expand Up @@ -1335,9 +1335,9 @@ def get_image_quality(
>>> s.remove_dynamic_background()
>>> iq = s.get_image_quality()
>>> iq
array([[0.19935645, 0.16657268, 0.18803978],
[0.19040637, 0.1616931 , 0.17834103],
[0.19411428, 0.16031407, 0.18413563]], dtype=float32)
array([[0.19935645, 0.16657268, 0.18802597],
[0.19040637, 0.16169308, 0.17834103],
[0.19411428, 0.16031112, 0.18414427]], dtype=float32)
"""
# Calculate frequency vectors
sx, sy = self.axes_manager.signal_shape
Expand Down
6 changes: 5 additions & 1 deletion kikuchipy/signals/util/_master_pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
patterns into a detector.
"""

from typing import Optional, Tuple, Union
from typing import TYPE_CHECKING, Optional, Tuple, Union

import numba as nb
from numba import njit
Expand All @@ -67,6 +67,10 @@
from kikuchipy._rotation import _rotate_vector
from kikuchipy.pattern._pattern import _rescale_with_min_max

if TYPE_CHECKING: # pragma: no cover
from kikuchipy.detectors import EBSDDetector


# Reusable constants
SQRT_PI = np.sqrt(np.pi)
SQRT_PI_HALF = np.sqrt(np.pi / 2)
Expand Down

0 comments on commit f4946c7

Please sign in to comment.