From b406a4b584236a59a1d7ea9c6a76fb03408bbc2f Mon Sep 17 00:00:00 2001 From: maclariz Date: Tue, 17 Nov 2026 11:39:14 +0000 Subject: [PATCH 1/7] Move color_wheel to core visualization_utils and extend it color_wheel is useful beyond digital dark field, for example to label DPC or phase gradient directions, so it now lives in quantem.core.visualization.visualization_utils; digital_dark_field re-exports it, so existing imports keep working. It can also take a list of colors to place evenly around the wheel, joined back to the first color so the wheel has no seam, a repeat count for the hues, and a gamma for how the brightness grows with radius. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 63 +++++++++++++++++++ src/quantem/diffraction/digital_dark_field.py | 24 +------ .../visualization/test_visualization_utils.py | 14 +++++ 3 files changed, 78 insertions(+), 23 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 21637605..7c3ad7c7 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -690,6 +690,69 @@ 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, + colorslist: list | None = None, + gamma: float = 1.0, +) -> 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. + + 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). + repeat : int, default=1 + Number of times the hues (or `colorslist`) go round the wheel. + colorslist : list, optional + Colors placed evenly around the wheel, as matplotlib color names, hex + strings or RGB tuples (0-1 or 0-255). 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. None uses the HSV hues. + 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. + + 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) * repeat / (2 * np.pi)) % 1.0 + value = np.clip(r, 0, 1) ** gamma + alpha = (r <= 1.0).astype(float)[..., None] + + if colorslist is None: + hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) + rgb = colors.hsv_to_rgb(hsv) + else: + cols = [] + for c in colorslist: + if isinstance(c, str): + cols.append(colors.to_rgb(c)) + else: + c = np.asarray(c, dtype=float)[:3] + cols.append(tuple(c / 255.0 if c.max() > 1 else c)) + 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..381ebd35 100644 --- a/src/quantem/diffraction/digital_dark_field.py +++ b/src/quantem/diffraction/digital_dark_field.py @@ -57,6 +57,7 @@ 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 color_wheel # noqa: F401 def _scan_cells(vector) -> np.ndarray: @@ -924,29 +925,6 @@ def composite_ddf( 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 - - def plot_cluster_scatter( labeled, q_fields=None, diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index b7c3356e..80dc7658 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,19 @@ 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, repeat=1, colorslist=["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" + # pixel (32, 48) is at radius 0.5 on the red axis + for gamma in (1.0, 0.5): + wheel = color_wheel(65, colorslist=["red", "lime", "blue"], gamma=gamma) + np.testing.assert_allclose(wheel[32, 48, 0], 0.5**gamma, err_msg=f"gamma={gamma}") + + class TestBilinearHistogram2D: def test_bins_weights(self): x = np.array([0.5, 0.5, 2.5]) From 2621ed09131f503f562d04ceb8c5c84882a029ef Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:30:37 +0000 Subject: [PATCH 2/7] Add a perceptual mode to color_wheel mode="perceptual" colors the wheel with array_to_rgba, the CIECAM02 JCh coloring that show_2d uses for complex arrays, add_arg_cbar_to_ax and the ACOM angle maps, so the wheel is an exact legend for those images. Its rim keeps a lightness J of about 58 all the way round, where the HSV rim runs from 19 (blue) to 91 (yellow). saturation sets chroma_boost, and repeat and gamma work as in the HSV mode. HSV stays the default, so composite_ddf still matches its legend. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 31 ++++++++++++++++--- .../visualization/test_visualization_utils.py | 15 +++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 7c3ad7c7..8e174eea 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -696,42 +696,65 @@ def color_wheel( repeat: int = 1, colorslist: list | None = None, gamma: float = 1.0, + mode: str = "hsv", ) -> 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 HSV wheel matches composite_ddf. The perceptual wheel matches + the angle coloring of array_to_rgba, used by show_2d for complex arrays, + add_arg_cbar_to_ax and the ACOM angle maps: hue at constant CIECAM02 + lightness, so the rim keeps one lightness all the way round, whereas the + HSV 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). + 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 `colorslist`) go round the wheel. colorslist : list, optional Colors placed evenly around the wheel, as matplotlib color names, hex strings or RGB tuples (0-1 or 0-255). 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. None uses the HSV hues. + first color is used as is. None uses the hues of `mode`. 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 : {"hsv", "perceptual"}, default="hsv" + "hsv" uses HSV hues. "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. Cannot be combined with `colorslist`. Returns ------- np.ndarray (n, n, 4) RGBA image in [0, 1], transparent outside the wheel. """ + if mode not in ("hsv", "perceptual"): + raise ValueError(f"mode must be 'hsv' or 'perceptual', got {mode!r}") + if mode == "perceptual" and colorslist is not None: + raise ValueError( + "colorslist sets its own colors; it cannot be used with mode='perceptual'" + ) + y, x = np.mgrid[-1 : 1 : n * 1j, -1 : 1 : n * 1j] r = np.hypot(x, y) - hue = (np.arctan2(y, x) * repeat / (2 * np.pi)) % 1.0 + 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 colorslist is None: + if mode == "perceptual": + wrapped = np.angle(np.exp(1j * repeat * angle)) + rgb = array_to_rgba(value, wrapped, chroma_boost=saturation)[..., :3] + elif colorslist is None: hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) rgb = colors.hsv_to_rgb(hsv) else: diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index 80dc7658..98fd542a 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -158,6 +158,21 @@ def test_color_list_wheel_has_no_seam(self): wheel = color_wheel(65, colorslist=["red", "lime", "blue"], gamma=gamma) np.testing.assert_allclose(wheel[32, 48, 0], 0.5**gamma, err_msg=f"gamma={gamma}") + 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", colorslist=["red", "blue"]) + class TestBilinearHistogram2D: def test_bins_weights(self): From d0f29065174316d28830218ccb38cd89f83840d7 Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:33:44 +0000 Subject: [PATCH 3/7] Rename color_wheel's colorslist argument to color_list Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 16 ++++++++-------- tests/visualization/test_visualization_utils.py | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 8e174eea..dcf60d72 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -694,7 +694,7 @@ def color_wheel( n: int = 256, saturation: float = 1.0, repeat: int = 1, - colorslist: list | None = None, + color_list: list | None = None, gamma: float = 1.0, mode: str = "hsv", ) -> np.ndarray: @@ -717,8 +717,8 @@ def color_wheel( 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 `colorslist`) go round the wheel. - colorslist : list, optional + Number of times the hues (or `color_list`) go round the wheel. + color_list : list, optional Colors placed evenly around the wheel, as matplotlib color names, hex strings or RGB tuples (0-1 or 0-255). The last color is joined back to the first, so the wheel has no seam; a list that already ends with its @@ -730,7 +730,7 @@ def color_wheel( mode : {"hsv", "perceptual"}, default="hsv" "hsv" uses HSV hues. "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. Cannot be combined with `colorslist`. + np.angle of the value. Cannot be combined with `color_list`. Returns ------- @@ -739,9 +739,9 @@ def color_wheel( """ if mode not in ("hsv", "perceptual"): raise ValueError(f"mode must be 'hsv' or 'perceptual', got {mode!r}") - if mode == "perceptual" and colorslist is not None: + if mode == "perceptual" and color_list is not None: raise ValueError( - "colorslist sets its own colors; it cannot be used with mode='perceptual'" + "color_list sets its own colors; it cannot be used with mode='perceptual'" ) y, x = np.mgrid[-1 : 1 : n * 1j, -1 : 1 : n * 1j] @@ -754,12 +754,12 @@ def color_wheel( if mode == "perceptual": wrapped = np.angle(np.exp(1j * repeat * angle)) rgb = array_to_rgba(value, wrapped, chroma_boost=saturation)[..., :3] - elif colorslist is None: + elif color_list is None: hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) rgb = colors.hsv_to_rgb(hsv) else: cols = [] - for c in colorslist: + for c in color_list: if isinstance(c, str): cols.append(colors.to_rgb(c)) else: diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index 98fd542a..b9fc053c 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -148,14 +148,14 @@ def test_turbo_black(self): class TestColorWheel: def test_color_list_wheel_has_no_seam(self): - wheel = color_wheel(65, repeat=1, colorslist=["red", "lime", (0, 0, 255)]) + wheel = color_wheel(65, repeat=1, 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" # pixel (32, 48) is at radius 0.5 on the red axis for gamma in (1.0, 0.5): - wheel = color_wheel(65, colorslist=["red", "lime", "blue"], gamma=gamma) + wheel = color_wheel(65, color_list=["red", "lime", "blue"], gamma=gamma) np.testing.assert_allclose(wheel[32, 48, 0], 0.5**gamma, err_msg=f"gamma={gamma}") def test_perceptual_wheel_has_constant_lightness(self): @@ -171,7 +171,7 @@ def test_perceptual_wheel_has_constant_lightness(self): assert spread["perceptual"] < 3, spread assert spread["hsv"] > 30, spread with pytest.raises(ValueError): - color_wheel(mode="perceptual", colorslist=["red", "blue"]) + color_wheel(mode="perceptual", color_list=["red", "blue"]) class TestBilinearHistogram2D: From 519843bd525e2f8ec57f16a02ee743856ac09890 Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:35:31 +0000 Subject: [PATCH 4/7] Read all color_wheel RGB tuples on one scale The 0-255 check ran per color, so (1, 1, 1) in a list of 0-255 colors was read as white rather than near black. The scale is now decided once for the whole list: if any tuple has a value above 1, all of them are read as 0-255. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 23 +++++++++++-------- .../visualization/test_visualization_utils.py | 3 +++ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index dcf60d72..3f501c0e 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -720,9 +720,10 @@ def color_wheel( Number of times the hues (or `color_list`) go round the wheel. color_list : list, optional Colors placed evenly around the wheel, as matplotlib color names, hex - strings or RGB tuples (0-1 or 0-255). 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. None uses the hues of `mode`. + 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. None uses the hues of `mode`. 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 @@ -758,13 +759,15 @@ def color_wheel( hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) rgb = colors.hsv_to_rgb(hsv) else: - cols = [] - for c in color_list: - if isinstance(c, str): - cols.append(colors.to_rgb(c)) - else: - c = np.asarray(c, dtype=float)[:3] - cols.append(tuple(c / 255.0 if c.max() > 1 else c)) + # 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) diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index b9fc053c..81e81049 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -153,6 +153,9 @@ def test_color_list_wheel_has_no_seam(self): 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) # pixel (32, 48) is at radius 0.5 on the red axis for gamma in (1.0, 0.5): wheel = color_wheel(65, color_list=["red", "lime", "blue"], gamma=gamma) From 667958ba815d7e7095e5049207d177d9d29bef20 Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:41:57 +0000 Subject: [PATCH 5/7] Make perceptual coloring the default for color_wheel and composite_ddf color_wheel and composite_ddf now color with array_to_rgba (CIECAM02 hue at constant lightness) by default, as show_2d does for complex arrays, add_arg_cbar_to_ax and the ACOM angle maps. mode="hsv" gives the HSV hues instead. Both take mode=None by default, which means perceptual unless the caller passes its own colors (color_list, or colors for composite_ddf); giving both a mode and colors is an error. In both modes composite_ddf colors image k with the wheel's hue at angle 2 pi k / K and its scaled intensity as the radius, so color_wheel(gamma=gamma, mode=mode) is an exact legend of the composite. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 38 ++++++++-------- src/quantem/diffraction/digital_dark_field.py | 44 +++++++++++++++---- tests/diffraction/test_digital_dark_field.py | 12 +++++ 3 files changed, 68 insertions(+), 26 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 3f501c0e..57f35357 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -696,18 +696,18 @@ def color_wheel( repeat: int = 1, color_list: list | None = None, gamma: float = 1.0, - mode: str = "hsv", + 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 HSV wheel matches composite_ddf. The perceptual wheel matches - the angle coloring of array_to_rgba, used by show_2d for complex arrays, - add_arg_cbar_to_ax and the ACOM angle maps: hue at constant CIECAM02 - lightness, so the rim keeps one lightness all the way round, whereas the - HSV rim runs from dark blue to bright yellow. + 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 ---------- @@ -723,27 +723,29 @@ def color_wheel( 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. None uses the hues of `mode`. + 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 : {"hsv", "perceptual"}, default="hsv" - "hsv" uses HSV hues. "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. Cannot be combined with `color_list`. + 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 mode not in ("hsv", "perceptual"): - raise ValueError(f"mode must be 'hsv' or 'perceptual', got {mode!r}") - if mode == "perceptual" and color_list is not None: - raise ValueError( - "color_list sets its own colors; it cannot be used with mode='perceptual'" - ) + 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 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) @@ -755,7 +757,7 @@ def color_wheel( if mode == "perceptual": wrapped = np.angle(np.exp(1j * repeat * angle)) rgb = array_to_rgba(value, wrapped, chroma_boost=saturation)[..., :3] - elif color_list is None: + elif mode == "hsv": hsv = np.stack([hue, np.full_like(hue, saturation), value], axis=-1) rgb = colors.hsv_to_rgb(hsv) else: diff --git a/src/quantem/diffraction/digital_dark_field.py b/src/quantem/diffraction/digital_dark_field.py index 381ebd35..a343826b 100644 --- a/src/quantem/diffraction/digital_dark_field.py +++ b/src/quantem/diffraction/digital_dark_field.py @@ -57,7 +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 color_wheel # noqa: F401 +from quantem.core.visualization.visualization_utils import ( # noqa: F401 + array_to_rgba, + color_wheel, +) def _scan_cells(vector) -> np.ndarray: @@ -891,37 +894,62 @@ 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) + + 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) 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) From 1163617e56f91bf1a4c38c3b364ac60f314420ae Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:45:00 +0000 Subject: [PATCH 6/7] Reject a color_wheel color_list with fewer than two colors An empty list failed with an IndexError and a single color with a matplotlib ValueError; both now raise a ValueError that says the list needs at least two colors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- .../core/visualization/visualization_utils.py | 13 ++++++++----- tests/visualization/test_visualization_utils.py | 3 +++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 57f35357..1a6f08e3 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -719,11 +719,12 @@ def color_wheel( repeat : int, default=1 Number of times the hues (or `color_list`) go round the wheel. color_list : list, optional - 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. + 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 @@ -742,6 +743,8 @@ def color_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"): diff --git a/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index 81e81049..d95a3e08 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -156,6 +156,9 @@ def test_color_list_wheel_has_no_seam(self): # (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 for gamma in (1.0, 0.5): wheel = color_wheel(65, color_list=["red", "lime", "blue"], gamma=gamma) From 97cea6ba02caf6a7961e189c2cf90a693a48825a Mon Sep 17 00:00:00 2001 From: maclariz Date: Sun, 6 Dec 2026 17:46:04 +0000 Subject: [PATCH 7/7] Export color_wheel from quantem.core.visualization Also drop test arguments that repeated the defaults (repeat=1 and the gamma=1.0 case). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfi2sFksBeLfpxq732 --- src/quantem/core/visualization/__init__.py | 1 + tests/visualization/test_visualization_utils.py | 7 +++---- 2 files changed, 4 insertions(+), 4 deletions(-) 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/tests/visualization/test_visualization_utils.py b/tests/visualization/test_visualization_utils.py index d95a3e08..7c2bdb09 100644 --- a/tests/visualization/test_visualization_utils.py +++ b/tests/visualization/test_visualization_utils.py @@ -148,7 +148,7 @@ def test_turbo_black(self): class TestColorWheel: def test_color_list_wheel_has_no_seam(self): - wheel = color_wheel(65, repeat=1, color_list=["red", "lime", (0, 0, 255)]) + 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]) @@ -160,9 +160,8 @@ def test_color_list_wheel_has_no_seam(self): 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 - for gamma in (1.0, 0.5): - wheel = color_wheel(65, color_list=["red", "lime", "blue"], gamma=gamma) - np.testing.assert_allclose(wheel[32, 48, 0], 0.5**gamma, err_msg=f"gamma={gamma}") + 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