-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfigure_plots.py
More file actions
3431 lines (2978 loc) · 133 KB
/
figure_plots.py
File metadata and controls
3431 lines (2978 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
figure_plots.py
===============
Pure-Python plot objects returned by Axes.imshow() / Axes.plot().
These are NOT anywidget subclasses. They hold all state in plain dicts and
push changes into the parent Figure's per-panel traitlet via _push().
Public classes
--------------
GridSpec – describes a grid layout (nrows x ncols, ratios).
SubplotSpec – a slice of a GridSpec (row/col spans).
Axes – a grid cell; .imshow() / .plot() return a plot object.
Plot2D – 2-D image panel, full Viewer2D-compatible API.
Plot1D – 1-D line panel, full Viewer1D-compatible API.
"""
from __future__ import annotations
import uuid as _uuid
import numpy as np
from typing import Callable
from anyplotlib.markers import MarkerRegistry
from anyplotlib.callbacks import CallbackRegistry
from anyplotlib.widgets import (
Widget,
RectangleWidget, CircleWidget, AnnularWidget,
CrosshairWidget, PolygonWidget, LabelWidget,
VLineWidget as _VLineWidget,
HLineWidget as _HLineWidget,
RangeWidget as _RangeWidget,
PointWidget as _PointWidget,
)
__all__ = ["GridSpec", "SubplotSpec", "Axes", "Line1D", "Plot1D", "Plot2D", "PlotMesh",
"Plot3D", "PlotBar", "_resample_mesh", "_norm_linestyle"]
# ---------------------------------------------------------------------------
# Linestyle normalisation
# ---------------------------------------------------------------------------
_LINESTYLE_ALIASES: dict[str, str] = {
"-": "solid",
"--": "dashed",
":": "dotted",
"-.": "dashdot",
"solid": "solid",
"dashed": "dashed",
"dotted": "dotted",
"dashdot": "dashdot",
}
def _arr_to_b64(arr: np.ndarray, dtype) -> str:
"""Encode a NumPy array as base-64 (little-endian raw bytes).
Uses little-endian byte order so the result is compatible with
JavaScript's ``Float64Array`` / ``Float32Array`` / ``Int32Array``
on all modern platforms (x86, ARM).
"""
import base64
le_dtype = np.dtype(dtype).newbyteorder("<")
return base64.b64encode(np.asarray(arr).astype(le_dtype).tobytes()).decode("ascii")
def _norm_linestyle(ls: str) -> str:
"""Normalise a linestyle name or shorthand to its canonical form.
Accepted values
---------------
``"solid"`` / ``"-"``, ``"dashed"`` / ``"--"``,
``"dotted"`` / ``":"``, ``"dashdot"`` / ``"-."``.
Raises
------
ValueError
If *ls* is not a recognised name or shorthand.
"""
canonical = _LINESTYLE_ALIASES.get(ls)
if canonical is None:
raise ValueError(
f"Unknown linestyle {ls!r}. Expected one of: "
"'solid', 'dashed', 'dotted', 'dashdot', "
"or shorthands '-', '--', ':', '-.'."
)
return canonical
# ---------------------------------------------------------------------------
# GridSpec / SubplotSpec
# ---------------------------------------------------------------------------
class SubplotSpec:
"""Describes which grid cells a subplot occupies."""
def __init__(self, gs: "GridSpec", row_start: int, row_stop: int,
col_start: int, col_stop: int):
self._gs = gs
self.row_start = row_start
self.row_stop = row_stop
self.col_start = col_start
self.col_stop = col_stop
def __repr__(self) -> str:
return (f"SubplotSpec(rows={self.row_start}:{self.row_stop}, "
f"cols={self.col_start}:{self.col_stop})")
class GridSpec:
"""Define a grid of subplot cells.
Parameters
----------
nrows, ncols : int
Grid dimensions.
width_ratios : list of float, optional
Relative column widths (length ncols). Defaults to equal widths.
height_ratios : list of float, optional
Relative row heights (length nrows). Defaults to equal heights.
Examples
--------
>>> gs = GridSpec(2, 3, width_ratios=[2, 1, 1])
>>> spec = gs[0, :] # top row spanning all columns
>>> spec = gs[1, 1:3] # bottom-right 2 columns
"""
def __init__(self, nrows: int, ncols: int, *,
width_ratios: list | None = None,
height_ratios: list | None = None):
self.nrows = nrows
self.ncols = ncols
self.width_ratios = list(width_ratios) if width_ratios else [1] * ncols
self.height_ratios = list(height_ratios) if height_ratios else [1] * nrows
if len(self.width_ratios) != ncols:
raise ValueError("len(width_ratios) must equal ncols")
if len(self.height_ratios) != nrows:
raise ValueError("len(height_ratios) must equal nrows")
def __getitem__(self, key) -> SubplotSpec:
"""Return a SubplotSpec for the given (row, col) index or slice pair.
Matches matplotlib's GridSpec indexing exactly:
- Integer index ``i`` selects a single row or column (negative indices
count from the end, just like Python lists).
- Slice ``start:stop`` selects rows/columns ``start`` up to (but not
including) ``stop``. The full-span slice ``:`` selects all rows or
columns.
- Step values other than 1 (or None) raise ``ValueError``.
- Out-of-range or empty slices raise ``IndexError``.
"""
if not isinstance(key, tuple) or len(key) != 2:
raise IndexError("GridSpec requires a (row, col) index or slice pair")
row_idx, col_idx = key
def _resolve(idx, n, axis_name):
if isinstance(idx, int):
i = idx if idx >= 0 else n + idx
if not (0 <= i < n):
raise IndexError(
f"{axis_name} index {idx} is out of bounds for size {n}"
)
return i, i + 1
if isinstance(idx, slice):
start, stop, step = idx.indices(n)
if step != 1:
raise ValueError(
f"GridSpec slices must have step 1 (got {step})"
)
if start >= stop:
raise IndexError(
f"GridSpec slice {idx} produces an empty span on axis of size {n}"
)
return start, stop
raise IndexError(f"Invalid GridSpec index: {idx!r}")
r0, r1 = _resolve(row_idx, self.nrows, "row")
c0, c1 = _resolve(col_idx, self.ncols, "col")
return SubplotSpec(self, r0, r1, c0, c1)
def __repr__(self) -> str:
return f"GridSpec({self.nrows}, {self.ncols})"
# ---------------------------------------------------------------------------
# Axes — grid cell container
# ---------------------------------------------------------------------------
class Axes:
"""A single grid cell in a Figure.
Returned by Figure.add_subplot() and Figure.subplots().
Call .imshow() or .plot() to attach a data plot and get back
a Plot2D or Plot1D object.
"""
def __init__(self, fig: "Figure", spec: SubplotSpec): # noqa: F821
self._fig = fig
self._spec = spec
self._plot: "Plot1D | Plot2D | None" = None
# ------------------------------------------------------------------
def imshow(self, data: np.ndarray,
axes: list | None = None,
units: str = "px",
cmap: str | None = None,
vmin: float | None = None,
vmax: float | None = None,
origin: str = "upper") -> "Plot2D":
"""Attach a 2-D image to this axes cell.
Parameters
----------
data : np.ndarray, shape (H, W) or (H, W, C)
Image data. RGB/RGBA arrays use only the first channel.
axes : [x_axis, y_axis], optional
Physical coordinate arrays for each axis.
units : str, optional
Axis units label. Default ``"px"``.
cmap : str, optional
Colormap name (e.g. ``"viridis"``, ``"inferno"``).
Defaults to ``"gray"``.
vmin, vmax : float, optional
Colormap clipping limits in data units. Values outside this
range are clamped to the colormap endpoints. Defaults to the
data min / max.
origin : ``"upper"`` | ``"lower"``, optional
Where row 0 of the array is placed. ``"upper"`` (default)
puts row 0 at the top, matching the usual image convention.
``"lower"`` puts row 0 at the bottom, matching the matplotlib
convention for matrices / scientific plots.
Returns
-------
Plot2D
"""
x_axis = axes[0] if axes and len(axes) > 0 else None
y_axis = axes[1] if axes and len(axes) > 1 else None
plot = Plot2D(data, x_axis=x_axis, y_axis=y_axis, units=units,
cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
self._attach(plot)
return plot
def pcolormesh(self, data: np.ndarray,
x_edges=None, y_edges=None,
units: str = "") -> "PlotMesh":
"""Attach a 2-D mesh to this axes cell using edge coordinates.
Follows the matplotlib pcolormesh convention: x_edges and y_edges
are the cell *edge* coordinates, so they have length N+1 and M+1
respectively for an (M, N) data array.
Parameters
----------
data : np.ndarray shape (M, N)
x_edges : array-like, length N+1, optional
Column edge coordinates. Defaults to ``np.arange(N+1)``.
y_edges : array-like, length M+1, optional
Row edge coordinates. Defaults to ``np.arange(M+1)``.
units : str, optional
Returns
-------
PlotMesh
"""
plot = PlotMesh(data, x_edges=x_edges, y_edges=y_edges, units=units)
self._attach(plot)
return plot
def plot_surface(self, X, Y, Z, *,
colormap: str = "viridis",
x_label: str = "x", y_label: str = "y", z_label: str = "z",
azimuth: float = -60.0, elevation: float = 30.0,
zoom: float = 1.0) -> "Plot3D":
"""Attach a 3-D surface to this axes cell.
Parameters
----------
X, Y, Z : array-like
2-D grid arrays of the same shape (e.g. from ``np.meshgrid``),
or 1-D centre arrays for X/Y with a 2-D Z.
colormap : str, optional Matplotlib colormap name. Default ``'viridis'``.
x_label, y_label, z_label : str, optional Axis labels.
azimuth, elevation : float, optional Initial camera angles in degrees.
zoom : float, optional Initial zoom factor.
Returns
-------
Plot3D
"""
plot = Plot3D("surface", X, Y, Z, colormap=colormap,
x_label=x_label, y_label=y_label, z_label=z_label,
azimuth=azimuth, elevation=elevation, zoom=zoom)
self._attach(plot)
return plot
def scatter3d(self, x, y, z, *,
color: str = "#4fc3f7",
point_size: float = 4.0,
x_label: str = "x", y_label: str = "y", z_label: str = "z",
azimuth: float = -60.0, elevation: float = 30.0,
zoom: float = 1.0) -> "Plot3D":
"""Attach a 3-D scatter plot to this axes cell.
Parameters
----------
x, y, z : array-like, shape (N,) Point coordinates.
color : str, optional CSS colour for all points.
point_size : float, optional Radius of each point in pixels.
x_label, y_label, z_label : str, optional Axis labels.
azimuth, elevation : float, optional Initial camera angles in degrees.
zoom : float, optional Initial zoom factor.
Returns
-------
Plot3D
"""
plot = Plot3D("scatter", x, y, z, color=color, point_size=point_size,
x_label=x_label, y_label=y_label, z_label=z_label,
azimuth=azimuth, elevation=elevation, zoom=zoom)
self._attach(plot)
return plot
def plot3d(self, x, y, z, *,
color: str = "#4fc3f7",
linewidth: float = 1.5,
x_label: str = "x", y_label: str = "y", z_label: str = "z",
azimuth: float = -60.0, elevation: float = 30.0,
zoom: float = 1.0) -> "Plot3D":
"""Attach a 3-D line plot to this axes cell.
Parameters
----------
x, y, z : array-like, shape (N,) Point coordinates along the line.
color : str, optional CSS colour.
linewidth : float, optional Stroke width in pixels.
x_label, y_label, z_label : str, optional Axis labels.
azimuth, elevation : float, optional Initial camera angles in degrees.
zoom : float, optional Initial zoom factor.
Returns
-------
Plot3D
"""
plot = Plot3D("line", x, y, z, color=color, linewidth=linewidth,
x_label=x_label, y_label=y_label, z_label=z_label,
azimuth=azimuth, elevation=elevation, zoom=zoom)
self._attach(plot)
return plot
def plot(self, data: np.ndarray,
axes: list | None = None,
units: str = "px",
y_units: str = "",
color: str = "#4fc3f7",
linewidth: float = 1.5,
linestyle: str = "solid",
ls: str | None = None,
alpha: float = 1.0,
marker: str = "none",
markersize: float = 4.0,
label: str = "") -> "Plot1D":
"""Attach a 1-D line to this axes cell.
Parameters
----------
data : array-like, shape (N,)
Y values. Must be 1-D.
axes : list, optional
``[x_axis]`` — a one-element list containing the x-coordinates
(shape ``(N,)``). If omitted the x-axis defaults to
``0, 1, …, N-1``.
units : str, optional
Label for the x-axis (e.g. ``"eV"``, ``"s"``). Default
``"px"``.
y_units : str, optional
Label for the y-axis. Default ``""`` (no label).
color : str, optional
CSS colour string for the line (hex, ``rgb()``, named colour,
etc.). Default ``"#4fc3f7"``.
linewidth : float, optional
Stroke width in pixels. Default ``1.5``.
linestyle : str, optional
Dash pattern. Accepted values: ``"solid"`` (``"-"``),
``"dashed"`` (``"--"``), ``"dotted"`` (``":"``),
``"dashdot"`` (``"-."``) . Default ``"solid"``.
ls : str, optional
Short alias for *linestyle*. Takes precedence if both are given.
alpha : float, optional
Line opacity in the range 0–1. Default ``1.0`` (fully opaque).
marker : str, optional
Per-point marker symbol. Supported values: ``"o"`` (circle),
``"s"`` (square), ``"^"`` (triangle-up), ``"v"`` (triangle-down),
``"D"`` (diamond), ``"+"`` (plus), ``"x"`` (cross),
``"none"`` (no markers). Default ``"none"``.
markersize : float, optional
Marker radius / half-side in pixels. Default ``4.0``.
label : str, optional
Legend label. A legend is only drawn when at least one line has
a non-empty label. Default ``""`` (no legend entry).
Returns
-------
Plot1D
Live plot object. Call methods on it to update data, add
overlays, register callbacks, etc.
Examples
--------
Basic sine wave with a physical x-axis::
import numpy as np
import anyplotlib as vw
x = np.linspace(0, 4 * np.pi, 512)
fig, ax = vw.subplots(1, 1, figsize=(620, 320))
v = ax.plot(np.sin(x), axes=[x], units="rad",
color="#ff7043", linewidth=2, label="sin")
v # display in a Jupyter cell
Dashed line with semi-transparent markers::
v = ax.plot(data, linestyle="dashed", alpha=0.7,
marker="o", markersize=4)
Overlay a second curve with :meth:`Plot1D.add_line`::
v.add_line(np.cos(x), x_axis=x, color="#aed581", label="cos")
"""
x_axis = axes[0] if axes and len(axes) > 0 else None
plot = Plot1D(data, x_axis=x_axis, units=units, y_units=y_units,
color=color, linewidth=linewidth,
linestyle=ls if ls is not None else linestyle,
alpha=alpha, marker=marker, markersize=markersize,
label=label)
self._attach(plot)
return plot
def bar(self, x, height=None, width: float = 0.8, bottom: float = 0.0, *,
align: str = "center",
color: str = "#4fc3f7",
colors=None,
orient: str = "v",
log_scale: bool = False,
group_labels=None,
group_colors=None,
show_values: bool = False,
units: str = "",
y_units: str = "",
# ── legacy backward-compat kwargs ──────────────────────────────
x_labels=None,
x_centers=None,
bar_width=None,
baseline=None,
values=None) -> "PlotBar":
"""Attach a bar chart to this axes cell.
Signature mirrors ``matplotlib.pyplot.bar``::
ax.bar(x, height, width=0.8, bottom=0.0, ...)
Parameters
----------
x : array-like of str or numeric
Bar positions. Strings become category labels with auto-numeric
centres; numbers are used directly as bar centres.
height : array-like, shape ``(N,)`` or ``(N, G)``, optional
Bar heights. Pass a 2-D array to draw *G* grouped bars per
category. If omitted *x* is treated as the heights and positions
are generated automatically (backward-compatible call form).
width : float, optional
Bar width as a fraction of the category slot (0–1). Default ``0.8``.
bottom : float, optional
Value at which bars are rooted (baseline). Default ``0``.
align : ``"center"`` | ``"edge"``, optional
Alignment of the bar relative to its *x* position. Currently only
``"center"`` is rendered; stored for future use.
color : str, optional
Single CSS colour applied to every bar. Default ``"#4fc3f7"``.
colors : list of str, optional
Per-bar colour list (ungrouped) or ignored when *group_colors* is set.
orient : ``"v"`` | ``"h"``, optional
Vertical (default) or horizontal orientation.
log_scale : bool, optional
Use a logarithmic value axis. Non-positive values are clamped to
``1e-10`` for display. Default ``False``.
group_labels : list of str, optional
Legend labels for each group in a grouped bar chart.
group_colors : list of str, optional
CSS colours per group. Defaults to a built-in palette.
show_values : bool, optional
Draw the numeric value above / beside each bar.
units : str, optional
Label for the categorical axis.
y_units : str, optional
Label for the value axis.
Backward-compatible keyword aliases
------------------------------------
``values`` → ``height``
``x_centers`` → ``x``
``bar_width`` → ``width``
``baseline`` → ``bottom``
``x_labels`` → strings passed via ``x``
Returns
-------
PlotBar
"""
# ── legacy backward-compat resolution ─────────────────────────────
if height is None:
if values is not None:
height = values
else:
height = x
x = None
if baseline is not None:
bottom = baseline
if bar_width is not None:
width = bar_width
plot = PlotBar(x, height, width=width, bottom=bottom,
align=align, color=color, colors=colors,
orient=orient, log_scale=log_scale,
group_labels=group_labels, group_colors=group_colors,
show_values=show_values, units=units, y_units=y_units,
x_labels=x_labels, x_centers=x_centers)
self._attach(plot)
return plot
def _attach(self, plot: "Plot1D | Plot2D | PlotMesh | Plot3D | PlotBar") -> None:
"""Register a plot on this axes (replace any previous plot)."""
# Allocate a panel id if needed; reuse if replacing
if self._plot is not None:
panel_id = self._plot._id
else:
panel_id = str(_uuid.uuid4())[:8]
plot._id = panel_id
plot._fig = self._fig
self._plot = plot
self._fig._register_panel(self, plot)
def __repr__(self) -> str:
kind = type(self._plot).__name__ if self._plot else "empty"
return f"Axes(rows={self._spec.row_start}:{self._spec.row_stop}, cols={self._spec.col_start}:{self._spec.col_stop}, {kind})"
# ---------------------------------------------------------------------------
# Shared normalisation helpers (duplicated from Viewer2D to keep standalone)
# ---------------------------------------------------------------------------
def _normalize_image(data: np.ndarray):
"""Normalise data to uint8, returning (img_u8, vmin, vmax)."""
img = data.astype(np.float64, copy=False)
vmin = float(np.nanmin(img))
vmax = float(np.nanmax(img))
if vmax > vmin:
buf = np.empty_like(img)
np.subtract(img, vmin, out=buf)
np.divide(buf, vmax - vmin, out=buf)
np.multiply(buf, 255.0, out=buf)
img_u8 = buf.astype(np.uint8)
else:
img_u8 = np.zeros(data.shape, dtype=np.uint8)
return img_u8, vmin, vmax
# Mapping from common matplotlib colormap names to their nearest colorcet
# equivalents so callers can keep using familiar names without any matplotlib
# dependency.
_CMAP_ALIASES: dict[str, str] = {
"viridis": "bmy", # blue→magenta→yellow, perceptually uniform
"plasma": "fire", # warm sequential (dark→bright)
"inferno": "kb", # dark→blue→white
"magma": "kbc", # dark→blue→cyan sequential
"cividis": "bgy", # accessible, blue→green→yellow sequential
"hot": "fire",
"afmhot": "fire",
"jet": "rainbow4",
"hsv": "rainbow4",
"nipy_spectral": "rainbow4",
"RdBu": "coolwarm",
"bwr": "cwr", # blue→white→red diverging
"seismic": "coolwarm",
}
def _build_colormap_lut(name: str) -> list:
"""Return a 256-entry ``[[r, g, b], ...]`` LUT for the named colormap.
Uses **colorcet** exclusively. Common matplotlib colormap names are
transparently remapped via :data:`_CMAP_ALIASES` so callers can keep
using names like ``"viridis"`` or ``"hot"`` without any matplotlib
dependency. Falls back to a plain gray ramp for unknown names.
"""
import colorcet as cc
resolved = _CMAP_ALIASES.get(name, name)
palette = cc.palette.get(resolved)
if palette is None:
# Unknown name → linear gray ramp
return [[v, v, v] for v in range(256)]
n = len(palette)
lut: list = []
for i in range(256):
h = palette[int(round(i * (n - 1) / 255))].lstrip("#")
lut.append([int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)])
return lut
def _resample_mesh(data: np.ndarray, x_edges, y_edges) -> np.ndarray:
"""Resample a mesh to a regular pixel grid via nearest-neighbour lookup.
For uniform edges this is an identity operation. For non-uniform edges
(e.g. log-spaced) it maps each uniform output pixel to the nearest input
cell, producing a visually correct linear-axis image.
Parameters
----------
data : ndarray, shape (M, N) — one value per mesh cell.
x_edges : array-like, length N+1 — column edge coordinates.
y_edges : array-like, length M+1 — row edge coordinates.
Returns
-------
ndarray, shape (M, N)
"""
rows, cols = data.shape
x_edges = np.asarray(x_edges, dtype=float)
y_edges = np.asarray(y_edges, dtype=float)
# Cell centres
x_c = (x_edges[:-1] + x_edges[1:]) / 2.0
y_c = (y_edges[:-1] + y_edges[1:]) / 2.0
# Uniform sample points (same count as original cells)
x_samp = np.linspace(x_c[0], x_c[-1], cols)
y_samp = np.linspace(y_c[0], y_c[-1], rows)
# Nearest-neighbour cell lookup via edge-sorted searchsorted
xi = np.searchsorted(x_edges, x_samp) - 1
xi = np.clip(xi, 0, cols - 1)
yi = np.searchsorted(y_edges, y_samp) - 1
yi = np.clip(yi, 0, rows - 1)
return data[np.ix_(yi, xi)]
# ---------------------------------------------------------------------------
# Plot2D
# ---------------------------------------------------------------------------
class Plot2D:
"""2-D image plot panel.
Not an anywidget. Holds state in ``_state`` dict; every mutation calls
``_push()`` which writes to the parent Figure's panel trait.
The marker API follows matplotlib conventions:
plot.add_circles(offsets, name="g1", facecolors="#f00", radius=5)
plot.markers["circles"]["g1"].set(radius=8)
"""
def __init__(self, data: np.ndarray,
x_axis=None, y_axis=None, units: str = "px",
cmap: str | None = None,
vmin: float | None = None,
vmax: float | None = None,
origin: str = "upper"):
self._id: str = "" # assigned by Axes._attach
self._fig: object = None # assigned by Axes._attach
_valid_origins = ("upper", "lower")
if origin not in _valid_origins:
raise ValueError(
f"origin must be one of {_valid_origins!r}, got {origin!r}"
)
self._origin: str = origin
data = np.asarray(data)
if data.ndim == 3:
data = data[:, :, 0]
if data.ndim != 2:
raise ValueError(f"data must be 2-D (H x W), got {data.shape}")
h, w = data.shape
# origin='lower' — row 0 at the bottom, matching matplotlib's matrix
# convention. Flip the data so our renderer (which always draws row 0
# at the top) shows the correct orientation, and reverse the y-axis so
# tick values increase upward.
if origin == "lower":
data = np.flipud(data)
self._data: np.ndarray = data.astype(float)
x_axis_given = x_axis is not None
y_axis_given = y_axis is not None
if x_axis is None:
x_axis = np.arange(w, dtype=float)
if y_axis is None:
y_axis = np.arange(h, dtype=float)
x_axis = np.asarray(x_axis, dtype=float)
y_axis = np.asarray(y_axis, dtype=float)
if origin == "lower":
y_axis = y_axis[::-1]
img_u8, raw_vmin, raw_vmax = _normalize_image(data)
self._raw_u8 = img_u8
self._raw_vmin = raw_vmin
self._raw_vmax = raw_vmax
cmap_name = cmap if cmap is not None else "gray"
cmap_lut = _build_colormap_lut(cmap_name)
# vmin/vmax clip the colormap in data units; default to the full range.
disp_min = float(vmin) if vmin is not None else raw_vmin
disp_max = float(vmax) if vmax is not None else raw_vmax
# Compute physical pixel scale (data-units per pixel) from axis arrays
scale_x = float(abs(x_axis[-1] - x_axis[0]) / max(w - 1, 1)) if len(x_axis) >= 2 else 1.0
scale_y = float(abs(y_axis[-1] - y_axis[0]) / max(h - 1, 1)) if len(y_axis) >= 2 else 1.0
self._state: dict = {
"kind": "2d",
"is_mesh": False,
"has_axes": x_axis_given or y_axis_given,
"image_b64": self._encode_bytes(img_u8),
"image_width": w,
"image_height": h,
"x_axis": x_axis.tolist(),
"y_axis": y_axis.tolist(),
"units": units,
"scale_x": scale_x,
"scale_y": scale_y,
"display_min": disp_min,
"display_max": disp_max,
"raw_min": raw_vmin,
"raw_max": raw_vmax,
"show_colorbar": False,
"log_scale": False,
"scale_mode": "linear",
"colormap_name": cmap_name,
"colormap_data": cmap_lut,
"zoom": 1.0,
"center_x": 0.5,
"center_y": 0.5,
"overlay_widgets": [],
"markers": [],
"registered_keys": [],
}
self.markers = MarkerRegistry(self._push_markers,
allowed=MarkerRegistry._KNOWN_2D)
self.callbacks = CallbackRegistry()
self._widgets: dict[str, Widget] = {}
@staticmethod
def _encode_bytes(arr: np.ndarray) -> str:
import base64
return base64.b64encode(arr.tobytes()).decode("ascii")
def _push(self) -> None:
"""Serialise _state + markers and write to Figure trait."""
if self._fig is None:
return
self._state["overlay_widgets"] = [w.to_dict() for w in self._widgets.values()]
self._fig._push(self._id)
def _push_markers(self) -> None:
"""Called by MarkerRegistry whenever markers change."""
self._state["markers"] = self.markers.to_wire_list()
self._push()
def to_state_dict(self) -> dict:
"""Return a JSON-serialisable copy of the current state."""
d = dict(self._state)
d["overlay_widgets"] = [w.to_dict() for w in self._widgets.values()]
d["markers"] = self.markers.to_wire_list()
return d
# ------------------------------------------------------------------
# Data
# ------------------------------------------------------------------
@property
def data(self) -> np.ndarray:
"""The image data in the original user coordinate system (read-only).
Returns a float64 copy with ``writeable=False``. To replace the
data call :meth:`set_data`.
"""
arr = np.flipud(self._data).copy() if self._origin == "lower" else self._data.copy()
arr.flags.writeable = False
return arr
def set_data(self, data: np.ndarray,
x_axis=None, y_axis=None, units: str | None = None) -> None:
"""Replace the image data.
The ``origin`` supplied at construction is automatically re-applied
so the new data is displayed with the same orientation.
"""
data = np.asarray(data)
if data.ndim == 3:
data = data[:, :, 0]
if data.ndim != 2:
raise ValueError(f"data must be 2-D, got {data.shape}")
h, w = data.shape
if self._origin == "lower":
data = np.flipud(data)
self._data = data.astype(float)
img_u8, vmin, vmax = _normalize_image(data)
self._raw_u8, self._raw_vmin, self._raw_vmax = img_u8, vmin, vmax
if x_axis is not None:
self._state["x_axis"] = np.asarray(x_axis, float).tolist()
self._state["image_width"] = w
self._state["has_axes"] = True
if y_axis is not None:
ya = np.asarray(y_axis, float)
if self._origin == "lower":
ya = ya[::-1]
self._state["y_axis"] = ya.tolist()
self._state["image_height"] = h
self._state["has_axes"] = True
if units is not None:
self._state["units"] = units
self._state.update({
"image_b64": self._encode_bytes(img_u8),
"image_width": w,
"image_height": h,
"display_min": vmin,
"display_max": vmax,
"raw_min": vmin,
"raw_max": vmax,
"colormap_data": _build_colormap_lut(self._state["colormap_name"]),
})
self._push()
# ------------------------------------------------------------------
# Display settings
# ------------------------------------------------------------------
def set_colormap(self, name: str) -> None:
self._state["colormap_name"] = name
self._state["colormap_data"] = _build_colormap_lut(name)
self._push()
def set_clim(self, vmin=None, vmax=None) -> None:
if vmin is not None:
self._state["display_min"] = float(vmin)
if vmax is not None:
self._state["display_max"] = float(vmax)
self._push()
def set_scale_mode(self, mode: str) -> None:
valid = ("linear", "log", "symlog")
if mode not in valid:
raise ValueError(f"mode must be one of {valid}")
self._state["scale_mode"] = mode
self._push()
@property
def colormap_name(self) -> str:
return self._state["colormap_name"]
@colormap_name.setter
def colormap_name(self, name: str) -> None:
self.set_colormap(name)
# ------------------------------------------------------------------
# Overlay Widgets
# ------------------------------------------------------------------
def add_widget(self, kind: str, color: str = "#00e5ff", **kwargs) -> Widget:
kind = kind.lower()
valid = ("circle", "rectangle", "annular", "polygon", "label", "crosshair")
if kind not in valid:
raise ValueError(f"kind must be one of {valid}")
iw, ih = self._state["image_width"], self._state["image_height"]
def _f(k, default): return float(kwargs.get(k, default))
def _i(k, default): return int(kwargs.get(k, default))
if kind == "circle":
widget = CircleWidget(lambda: None,
cx=_f("cx", iw / 2), cy=_f("cy", ih / 2),
r=_f("r", iw * 0.1), color=color)
elif kind == "rectangle":
widget = RectangleWidget(lambda: None,
x=_f("x", iw * 0.25), y=_f("y", ih * 0.25),
w=_f("w", iw * 0.5), h=_f("h", ih * 0.5),
color=color)
elif kind == "annular":
r_outer = _f("r_outer", iw * 0.2)
r_inner = _f("r_inner", iw * 0.1)
widget = AnnularWidget(lambda: None,
cx=_f("cx", iw / 2), cy=_f("cy", ih / 2),
r_outer=r_outer, r_inner=r_inner, color=color)
elif kind == "polygon":
raw = kwargs.get("vertices", [[iw * .25, ih * .25], [iw * .75, ih * .25],
[iw * .75, ih * .75], [iw * .25, ih * .75]])
widget = PolygonWidget(lambda: None, vertices=raw, color=color)
elif kind == "crosshair":
widget = CrosshairWidget(lambda: None,
cx=_f("cx", iw / 2), cy=_f("cy", ih / 2),
color=color)
else: # label
widget = LabelWidget(lambda: None,
x=_f("x", iw * 0.1), y=_f("y", ih * 0.1),
text=str(kwargs.get("text", "Label")),
fontsize=_i("fontsize", 14), color=color)
# Replace the temporary push_fn with a targeted one now that
# we have both the widget's _id and the plot's _id.
plot_ref = self
wid_id = widget._id
def _targeted_push():
if plot_ref._fig is not None:
fields = {k: v for k, v in widget._data.items()
if k not in ("id", "type")}
plot_ref._fig._push_widget(plot_ref._id, wid_id, fields)
widget._push_fn = _targeted_push
self._widgets[widget.id] = widget
self._push() # full panel push once so JS knows about the widget
return widget
def get_widget(self, wid) -> Widget:
"""Return the Widget object by ID string or Widget instance."""
if isinstance(wid, Widget):
wid = wid.id
try:
return self._widgets[wid]
except KeyError:
raise KeyError(wid)
def remove_widget(self, wid) -> None:
"""Remove a widget by ID string or Widget instance."""
if isinstance(wid, Widget):
wid = wid.id
if wid not in self._widgets:
raise KeyError(wid)
del self._widgets[wid]
self._push()
def list_widgets(self) -> list:
return list(self._widgets.values())
def clear_widgets(self) -> None:
self._widgets.clear()
self._push()
# ------------------------------------------------------------------
# Callback API (Plot2D)
# ------------------------------------------------------------------
def on_changed(self, fn: Callable) -> Callable:
"""Decorator: fires on every pan/zoom/drag frame on this panel."""
cid = self.callbacks.connect("on_changed", fn)
fn._cid = cid
return fn
def on_release(self, fn: Callable) -> Callable:
"""Decorator: fires once when pan/zoom/drag settles on this panel."""
cid = self.callbacks.connect("on_release", fn)
fn._cid = cid
return fn
def on_click(self, fn: Callable) -> Callable:
"""Decorator: fires on click on this panel."""
cid = self.callbacks.connect("on_click", fn)
fn._cid = cid
return fn
def on_key(self, key_or_fn=None) -> Callable:
"""Register a key-press handler for this panel.
Two call forms are supported::
@plot.on_key('q') # fires only when 'q' is pressed
def handler(event): ...
@plot.on_key # fires for every registered key
def handler(event): ...
The event carries: ``key``, ``mouse_x``, ``mouse_y``, ``phys_x``,
and ``last_widget_id``.
.. note::
Registered keys take priority over the built-in **r** (reset view)
shortcut.
"""