diff --git a/src/quantem/core/visualization/__init__.py b/src/quantem/core/visualization/__init__.py index 125fb02e..f7264bab 100644 --- a/src/quantem/core/visualization/__init__.py +++ b/src/quantem/core/visualization/__init__.py @@ -7,6 +7,7 @@ from quantem.core.visualization.visualization_utils import ( ScalebarConfig as ScalebarConfig, turbo_black as turbo_black, + color_wheel as color_wheel, axes_with_inset as axes_with_inset, ) from quantem.core.visualization.line_scan import linescan as linescan diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 21637605..1a6f08e3 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -690,6 +690,100 @@ def turbo_black(num_colors: int = 256, fade_len: int | None = None) -> colors.Li pass +def color_wheel( + n: int = 256, + saturation: float = 1.0, + repeat: int = 1, + color_list: list | None = None, + gamma: float = 1.0, + mode: str | None = None, +) -> np.ndarray: + """Color wheel legend: angle sets the hue and radius sets the brightness. + + Used to label images colored by direction, such as composite dark field + images or differential phase contrast. + + The default perceptual wheel uses the angle coloring of array_to_rgba, + as do show_2d for complex arrays, add_arg_cbar_to_ax, the ACOM angle maps + and composite_ddf: hue at constant CIECAM02 lightness, so the rim keeps + one lightness all the way round. The HSV wheel (mode="hsv") is the + alternative; its rim runs from dark blue to bright yellow. + + Parameters + ---------- + n : int, default=256 + Size of the output image in pixels. + saturation : float, default=1.0 + Saturation of the hues, from 0 (gray) to 1 (full color). In the + perceptual mode it is the chroma_boost of array_to_rgba. + repeat : int, default=1 + Number of times the hues (or `color_list`) go round the wheel. + color_list : list, optional + Two or more colors placed evenly around the wheel, as matplotlib + color names, hex strings or RGB tuples. The tuples are all read as + 0-1, or all as 0-255 when any of them has a value above 1. The last + color is joined back to the first, so the wheel has no seam; a list + that already ends with its first color is used as is. Leave `mode` + as None with a list. + gamma : float, default=1.0 + Brightness at radius r (0 at the center, 1 at the edge) is r**gamma. + Use the gamma of the image the wheel labels, such as the gamma of + composite_ddf, so the legend matches it. + mode : {"perceptual", "hsv"}, optional + "perceptual" uses array_to_rgba, so the wheel is an exact legend for + show_2d of a complex image, where the angle is np.angle of the value, + and for composite_ddf. "hsv" uses HSV hues, matching + composite_ddf(mode="hsv"). None (default) is "perceptual", or the + colors of `color_list` when one is given. + + Returns + ------- + np.ndarray + (n, n, 4) RGBA image in [0, 1], transparent outside the wheel. + """ + if color_list is not None and mode is not None: + raise ValueError(f"color_list sets its own colors; it cannot be used with mode={mode!r}") + if color_list is not None and len(color_list) < 2: + raise ValueError(f"color_list needs at least two colors, got {len(color_list)}") + if mode is None: + mode = "perceptual" if color_list is None else "list" + elif mode not in ("perceptual", "hsv"): + raise ValueError(f"mode must be 'perceptual' or 'hsv', got {mode!r}") + + y, x = np.mgrid[-1 : 1 : n * 1j, -1 : 1 : n * 1j] + r = np.hypot(x, y) + angle = np.arctan2(y, x) + hue = (angle * repeat / (2 * np.pi)) % 1.0 + value = np.clip(r, 0, 1) ** gamma + alpha = (r <= 1.0).astype(float)[..., None] + + if mode == "perceptual": + wrapped = np.angle(np.exp(1j * repeat * angle)) + rgb = array_to_rgba(value, wrapped, chroma_boost=saturation)[..., :3] + elif mode == "hsv": + hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) + rgb = colors.hsv_to_rgb(hsv) + else: + # one scale for every tuple, so (1, 1, 1) among 0-255 colors is near black + tuples = [np.asarray(c, dtype=float)[:3] for c in color_list if not isinstance(c, str)] + scale = 255.0 if any(c.max() > 1 for c in tuples) else 1.0 + cols = [ + colors.to_rgb(c) + if isinstance(c, str) + else tuple(np.asarray(c, dtype=float)[:3] / scale) + for c in color_list + ] + if not np.allclose(cols[0], cols[-1]): + cols.append(cols[0]) + cmap = colors.LinearSegmentedColormap.from_list("wheel", cols, N=256) + rgb = cmap(hue)[..., :3] + gray = rgb.mean(axis=-1, keepdims=True) + rgb = gray + saturation * (rgb - gray) + rgb = rgb * value[..., None] + + return np.concatenate([rgb, alpha], axis=-1) + + def bilinear_histogram_2d( shape: tuple[int, int], x: NDArray, diff --git a/src/quantem/diffraction/digital_dark_field.py b/src/quantem/diffraction/digital_dark_field.py index 3297056e..a343826b 100644 --- a/src/quantem/diffraction/digital_dark_field.py +++ b/src/quantem/diffraction/digital_dark_field.py @@ -57,6 +57,10 @@ from matplotlib.colors import hsv_to_rgb from quantem.core.utils.clustering import cluster_vector, dbscan # noqa: F401 +from quantem.core.visualization.visualization_utils import ( # noqa: F401 + array_to_rgba, + color_wheel, +) def _scan_cells(vector) -> np.ndarray: @@ -890,61 +894,63 @@ def composite_ddf( colors=None, gamma: float = 0.33, normalize: str = "each", + mode: str | None = None, ) -> np.ndarray: """Blend a stack of DDF images into one RGB composite. + Image k gets the hue at angle 2 pi k / K of color_wheel, and its scaled + intensity sets the brightness as the radius does on the wheel, so + color_wheel(gamma=gamma, mode=mode) is the legend of the composite. + Parameters ---------- images : np.ndarray (K, R, C) cluster images. colors : array-like | None - (K, 3) RGB color per image; defaults to evenly spaced hues. + (K, 3) RGB color per image, scaled by the image intensity. None uses + evenly spaced hues of `mode`. gamma : float, default=0.33 Power scaling applied to each normalized image before coloring. normalize : {"each", "global"} Normalize each image to its own maximum, or all to the stack max. + mode : {"perceptual", "hsv"}, optional + "perceptual" colors each image with array_to_rgba (CIECAM02 hue at + constant lightness), like show_2d for complex arrays. "hsv" uses HSV + hues. None (default) is "perceptual", or `colors` when given. Returns ------- np.ndarray (R, C, 3) RGB image in [0, 1]. """ - K = images.shape[0] - if colors is None: - hues = np.linspace(0, 1, K, endpoint=False) - colors = hsv_to_rgb(np.stack([hues, np.ones(K), np.ones(K)], axis=1)) - colors = np.asarray(colors, dtype=float) + if colors is not None and mode is not None: + raise ValueError(f"colors sets its own colors; it cannot be used with mode={mode!r}") + if mode is None: + mode = "perceptual" if colors is None else "colors" + elif mode not in ("perceptual", "hsv"): + raise ValueError(f"mode must be 'perceptual' or 'hsv', got {mode!r}") + K = images.shape[0] if normalize == "global": norm = np.full(K, max(float(images.max()), 1e-12)) else: norm = np.maximum(images.reshape(K, -1).max(axis=1), 1e-12) scaled = (images / norm[:, None, None]) ** gamma - rgb = np.einsum("krc,kj->rcj", scaled, colors) - return np.clip(rgb, 0, 1) - - -def color_wheel(n: int = 256, saturation: float = 1.0) -> np.ndarray: - """Hue wheel for labeling composite images. - - Parameters - ---------- - n : int, default=256 - Size of the output image in pixels. - saturation : float, default=1.0 - Saturation of the hues, from 0 (gray) to 1 (full color). - Returns - ------- - np.ndarray - (n, n, 4) RGBA image in [0, 1], transparent outside the wheel. - """ - y, x = np.mgrid[-1 : 1 : n * 1j, -1 : 1 : n * 1j] - r = np.hypot(x, y) - hue = (np.arctan2(y, x) / (2 * np.pi)) % 1.0 - hsv = np.stack([hue, np.full_like(hue, saturation), np.clip(r, 0, 1)], axis=-1) - rgba = np.concatenate([hsv_to_rgb(hsv), (r <= 1.0)[..., None].astype(float)], axis=-1) - return rgba + if mode == "perceptual": + # the same angles as the hues of the HSV mode, wrapped to (-pi, pi] + angles = np.angle(np.exp(2j * np.pi * np.arange(K) / K)) + rgb = sum( + array_to_rgba(scaled[k], np.full(scaled[k].shape, angles[k]))[..., :3] + for k in range(K) + ) + else: + if mode == "hsv": + hues = np.linspace(0, 1, K, endpoint=False) + colors = hsv_to_rgb(np.stack([hues, np.ones(K), np.ones(K)], axis=1)) + colors = np.asarray(colors, dtype=float) + rgb = np.einsum("krc,kj->rcj", scaled, colors) + return np.clip(rgb, 0, 1) def plot_cluster_scatter( diff --git a/tests/diffraction/test_digital_dark_field.py b/tests/diffraction/test_digital_dark_field.py index b569f82b..b39b6cb4 100644 --- a/tests/diffraction/test_digital_dark_field.py +++ b/tests/diffraction/test_digital_dark_field.py @@ -238,3 +238,15 @@ def test_plot_cluster_scatter_center(): assert np.isclose(np.mean(ax.get_xlim()), 0.0) assert np.isclose(np.mean(ax.get_ylim()), 0.0) plt.close(fig) + + +def test_composite_matches_color_wheel(): + # image 1 of 4 sits at angle pi / 2, straight down the wheel; full intensity + # is the rim (row 64) and an intensity of 0.5 after gamma is radius 0.5 (row 48) + images = np.zeros((4, 1, 2)) + images[1, 0] = [1.0, 0.5**3] + for mode in ("perceptual", "hsv"): + comp = ddf.composite_ddf(images, gamma=1 / 3, mode=mode) + wheel = ddf.color_wheel(65, mode=mode) + np.testing.assert_allclose(comp[0, 0], wheel[64, 32, :3], atol=1e-12, err_msg=mode) + np.testing.assert_allclose(comp[0, 1], wheel[48, 32, :3], atol=1e-12, err_msg=mode) diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index b7c3356e..7c2bdb09 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -15,6 +15,7 @@ add_scalebar_to_ax, array_to_rgba, bilinear_histogram_2d, + color_wheel, combine_arrays_to_rgba, estimate_scalebar_length, turbo_black, @@ -145,6 +146,39 @@ def test_turbo_black(self): assert np.allclose(colors[fade - 1], turbo[fade - 1]), (num_colors, fade_len) +class TestColorWheel: + def test_color_list_wheel_has_no_seam(self): + wheel = color_wheel(65, color_list=["red", "lime", (0, 0, 255)]) + # just above and below the +x axis, where the list wraps from last to first + np.testing.assert_allclose(wheel[31, 63, :3], wheel[33, 63, :3], atol=0.1) + np.testing.assert_allclose(wheel[32, 64], [1, 0, 0, 1]) + assert wheel[0, 0, 3] == 0, "corner should be outside the wheel" + # (1, 1, 1) among 0-255 colors is near black, not white + wheel = color_wheel(65, color_list=[(1, 1, 1), (255, 0, 0), (0, 0, 255)]) + np.testing.assert_allclose(wheel[32, 64, :3], 1 / 255) + for too_few in ([], ["red"]): + with pytest.raises(ValueError, match="at least two"): + color_wheel(color_list=too_few) + # pixel (32, 48) is at radius 0.5 on the red axis + wheel = color_wheel(65, color_list=["red", "lime", "blue"], gamma=0.5) + np.testing.assert_allclose(wheel[32, 48, 0], 0.5**0.5) + + def test_perceptual_wheel_has_constant_lightness(self): + from colorspacious import cspace_convert + + n = 129 + y, x = np.mgrid[-1 : 1 : n * 1j, -1 : 1 : n * 1j] + rim = np.abs(np.hypot(x, y) - 0.95) < 0.02 + spread = {} + for mode in ("hsv", "perceptual"): + J = cspace_convert(color_wheel(n, mode=mode)[rim, :3], "sRGB1", "JCh")[:, 0] + spread[mode] = J.max() - J.min() + assert spread["perceptual"] < 3, spread + assert spread["hsv"] > 30, spread + with pytest.raises(ValueError): + color_wheel(mode="perceptual", color_list=["red", "blue"]) + + class TestBilinearHistogram2D: def test_bins_weights(self): x = np.array([0.5, 0.5, 2.5])