Repository navigation
Expand file tree
/
Copy path_ndw_subplot.py
More file actions
1119 lines (903 loc) · 53.4 KB
/
Copy path_ndw_subplot.py
File metadata and controls
1119 lines (903 loc) · 53.4 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
import warnings
from collections.abc import Callable
from typing import Any, Literal, Sequence, Hashable
import numpy as np
from numpy.typing import ArrayLike
from ... import (
ScatterCollection,
ScatterStack,
LineCollection,
LineStack,
ImageGraphic,
)
from ...layouts import Subplot
from ...utils import ArrayProtocol, enums
from . import NDImageSlicer, NDImage, NDPositions, NDTimeseries, NDVectors
from ._nd_positions._nd_positions import (
NDPositionsSlicer,
ColorsType,
FeatureCallable,
MarkersType,
SizesType,
)
from ._index import AutoRangeContinuous
from ._video import VideoSlicer
from ._base import NDGraphic, WindowFuncCallable
class NDWSubplot:
"""
Entry point for adding ``NDGraphic`` objects to a subplot of an ``NDWidget``.
Accessed via ``ndw[row, col]`` or ``ndw["subplot_name"]``.
Each ``add_nd_<...>`` method constructs the appropriate ``NDGraphic``, registers it with the parent
``ReferenceIndex``, appends it to this subplot and returns the ``NDGraphic`` instance to the user.
Note: ``NDWSubplot`` is not meant to be constructed directly, it only exists as part of an ``NDWidget``
"""
def __init__(self, ndw, subplot: Subplot):
self.ndw = ndw
self._subplot = subplot
self._nd_graphics = list()
@property
def subplot(self) -> Subplot:
"""The ``Subplot`` of the ``NDWidget`` figure that this ``NDWSubplot`` adds graphics to"""
return self._subplot
@property
def nd_graphics(self) -> tuple[NDGraphic]:
"""all the NDGraphic instance in this subplot"""
return tuple(self._nd_graphics)
def __getitem__(self, key) -> NDGraphic:
# get a specific NDGraphic by index or name
if isinstance(key, (int, np.integer)):
return self.nd_graphics[key]
for g in self.nd_graphics:
if g.name == key:
return g
else:
raise KeyError(f"NDGraphc with given key not found: {key}")
def delete_nd_graphic(self, ndg: NDGraphic):
"""
Delete an NDGraphic from the subplot
.. important::
Not implemented yet.
"""
raise NotImplementedError("Not yet implemented")
# TODO: verify that this actually garbage collects, and shut down the
# slicer's thread pool with `ndg.slicer.close()`
# del ndg.data
# self.subplot.delete_graphic(ndg.graphic)
# self._nd_graphics.remove(ndg)
#
# del ndg
def _check_slider_dims(
self,
dims: Sequence[Hashable],
display_dims: Sequence[Hashable],
data: ArrayProtocol | None,
positions: bool = False,
):
"""
Make sure every slider (non-spatial) dim of a graphic being added has a
reference range. A dim without one gets an ``AutoRangeContinuous`` sized to
the data, an existing ``AutoRangeContinuous`` is grown to fit, and an
explicit range is left untouched.
"""
if data is None:
# size is unknown, an explicit range is still required
return
if not isinstance(data, ArrayProtocol):
return
dims = tuple(dims)
slider_dims = set(dims) - set(display_dims)
if positions:
# the datapoints `p` axis is a spatial dim that also needs a reference range
slider_dims.add(display_dims[1])
for dim in slider_dims:
size = data.shape[dims.index(dim)]
if dim not in self.ndw.indices.dims:
warnings.warn(
f"No reference range specified for non-spatial dim '{dim}', "
f"auto-generating an `AutoRangeContinuous(0, {size}, 1)`."
)
self.ndw.indices.push_dims({dim: AutoRangeContinuous(0, size, 1)})
elif isinstance(self.ndw.indices.ref_ranges[dim], AutoRangeContinuous):
# grow the existing auto range to fit this array
self.ndw.indices.ref_ranges[dim].stop = max(
self.ndw.indices.ref_ranges[dim].stop, size
)
def add_nd_image(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: (
tuple[str, str] | tuple[str, str, str]
), # must be in order! [rows, cols] | [z, rows, cols]
rgb_dim: str | None = None,
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
compute_histogram: bool = True,
clim_quantiles: tuple[float, float] | None = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
slicer_type: type[NDImageSlicer] = NDImageSlicer,
colorspace: Literal[
"srgb", "tex-srgb", "physical", "yuv420p", "yuv444p"
] = "srgb",
colorrange: Literal["full", "limited"] = "full",
name: str = None,
graphic_kwargs: dict = None,
) -> NDImage:
"""
Add an n-dimensional image or volume to this subplot.
Every dim that is not listed in ``display_dims`` becomes a slider dim.
Parameters
----------
data: ArrayProtocol or None
n-dimensional image data, must have 2 or more dims. Pass ``None`` to create the ``NDImage`` without a
graphic and set the data later using ``nd_image.data``, the slider dims then require an explicit
reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order. They do not need to be in display order, ex: an array whose
dims are ``("col", "depth", "row", "time")`` with ``display_dims`` of ``("row", "col")``.
display_dims: tuple[str, str] | tuple[str, str, str]
The 2 or 3 spatial dims **in display order**, which also determines the graphic used for rendering:
* ``(rows, cols)``, a 2D grayscale ``ImageGraphic``
* ``(rows, cols, rgb_dim)``, a 2D RGB(A) ``ImageGraphic``
* ``(z, rows, cols)``, a 3D ``ImageVolumeGraphic``
rgb_dim: str, optional
Name of the RGB(A) dim, if present. It must be listed in ``display_dims`` and be of size 3 or 4.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions applied around the current slider position, ex:
``{"time": (np.mean, 2.5)}``. Each value is a ``(func, window_size)`` pair where:
* *func* must accept ``axis: int`` and ``keepdims: bool`` kwargs (ex: ``np.mean``, ``np.max``). It
**must** return an array that has the same dims as the input, therefore the size of any dim along
which it was applied should reduce to ``1``. These dims must not be removed by the window func.
* *window_size* is in reference-space units (ex: 2.5 seconds).
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Only dims listed here have their window
function applied, ``window_funcs`` are ignored for any dim not specified in ``window_order``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional
A function applied to the spatial slice *after* the window funcs, right before rendering. It is
given the slice in ``display_dims`` order, i.e. the array as it is rendered, and must return an
array with those same dims.
compute_histogram: bool, default ``True``
Estimate a histogram of the data and display an ``ImguiColorbar`` on the right edge of the subplot,
which is used to interactively set vmin, vmax. Disable if random access of the data is not
blazing-fast (ex: data that uses video codecs), or if a histogram is not useful for this data.
clim_quantiles: (float, float), optional
``(low, high)`` quantiles of the histogram, within ``[0, 1]``, used as vmin, vmax. Requires
``compute_histogram=True``, overrides any passed vmin, vmax in ``graphic_kwargs``. The limits
are recomputed whenever the histogram is, so they follow the data.
slider_maps: dict mapping dim_name -> Callable, an ArrayLike, or None, optional
Per-slider-dim mapping from reference-space values to local array indices. An array of reference
values may be given instead of a callable, ``searchsorted`` is then used as the transform (ex: a
timestamps array). Any dim without a transform uses the identity mapping, i.e. the current reference
value is rounded to the nearest integer and used as the array index.
slicer_type: type[NDImageSlicer], default ``NDImageSlicer``
``NDImageSlicer`` subclass that manages the data and produces the data slices.
colorspace: "srgb" | "tex-srgb" | "physical" | "yuv420p" | "yuv444p", default "srgb"
Colorspace in which to interpret the data. The RGB colorspaces are rendered using an ``ImageGraphic``
or ``ImageVolumeGraphic``, see :class:`.ImageGraphic` for their meaning. The YUV colorspaces are
rendered using an ``ImageYUVGraphic``, see :class:`.ImageYUVGraphic`.
colorrange: "full" | "limited", default "full"
Used only for the YUV colorspaces, see :class:`.ImageYUVGraphic`.
name: str, optional
Name for this ``NDGraphic``, used to retrieve it with ``nd_subplot[name]``.
graphic_kwargs: dict, optional
passed to the underlying image graphic, ex: ``{"cmap": "viridis", "interpolation": "linear"}``
Returns
-------
NDImage
"""
self._check_slider_dims(dims, display_dims, data)
nd = NDImage(
self.ndw.indices,
nd_subplot=self,
data=data,
dims=dims,
display_dims=display_dims,
rgb_dim=rgb_dim,
window_funcs=window_funcs,
window_order=window_order,
spatial_func=spatial_func,
compute_histogram=compute_histogram,
clim_quantiles=clim_quantiles,
slider_maps=slider_maps,
slicer_type=slicer_type,
colorspace=colorspace,
colorrange=colorrange,
name=name,
graphic_kwargs=graphic_kwargs,
)
self._nd_graphics.append(nd)
return nd
def add_video(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: tuple[str, str] | tuple[str, str, str],
rgb_dim: str | None = None,
colorspace: enums.ColorspacesYUV | enums.ColorspacesRGB = "yuv420p",
colorrange: enums.ColorRange = "limited",
slicer_type: NDImageSlicer = VideoSlicer,
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
name: str = None,
graphic_kwargs: dict = None,
) -> NDImage:
"""
Add a video to this subplot.
This is usually what you want for video data. Videos are usually stored in a YUV colorspace, and sending
the YUV planes to the GPU is much faster than converting each frame to RGB and copying it into an sRGB
texture.
We strongly recommend using ``asyncvideo`` for the ``data`` object, it is the most efficient async video
reader that we know of for visualization purposes: https://pypi.org/project/asyncvideo/
Same as :meth:`add_nd_image` but uses a :class:`VideoSlicer` and YUV defaults. The ``VideoSlicer``
reads the frame at the current index directly, it does not apply ``window_funcs``.
Parameters
----------
data: ArrayProtocol or None
video data, an object that decodes frames on demand, ex: an ``asyncvideo`` reader. Pass ``None`` to
create the ``NDImage`` without a graphic and set the data later using ``nd_image.data``, the slider
dims then require an explicit reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order. They do not need to be in display order.
display_dims: tuple[str, str] | tuple[str, str, str]
The 2 or 3 spatial dims **in display order**, see :meth:`add_nd_image`.
rgb_dim: str, optional
Name of the RGB(A) dim, if present. It must be listed in ``display_dims`` and be of size 3 or 4.
colorspace: "yuv420p" | "yuv444p" | "srgb" | "tex-srgb" | "physical", default "yuv420p"
Colorspace in which to interpret the data. The YUV colorspaces are rendered using an
``ImageYUVGraphic``, see :class:`.ImageYUVGraphic`. The RGB colorspaces are rendered using an
``ImageGraphic`` or ``ImageVolumeGraphic``, see :class:`.ImageGraphic`.
colorrange: "full" | "limited", default "limited"
Used only for the YUV colorspaces, see :class:`.ImageYUVGraphic`. Most videos use "limited".
slicer_type: type[NDImageSlicer], default ``VideoSlicer``
``NDImageSlicer`` subclass that manages the data and produces the data slices.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions, see :meth:`add_nd_image`. Ignored by the default
``VideoSlicer``.
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Ignored by the default
``VideoSlicer``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional
A function applied to the spatial slice right before rendering. It is given the frame in
``display_dims`` order, i.e. the array as it is rendered, and must return an array with those
same dims.
slider_maps: dict mapping dim_name -> Callable, an ArrayLike, or None, optional
Per-slider-dim mapping from reference-space values to local array indices, ex: an array of frame
timestamps to map seconds onto frame indices. See :meth:`add_nd_image`.
name: str, optional
Name for this ``NDGraphic``, used to retrieve it with ``nd_subplot[name]``.
graphic_kwargs: dict, optional
passed to the underlying image graphic
Returns
-------
NDImage
"""
return self.add_nd_image(
data=data,
dims=dims,
display_dims=display_dims,
rgb_dim=rgb_dim,
colorspace=colorspace,
colorrange=colorrange,
slicer_type=slicer_type,
window_funcs=window_funcs,
window_order=window_order,
spatial_func=spatial_func,
compute_histogram=False,
slider_maps=slider_maps,
name=name,
graphic_kwargs=graphic_kwargs,
)
def add_nd_vectors(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: tuple[str, str, str],
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
name: str = None,
graphic_kwargs: dict = None,
) -> NDVectors:
"""
Add n-dimensional vectors to this subplot, similar to matplotlib quiver.
Every dim that is not listed in ``display_dims`` becomes a slider dim.
Parameters
----------
data: ArrayProtocol or None
n-dimensional vector data of shape ``[..., n_vectors, 2, 2]`` or ``[..., n_vectors, 2, 3]``, where
``data[..., 0, :]`` are the vector positions and ``data[..., 1, :]`` are the vector directions. Pass
``None`` to create the ``NDVectors`` without a graphic and set the data later using
``nd_vectors.data``, the slider dims then require an explicit reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order. They do not need to be in display order.
display_dims: tuple[str, str, str]
The 3 spatial dims **in order**: ``(n_vectors, positions_and_directions, xy(z))``. The
positions/directions dim must be of size 2 and the coordinate dim of size 2 or 3.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions applied around the current slider position, ex:
``{"time": (np.mean, 2.5)}``. Each value is a ``(func, window_size)`` pair where:
* *func* must accept ``axis: int`` and ``keepdims: bool`` kwargs (ex: ``np.mean``, ``np.max``). It
**must** return an array that has the same dims as the input, therefore the size of any dim along
which it was applied should reduce to ``1``. These dims must not be removed by the window func.
* *window_size* is in reference-space units (ex: 2.5 seconds).
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Only dims listed here have their window
function applied, ``window_funcs`` are ignored for any dim not specified in ``window_order``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional
A function applied to the spatial slice *after* the window funcs, right before rendering. It is
given the slice in ``display_dims`` order, i.e. the array as it is rendered, and must return an
array with those same dims.
slider_maps: dict mapping dim_name -> Callable, an ArrayLike, or None, optional
Per-slider-dim mapping from reference-space values to local array indices. An array of reference
values may be given instead of a callable, ``searchsorted`` is then used as the transform (ex: a
timestamps array). Any dim without a transform uses the identity mapping, i.e. the current reference
value is rounded to the nearest integer and used as the array index.
name: str, optional
Name for this ``NDGraphic``, used to retrieve it with ``nd_subplot[name]``.
graphic_kwargs: dict, optional
passed to the underlying :class:`.VectorsGraphic`, ex: ``{"color": "cyan", "size": 0.5}``
Returns
-------
NDVectors
"""
self._check_slider_dims(dims, display_dims, data)
nd = NDVectors(
self.ndw.indices,
nd_subplot=self,
data=data,
dims=dims,
display_dims=display_dims,
window_funcs=window_funcs,
window_order=window_order,
spatial_func=spatial_func,
slider_maps=slider_maps,
name=name,
graphic_kwargs=graphic_kwargs,
)
self._nd_graphics.append(nd)
return nd
def add_nd_scatter(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: tuple[str, str, str],
*args,
slicer: type[NDPositionsSlicer] = NDPositionsSlicer,
display_window: int | float | None = 10,
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
max_display_datapoints: int | None = 1_000,
datapoints_window_func: tuple[Callable, str, int | float] | None = None,
colors: ColorsType = None,
cmap: str | Sequence[str] = None,
cmap_transform: np.ndarray | FeatureCallable = None,
cmap_range: tuple[float, float] = None,
sizes: SizesType = None,
markers: MarkersType = None,
name: str = None,
graphic_kwargs: dict = None,
slicer_kwargs: dict = None,
) -> NDPositions:
"""
Add n-dimensional positional data to this subplot, rendered as a ``ScatterCollection``.
Every dim that is not listed in ``display_dims`` becomes a slider dim. The datapoints dim, ``p``, is both
a spatial dim and a slider dim, it is windowed by ``display_window`` and ``datapoints_window_func``
rather than by ``window_funcs``.
Parameters
----------
data: ArrayProtocol or None
n-dimensional positional data.
Ex: an array of shape ``[n_trials, n_scatters, n_points, 2]`` with ``dims`` of
``("trial", "scatter", "point", "xy")`` and ``display_dims`` of ``("scatter", "point", "xy")``.
Pass ``None`` to create the ``NDPositions`` without a graphic and set the data later using
``nd_positions.data``, the slider dims then require an explicit reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order.
display_dims: tuple[str, str, str]
The 3 spatial dims **in display order**: ``(n_graphics, p, <value dim>)``, i.e. the number of
scatters in the collection, the number of datapoints ``p`` in each of them, and the value dim which
holds the xy or xyz coordinate and must be of size 2 or 3. The dims do not need to be in this order
in the array, the data slice is transposed into display order.
args
extra positional arguments passed to the ``slicer`` constructor.
slicer: type[NDPositionsSlicer], default ``NDPositionsSlicer``
``NDPositionsSlicer`` subclass that manages the data and produces the data slices.
display_window: int, float or None, default 10
Size of the window of the ``p`` dim to render, in the reference units of that dim, centered on its
current index. Use ``None`` to render every datapoint, or ``0`` to render only the datapoint at the
current index. This is what makes out-of-core rendering possible, i.e. rendering a window of a
dataset that is larger than GPU VRAM.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions applied around the current slider position, ex:
``{"trial": (np.mean, 5)}``. Each value is a ``(func, window_size)`` pair where:
* *func* must accept ``axis: int`` and ``keepdims: bool`` kwargs (ex: ``np.mean``, ``np.max``). It
**must** return an array that has the same dims as the input, therefore the size of any dim along
which it was applied should reduce to ``1``. These dims must not be removed by the window func.
* *window_size* is in reference-space units.
Not used for the ``p`` dim, see ``datapoints_window_func``.
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Only dims listed here have their window
function applied, ``window_funcs`` are ignored for any dim not specified in ``window_order``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional
A function applied to the spatial slice *after* the window funcs, right before rendering. It is
given the slice in ``display_dims`` order, i.e. the array as it is rendered, and must return an
array with those same dims.
slider_maps: dict[str, Callable[[Any], int] | ArrayLike], optional
Per-slider-dim mapping from reference-space values to local array indices. An array of reference
values may be given instead of a Callable, ``searchsorted`` is then used as the transform (ex: a
timestamps array). Any dim without a transform uses the identity mapping, i.e. the current reference
value is rounded to the nearest integer and used as the array index.
max_display_datapoints: int | None, default 1_000
Maximum number of datapoints to render per graphic. The step size of the display window slice is set
from this using floor division. ``None`` renders every datapoint in the window, with no decimation.
Neither ``None`` nor a very large value is recommended: the entire window is then read into RAM and
uploaded, which is slow for a large window over a large array.
datapoints_window_func: tuple[Callable, str, int | float], optional
Window function applied along the ``p`` dim after the display window has been taken, as
``(func, apply_dims, window_size)`` where:
* *func* must accept an ``axis: int`` kwarg (ex: ``np.mean``, ``np.max``). It is given a sliding
window view of the data and is reduced along the window axis.
* *apply_dims* names the coordinates of the value dim to apply it to, one of ``"all", "x", "y",
"z", "xy", "xz", "yz", "xyz"``. Coordinates that are not named are passed through unchanged.
* *window_size* is in the reference units of the ``p`` dim. It is mapped to array indices, clamped to
a minimum of 3, and rounded up to an odd size.
If used, ``display_window`` is approximate and not exact due to padding from the window size.
colors: str | Sequence[str] | np.ndarray | FeatureCallable, optional
Colors of the scatters. Mutually exclusive with ``cmap``, setting one clears the other.
* static, a single color for every graphic, ex: ``"cyan"`` or an RGBA sequence of 4 floats
* static, one color per graphic, ``[n_graphics]`` of str or ``[n_graphics, 4]`` RGBA
* windowed, one color per datapoint, ``[n_graphics, p, 4]`` RGBA
* windowed, a ``FeatureCallable``
cmap: str | Sequence[str], optional
Colormap applied to the scatters, always static. A single name for every graphic, or an iterable of
``[n_graphics]`` names for a colormap per graphic. Mutually exclusive with ``colors``.
cmap_transform: np.ndarray | FeatureCallable, optional
Values that the colormap colors are mapped from.
* static, one value per graphic, ``[n_graphics]``, so each graphic gets a single color
* windowed, one value per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
cmap_range: (float, float) | np.ndarray, optional
The (min, max) of ``cmap_transform`` mapped onto the colormap, or ``[n_graphics, 2]`` for a range per
graphic. A windowed array ``cmap_transform`` defaults to its own (min, max) over the full ``p`` dim,
so the display window keeps its position within the colormap. A ``FeatureCallable`` transform
requires an explicit range, its full range is not knowable without evaluating it everywhere.
sizes: float | Sequence[float] | np.ndarray | FeatureCallable, optional
Size of the scatter points.
* static, a single size for every graphic, or ``[n_graphics]`` sizes for one size per graphic
* windowed, one size per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
markers: str | Sequence[str] | np.ndarray | FeatureCallable, optional
Marker shape of the scatter points.
* static, a single marker for every graphic, or ``[n_graphics]`` markers for one per graphic
* windowed, one marker per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
name: str, optional
Name for this ``NDGraphic``, used to retrieve it with ``nd_subplot[name]``.
graphic_kwargs: dict, optional
passed to the underlying ``ScatterCollection``
slicer_kwargs: dict, optional
passed to the ``slicer`` constructor.
Returns
-------
NDPositions
Notes
-----
Each of the other graphic features is either *windowed* or *static*, decided from the value itself:
* **windowed**: a ``FeatureCallable``, or an array whose axis 1 spans the ``p`` dim. It is re-sliced with
the same display window slice as the data on every update, so the feature carries a value per
displayed datapoint. An array **must** span the **full** ``p`` dim of the data, i.e.
``[n_graphics, p, <value dim>]``, since it is indexed with an index into the full ``p`` dim. A
``FeatureCallable`` is passed the data slice and that display window slice, and returns the feature
values for the displayed datapoints.
* **static**: anything else. It is set once on the collection, ex: a single value for every graphic,
``[n_graphics]`` values for one per graphic, or an iterator of per-graphic values such as
``itertools.cycle(["jet", "viridis"])``.
"""
self._check_slider_dims(dims, display_dims, data, positions=True)
nd = NDPositions(
self.ndw.indices,
self,
data,
dims,
display_dims,
*args,
graphic_type=ScatterCollection,
slicer=slicer,
display_window=display_window,
window_funcs=window_funcs,
window_order=window_order,
spatial_func=spatial_func,
slider_maps=slider_maps,
max_display_datapoints=max_display_datapoints,
datapoints_window_func=datapoints_window_func,
colors=colors,
cmap=cmap,
cmap_transform=cmap_transform,
cmap_range=cmap_range,
sizes=sizes,
markers=markers,
name=name,
graphic_kwargs=graphic_kwargs,
slicer_kwargs=slicer_kwargs,
)
self._nd_graphics.append(nd)
return nd
def add_nd_timeseries(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: tuple[str, str, str],
*args,
graphic_type: type[
LineCollection | LineStack | ScatterCollection | ScatterStack | ImageGraphic
] = LineStack,
x_range_mode: Literal["fixed", "auto"] | None = "auto",
slicer: type[NDPositionsSlicer] = NDPositionsSlicer,
display_window: int | float | None = 10,
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
max_display_datapoints: int | None = 1_000,
datapoints_window_func: tuple[Callable, str, int | float] | None = None,
colors: ColorsType = None,
cmap: str | Sequence[str] = None,
cmap_transform: np.ndarray | FeatureCallable = None,
cmap_range: tuple[float, float] = None,
thickness: float | Sequence[float] = None,
sizes: SizesType = None,
markers: MarkersType = None,
name: str = None,
graphic_kwargs: dict = None,
slicer_kwargs: dict = None,
) -> NDTimeseries:
"""
Add n-dimensional timeseries data to this subplot, where the ``p`` dim is a time-like x-axis.
Every dim that is not listed in ``display_dims`` becomes a slider dim. The datapoints dim, ``p``, is both
a spatial dim and a slider dim, it is windowed by ``display_window`` and ``datapoints_window_func``
rather than by ``window_funcs``.
A ``LinearSelector`` that marks the current index of the ``p`` dim is added to the subplot. Dragging it
sets that index in the ``ReferenceIndex``, so it drives every other graphic that uses this dim. Only one
is created per subplot.
Parameters
----------
data: ArrayProtocol or None
n-dimensional timeseries data. The value dim holds the (x, y) of each datapoint, where x is the
time-like coordinate.
Ex: an array of shape ``[n_trials, n_traces, n_timepoints, 2]`` with ``dims`` of
``("trial", "trace", "time", "xy")`` and ``display_dims`` of ``("trace", "time", "xy")``.
Pass ``None`` to create the ``NDTimeseries`` without a graphic and set the data later using
``nd_timeseries.data``, the slider dims then require an explicit reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order.
display_dims: tuple[str, str, str]
The 3 spatial dims **in display order**: ``(n_graphics, p, <value dim>)``, i.e. the number of traces
in the collection, the number of datapoints ``p`` in each of them, and the value dim which holds the
xy or xyz coordinate. A heatmap requires a value dim of size exactly 2. The dims do not need to be in
this order in the array, the data slice is transposed into display order.
args
extra positional arguments passed to the ``slicer`` constructor.
graphic_type: type[LineCollection | LineStack | ScatterCollection | ScatterStack | ImageGraphic], default ``LineStack``
The graphical representation used to display the data slice. ``ImageGraphic`` renders the traces as a
heatmap, one row per trace, where the color represents the y coordinate. The x coordinates are
applied as the offset and scale of the image, and the y values are interpolated onto a uniform x grid
if the x sampling is not uniform.
x_range_mode: "fixed" | "auto" | None, default "auto"
How the camera x-range is coupled to the ``p`` dim.
* ``None``: the camera is left alone.
* ``"fixed"``: the x-range is set from ``display_window``, centered on the current ``p`` index, on
every update.
* ``"auto"``: as ``"fixed"``, and the camera x-range is also polled on every render. Panning or
zooming then sets ``display_window`` to the new width and the ``p`` index to the new center, with
a lower bound of 3 datapoints on the width.
Forced to ``None`` when ``display_window`` is ``None``.
slicer: type[NDPositionsSlicer], default ``NDPositionsSlicer``
``NDPositionsSlicer`` subclass that manages the data and produces the data slices.
display_window: int, float or None, default 10
Size of the window of the ``p`` dim to render, in the reference units of that dim, centered on its
current index. Use ``None`` to render every datapoint, which also forces ``x_range_mode`` to
``None``. This is what makes out-of-core rendering possible, i.e. rendering a window of a dataset
that is larger than GPU VRAM.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions applied around the current slider position, ex:
``{"trial": (np.mean, 5)}``. Each value is a ``(func, window_size)`` pair where:
* *func* must accept ``axis: int`` and ``keepdims: bool`` kwargs (ex: ``np.mean``, ``np.max``). It
**must** return an array that has the same dims as the input, therefore the size of any dim along
which it was applied should reduce to ``1``. These dims must not be removed by the window func.
* *window_size* is in reference-space units.
Not used for the ``p`` dim, see ``datapoints_window_func``.
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Only dims listed here have their window
function applied, ``window_funcs`` are ignored for any dim not specified in ``window_order``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional
A function applied to the spatial slice *after* the window funcs, right before rendering. It is
given the slice in ``display_dims`` order, i.e. the array as it is rendered, and must return an
array with those same dims.
slider_maps: dict[str, Callable[[Any], int] | ArrayLike], optional
Per-slider-dim mapping from reference-space values to local array indices. An array of reference
values may be given instead of a Callable, ``searchsorted`` is then used as the transform. The
transform for the ``p`` dim is typically the array of x values, ex: a timestamps array, so the
slider is in seconds rather than sample indices. Any dim without a transform uses the identity
mapping, i.e. the current reference value is rounded to the nearest integer and used as the array
index.
max_display_datapoints: int | None, default 1_000
Maximum number of datapoints to render per graphic. The step size of the display window slice is set
from this using floor division. ``None`` renders every datapoint in the window, with no decimation.
Neither ``None`` nor a very large value is recommended: the entire window is then read into RAM and
uploaded, which is slow for a large window over a large array.
datapoints_window_func: tuple[Callable, str, int | float], optional
Window function applied along the ``p`` dim after the display window has been taken, as
``(func, apply_dims, window_size)`` where:
* *func* must accept an ``axis: int`` kwarg (ex: ``np.mean``, ``np.max``). It is given a sliding
window view of the data and is reduced along the window axis.
* *apply_dims* names the coordinates of the value dim to apply it to, one of ``"all", "x", "y",
"z", "xy", "xz", "yz", "xyz"``. Coordinates that are not named are passed through unchanged.
* *window_size* is in the reference units of the ``p`` dim. It is mapped to array indices, clamped to
a minimum of 3, and rounded up to an odd size.
If used, ``display_window`` is approximate and not exact due to padding from the window size.
colors: str | Sequence[str] | np.ndarray | FeatureCallable, optional
Colors of the traces. Mutually exclusive with ``cmap``, setting one clears the other.
* static, a single color for every graphic, ex: ``"cyan"`` or an RGBA sequence of 4 floats
* static, one color per graphic, ``[n_graphics]`` of str or ``[n_graphics, 4]`` RGBA
* windowed, one color per datapoint, ``[n_graphics, p, 4]`` RGBA
* windowed, a ``FeatureCallable``
cmap: str | Sequence[str], optional
Colormap applied to the traces, always static. A single name for every graphic, or an iterable of
``[n_graphics]`` names for a colormap per graphic. Mutually exclusive with ``colors``. It is the only
feature that is carried over to the heatmap representation.
cmap_transform: np.ndarray | FeatureCallable, optional
Values that the colormap colors are mapped from.
* static, one value per graphic, ``[n_graphics]``, so each graphic gets a single color
* windowed, one value per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
cmap_range: (float, float) | np.ndarray, optional
The (min, max) of ``cmap_transform`` mapped onto the colormap, or ``[n_graphics, 2]`` for a range per
graphic. A windowed array ``cmap_transform`` defaults to its own (min, max) over the full ``p`` dim,
so the display window keeps its position within the colormap. A ``FeatureCallable`` transform
requires an explicit range, its full range is not knowable without evaluating it everywhere.
thickness: float | Sequence[float], optional
Thickness of the lines, always static. A single value for every graphic, or ``[n_graphics]`` values
for a thickness per graphic.
sizes: float | Sequence[float] | np.ndarray | FeatureCallable, optional
Size of the scatter points.
* static, a single size for every graphic, or ``[n_graphics]`` sizes for one size per graphic
* windowed, one size per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
markers: str | Sequence[str] | np.ndarray | FeatureCallable, optional
Marker shape of the scatter points.
* static, a single marker for every graphic, or ``[n_graphics]`` markers for one per graphic
* windowed, one marker per datapoint, ``[n_graphics, p]``
* windowed, a ``FeatureCallable``
name: str, optional
Name for this ``NDGraphic``, used to retrieve it with ``nd_subplot[name]``.
graphic_kwargs: dict, optional
passed to the ``graphic_type`` constructor.
slicer_kwargs: dict, optional
passed to the ``slicer`` constructor.
Returns
-------
NDTimeseries
Notes
-----
Each of the other graphic features is either *windowed* or *static*, decided from the value itself:
* **windowed**: a ``FeatureCallable``, or an array whose axis 1 spans the ``p`` dim. It is re-sliced with
the same display window slice as the data on every update, so the feature carries a value per
displayed datapoint. An array **must** span the **full** ``p`` dim of the data, i.e.
``[n_graphics, p, <value dim>]``, since it is indexed with an index into the full ``p`` dim. A
``FeatureCallable`` is passed the data slice and that display window slice, and returns the feature
values for the displayed datapoints.
* **static**: anything else. It is set once on the collection, ex: a single value for every graphic,
``[n_graphics]`` values for one per graphic, or an iterator of per-graphic values such as
``itertools.cycle(["jet", "viridis"])``.
A feature the graphic type does not have is ignored, ex: ``thickness`` for scatters, ``markers`` for
lines. The heatmap representation uses only ``cmap``.
"""
self._check_slider_dims(dims, display_dims, data, positions=True)
nd = NDTimeseries(
self.ndw.indices,
self,
data,
dims,
display_dims,
*args,
graphic_type=graphic_type,
linear_selector=True,
x_range_mode=x_range_mode,
slicer=slicer,
display_window=display_window,
window_funcs=window_funcs,
window_order=window_order,
spatial_func=spatial_func,
slider_maps=slider_maps,
max_display_datapoints=max_display_datapoints,
datapoints_window_func=datapoints_window_func,
colors=colors,
cmap=cmap,
cmap_transform=cmap_transform,
cmap_range=cmap_range,
thickness=thickness,
sizes=sizes,
markers=markers,
name=name,
graphic_kwargs=graphic_kwargs,
slicer_kwargs=slicer_kwargs,
)
self._nd_graphics.append(nd)
return nd
def add_nd_lines(
self,
data: ArrayProtocol | None,
dims: Sequence[str],
display_dims: tuple[str, str, str],
*args,
slicer: type[NDPositionsSlicer] = NDPositionsSlicer,
display_window: int | float | None = 10,
window_funcs: dict[
str, tuple[WindowFuncCallable | None, int | float | None]
] = None,
window_order: tuple[str, ...] = None,
spatial_func: Callable[[ArrayProtocol], ArrayProtocol] = None,
slider_maps: dict[str, Callable[[Any], int] | ArrayLike] = None,
max_display_datapoints: int | None = 1_000,
datapoints_window_func: tuple[Callable, str, int | float] | None = None,
colors: ColorsType = None,
cmap: str | Sequence[str] = None,
cmap_transform: np.ndarray | FeatureCallable = None,
cmap_range: tuple[float, float] = None,
thickness: float | Sequence[float] = None,
name: str = None,
graphic_kwargs: dict = None,
slicer_kwargs: dict = None,
) -> NDPositions:
"""
Add n-dimensional positional data to this subplot, rendered as a ``LineCollection``.
Every dim that is not listed in ``display_dims`` becomes a slider dim. The datapoints dim, ``p``, is both
a spatial dim and a slider dim, it is windowed by ``display_window`` and ``datapoints_window_func``
rather than by ``window_funcs``.
Parameters
----------
data: ArrayProtocol or None
n-dimensional positional data.
Ex: an array of shape ``[n_trials, n_keypoints, n_timepoints, 2]`` with ``dims`` of
``("trial", "keypoint", "time", "xy")`` and ``display_dims`` of ``("keypoint", "time", "xy")``.
Pass ``None`` to create the ``NDPositions`` without a graphic and set the data later using
``nd_positions.data``, the slider dims then require an explicit reference range in the ``NDWidget``.
dims: Sequence[str]
name for every dim of ``data``, in order.
display_dims: tuple[str, str, str]
The 3 spatial dims **in display order**: ``(n_graphics, p, <value dim>)``, i.e. the number of lines
in the collection, the number of datapoints ``p`` in each of them, and the value dim which holds the
xy or xyz coordinate and must be of size 2 or 3. The dims do not need to be in this order in the
array, the data slice is transposed into display order.
args
extra positional arguments passed to the ``slicer`` constructor.
slicer: type[NDPositionsSlicer], default ``NDPositionsSlicer``
``NDPositionsSlicer`` subclass that manages the data and produces the data slices.
display_window: int, float or None, default 10
Size of the window of the ``p`` dim to render, in the reference units of that dim, centered on its
current index. Use ``None`` to render every datapoint, or ``0`` to render only the datapoint at the
current index. This is what makes out-of-core rendering possible, i.e. rendering a window of a
dataset that is larger than GPU VRAM.
window_funcs: dict[str, tuple[WindowFuncCallable | None, int | float | None]], optional
Per-slider-dim window functions applied around the current slider position, ex:
``{"trial": (np.mean, 5)}``. Each value is a ``(func, window_size)`` pair where:
* *func* must accept ``axis: int`` and ``keepdims: bool`` kwargs (ex: ``np.mean``, ``np.max``). It
**must** return an array that has the same dims as the input, therefore the size of any dim along
which it was applied should reduce to ``1``. These dims must not be removed by the window func.
* *window_size* is in reference-space units.
Not used for the ``p`` dim, see ``datapoints_window_func``.
window_order: tuple[str, ...], optional
Order in which the window functions are applied across dims. Only dims listed here have their window
function applied, ``window_funcs`` are ignored for any dim not specified in ``window_order``.
spatial_func: Callable[[ArrayProtocol], ArrayProtocol], optional