diff --git a/src/quantem/core/datastructures/dataset3d.py b/src/quantem/core/datastructures/dataset3d.py index 2e841c79..a4af93ef 100644 --- a/src/quantem/core/datastructures/dataset3d.py +++ b/src/quantem/core/datastructures/dataset3d.py @@ -10,7 +10,10 @@ from quantem.core.utils.validators import ensure_valid_array from quantem.core.visualization import show_2d from quantem.core.visualization.custom_normalizations import NormalizationConfig -from quantem.core.visualization.visualization_utils import ScalebarConfig +from quantem.core.visualization.visualization_utils import ( + ScalebarConfig, + _fill_scalebar_calibration, +) # show_2d keywords that set the normalization; same_scale leaves them alone _NORM_KEYS = ("norm", *(f.name for f in fields(NormalizationConfig))) @@ -348,6 +351,10 @@ def show( ): vmin, vmax = np.nanquantile(np.stack(images[:n_frames]), [0.02, 0.98]) kwargs["vmin"], kwargs["vmax"] = float(vmin), float(vmax) + # the frames go to show_2d as plain arrays, so carry the calibration + scalebar = _fill_scalebar_calibration( + scalebar, float(self.sampling[-1]), str(self.units[-1]) + ) fig, axes = show_2d(image_grid, scalebar=scalebar, title=label_grid, **kwargs) if pad_count > 0: for ax in np.array(axes).flat[-pad_count:]: diff --git a/src/quantem/core/visualization/show_params.py b/src/quantem/core/visualization/show_params.py index 27ef0104..8107df43 100644 --- a/src/quantem/core/visualization/show_params.py +++ b/src/quantem/core/visualization/show_params.py @@ -241,10 +241,13 @@ class Scalebar: ``"nm"`` for data calibrated in ``"μm"``, or ``"1/Å"`` for data in ``"1/nm"``. Supports pm, Å, nm, μm, mm, cm, m and their reciprocals. ``None`` picks units automatically from the bar length. - width_px : float - Thickness of the bar in image pixels. Default 1. - pad_px : float - Padding between bar and plot edge in image pixels. Default 0.5. + width_px : float | None + Thickness of the bar in image pixels; fractions are kept. Default + None: 1 pixel on an image, scaled to the map size on orientation + and phase maps. + pad_px : float | None + Padding between bar and plot edge in image pixels. Default None, + matplotlib's spacing, which scales with the font size. color : str Bar and label colour. Default ``"white"``. loc : ``"lower right"`` | ``"lower left"`` | ``"upper right"`` | ``"upper left"`` @@ -277,8 +280,8 @@ class Scalebar: units: str = "pixels" length: float | None = None display_units: str | None = None - width_px: float = 1 - pad_px: float = 0.5 + width_px: float | None = None + pad_px: float | None = None color: str = "white" loc: Literal["lower right", "lower left", "upper right", "upper left"] = "lower right" fontsize: int = 12 @@ -293,7 +296,8 @@ def __post_init__(self) -> None: validate_gt(self.sampling, 0, "sampling") if self.length is not None: validate_gt(self.length, 0, "length") - validate_gt(self.width_px, 0, "width_px") + if self.width_px is not None: + validate_gt(self.width_px, 0, "width_px") validate_gt(self.fontsize, 0, "fontsize") validate_gt(self.outline_width, 0, "outline_width") if self.display_units is not None and _parse_length_units(self.display_units) is None: diff --git a/src/quantem/core/visualization/visualization.py b/src/quantem/core/visualization/visualization.py index e1fc2a18..8c3b965c 100644 --- a/src/quantem/core/visualization/visualization.py +++ b/src/quantem/core/visualization/visualization.py @@ -25,6 +25,9 @@ ScalebarConfig, _fill_scalebar_calibration, _resolve_scalebar, + _scalebar_display_units, + _scalebar_lacks_calibration, + _warn_from_caller, add_arg_cbar_to_ax, add_cbar_to_ax, add_scalebar_to_ax, @@ -335,6 +338,26 @@ def calib(obj: Any) -> tuple[float, str] | None: return [[calib(a) for a in row] for row in arrays] +_UNCALIBRATED_SCALEBAR_WARNING = ( + "A scale bar was requested for a plain array, which carries no calibration, so it " + "is drawn in pixels. Pass the calibrated dataset (e.g. a Dataset2d) rather than its " + "array, or give 'sampling' and 'units' in the scale bar." +) + + +def _check_uncalibrated_scalebar(scalebar: Any, calibration: Any) -> bool: + """Whether a panel's scale bar falls back to pixels with no warning of its own. + + A bar asking for display_units is left to :func:`add_scalebar_to_ax`, + which warns that the conversion was skipped. + """ + return ( + calibration is None + and _scalebar_lacks_calibration(scalebar) + and _scalebar_display_units(scalebar) is None + ) + + def _normalize_show_input_to_grid( arrays: Any, # NDArray | Sequence[NDArray] | Sequence[Sequence[NDArray]] ) -> list[list[NDArray]]: @@ -615,6 +638,8 @@ def show_2d( scalebar = scalebar[0] if not isinstance(scalebar[0], Sequence) else scalebar[0][0] if calibrations[0][0] is not None: scalebar = _fill_scalebar_calibration(scalebar, *calibrations[0][0]) + elif _check_uncalibrated_scalebar(scalebar, None): + _warn_from_caller(_UNCALIBRATED_SCALEBAR_WARNING) if isinstance(title, Sequence) and not isinstance(title, str): # flatten title title = title[0] if isinstance(title[0], str) else title[0][0] @@ -651,6 +676,16 @@ def show_2d( figsize = kwargs.pop("figsize", (axsize[0] * ncols, axsize[1] * nrows)) fig, axs = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) + if any( + _check_uncalibrated_scalebar( + normalized_args[i][j]["scalebar"], + calibrations[i][j] if i < len(calibrations) and j < len(calibrations[i]) else None, + ) + for i, row in enumerate(grid) + for j in range(len(row)) + ): + _warn_from_caller(_UNCALIBRATED_SCALEBAR_WARNING) + for i, row in enumerate(grid): for j, array in enumerate(row): figax_local = (fig, axs[i][j]) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 21637605..ab2fe0f3 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -1,3 +1,6 @@ +import os +import sys +import warnings from dataclasses import dataclass from typing import Any, cast @@ -136,10 +139,14 @@ class ScalebarConfig: Converts between pm, Å, nm, μm, mm, cm and m, or between their reciprocals (e.g. "1/nm" to "1/Å"). If None, units are chosen automatically from the bar length. - width_px : float, default=1 - Width of the scale bar in pixels. - pad_px : float, default=0.5 - Padding around the scale bar in pixels. + width_px : float, optional + Thickness of the scale bar in image pixels; fractions are kept. If + None, the plot chooses: 1 pixel for an image, or a fraction of the + map size for orientation and phase maps. + pad_px : float, optional + Gap between the scale bar (or its box) and the edge of the plot, in + image pixels. If None, matplotlib's default spacing is used, which + scales with the label font size rather than the image. color : str, default="white" Color of the scale bar. loc : str or int, default="lower right" @@ -167,8 +174,8 @@ class ScalebarConfig: units: str = "pixels" length: float | None = None display_units: str | None = None - width_px: float = 1 - pad_px: float = 0.5 + width_px: float | None = None + pad_px: float | None = None color: str = "white" loc: str | int = "lower right" fontsize: int = 12 @@ -256,6 +263,64 @@ def _fill_scalebar_calibration(cfg: Any, sampling: float, units: str) -> Any: return resolved +_QUANTEM_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def _warn_from_caller(message: str) -> None: + """Issue a UserWarning attributed to the first frame outside quantem. + + Python shows a warning once per source line, so a warning raised inside + quantem would appear only the first time. Attributing it to the caller's + line shows it for every call site in a script or notebook. + """ + if sys.version_info >= (3, 12): + warnings.warn(message, UserWarning, skip_file_prefixes=(_QUANTEM_ROOT + os.sep,)) + else: + # stacklevel counts from this function; step past every quantem frame + level, frame = 2, sys._getframe(1) + while frame is not None and frame.f_code.co_filename.startswith(_QUANTEM_ROOT + os.sep): + frame, level = frame.f_back, level + 1 + warnings.warn(message, UserWarning, stacklevel=level) + + +def _is_pixel_units(units: Any) -> bool: + """True for the uncalibrated scale bar units ("pixels", "pixel", "px").""" + return isinstance(units, str) and units.strip().lower() in ("pixels", "pixel", "px") + + +def _scalebar_lacks_calibration(cfg: Any) -> bool: + """Whether a requested scale bar carries no sampling and units of its own. + + Parameters + ---------- + cfg : None, bool, dict, ScalebarConfig or ShowParams.Scalebar + The scale bar as passed by the user. + + Returns + ------- + bool + False when no bar is requested. For a dict, True unless it gives both + "sampling" and "units". For anything else, True when its units are + still pixels. + """ + if cfg is None or cfg is False: + return False + if isinstance(cfg, dict): + return not ("sampling" in cfg and "units" in cfg) + resolved = _resolve_scalebar(cfg) + return resolved is not None and _is_pixel_units(resolved.units) + + +def _scalebar_display_units(cfg: Any) -> str | None: + """The display_units a scale bar asks for, or None.""" + if cfg is None or cfg is False or cfg is True: + return None + if isinstance(cfg, dict): + return cfg.get("display_units") + resolved = _resolve_scalebar(cfg) + return None if resolved is None else resolved.display_units + + def estimate_scalebar_length(length: float, sampling: float) -> tuple[float, float]: """Estimate an appropriate scale bar length based on data dimensions. @@ -310,9 +375,7 @@ def estimate_scalebar_length(length: float, sampling: float) -> tuple[float, flo # Accepted spellings (compared in lower case) for each unit above. _LENGTH_UNIT_ALIASES = { **dict.fromkeys(["pm", "picometer", "picometre", "picometers", "picometres"], "pm"), - **dict.fromkeys( - ["a", "å", "Å", "ang", "angstrom", "angstroms", "ångström", "ångströms"], "Å" - ), + **dict.fromkeys(["a", "å", "Å", "ang", "angstrom", "angstroms", "ångström", "ångströms"], "Å"), **dict.fromkeys(["nm", "nanometer", "nanometre", "nanometers", "nanometres"], "nm"), **dict.fromkeys( [ @@ -393,8 +456,7 @@ def _length_unit_factor(from_units: str, to_units: str) -> float: if src[1] != dst[1]: kinds = {1: "a real-space length", -1: "a reciprocal length"} raise ValueError( - f"Cannot convert {from_units!r} ({kinds[src[1]]}) to {to_units!r} " - f"({kinds[dst[1]]})." + f"Cannot convert {from_units!r} ({kinds[src[1]]}) to {to_units!r} ({kinds[dst[1]]})." ) ratio = _LENGTH_UNITS_IN_ANGSTROM[src[0]] / _LENGTH_UNITS_IN_ANGSTROM[dst[0]] return ratio if src[1] == 1 else 1 / ratio @@ -434,14 +496,38 @@ def _normalize_length_units(length_units: float, units: str) -> tuple[float, str return length_A / 1e10, "m" +class _PixelPaddedSizeBar(AnchoredSizeBar): + """AnchoredSizeBar held `pad_px` image pixels from the edge of the axes. + + matplotlib measures `borderpad` in multiples of the label font size, so + a gap in image pixels has to be converted with the current data-to-screen + scale. That is redone every time the bar is placed, so the gap follows + any later change of figure size or layout (e.g. ``tight_layout``). + """ + + def __init__(self, transform, *args, pad_px: float, **kwargs): + super().__init__(transform, *args, borderpad=0.0, **kwargs) + self._pad_px = float(pad_px) + self._pad_transform = transform + + def get_offset(self, *args, **kwargs): + renderer = kwargs.get("renderer", args[-1] if args else None) + if renderer is not None: + (x0, y0), (x1, y1) = self._pad_transform.transform([(0, 0), (1, 1)]) + screen_px_per_image_px = 0.5 * (abs(x1 - x0) + abs(y1 - y0)) + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + self.borderpad = self._pad_px * screen_px_per_image_px / fontsize + return super().get_offset(*args, **kwargs) + + def add_scalebar_to_ax( ax: Axes, array_size: float, sampling: float, length_units: float | None, units: str, - width_px: float, - pad_px: float, + width_px: float | None, + pad_px: float | None, color: str, loc: str | int, fontsize: int = 12, @@ -468,10 +554,11 @@ def add_scalebar_to_ax( will be estimated. units : str Units to display on the scale bar. - width_px : float - Width of the scale bar in pixels. - pad_px : float - Padding around the scale bar in pixels. + width_px : float or None + Thickness of the scale bar in image pixels. None means 1 pixel. + pad_px : float or None + Gap between the scale bar (or its box) and the edge of the plot, in + image pixels. None uses matplotlib's default spacing. color : str Color of the scale bar. loc : str or int @@ -501,6 +588,14 @@ def add_scalebar_to_ax( """ from matplotlib.font_manager import FontProperties + if display_units is not None and _parse_length_units(units) is None: + _warn_from_caller( + f"display_units={display_units!r} ignored: the scale bar is in {units!r}, " + "which is not a calibrated length, so it is drawn without conversion. Pass a " + "calibrated dataset rather than its array, or give 'sampling' and 'units' in " + "the scale bar." + ) + display_units = None if display_units is not None: if isinstance(sampling, (tuple, list)): sampling = np.asarray(sampling, dtype=float) @@ -530,25 +625,31 @@ def add_scalebar_to_ax( fontprops = FontProperties(size=fontsize, weight="bold" if bold else "normal") label_top = loc[:3] == "low" - bar = AnchoredSizeBar( - ax.transData, - length_px, - label, - loc, - pad=pad_px, + bar_kwargs = dict( color=color, frameon=box, label_top=label_top, - size_vertical=int(width_px), + size_vertical=1.0 if width_px is None else float(width_px), fontproperties=fontprops, sep=2 if label_top else int(round(0.3 * fontsize)), ) + if pad_px is None: + # matplotlib's own spacing, in multiples of the label font size + bar = AnchoredSizeBar(ax.transData, length_px, label, loc, pad=0.5, **bar_kwargs) + else: + bar = _PixelPaddedSizeBar( + ax.transData, + length_px, + label, + loc, + pad=0.3 if box else 0.0, + pad_px=pad_px, + **bar_kwargs, + ) if box: bar.patch.set(facecolor=box_color, edgecolor="none", alpha=box_alpha) if outline_color is not None: - effects = [ - patheffects.withStroke(linewidth=outline_width, foreground=outline_color) - ] + effects = [patheffects.withStroke(linewidth=outline_width, foreground=outline_color)] for artist in bar.size_bar.get_children(): artist.set_path_effects(effects) for artist in bar.txt_label.get_children(): diff --git a/src/quantem/diffraction/crystal_map.py b/src/quantem/diffraction/crystal_map.py index acd98923..1d863893 100644 --- a/src/quantem/diffraction/crystal_map.py +++ b/src/quantem/diffraction/crystal_map.py @@ -537,7 +537,9 @@ def plot_dynamical(self, phase=None, strain: bool = False, crop: bool = True, ** if crop and m.any(): rows, cols = np.nonzero(m) sl = (slice(rows.min(), rows.max() + 1), slice(cols.min(), cols.max() + 1)) - kwargs.setdefault("scalebar", self.orientation_maps[0].scan_scalebar) + kwargs["scalebar"] = self.orientation_maps[0]._scalebar_with_calibration( + kwargs.get("scalebar", True) + ) if strain: comps = {k: v.numpy()[sl] for k, v in maps["strain"].items()} return bloch.plot_strain_crystal_frame(comps, mask=m[sl], **kwargs) @@ -750,9 +752,8 @@ def plot_phase(self, **kwargs): positions without moving a real boundary. phase_colors : np.ndarray, optional One RGB color per crystal. - scalebar : dict, "auto" or None, default="auto" - Real-space scale bar; "auto" takes the scan step carried by the - peaks. + scalebar : "auto", bool, dict, ScalebarConfig or None, default="auto" + Real-space scale bar; see :meth:`PhaseMap.plot_phase`. **kwargs Further arguments of :meth:`PhaseMap.plot_phase`. @@ -1220,9 +1221,14 @@ def plot_correlation(self, **kwargs): [f"{n} reliability" for n in self.names], ], ) - sb = self.orientation_maps[0].scan_scalebar - if sb is not None: - kwargs.setdefault("scalebar", [[sb] + [False] * (len(corr) - 1), [False] * len(corr)]) + # one bar, on the first panel; a nested list is taken as given + sb = kwargs.get("scalebar", True) + if not isinstance(sb, (list, tuple)): + sb = self.orientation_maps[0]._scalebar_with_calibration(sb) + if sb is None: + kwargs.pop("scalebar", None) + else: + kwargs["scalebar"] = [[sb] + [False] * (len(corr) - 1), [False] * len(corr)] return show_2d([corr, rel], **kwargs) def _phase_indices(self, phase) -> list[int]: diff --git a/src/quantem/diffraction/orientation.py b/src/quantem/diffraction/orientation.py index ab000c81..8740338f 100644 --- a/src/quantem/diffraction/orientation.py +++ b/src/quantem/diffraction/orientation.py @@ -114,6 +114,70 @@ def scan_scalebar(metadata: dict) -> dict | None: return {"sampling": step, "units": units} +def with_scan_calibration(scalebar, calibration: dict | None): + """Fill a requested scale bar's sampling and units from the scan. + + Parameters + ---------- + scalebar : bool | "auto" | dict | ScalebarConfig | None + The scale bar asked for. True and "auto" mean the scan calibration + as it stands; a dict or ScalebarConfig that does not set its own + sampling and units takes them from `calibration`. None or False + draws no bar. + calibration : dict | None + :func:`scan_scalebar` of the scan, or None when it was never + calibrated. + + Returns + ------- + bool | dict | ScalebarConfig | None + A scale bar any quantem plot accepts, or None for no bar. + + Raises + ------ + ValueError + If `scalebar` is an unknown string. + + Warns + ----- + UserWarning + When a scale bar is asked for on an uncalibrated scan without its own + sampling and units: it is drawn in pixels, and any `display_units` + is dropped. + """ + from dataclasses import replace + + from quantem.core.visualization.visualization_utils import ( + _fill_scalebar_calibration, + _resolve_scalebar, + _scalebar_display_units, + _scalebar_lacks_calibration, + _warn_from_caller, + ) + + if isinstance(scalebar, str): + if scalebar != "auto": + raise ValueError( + f"scalebar must be 'auto', True, a dict or a ScalebarConfig, got {scalebar!r}" + ) + scalebar = True + if calibration is not None: + return _fill_scalebar_calibration(scalebar, calibration["sampling"], calibration["units"]) + if scalebar is True: + return None + if _scalebar_lacks_calibration(scalebar): + display_units = _scalebar_display_units(scalebar) + dropped = f"; display_units={display_units!r} is ignored" if display_units else "" + _warn_from_caller( + f"This scan has no length calibration, so the scale bar is drawn in pixels" + f"{dropped}. Set dataset.sampling and dataset.units before detecting the " + "Bragg disks, or give 'sampling' and 'units' in the scale bar." + ) + if display_units: + scalebar = replace(_resolve_scalebar(scalebar), display_units=None) + return scalebar + + def smooth_quaternions( quats: torch.Tensor, active: torch.Tensor, @@ -2731,6 +2795,15 @@ def scan_scalebar(self) -> dict | None: md = self.metadata.get("peaks", {}) or {} return scan_scalebar(md) + def _scalebar_with_calibration(self, scalebar): + """Fill a requested scale bar's sampling and units from the scan. + + A dict, ScalebarConfig or True that does not set its own sampling + and units takes them from :attr:`scan_scalebar`; see + :func:`with_scan_calibration`. + """ + return with_scan_calibration(scalebar, self.scan_scalebar) + def plot_orientation(self, direction: str = "z", match: int = 0, **kwargs): """IPF-colored orientation map with the color wedge beside it. @@ -2755,7 +2828,7 @@ def plot_orientation(self, direction: str = "z", match: int = 0, **kwargs): """ from quantem.diffraction.orientation_visualization import plot_orientation_map - kwargs.setdefault("scalebar", self.scan_scalebar) + kwargs["scalebar"] = self._scalebar_with_calibration(kwargs.get("scalebar", True)) return plot_orientation_map( self, direction=direction, match=match, **self._default_mask(kwargs) ) @@ -2803,7 +2876,7 @@ def plot_cluster_map(self, clusters: dict, **kwargs): """ from quantem.diffraction.orientation_visualization import plot_cluster_map - kwargs.setdefault("scalebar", self.scan_scalebar) + kwargs["scalebar"] = self._scalebar_with_calibration(kwargs.get("scalebar", True)) return plot_cluster_map(self, clusters, **kwargs) def plot_cluster_pole_figure(self, clusters: dict, pole=(0, 0, 1), **kwargs): diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index 4534f134..66e57adc 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -6,7 +6,10 @@ import torch from quantem.core.utils.rotations import quat_to_matrix -from quantem.core.visualization.visualization_utils import add_scalebar_to_ax +from quantem.core.visualization.visualization_utils import ( + _resolve_scalebar, + add_scalebar_to_ax, +) from quantem.diffraction.crystal import Crystal # one color per candidate phase, used consistently across every plot; index @@ -361,12 +364,46 @@ def wedge_legend( ax.axis("off") +def _draw_map_scalebar(ax, scalebar, shape) -> None: + """Draw a scale bar on a scan map from any form `scalebar` may take. + + Accepts None/False (no bar), True, a dict of :class:`ScalebarConfig` + fields, a ScalebarConfig or a ``ShowParams.Scalebar``. Every field is + honored. With no width_px set, the bar is 1/40 of the map height thick, + since a one-pixel bar is invisible on a scan; any width_px given, + including 1, is used as it is. + """ + cfg = _resolve_scalebar(scalebar) + if cfg is None: + return + width_px = shape[0] / 40 if cfg.width_px is None else cfg.width_px + add_scalebar_to_ax( + ax, + array_size=shape[1], + sampling=cfg.sampling, + length_units=cfg.length, + units=cfg.units, + width_px=width_px, + pad_px=cfg.pad_px, + color=cfg.color, + loc=cfg.loc, + fontsize=cfg.fontsize, + bold=cfg.bold, + box=cfg.box, + box_color=cfg.box_color, + box_alpha=cfg.box_alpha, + outline_color=cfg.outline_color, + outline_width=cfg.outline_width, + display_units=cfg.display_units, + ) + + def plot_orientation_map( om, direction: str = "z", match: int = 0, mask: np.ndarray | None = None, - scalebar: dict | None = None, + scalebar=None, figax=None, legend: bool = True, axsize: tuple[float, float] = (9.0, 4.5), @@ -427,8 +464,9 @@ def plot_orientation_map( Colorfulness relative to the corner colors: 1 keeps them exact, lower washes the map toward white. The legend is drawn with the same values. - scalebar : dict | None - Real-space scale bar, e.g. {"sampling": 30, "units": "A"}. + scalebar : bool | dict | ScalebarConfig | None + Real-space scale bar: True, a ScalebarConfig, or a dict of its + fields, e.g. {"sampling": 30, "units": "A", "loc": "lower left"}. crop : (r0, r1, c0, c1) | None Show only this window of the map (rows r0:r1, columns c0:c1). title : str | None @@ -501,18 +539,7 @@ def plot_orientation_map( ax.set_title(f"{om.crystal.name} in-plane orientation ({direction:g}\u00b0)") else: ax.set_title(f"{om.crystal.name} in-plane orientation") - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) if legend and ax_leg is not None: wedge_legend( om.crystal, @@ -855,7 +882,7 @@ def plot_cluster_map( om, clusters: dict, colors: np.ndarray | None = None, - scalebar: dict | None = None, + scalebar=None, figax=None, ): """Map of orientation clusters (variants), one color per cluster. @@ -870,8 +897,9 @@ def plot_cluster_map( Output of :meth:`OrientationMap.cluster_orientations`. colors : sequence | None One color per cluster, cycled; defaults to `CLUSTER_COLORS`. - scalebar : dict | None - Real-space scale bar, e.g. {"sampling": 30, "units": "A"}. + scalebar : bool | dict | ScalebarConfig | None + Real-space scale bar: True, a ScalebarConfig, or a dict of its + fields, e.g. {"sampling": 30, "units": "A", "loc": "lower left"}. figax : (fig, ax) | None Existing axes to draw into. @@ -910,18 +938,7 @@ def plot_cluster_map( for k in range(K) ] ax.legend(handles=handles, loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8) - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) return fig, ax @@ -1014,6 +1031,28 @@ def _pole_scatter_xy(quats: torch.Tensor, crystal: Crystal, pole) -> np.ndarray: return np.stack((x, y), axis=1) +def _draw_scan_axes_glyph(ax) -> None: + """Scan-axes arrows in the top-left corner of a pole figure. + + Pole figures are drawn in the scan (image) frame of the orientation maps: + c (column) rightward and r (row) downward, so the y axis is inverted. + """ + gx, gy = -1.06, -1.06 + for dx, dy, lbl, ha, va in ( + (0.22, 0.0, "c", "left", "center"), + (0.0, 0.22, "r", "center", "top"), + ): + ax.annotate( + "", + xy=(gx + dx, gy + dy), + xytext=(gx, gy), + arrowprops=dict(arrowstyle="-|>", color="0.3", lw=1.2), + annotation_clip=False, + ) + ax.text(gx + dx * 1.25, gy + dy * 1.25, lbl, fontsize=9, ha=ha, va=va, color="0.3") + ax.text(gx - 0.03, gy - 0.06, "scan axes", fontsize=7, ha="left", va="bottom", color="0.45") + + def plot_cluster_pole_figure( om, clusters: dict, @@ -1025,6 +1064,10 @@ def plot_cluster_pole_figure( ): """Pole figure of the cluster mean orientations, one color per cluster. + Drawn in the scan frame, the same as :func:`plot_pole_figure`: the scan + column axis c to the right and the row axis r downward, so the two + figures can be compared or overlaid directly. + Also available as :meth:`OrientationMap.plot_cluster_pole_figure`. Parameters @@ -1074,9 +1117,10 @@ def plot_cluster_pole_figure( K = clusters["mean_quats"].shape[0] for k in range(K): xy = _pole_scatter_xy(clusters["mean_quats"][k], om.crystal, pole) + # scan frame, as in plot_pole_figure: c (lab y) across, r (lab x) down ax.scatter( - xy[:, 0], xy[:, 1], + xy[:, 0], s=60, marker="h", color=colors[k % len(colors)], @@ -1087,8 +1131,8 @@ def plot_cluster_pole_figure( if overlay is not None: xy = _pole_scatter_xy(overlay["quats"], overlay["crystal"], overlay["pole"]) ax.scatter( - xy[:, 0], xy[:, 1], + xy[:, 0], s=70, marker="D", facecolors="none", @@ -1096,8 +1140,9 @@ def plot_cluster_pole_figure( lw=1.0, label=overlay.get("label", "overlay"), ) + _draw_scan_axes_glyph(ax) ax.set_xlim(-1.15, 1.15) - ax.set_ylim(-1.15, 1.15) + ax.set_ylim(1.2, -1.15) ax.set_aspect("equal") ax.set_xticks([]) ax.set_yticks([]) @@ -1268,38 +1313,7 @@ def plot_pole_figure( for az in range(0, 180, 30): ca, sa = np.cos(np.deg2rad(az)), np.sin(np.deg2rad(az)) ax.plot([-ca, ca], [-sa, sa], color="0.85", lw=0.4) - # compact scan-axes glyph, top-left corner: the pole figure is in - # the scan (image) frame -- c rightward, r downward - gx, gy = -1.06, -1.06 - for dx, dy, lbl, ha, va in ( - (0.22, 0.0, "c", "left", "center"), - (0.0, 0.22, "r", "center", "top"), - ): - ax.annotate( - "", - xy=(gx + dx, gy + dy), - xytext=(gx, gy), - arrowprops=dict(arrowstyle="-|>", color="0.3", lw=1.2), - annotation_clip=False, - ) - ax.text( - gx + dx * 1.25, - gy + dy * 1.25, - lbl, - fontsize=9, - ha=ha, - va=va, - color="0.3", - ) - ax.text( - gx - 0.03, - gy - 0.06, - "scan axes", - fontsize=7, - ha="left", - va="bottom", - color="0.45", - ) + _draw_scan_axes_glyph(ax) if overlay is not None: if "om" in overlay: # raw-histogram contour of another map's pole family diff --git a/src/quantem/diffraction/phase.py b/src/quantem/diffraction/phase.py index 1e33796f..a4974a6b 100644 --- a/src/quantem/diffraction/phase.py +++ b/src/quantem/diffraction/phase.py @@ -512,7 +512,7 @@ def plot_phase( shade_gamma: float = 1.0, majority_filter: int = 0, reliability_range: tuple[float, float] | None = None, - scalebar: dict | str | None = "auto", + scalebar="auto", figax=None, ): """Dominant-phase map: color gives the crystal, brightness the evidence. @@ -553,11 +553,13 @@ def plot_phase( reliability_range : tuple | None Backwards-compatible shortcut: setting it selects ``shade_by="reliability"`` with this range. - scalebar : dict | "auto" | None - Real-space scale bar. "auto" (the default) takes the scan step - and units carried from the dataset by the orientation maps; a - dict such as {"sampling": 30, "units": "A"} overrides it, and - None draws no bar. + scalebar : "auto" | bool | dict | ScalebarConfig | None + Real-space scale bar. "auto" (the default) or True takes the + scan step and units carried from the dataset by the orientation + maps. A dict of ScalebarConfig fields or a ScalebarConfig + changes any of them, e.g. {"display_units": "nm", "loc": "lower + left"}, and keeps the scan calibration unless it sets its own + sampling and units. None or False draws no bar. figax : (fig, ax) | None Existing axes to draw into. @@ -571,12 +573,15 @@ def plot_phase( ValueError If `shade_by` is unknown or `shade_gamma` is not positive. """ - if isinstance(scalebar, str): - scalebar = self.orientation_maps[0].scan_scalebar if scalebar == "auto" else None import matplotlib.pyplot as plt - from quantem.core.visualization.visualization_utils import add_scalebar_to_ax - from quantem.diffraction.orientation_visualization import phase_color_cycle + from quantem.diffraction.orientation import with_scan_calibration + from quantem.diffraction.orientation_visualization import ( + _draw_map_scalebar, + phase_color_cycle, + ) + + scalebar = with_scan_calibration(scalebar, self.orientation_maps[0].scan_scalebar) assert self.phase_index is not None and self.reliability is not None phase_colors = phase_color_cycle(len(self.names), phase_colors) @@ -627,18 +632,7 @@ def plot_phase( ax.imshow(rgb, interpolation="nearest") ax.set_xticks([]) ax.set_yticks([]) - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) handles = [ plt.Line2D([0], [0], marker="s", ls="", color=c, label=n) for c, n in zip(phase_colors, self.names) diff --git a/src/quantem/diffraction/strain_visualization.py b/src/quantem/diffraction/strain_visualization.py index e141232d..fa1acb64 100644 --- a/src/quantem/diffraction/strain_visualization.py +++ b/src/quantem/diffraction/strain_visualization.py @@ -273,7 +273,7 @@ def _roi_compose(norm_vals, color_cm): "units": ds_units, "length": None, "width_px": 1, - "pad_px": 0.5, + "pad_px": None, "color": "white" if box and box_color == "black" else "black", "loc": "lower left", "fontsize": 12,