-
-
Notifications
You must be signed in to change notification settings - Fork 410
/
base.py
1799 lines (1562 loc) · 61.6 KB
/
base.py
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
from __future__ import annotations
import itertools
import os.path
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict, namedtuple
from contextlib import contextmanager
from functools import cached_property
from typing import List, Optional, Tuple, Union
import magicgui as mgui
import numpy as np
from npe2 import plugin_manager as pm
from napari.layers.base._base_constants import Blending
from napari.layers.utils._slice_input import _SliceInput
from napari.layers.utils.interactivity_utils import (
drag_data_to_projected_distance,
)
from napari.layers.utils.layer_utils import (
coerce_affine,
compute_multiscale_level_and_corners,
convert_to_uint8,
dims_displayed_world_to_layer,
get_extent_world,
)
from napari.layers.utils.plane import ClippingPlane, ClippingPlaneList
from napari.utils._dask_utils import configure_dask
from napari.utils._magicgui import (
add_layer_to_viewer,
add_layers_to_viewer,
get_layers,
)
from napari.utils.events import EmitterGroup, Event
from napari.utils.events.event import WarningEmitter
from napari.utils.geometry import (
find_front_back_face,
intersect_line_with_axis_aligned_bounding_box_3d,
)
from napari.utils.key_bindings import KeymapProvider
from napari.utils.mouse_bindings import MousemapProvider
from napari.utils.naming import magic_name
from napari.utils.status_messages import generate_layer_coords_status
from napari.utils.transforms import Affine, CompositeAffine, TransformChain
from napari.utils.translations import trans
Extent = namedtuple('Extent', 'data world step')
def no_op(layer: Layer, event: Event) -> None:
"""
A convenient no-op event for the layer mouse binding.
This makes it easier to handle many cases by inserting this as
as place holder
Parameters
----------
layer : Layer
Current layer on which this will be bound as a callback
event : Event
event that triggered this mouse callback.
Returns
-------
None
"""
return None
@mgui.register_type(choices=get_layers, return_callback=add_layer_to_viewer)
class Layer(KeymapProvider, MousemapProvider, ABC):
"""Base layer class.
Parameters
----------
name : str
Name of the layer.
metadata : dict
Layer metadata.
scale : tuple of float
Scale factors for the layer.
translate : tuple of float
Translation values for the layer.
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll convention. Otherwise assume an nD rotation. Angles are
assumed to be in degrees. They can be converted from radians with
np.degrees if needed.
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
affine : n-D array or napari.utils.transforms.Affine
(N+1, N+1) affine transformation matrix in homogeneous coordinates.
The first (N, N) entries correspond to a linear transform and
the final column is a length N translation vector and a 1 or a napari
`Affine` transform object. Applied as an extra transform on top of the
provided scale, rotate, and shear values.
opacity : float
Opacity of the layer visual, between 0.0 and 1.0.
blending : str
One of a list of preset blending modes that determines how RGB and
alpha values of the layer visual get mixed. Allowed values are
{'opaque', 'translucent', 'translucent_no_depth', 'additive', and 'minimum'}.
visible : bool
Whether the layer visual is currently being displayed.
multiscale : bool
Whether the data is multiscale or not. Multiscale data is
represented by a list of data objects and should go from largest to
smallest.
Attributes
----------
name : str
Unique name of the layer.
opacity : float
Opacity of the layer visual, between 0.0 and 1.0.
visible : bool
Whether the layer visual is currently being displayed.
blending : Blending
Determines how RGB and alpha values get mixed.
* ``Blending.OPAQUE``
Allows for only the top layer to be visible and corresponds to
``depth_test=True``, ``cull_face=False``, ``blend=False``.
* ``Blending.TRANSLUCENT``
Allows for multiple layers to be blended with different opacity and
corresponds to ``depth_test=True``, ``cull_face=False``,
``blend=True``, ``blend_func=('src_alpha', 'one_minus_src_alpha')``,
and ``blend_equation=('func_add')``.
* ``Blending.TRANSLUCENT_NO_DEPTH``
Allows for multiple layers to be blended with different opacity, but
no depth testing is performed. Corresponds to ``depth_test=False``,
``cull_face=False``, ``blend=True``,
``blend_func=('src_alpha', 'one_minus_src_alpha')``, and
``blend_equation=('func_add')``.
* ``Blending.ADDITIVE``
Allows for multiple layers to be blended together with different
colors and opacity. Useful for creating overlays. It corresponds to
``depth_test=False``, ``cull_face=False``, ``blend=True``,
``blend_func=('src_alpha', 'one')``, and ``blend_equation=('func_add')``.
* ``Blending.MINIMUM``
Allows for multiple layers to be blended together such that
the minimum of each RGB component and alpha are selected.
Useful for creating overlays with inverted colormaps. It
corresponds to ``depth_test=False``, ``cull_face=False``, ``blend=True``,
``blend_equation=('min')``.
scale : tuple of float
Scale factors for the layer.
translate : tuple of float
Translation values for the layer.
rotate : float, 3-tuple of float, or n-D array.
If a float convert into a 2D rotation matrix using that value as an
angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,
pitch, roll convention. Otherwise assume an nD rotation. Angles are
assumed to be in degrees. They can be converted from radians with
np.degrees if needed.
shear : 1-D array or n-D array
Either a vector of upper triangular values, or an nD shear matrix with
ones along the main diagonal.
affine : n-D array or napari.utils.transforms.Affine
(N+1, N+1) affine transformation matrix in homogeneous coordinates.
The first (N, N) entries correspond to a linear transform and
the final column is a length N translation vector and a 1 or a napari
`Affine` transform object. Applied as an extra transform on top of the
provided scale, rotate, and shear values.
multiscale : bool
Whether the data is multiscale or not. Multiscale data is
represented by a list of data objects and should go from largest to
smallest.
cache : bool
Whether slices of out-of-core datasets should be cached upon retrieval.
Currently, this only applies to dask arrays.
z_index : int
Depth of the layer visual relative to other visuals in the scenecanvas.
corner_pixels : array
Coordinates of the top-left and bottom-right canvas pixels in the data
coordinates of each layer. For multiscale data the coordinates are in
the space of the currently viewed data level, not the highest resolution
level.
ndim : int
Dimensionality of the layer.
thumbnail : (N, M, 4) array
Array of thumbnail data for the layer.
status : str
Displayed in status bar bottom left.
help : str
Displayed in status bar bottom right.
interactive : bool
Determine if canvas pan/zoom interactivity is enabled.
cursor : str
String identifying which cursor displayed over canvas.
cursor_size : int | None
Size of cursor if custom. None yields default size
scale_factor : float
Conversion factor from canvas coordinates to image coordinates, which
depends on the current zoom level.
source : Source
source of the layer (such as a plugin or widget)
Notes
-----
Must define the following:
* `_extent_data`: property
* `data` property (setter & getter)
May define the following:
* `_set_view_slice()`: called to set currently viewed slice
* `_basename()`: base/default name of the layer
"""
def __init__(
self,
data,
ndim,
*,
name=None,
metadata=None,
scale=None,
translate=None,
rotate=None,
shear=None,
affine=None,
opacity=1,
blending='translucent',
visible=True,
multiscale=False,
cache=True, # this should move to future "data source" object.
experimental_clipping_planes=None,
):
super().__init__()
if name is None and data is not None:
name = magic_name(data)
if scale is not None and not np.all(scale):
raise ValueError(
trans._(
"Layer {name} is invalid because it has scale values of 0. The layer's scale is currently {scale}",
deferred=True,
name=repr(name),
scale=repr(scale),
)
)
# Needs to be imported here to avoid circular import in _source
from napari.layers._source import current_source
self._source = current_source()
self.dask_optimized_slicing = configure_dask(data, cache)
self._metadata = dict(metadata or {})
self._opacity = opacity
self._blending = Blending(blending)
self._visible = visible
self._freeze = False
self._status = 'Ready'
self._help = ''
self._cursor = 'standard'
self._cursor_size = 1
self._interactive = True
self._value = None
self.scale_factor = 1
self.multiscale = multiscale
self._experimental_clipping_planes = ClippingPlaneList()
self._ndim = ndim
self._slice_input = _SliceInput(
ndisplay=2,
point=(0,) * ndim,
order=tuple(range(ndim)),
)
# Create a transform chain consisting of four transforms:
# 1. `tile2data`: An initial transform only needed to display tiles
# of an image. It maps pixels of the tile into the coordinate space
# of the full resolution data and can usually be represented by a
# scale factor and a translation. A common use case is viewing part
# of lower resolution level of a multiscale image, another is using a
# downsampled version of an image when the full image size is larger
# than the maximum allowed texture size of your graphics card.
# 2. `data2physical`: The main transform mapping data to a world-like
# physical coordinate that may also encode acquisition parameters or
# sample spacing.
# 3. `physical2world`: An extra transform applied in world-coordinates that
# typically aligns this layer with another.
# 4. `world2grid`: An additional transform mapping world-coordinates
# into a grid for looking at layers side-by-side.
if scale is None:
scale = [1] * ndim
if translate is None:
translate = [0] * ndim
self._transforms = TransformChain(
[
Affine(np.ones(ndim), np.zeros(ndim), name='tile2data'),
CompositeAffine(
scale,
translate,
rotate=rotate,
shear=shear,
ndim=ndim,
name='data2physical',
),
coerce_affine(affine, ndim=ndim, name='physical2world'),
Affine(np.ones(ndim), np.zeros(ndim), name='world2grid'),
]
)
self.corner_pixels = np.zeros((2, ndim), dtype=int)
self._editable = True
self._array_like = False
self._thumbnail_shape = (32, 32, 4)
self._thumbnail = np.zeros(self._thumbnail_shape, dtype=np.uint8)
self._update_properties = True
self._name = ''
self.experimental_clipping_planes = experimental_clipping_planes
self.events = EmitterGroup(
source=self,
refresh=Event,
set_data=Event,
blending=Event,
opacity=Event,
visible=Event,
scale=Event,
translate=Event,
rotate=Event,
shear=Event,
affine=Event,
data=Event,
name=Event,
thumbnail=Event,
status=Event,
help=Event,
interactive=Event,
cursor=Event,
cursor_size=Event,
editable=Event,
loaded=Event,
extent=Event,
_ndisplay=Event,
select=WarningEmitter(
trans._(
"'layer.events.select' is deprecated and will be removed in napari v0.4.9, use 'viewer.layers.selection.events.changed' instead, and inspect the 'added' attribute on the event.",
deferred=True,
),
type='select',
),
deselect=WarningEmitter(
trans._(
"'layer.events.deselect' is deprecated and will be removed in napari v0.4.9, use 'viewer.layers.selection.events.changed' instead, and inspect the 'removed' attribute on the event.",
deferred=True,
),
type='deselect',
),
)
self.name = name
def __str__(self):
"""Return self.name."""
return self.name
def __repr__(self):
cls = type(self)
return f"<{cls.__name__} layer {repr(self.name)} at {hex(id(self))}>"
def _mode_setter_helper(self, mode, Modeclass):
"""
Helper to manage callbacks in multiple layers
Parameters
----------
mode : Modeclass | str
New mode for the current layer.
Modeclass : Enum
Enum for the current class representing the modes it can takes,
this is usually specific on each subclass.
Returns
-------
tuple (new Mode, mode changed)
"""
mode = Modeclass(mode)
assert mode is not None
if not self.editable:
mode = Modeclass.PAN_ZOOM
if mode == self._mode:
return mode, False
if mode.value not in Modeclass.keys():
raise ValueError(
trans._(
"Mode not recognized: {mode}", deferred=True, mode=mode
)
)
old_mode = self._mode
self._mode = mode
for callback_list, mode_dict in [
(self.mouse_drag_callbacks, self._drag_modes),
(self.mouse_move_callbacks, self._move_modes),
(
self.mouse_double_click_callbacks,
getattr(
self, '_double_click_modes', defaultdict(lambda: no_op)
),
),
]:
if mode_dict[old_mode] in callback_list:
callback_list.remove(mode_dict[old_mode])
callback_list.append(mode_dict[mode])
self.cursor = self._cursor_modes[mode]
self.interactive = mode == Modeclass.PAN_ZOOM
return mode, True
@classmethod
def _basename(cls):
return f'{cls.__name__}'
@property
def name(self):
"""str: Unique name of the layer."""
return self._name
@name.setter
def name(self, name):
if name == self.name:
return
if not name:
name = self._basename()
self._name = str(name)
self.events.name()
@property
def metadata(self) -> dict:
"""Key/value map for user-stored data."""
return self._metadata
@metadata.setter
def metadata(self, value: dict) -> None:
self._metadata.clear()
self._metadata.update(value)
@property
def source(self):
return self._source
@property
def loaded(self) -> bool:
"""Return True if this layer is fully loaded in memory.
This base class says that layers are permanently in the loaded state.
Derived classes that do asynchronous loading can override this.
"""
return True
@property
def opacity(self):
"""float: Opacity value between 0.0 and 1.0."""
return self._opacity
@opacity.setter
def opacity(self, opacity):
if not 0.0 <= opacity <= 1.0:
raise ValueError(
trans._(
'opacity must be between 0.0 and 1.0; got {opacity}',
deferred=True,
opacity=opacity,
)
)
self._opacity = opacity
self._update_thumbnail()
self.events.opacity()
@property
def blending(self):
"""Blending mode: Determines how RGB and alpha values get mixed.
Blending.OPAQUE
Allows for only the top layer to be visible and corresponds to
depth_test=True, cull_face=False, blend=False.
Blending.TRANSLUCENT
Allows for multiple layers to be blended with different opacity
and corresponds to depth_test=True, cull_face=False,
blend=True, blend_func=('src_alpha', 'one_minus_src_alpha'),
and blend_equation=('func_add').
Blending.TRANSLUCENT_NO_DEPTH
Allows for multiple layers to be blended with different opacity, but
no depth testing is performed. Corresponds to ``depth_test=False``,
cull_face=False, blend=True, blend_func=('src_alpha', 'one_minus_src_alpha'),
and blend_equation=('func_add').
Blending.ADDITIVE
Allows for multiple layers to be blended together with
different colors and opacity. Useful for creating overlays. It
corresponds to depth_test=False, cull_face=False, blend=True,
blend_func=('src_alpha', 'one'), and blend_equation=('func_add').
Blending.MINIMUM
Allows for multiple layers to be blended together such that
the minimum of each RGB component and alpha are selected.
Useful for creating overlays with inverted colormaps. It
corresponds to depth_test=False, cull_face=False, blend=True,
blend_equation=('min').
"""
return str(self._blending)
@blending.setter
def blending(self, blending):
self._blending = Blending(blending)
self.events.blending()
@property
def visible(self):
"""bool: Whether the visual is currently being displayed."""
return self._visible
@visible.setter
def visible(self, visibility):
self._visible = visibility
self.refresh()
self.events.visible()
self.editable = self._set_editable() if self.visible else False
@property
def editable(self):
"""bool: Whether the current layer data is editable from the viewer."""
return self._editable
@editable.setter
def editable(self, editable):
if self._editable == editable:
return
self._editable = editable
self._set_editable(editable=editable)
self.events.editable()
@property
def scale(self):
"""list: Anisotropy factors to scale data into world coordinates."""
return self._transforms['data2physical'].scale
@scale.setter
def scale(self, scale):
if scale is None:
scale = [1] * self.ndim
self._transforms['data2physical'].scale = np.array(scale)
self._clear_extent()
self.events.scale()
@property
def translate(self):
"""list: Factors to shift the layer by in units of world coordinates."""
return self._transforms['data2physical'].translate
@translate.setter
def translate(self, translate):
self._transforms['data2physical'].translate = np.array(translate)
self._clear_extent()
self.events.translate()
@property
def rotate(self):
"""array: Rotation matrix in world coordinates."""
return self._transforms['data2physical'].rotate
@rotate.setter
def rotate(self, rotate):
self._transforms['data2physical'].rotate = rotate
self._clear_extent()
self.events.rotate()
@property
def shear(self):
"""array: Shear matrix in world coordinates."""
return self._transforms['data2physical'].shear
@shear.setter
def shear(self, shear):
self._transforms['data2physical'].shear = shear
self._clear_extent()
self.events.shear()
@property
def affine(self):
"""napari.utils.transforms.Affine: Extra affine transform to go from physical to world coordinates."""
return self._transforms['physical2world']
@affine.setter
def affine(self, affine):
# Assignment by transform name is not supported by TransformChain and
# EventedList, so use the integer index instead. For more details, see:
# https://github.com/napari/napari/issues/3058
self._transforms[2] = coerce_affine(
affine, ndim=self.ndim, name='physical2world'
)
self._clear_extent()
self.events.affine()
@property
def translate_grid(self):
warnings.warn(
trans._(
"translate_grid will become private in v0.4.14. See Layer.translate or Layer.data_to_world() instead.",
),
DeprecationWarning,
stacklevel=2,
)
return self._translate_grid
@translate_grid.setter
def translate_grid(self, translate_grid):
warnings.warn(
trans._(
"translate_grid will become private in v0.4.14. See Layer.translate or Layer.data_to_world() instead.",
),
DeprecationWarning,
stacklevel=2,
)
self._translate_grid = translate_grid
@property
def _translate_grid(self):
"""list: Factors to shift the layer by."""
return self._transforms['world2grid'].translate
@_translate_grid.setter
def _translate_grid(self, translate_grid):
if np.all(self._translate_grid == translate_grid):
return
self._transforms['world2grid'].translate = np.array(translate_grid)
self.events.translate()
@property
def _is_moving(self):
return self._private_is_moving
@_is_moving.setter
def _is_moving(self, value):
assert value in (True, False)
if value:
assert self._moving_coordinates is not None
self._private_is_moving = value
def _update_dims(self):
"""Update the dimensionality of transforms and slices when data changes."""
ndim = self._get_ndim()
old_ndim = self._ndim
if old_ndim > ndim:
keep_axes = range(old_ndim - ndim, old_ndim)
self._transforms = self._transforms.set_slice(keep_axes)
elif old_ndim < ndim:
new_axes = range(ndim - old_ndim)
self._transforms = self._transforms.expand_dims(new_axes)
self._slice_input = self._slice_input.with_ndim(ndim)
self._ndim = ndim
self._clear_extent()
@property
@abstractmethod
def data(self):
# user writes own docstring
raise NotImplementedError()
@data.setter
@abstractmethod
def data(self, data):
raise NotImplementedError()
@property
@abstractmethod
def _extent_data(self) -> np.ndarray:
"""Extent of layer in data coordinates.
Returns
-------
extent_data : array, shape (2, D)
"""
raise NotImplementedError()
@property
def _extent_world(self) -> np.ndarray:
"""Range of layer in world coordinates.
Returns
-------
extent_world : array, shape (2, D)
"""
# Get full nD bounding box
return get_extent_world(
self._extent_data, self._data_to_world, self._array_like
)
@cached_property
def extent(self) -> Extent:
"""Extent of layer in data and world coordinates."""
extent_data = self._extent_data
data_to_world = self._data_to_world
extent_world = get_extent_world(
extent_data, data_to_world, self._array_like
)
return Extent(
data=extent_data,
world=extent_world,
step=abs(data_to_world.scale),
)
def _clear_extent(self):
"""Clears the cached extent.
This should be called whenever this data or transform information
changes, and should be called before any related events get emitted
so that they use the updated extent values.
"""
if 'extent' in self.__dict__:
del self.extent
self.events.extent()
self.refresh()
@property
def _slice_indices(self):
"""(D, ) array: Slice indices in data coordinates."""
if len(self._slice_input.not_displayed) == 0:
# All dims are displayed dimensions
return (slice(None),) * self.ndim
return self._slice_input.data_indices(
self._data_to_world.inverse,
getattr(self, '_round_index', True),
)
@abstractmethod
def _get_ndim(self):
raise NotImplementedError()
def _set_editable(self, editable=None):
if editable is None:
self.editable = True
def _get_base_state(self):
"""Get dictionary of attributes on base layer.
Returns
-------
state : dict
Dictionary of attributes on base layer.
"""
base_dict = {
'name': self.name,
'metadata': self.metadata,
'scale': list(self.scale),
'translate': list(self.translate),
'rotate': [list(r) for r in self.rotate],
'shear': list(self.shear),
'affine': self.affine.affine_matrix,
'opacity': self.opacity,
'blending': self.blending,
'visible': self.visible,
'experimental_clipping_planes': [
plane.dict() for plane in self.experimental_clipping_planes
],
}
return base_dict
@abstractmethod
def _get_state(self):
raise NotImplementedError()
@property
def _type_string(self):
return self.__class__.__name__.lower()
def as_layer_data_tuple(self):
state = self._get_state()
state.pop('data', None)
return self.data, state, self._type_string
@property
def thumbnail(self):
"""array: Integer array of thumbnail for the layer"""
return self._thumbnail
@thumbnail.setter
def thumbnail(self, thumbnail):
if 0 in thumbnail.shape:
thumbnail = np.zeros(self._thumbnail_shape, dtype=np.uint8)
if thumbnail.dtype != np.uint8:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
thumbnail = convert_to_uint8(thumbnail)
padding_needed = np.subtract(self._thumbnail_shape, thumbnail.shape)
pad_amounts = [(p // 2, (p + 1) // 2) for p in padding_needed]
thumbnail = np.pad(thumbnail, pad_amounts, mode='constant')
# blend thumbnail with opaque black background
background = np.zeros(self._thumbnail_shape, dtype=np.uint8)
background[..., 3] = 255
f_dest = thumbnail[..., 3][..., None] / 255
f_source = 1 - f_dest
thumbnail = thumbnail * f_dest + background * f_source
self._thumbnail = thumbnail.astype(np.uint8)
self.events.thumbnail()
@property
def ndim(self):
"""int: Number of dimensions in the data."""
return self._ndim
@property
def help(self):
"""str: displayed in status bar bottom right."""
return self._help
@help.setter
def help(self, help):
if help == self.help:
return
self._help = help
self.events.help(help=help)
@property
def interactive(self):
"""bool: Determine if canvas pan/zoom interactivity is enabled."""
return self._interactive
@interactive.setter
def interactive(self, interactive):
if interactive == self._interactive:
return
self._interactive = interactive
self.events.interactive(interactive=interactive)
@property
def cursor(self):
"""str: String identifying cursor displayed over canvas."""
return self._cursor
@cursor.setter
def cursor(self, cursor):
if cursor == self.cursor:
return
self._cursor = cursor
self.events.cursor(cursor=cursor)
@property
def cursor_size(self):
"""int | None: Size of cursor if custom. None yields default size."""
return self._cursor_size
@cursor_size.setter
def cursor_size(self, cursor_size):
if cursor_size == self.cursor_size:
return
self._cursor_size = cursor_size
self.events.cursor_size(cursor_size=cursor_size)
@property
def experimental_clipping_planes(self):
return self._experimental_clipping_planes
@experimental_clipping_planes.setter
def experimental_clipping_planes(
self,
value: Union[
dict,
ClippingPlane,
List[Union[ClippingPlane, dict]],
ClippingPlaneList,
],
):
self._experimental_clipping_planes.clear()
if value is None:
return
if isinstance(value, (ClippingPlane, dict)):
value = [value]
for new_plane in value:
plane = ClippingPlane()
plane.update(new_plane)
self._experimental_clipping_planes.append(plane)
def set_view_slice(self):
with self.dask_optimized_slicing():
self._set_view_slice()
@abstractmethod
def _set_view_slice(self):
raise NotImplementedError()
def _slice_dims(self, point=None, ndisplay=2, order=None):
"""Slice data with values from a global dims model.
Note this will likely be moved off the base layer soon.
Parameters
----------
point : list
Values of data to slice at in world coordinates.
ndisplay : int
Number of dimensions to be displayed.
order : list of int
Order of dimensions, where last `ndisplay` will be
rendered in canvas.
"""
slice_input = self._make_slice_input(point, ndisplay, order)
if self._slice_input == slice_input:
return
old_ndisplay = self._slice_input.ndisplay
self._slice_input = slice_input
if old_ndisplay != ndisplay:
self.events._ndisplay()
self.refresh()
self._set_editable()
def _make_slice_input(
self, point=None, ndisplay=2, order=None
) -> _SliceInput:
if point is None:
point = (0,) * self.ndim
else:
point = tuple(point)
ndim = len(point)
if order is None:
order = tuple(range(ndim))
# Correspondence between dimensions across all layers and
# dimensions of this layer.
point = point[-self.ndim :]
order = tuple(
self._world_to_layer_dims(world_dims=order, ndim_world=ndim)
)
return _SliceInput(
ndisplay=ndisplay,
point=point,
order=order,
)
@abstractmethod
def _update_thumbnail(self):
raise NotImplementedError()
@abstractmethod
def _get_value(self, position):
"""Value of the data at a position in data coordinates.
Parameters
----------
position : tuple
Position in data coordinates.
Returns
-------
value : tuple
Value of the data.
"""
raise NotImplementedError()
def get_value(
self,
position: Tuple[float],
*,
view_direction: Optional[np.ndarray] = None,
dims_displayed: Optional[List[int]] = None,
world=False,
):
"""Value of the data at a position.
If the layer is not visible, return None.
Parameters
----------
position : tuple of float
Position in either data or world coordinates.
view_direction : Optional[np.ndarray]
A unit vector giving the direction of the ray in nD world coordinates.
The default value is None.
dims_displayed : Optional[List[int]]
A list of the dimensions currently being displayed in the viewer.
The default value is None.
world : bool