-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathline_collection.py
More file actions
658 lines (513 loc) · 21.3 KB
/
line_collection.py
File metadata and controls
658 lines (513 loc) · 21.3 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
from itertools import repeat
from numbers import Number
from typing import *
import numpy as np
import pygfx
from ..utils import parse_cmap_values
from ._collection_base import CollectionIndexer, GraphicCollection, CollectionFeature
from .line import LineGraphic
from .selectors import (
LinearRegionSelector,
LinearSelector,
RectangleSelector,
PolygonSelector,
)
class _LineCollectionProperties:
"""Mix-in class for LineCollection properties"""
@property
def colors(self) -> CollectionFeature:
"""get or set colors of lines in the collection"""
return CollectionFeature(self.graphics, "colors")
@colors.setter
def colors(self, values: str | np.ndarray | tuple[float] | list[float] | list[str]):
if isinstance(values, str):
# set colors of all lines to one str color
for g in self:
g.colors = values
return
elif all(isinstance(v, str) for v in values):
# individual str colors for each line
if not len(values) == len(self):
raise IndexError
for g, v in zip(self.graphics, values):
g.colors = v
return
if isinstance(values, np.ndarray):
if values.ndim == 2:
# assume individual colors for each
for g, v in zip(self, values):
g.colors = v
return
elif len(values) == 4:
# assume RGBA
self.colors[:] = values
else:
# assume individual colors for each
for g, v in zip(self, values):
g.colors = v
@property
def data(self) -> CollectionFeature:
"""get or set data of lines in the collection"""
return CollectionFeature(self.graphics, "data")
@data.setter
def data(self, values):
for g, v in zip(self, values):
g.data = v
@property
def cmap(self) -> CollectionFeature:
"""
Get or set a cmap along the line collection.
Optionally set using a tuple ("cmap", <transform>) to set the transform..
Example:
line_collection.cmap = ("jet", sine_transform_vals, 0.7)
"""
return CollectionFeature(self.graphics, "cmap")
@cmap.setter
def cmap(self, args):
if isinstance(args, str):
name = args
transform = None
elif len(args) == 1:
name = args[0]
transform = None
elif len(args) == 2:
name, transform = args
else:
raise ValueError(
"Too many values for cmap (note that alpha is deprecated, set alpha on the graphic instead)"
)
self.colors = parse_cmap_values(
n_colors=len(self), cmap_name=name, transform=transform
)
@property
def thickness(self) -> np.ndarray:
"""get or set the thickness of the lines"""
return np.asarray([g.thickness for g in self])
@thickness.setter
def thickness(self, values: float | Sequence[float]):
if isinstance(values, Number):
values = repeat(values, len(self))
elif not len(values) == len(self):
raise IndexError
for g, v in zip(self, values):
g.thickness = v
class LineCollectionIndexer(CollectionIndexer, _LineCollectionProperties):
"""Indexer for line collections"""
pass
class LineCollection(GraphicCollection, _LineCollectionProperties):
_child_type = LineGraphic
_indexer = LineCollectionIndexer
def __init__(
self,
data: np.ndarray | List[np.ndarray],
thickness: float | Sequence[float] = 2.0,
colors: str | Sequence[str] | np.ndarray | Sequence[np.ndarray] = "w",
cmap: Sequence[str] | str = None,
cmap_transform: np.ndarray | List = None,
color_mode: Literal["auto", "uniform", "vertex"] = "auto",
name: str = None,
names: list[str] = None,
metadata: Any = None,
metadatas: Sequence[Any] | np.ndarray = None,
kwargs_lines: list[dict] = None,
**kwargs,
):
"""
Create a collection of :class:`.LineGraphic`
Parameters
----------
data: list of array-like
List or array-like of multiple line data to plot
| if ``list`` each item in the list must be a 1D, 2D, or 3D numpy array
| if array-like, must be of shape [n_lines, n_points_line, y | xy | xyz]
thickness: float or Iterable of float, default 2.0
| if ``float``, single thickness will be used for all lines
| if ``list`` of ``float``, each value will apply to the individual lines
colors: str, RGBA array, Iterable of RGBA array, or Iterable of str, default "w"
| if single ``str`` such as "w", "r", "b", etc, represents a single color for all lines
| if single ``RGBA array`` (tuple or list of size 4), represents a single color for all lines
| if ``list`` of ``str``, represents color for each individual line, example ["w", "b", "r",...]
| if ``RGBA array`` of shape [data_size, 4], represents a single RGBA array for each line
cmap: Iterable of str or str, optional
| if ``str``, single cmap will be used for all lines
| if ``list`` of ``str``, each cmap will apply to the individual lines
.. note::
``cmap`` overrides any arguments passed to ``colors``
cmap_transform: 1D array-like of numerical values, optional
if provided, these values are used to map the colors from the cmap
color_mode: one of "auto", "uniform", "vertex", default "auto"
The color mode for each line in the collection. See `color_mode` in :class:`.LineGraphic` for details.
name: str, optional
name of the line collection as a whole
names: list[str], optional
names of the individual lines in the collection, ``len(names)`` must equal ``len(data)``
metadata: Any
meatadata associated with the collection as a whole
metadatas: Iterable or array
metadata for each individual line associated with this collection, this is for the user to manage.
``len(metadata)`` must be same as ``len(data)``
kwargs_lines: list[dict], optional
list of kwargs passed to the individual lines, ``len(kwargs_lines)`` must equal ``len(data)``
kwargs_collection
kwargs for the collection, passed to GraphicCollection
"""
super().__init__(name=name, metadata=metadata, **kwargs)
if not isinstance(thickness, (float, int)):
if len(thickness) != len(data):
raise ValueError(
f"len(thickness) != len(data)\n{len(thickness)} != {len(data)}"
)
if names is not None:
if len(names) != len(data):
raise ValueError(
f"len(names) != len(data)\n{len(names)} != {len(data)}"
)
if metadatas is not None:
if len(metadatas) != len(data):
raise ValueError(
f"len(metadata) != len(data)\n{len(metadatas)} != {len(data)}"
)
if kwargs_lines is not None:
if len(kwargs_lines) != len(data):
raise ValueError(
f"len(kwargs_lines) != len(data)\n"
f"{len(kwargs_lines)} != {len(data)}"
)
self._cmap_transform = cmap_transform
self._cmap_str = cmap
# cmap takes priority over colors
if cmap is not None:
# cmap across lines
if isinstance(cmap, str):
colors = parse_cmap_values(
n_colors=len(data), cmap_name=cmap, transform=cmap_transform
)
single_color = False
cmap = None
elif isinstance(cmap, (tuple, list)):
if len(cmap) != len(data):
raise ValueError(
"cmap argument must be a single cmap or a list of cmaps "
"with the same length as the data"
)
single_color = False
else:
raise ValueError(
"cmap argument must be a single cmap or a list of cmaps "
"with the same length as the data"
)
else:
if isinstance(colors, np.ndarray):
# single color for all lines in the collection as RGBA
if colors.shape in [(3,), (4,)]:
single_color = True
# colors specified for each line as array of shape [n_lines, RGBA]
elif colors.shape == (len(data), 4):
single_color = False
else:
raise ValueError(
f"numpy array colors argument must be of shape (4,) or (n_lines, 4)."
f"You have pass the following shape: {colors.shape}"
)
elif isinstance(colors, str):
if colors == "random":
colors = np.random.rand(len(data), 3)
single_color = False
else:
# parse string color
single_color = True
colors = pygfx.Color(colors)
elif isinstance(colors, (tuple, list)):
if len(colors) == 4:
# single color specified as (R, G, B, A) tuple or list
if all([isinstance(c, (float, int)) for c in colors]):
single_color = True
elif len(colors) == len(data):
# colors passed as list/tuple of colors, such as list of string
single_color = False
else:
raise ValueError(
"tuple or list colors argument must be a single color represented as [R, G, B, A], "
"or must be a tuple/list of colors represented by a string with the same length as the data"
)
if kwargs_lines is None:
kwargs_lines = dict()
self._set_world_object(pygfx.Group())
for i, d in enumerate(data):
if isinstance(thickness, list):
_s = thickness[i]
else:
_s = thickness
if cmap is None:
_cmap = None
if single_color:
_c = colors
else:
_c = colors[i]
else:
_cmap = cmap[i]
_c = None
C2EF
if metadatas is not None:
_m = metadatas[i]
else:
_m = None
if names is not None:
_name = names[i]
else:
_name = None
lg = LineGraphic(
data=d,
thickness=_s,
colors=_c,
cmap=_cmap,
color_mode=color_mode,
name=_name,
metadata=_m,
**kwargs_lines,
)
self.add_graphic(lg)
def __getitem__(self, item) -> LineCollectionIndexer:
return super().__getitem__(item)
def add_linear_selector(
self, selection: float = None, padding: float = 0.0, axis: str = "x", **kwargs
) -> LinearSelector:
"""
Adds a linear selector.
Parameters
----------
Parameters
----------
selection: float, optional
selected point on the linear selector, computed from data if not provided
axis: str, default "x"
axis that the selector resides on
padding: float, default 0.0
Extra padding to extend the linear selector along the orthogonal axis to make it easier to interact with.
kwargs
passed to :class:`.LinearSelector`
Returns
-------
LinearSelector
"""
bounds_init, limits, size, center = self._get_linear_selector_init_args(
axis, padding
)
if selection is None:
selection = bounds_init[0]
selector = LinearSelector(
selection=selection,
limits=limits,
axis=axis,
parent=self,
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
return selector
def add_linear_region_selector(
self,
selection: tuple[float, float] = None,
padding: float = 0.0,
axis: str = "x",
**kwargs,
) -> LinearRegionSelector:
"""
Add a :class:`.LinearRegionSelector`. Selectors are just ``Graphic`` objects, so you can manage,
remove, or delete them from a plot area just like any other ``Graphic``.
Parameters
----------
selection: (float, float), optional
the starting bounds of the linear region selector, computed from data if not provided
axis: str, default "x"
axis that the selector resides on
padding: float, default 0.0
Extra padding to extend the linear region selector along the orthogonal axis to make it easier to interact with.
kwargs
passed to ``LinearRegionSelector``
Returns
-------
LinearRegionSelector
linear selection graphic
"""
bounds_init, limits, size, center = self._get_linear_selector_init_args(
axis, padding
)
if selection is None:
selection = bounds_init
# create selector
selector = LinearRegionSelector(
selection=selection,
limits=limits,
size=size,
center=center,
axis=axis,
parent=self,
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
# PlotArea manages this for garbage collection etc. just like all other Graphics
# so we should only work with a proxy on the user-end
return selector
def add_rectangle_selector(
self,
selection: tuple[float, float, float] = None,
**kwargs,
) -> RectangleSelector:
"""
Add a :class:`.RectangleSelector`. Selectors are just ``Graphic`` objects, so you can manage,
remove, or delete them from a plot area just like any other ``Graphic``.
Parameters
----------
selection: (float, float, float, float), optional
initial (xmin, xmax, ymin, ymax) of the selection
"""
bbox = self.world_object.get_world_bounding_box()
xdata = np.array(self.data[:, 0])
xmin, xmax = (np.nanmin(xdata), np.nanmax(xdata))
value_25px = (xmax - xmin) / 4
ydata = np.array(self.data[:, 1])
ymin = np.floor(ydata.min()).astype(int)
ymax = np.ptp(bbox[:, 1])
if selection is None:
selection = (xmin, value_25px, ymin, ymax)
limits = (xmin, xmax, ymin - (ymax * 1.5 - ymax), ymax * 1.5)
selector = RectangleSelector(
selection=selection,
limits=limits,
parent=self,
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
return selector
def add_polygon_selector(
self,
selection: List[tuple[float, float]] = None,
**kwargs,
) -> PolygonSelector:
"""
Add a :class:`.PolygonSelector`. Selectors are just ``Graphic`` objects, so you can manage,
remove, or delete them from a plot area just like any other ``Graphic``.
Parameters
----------
selection: list[tuple[float, float]], optional
Initial points for the polygon. If not given or None, you'll start drawing the selection (clicking adds points to the polygon).
"""
bbox = self.world_object.get_world_bounding_box()
xdata = np.array(self.data[:, 0])
xmin, xmax = (np.nanmin(xdata), np.nanmax(xdata))
ydata = np.array(self.data[:, 1])
ymin = np.floor(ydata.min()).astype(int)
ymax = np.ptp(bbox[:, 1])
limits = (xmin, xmax, ymin - (ymax * 1.5 - ymax), ymax * 1.5)
selector = PolygonSelector(
selection,
limits,
parent=self,
**kwargs,
)
self._plot_area.add_graphic(selector, center=False)
return selector
def _get_linear_selector_init_args(self, axis, padding):
# use bbox to get size and center
bbox = self.world_object.get_world_bounding_box()
if axis == "x":
xdata = np.array(self.data[:, 0])
xmin, xmax = (np.nanmin(xdata), np.nanmax(xdata))
value_25p = (xmax - xmin) / 4
bounds = (xmin, value_25p)
limits = (xmin, xmax)
# size from orthogonal axis
size = np.ptp(bbox[:, 1]) * 1.5
# center on orthogonal axis
center = bbox[:, 1].mean()
elif axis == "y":
ydata = np.array(self.data[:, 1])
xmin, xmax = (np.nanmin(ydata), np.nanmax(ydata))
value_25p = (xmax - xmin) / 4
bounds = (xmin, value_25p)
limits = (xmin, xmax)
size = np.ptp(bbox[:, 0]) * 1.5
# center on orthogonal axis
center = bbox[:, 0].mean()
return bounds, limits, size, center
axes = {"x": 0, "y": 1, "z": 2}
class LineStack(LineCollection):
def __init__(
self,
data: List[np.ndarray],
thickness: float | Iterable[float] = 2.0,
colors: str | Iterable[str] | np.ndarray | Iterable[np.ndarray] = "w",
cmap: Iterable[str] | str = None,
cmap_transform: np.ndarray | List = None,
name: str = None,
names: list[str] = None,
metadata: Any = None,
metadatas: Sequence[Any] | np.ndarray = None,
separation: float = 10.0,
separation_axis: str = "y",
kwargs_lines: list[dict] = None,
**kwargs,
):
"""
Create a stack of :class:`.LineGraphic` that are separated along the "x" or "y" axis.
Parameters
----------
data: list of array-like
List or array-like of multiple line data to plot
| if ``list`` each item in the list must be a 1D, 2D, or 3D numpy array
| if array-like, must be of shape [n_lines, n_points_line, y | xy | xyz]
thickness: float or Iterable of float, default 2.0
| if ``float``, single thickness will be used for all lines
| if ``list`` of ``float``, each value will apply to the individual lines
colors: str, RGBA array, Iterable of RGBA array, or Iterable of str, default "w"
| if single ``str`` such as "w", "r", "b", etc, represents a single color for all lines
| if single ``RGBA array`` (tuple or list of size 4), represents a single color for all lines
| if ``list`` of ``str``, represents color for each individual line, example ["w", "b", "r",...]
| if ``RGBA array`` of shape [data_size, 4], represents a single RGBA array for each line
cmap: Iterable of str or str, optional
| if ``str``, single cmap will be used for all lines
| if ``list`` of ``str``, each cmap will apply to the individual lines
.. note::
``cmap`` overrides any arguments passed to ``colors``
cmap_transform: 1D array-like of numerical values, optional
if provided, these values are used to map the colors from the cmap
name: str, optional
name of the line collection as a whole
names: list[str], optional
names of the individual lines in the collection, ``len(names)`` must equal ``len(data)``
metadata: Any
metadata associated with the collection as a whole
metadatas: Iterable or array
metadata for each individual line associated with this collection, this is for the user to manage.
``len(metadata)`` must be same as ``len(data)``
separation: float, default 10
space in between each line graphic in the stack
separation_axis: str, default "y"
axis in which the line graphics in the stack should be separated
kwargs_lines: list[dict], optional
list of kwargs passed to the individual lines, ``len(kwargs_lines)`` must equal ``len(data)``
kwargs_collection
kwargs for the collection, passed to GraphicCollection
"""
super().__init__(
data=data,
thickness=thickness,
colors=colors,
cmap=cmap,
cmap_transform=cmap_transform,
name=name,
names=names,
metadata=metadata,
metadatas=metadatas,
kwargs_lines=kwargs_lines,
**kwargs,
)
axis_zero = 0
for i, line in enumerate(self.graphics):
if separation_axis == "x":
line.offset = (axis_zero, *line.offset[1:])
elif separation_axis == "y":
line.offset = (line.offset[0], axis_zero, line.offset[2])
axis_zero = (
axis_zero + line.data.value[:, axes[separation_axis]].max() + separation
)
self.separation = separation