-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathfeatures.py
6662 lines (5268 loc) · 212 KB
/
features.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
"""Core features for building and processing pipelines in DeepTrack2.
This module defines the core classes and utilities used to create and
manipulate features in DeepTrack2, enabling users to build sophisticated data
processing pipelines with modular, reusable, and composable components.
Key Features
-------------
- **Features**
A `Feature` is a building block of a data processing pipeline.
It represents a transformation applied to data, such as image manipulation,
data augmentation, or computational operations. Features are highly
customizable and can be combined into pipelines for complex workflows.
- **Structural Features**
Structural features extend the basic `Feature` class by adding hierarchical
or logical structures, such as chains, branches, or probabilistic choices.
They enable the construction of pipelines with advanced data flow
requirements.
- **Feature Properties**
Features in DeepTrack2 can have dynamically sampled properties, enabling
parameterization of transformations. These properties are defined at
initialization and can be updated during pipeline execution.
- **Pipeline Composition**
Features can be composed into flexible pipelines using intuitive operators
(`>>`, `&`, etc.), making it easy to define complex data processing
workflows.
- **Lazy Evaluation**
DeepTrack2 supports lazy evaluation of features, ensuring that data is
processed only when needed, which improves performance and scalability.
Module Structure
----------------
Key Classes:
- `Feature`:
Base class for all features in DeepTrack2. Represents a modular data
transformation with properties and methods for customization.
- `StructuralFeature`:
A specialized feature for organizing and managing hierarchical or logical
structures in the pipeline.
- `Value`:
Stores a constant value as a feature. Useful for passing parameters through
the pipeline.
- `Chain`:
Sequentially applies multiple features to the input data (>>).
- `DummyFeature`:
A no-op feature that passes the input data unchanged.
- `ArithmeticOperationFeature`:
A parent class for features performing arithmetic operations like addition,
subtraction, multiplication, and division.
Functions:
- `propagate_data_to_dependencies`:
def propagate_data_to_dependencies(
feature: Feature,
**kwargs: Any
) -> None
Propagates data to all dependencies of a feature, updating their properties
with the provided values.
- `merge_features`:
def merge_features(
features: list[Feature],
merge_strategy: int = MERGE_STRATEGY_OVERRIDE,
) -> Feature
Merges multiple features into a single feature using the specified merge
strategy.
Examples
--------
Define a simple pipeline with features:
>>> import deeptrack as dt
>>> import numpy as np
Create a basic addition feature:
>>> class BasicAdd(dt.Feature):
... def get(self, image, value, **kwargs):
... return image + value
Create two features:
>>> add_five = BasicAdd(value=5)
>>> add_ten = BasicAdd(value=10)
Chain features together:
>>> pipeline = dt.Chain(add_five, add_ten)
Or equivalently:
>>> pipeline = add_five >> add_ten
Process an input image:
>>> input_image = np.array([[1, 2, 3], [4, 5, 6]])
>>> output_image = pipeline(input_image)
>>> print(output_image)
[[16 17 18]
[19 20 21]]
"""
from __future__ import annotations
import itertools
import operator
import random
from typing import Any, Callable, Iterable
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from pint import Quantity
from scipy.spatial.distance import cdist
from deeptrack import units
from deeptrack.backend import config
from deeptrack.backend.core import DeepTrackNode
from deeptrack.backend.units import ConversionTable, create_context
from deeptrack.image import Image
from deeptrack.properties import PropertyDict
from deeptrack.sources import SourceItem
from deeptrack.types import ArrayLike, PropertyLike
MERGE_STRATEGY_OVERRIDE: int = 0
MERGE_STRATEGY_APPEND: int = 1
class Feature(DeepTrackNode):
"""Base feature class.
Features define the image generation process. All features operate on lists
of images. Most features, such as noise, apply some tranformation to all
images in the list. This transformation can be additive, such as adding
some Gaussian noise or a background illumination, or non-additive, such as
introducing Poisson noise or performing a low-pass filter. This
transformation is defined by the method `get(image, **kwargs)`, which all
implementations of the class `Feature` need to define.
Whenever a Feature is initiated, all keyword arguments passed to the
constructor will be wrapped as a `Property`, and stored in the `properties`
attribute as a `PropertyDict`. When a Feature is resolved, the current
value of each property is sent as input to the get method.
Parameters
----------
_input: np.ndarray or list of np.ndarray or Image or list of Image,
optional.
A list of np.ndarray or `DeepTrackNode` objects or a single np.ndarray
or an `Image` object representing the input data for the feature. This
parameter specifies what the feature will process. If left empty, no
initial input is set.
**kwargs: dict of str and Any
Keyword arguments to configure the feature. Each keyword argument is
wrapped as a `Property` and added to the `properties` attribute,
allowing dynamic sampling and parameterization during the feature's
execution.
Attributes
----------
properties: PropertyDict
A dictionary containing all keyword arguments passed to the
constructor, wrapped as instances of `Property`. The properties can
dynamically sample values during pipeline execution. A sampled copy of
this dictionary is passed to the `get` function and appended to the
properties of the output image.
__list_merge_strategy__: int
Specifies how the output of `.get(image, **kwargs)` is merged with the
input list. Options include:
- `MERGE_STRATEGY_OVERRIDE` (0, default): The input list is replaced by
the new list.
- `MERGE_STRATEGY_APPEND` (1): The new list is appended to the end of
the input list.
__distributed__: bool
Determines whether `.get(image, **kwargs)` is applied to each element
of the input list independently (`__distributed__ = True`) or to the
list as a whole (`__distributed__ = False`).
__property_memorability__: int
Specifies whether to store the feature’s properties in the output
image. Properties with a memorability value of `1` or lower are stored
by default.
__conversion_table__: ConversionTable
Defines the unit conversions used by the feature to convert its
properties into the desired units.
__gpu_compatible__: bool
Indicates whether the feature can use GPU acceleration. When enabled,
GPU execution is triggered based on input size or backend settings.
Methods
-------
`get(image: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> Image | list[Image]`
Abstract method that defines how the feature transforms the input.
`__call__(image_list: np.ndarray | list[np.ndarray] | Image | list[Image] | None = None, _ID: tuple[int, ...] = (), **kwargs: Any) -> Any`
Executes the feature or pipeline on the input and applies property
overrides from `kwargs`.
`store_properties(x: bool = True, recursive: bool = True) -> None`
Controls whether the properties are stored in the output `Image` object.
`torch(dtype: torch.dtype | None = None, device: torch.device | None = None, permute_mode: str = "never") -> 'Feature'`
Converts the feature into a PyTorch-compatible feature.
`batch(batch_size: int = 32) -> tuple | list[Image]`
Batches the feature for repeated execution.
`action(_ID: tuple[int, ...] = ()) -> Image | list[Image]`
Core logic to create or transform the image.
`__use_gpu__(inp: np.ndarrary | Image, **_: Any) -> bool`
Determines if the feature should use the GPU.
`update(**global_arguments: Any) -> Feature`
Refreshes the feature to create a new image.
`add_feature(feature: Feature) -> Feature`
Adds a feature to the dependency graph of this one.
`seed(_ID: tuple[int, ...] = ()) -> None`
Sets the random seed for the feature, ensuring deterministic behavior.
`bind_arguments(arguments: Feature) -> Feature`
Binds another feature’s properties as arguments to this feature.
`_normalize(**properties: dict[str, Any]) -> dict[str, Any]`
Normalizes the properties of the feature.
`plot(input_image: np.ndarray | list[np.ndarray] | Image | list[Image] | None = None, resolve_kwargs: dict | None = None, interval: float | None = None, **kwargs) -> Any`
Visualizes the output of the feature.
`_process_properties(propertydict: dict[str, Any]) -> dict[str, Any]`
Preprocesses the input properties before calling the `get` method.
`_activate_sources(x: Any) -> None`
Activates sources in the input data.
`__getattr__(key: str) -> Any`
Custom attribute access for the Feature class.
`__iter__() -> Iterable`
Iterates over the feature.
`__next__() -> Any`
Returns the next element in the feature.
`__rshift__(other: Any) -> Feature`
Allows chaining of features.
`__rrshift__(other: Any) -> Feature`
Allows right chaining of features.
`__add__(other: Any) -> Feature`
Overrides add operator.
`__radd__(other: Any) -> Feature`
Overrides right add operator.
`__sub__(other: Any) -> Feature`
Overrides subtraction operator.
`__rsub__(other: Any) -> Feature`
Overrides right subtraction operator.
`__mul__(other: Any) -> Feature`
Overrides multiplication operator.
`__rmul__(other: Any) -> Feature`
Overrides right multiplication operator.
`__truediv__(other: Any) -> Feature`
Overrides division operator.
`__rtruediv__(other: Any) -> Feature`
Overrides right division operator.
`__floordiv__(other: Any) -> Feature`
Overrides floor division operator.
`__rfloordiv__(other: Any) -> Feature`
Overrides right floor division operator.
`__pow__(other: Any) -> Feature`
Overrides power operator.
`__rpow__(other: Any) -> Feature`
Overrides right power operator.
`__gt__(other: Any) -> Feature`
Overrides greater than operator.
`__rgt__(other: Any) -> Feature`
Overrides right greater than operator.
`__lt__(other: Any) -> Feature`
Overrides less than operator.
`__rlt__(other: Any) -> Feature`
Overrides right less than operator.
`__le__(other: Any) -> Feature`
Overrides less than or equal to operator.
`__rle__(other: Any) -> Feature`
Overrides right less than or equal to operator.
`__ge__(other: Any) -> Feature`
Overrides greater than or equal to operator.
`__rge__(other: Any) -> Feature`
Overrides right greater than or equal to operator.
`__xor__(other: Any) -> Feature`
Overrides XOR operator.
`__and__(other: Feature) -> Feature`
Overrides AND operator.
`__rand__(other: Feature) -> Feature`
Overrides right AND operator.
`__getitem__(key: Any) -> Feature`
Allows direct slicing of the data.
`_format_input(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Formats the input data for the feature.
`_process_and_get(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Calls the `get` method according to the `__distributed__` attribute.
`_process_output(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> None`
Processes the output of the feature.
`_image_wrapped_format_input(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Ensures the input is a list of Image.
`_no_wrap_format_input(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Ensures the input is a list of Image.
`_no_wrap_process_and_get(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Calls the `get` method according to the `__distributed__` attribute.
`_image_wrapped_process_and_get(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Calls the `get` method according to the `__distributed__` attribute.
`_image_wrapped_process_output(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> None`
Processes the output of the feature.
`_no_wrap_process_output(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> None`
Processes the output of the feature.
`_coerce_inputs(image_list: np.ndarray | list[np.ndarray] | Image | list[Image], **kwargs: Any) -> list[Image]`
Coerces the input to a list of Image.
"""
properties: PropertyDict
_input: DeepTrackNode
_random_seed: DeepTrackNode
arguments: Feature | None
__list_merge_strategy__ = MERGE_STRATEGY_OVERRIDE
__distributed__ = True
__property_memorability__ = 1
__conversion_table__ = ConversionTable()
__gpu_compatible__ = False
_wrap_array_with_image: bool = False
def __init__(
self: Feature,
_input: Any = [],
**kwargs: dict[str, Any],
) -> None:
"""Initialize a new Feature instance.
Parameters
----------
_input: np.ndarray or list[np.ndarray] or Image or list of Images, optional
The initial input(s) for the feature, often images or other data.
If not provided, defaults to an empty list.
**kwargs: dict of str to Any
Keyword arguments that are wrapped into `Property` instances and
stored in `self.properties`, allowing for dynamic or parameterized
behavior.
If not provided, defaults to an empty list.
"""
super().__init__()
# Ensure the feature has a 'name' property; default = class name.
kwargs.setdefault("name", type(self).__name__)
# 1) Create a PropertyDict to hold the feature’s properties.
self.properties = PropertyDict(**kwargs)
self.properties.add_child(self)
# self.add_dependency(self.properties) # Executed by add_child.
# 2) Initialize the input as a DeepTrackNode.
self._input = DeepTrackNode(_input)
self._input.add_child(self)
# self.add_dependency(self._input) # Executed by add_child.
# 3) Random seed node (for deterministic behavior if desired).
self._random_seed = DeepTrackNode(lambda: random.randint(
0, 2147483648)
)
self._random_seed = DeepTrackNode(lambda: random.randint(
0, 2147483648)
)
self._random_seed.add_child(self)
# self.add_dependency(self._random_seed) # Executed by add_child.
# Initialize arguments to None.
self.arguments = None
def get(
self: Feature,
image: np.ndarray | list[np.ndarray] | Image | list[Image],
**kwargs: dict[str, Any],
) -> Image | list[Image]:
"""Transform an image [abstract method].
Abstract method that defines how the feature transforms the input. The
current value of all properties will be passed as keyword arguments.
Parameters
----------
image: np.ndarray or list of np.ndarray or Image or list of Images
The image or list of images to transform.
**kwargs: dict of str to Any
The current value of all properties in `properties`, as well as any
global arguments passed to the feature.
Returns
-------
Image or list of Images
The transformed image or list of images.
Raises
------
NotImplementedError
Raised if this method is not overridden by subclasses.
"""
raise NotImplementedError
def __call__(
self: Feature,
image_list: np.ndarray | list[np.ndarray] | Image | list[Image] = None,
_ID: tuple[int, ...] = (),
**kwargs: dict[str, Any],
) -> Any:
"""Execute the feature or pipeline.
This method executes the feature or pipeline on the provided input and
updates the computation graph if necessary. It handles overriding
properties using additional keyword arguments.
The actual computation is performed by calling the parent `__call__`
method in the `DeepTrackNode` class, which manages lazy evaluation and
caching.
Parameters
----------
image_list: np.ndarrray or list[np.ndarrray] or Image or list of Images, optional
The input to the feature or pipeline. If `None`, the feature uses
previously set input values or propagates properties.
**kwargs: dict of str to Any
Additional parameters passed to the pipeline. These override
properties with matching names. For example, calling
`feature(x, value=4)` executes `feature` on the input `x` while
setting the property `value` to `4`. All features in a pipeline are
affected by these overrides.
Returns
-------
Any
The output of the feature or pipeline after execution.
"""
# If image_list is as Source, activate it.
self._activate_sources(image_list)
# Potentially fragile. Maybe a special variable dt._last_input instead?
# If the input is not empty, set the value of the input.
if (
image_list is not None
and not (isinstance(image_list, list) and len(image_list) == 0)
and not (isinstance(image_list, tuple)
and any(isinstance(x, SourceItem) for x in image_list))
):
self._input.set_value(image_list, _ID=_ID)
# A dict to store the values of self.arguments before updating them.
original_values = {}
# If there are no self.arguments, instead propagate the values of the
# kwargs to all properties in the computation graph.
if kwargs and self.arguments is None:
propagate_data_to_dependencies(self, **kwargs)
# If there are self.arguments, update the values of self.arguments to
# match kwargs.
if isinstance(self.arguments, Feature):
for key, value in kwargs.items():
if key in self.arguments.properties:
original_values[key] = \
self.arguments.properties[key](_ID=_ID)
self.arguments.properties[key].set_value(value, _ID=_ID)
# This executes the feature. DeepTrackNode will determine if it needs
# to be recalculated. If it does, it will call the `action` method.
output = super().__call__(_ID=_ID)
# If there are self.arguments, reset the values of self.arguments to
# their original values.
for key, value in original_values.items():
self.arguments.properties[key].set_value(value, _ID=_ID)
return output
resolve = __call__
def store_properties(
self: Feature,
toggle: bool = True,
recursive: bool = True,
) -> None:
"""Control whether to return an Image object.
If selected `True`, the output of the evaluation of the feature is an
Image object that also contains the properties.
Parameters
----------
toggle: bool
If `True`, store properties. If `False`, do not store.
recursive: bool
If `True`, also set the same behavior for all dependent features.
"""
self._wrap_array_with_image = toggle
if recursive:
for dependency in self.recurse_dependencies():
if isinstance(dependency, Feature):
dependency.store_properties(toggle, recursive=False)
def torch(
self: Feature,
dtype: torch.dtype = None,
device: torch.device = None,
permute_mode: str = "never",
) -> 'Feature':
"""Convert the feature to a PyTorch feature.
Parameters
----------
dtype: torch.dtype, optional
The data type of the output.
device: torch.device, optional
The target device of the output (e.g., CPU or GPU).
permute_mode: str
Controls whether to permute image axes for PyTorch.
Defaults to "never".
Returns
-------
Feature
The transformed, PyTorch-compatible feature.
"""
from deeptrack.pytorch.features import ToTensor
tensor_feature = ToTensor(
dtype=dtype,
device=device,
permute_mode=permute_mode,
)
tensor_feature.store_properties(False, recursive=False)
return self >> tensor_feature
def batch(
self: Feature,
batch_size: int = 32
) -> tuple | list[Image]:
"""Batch the feature.
This method produces a batch of outputs by repeatedly calling
`update()` and `__call__()`.
Parameters
----------
batch_size: int
The number of times to sample or generate data.
Returns
-------
tuple or list of Images
A tuple of stacked arrays (if the outputs are NumPy arrays or
torch tensors) or a list of images if the outputs are not
stackable.
"""
results = [self.update()() for _ in range(batch_size)]
results = list(zip(*results))
for idx, r in enumerate(results):
if isinstance(r[0], np.ndarray):
results[idx] = np.stack(r)
else:
import torch
if isinstance(r[0], torch.Tensor):
results[idx] = torch.stack(r)
return tuple(results)
def action(
self: Feature,
_ID: tuple[int, ...] = (),
) -> Image | list[Image]:
"""Core logic to create or transform the image.
This method creates or transforms the input image by calling the
`get()` method with the correct inputs.
Parameters
----------
_ID: tuple of int
The unique identifier for the current execution.
Returns
-------
Image or list of Images
The resolved image or list of resolved images.
"""
# Retrieve the input images.
image_list = self._input(_ID=_ID)
# Get the current property values.
feature_input = self.properties(_ID=_ID).copy()
# Call the _process_properties hook, default does nothing.
# For example, it can be used to ensure properties are formatted
# correctly or to rescale properties.
feature_input = self._process_properties(feature_input)
if _ID != ():
feature_input["_ID"] = _ID
# Ensure that input is a list.
image_list = self._format_input(image_list, **feature_input)
# Set the seed from the hash_key. Ensures equal results.
# self.seed(_ID=_ID)
# _process_and_get calls the get function correctly according
# to the __distributed__ attribute.
new_list = self._process_and_get(image_list, **feature_input)
self._process_output(new_list, feature_input)
# Merge input and new_list.
if self.__list_merge_strategy__ == MERGE_STRATEGY_OVERRIDE:
image_list = new_list
elif self.__list_merge_strategy__ == MERGE_STRATEGY_APPEND:
image_list = image_list + new_list
# For convencience, list images of length one are unwrapped.
if len(image_list) == 1:
return image_list[0]
else:
return image_list
def __use_gpu__(
self: Feature,
inp: np.ndarray | Image,
**_: Any,
) -> bool:
"""Determine if the feature should use the GPU.
Parameters
----------
inp: np.ndarray or Image
The input image to check.
**_: Any
Additional arguments (unused).
Returns
-------
bool
True if GPU acceleration is enabled and beneficial, otherwise
False.
"""
return self.__gpu_compatible__ and np.prod(np.shape(inp)) > (90000)
def update(
self: Feature,
**global_arguments: Any,
) -> Feature:
"""Refreshes the feature to generate a new output.
By default, when a feature is called multiple times, it returns the
same value. Calling `update()` forces the feature to recompute and
return a new value the next time it is evaluated.
Parameters
----------
**global_arguments: Any
Optional global arguments that can be passed to modify the
feature update behavior.
Returns
-------
Feature
The updated feature instance, ensuring the next evaluation produces
a fresh result.
"""
if global_arguments:
import warnings
# Deprecated, but not necessary to raise hard error.
warnings.warn(
"Passing information through .update is no longer supported. "
"A quick fix is to pass the information when resolving the feature. "
"The prefered solution is to use dt.Arguments",
DeprecationWarning,
)
super().update()
return self
def add_feature(
self: Feature,
feature: Feature,
) -> Feature:
"""Adds a feature to the dependecy graph of this one.
Parameters
----------
feature: Feature
The feature to add as a dependency.
Returns
-------
Feature
The newly added feature (for chaining).
"""
feature.add_child(self)
# self.add_dependency(feature) # Already done by add_child().
return feature
def seed(
self: Feature,
_ID: tuple[int, ...] = (),
) -> None:
"""Seed the random number generator.
Parameters
----------
_ID: tuple[int, ...], optional
Unique identifier for parallel evaluations.
"""
np.random.seed(self._random_seed(_ID=_ID))
def bind_arguments(
self: Feature,
arguments: Feature,
) -> Feature:
"""Binds another feature’s properties as arguments to this feature.
This method allows properties of `arguments` to be dynamically linked
to this feature, enabling shared configurations across multiple features.
It is commonly used in advanced feature pipelines.
See Also
--------
features.Arguments
A utility that helps manage and propagate feature arguments efficiently.
Parameters
----------
arguments: Feature
The feature whose properties will be bound as arguments to this feature.
Returns
-------
Feature
The current feature instance with bound arguments.
"""
self.arguments = arguments
return self
def _normalize(
self: Feature,
**properties: dict[str, Any],
) -> dict[str, Any]:
"""Normalizes the properties.
This method handles all unit normalizations and conversions. For each class in
the method resolution order (MRO), it checks if the class has a
`__conversion_table__` attribute. If found, it calls the `convert` method of
the conversion table using the properties as arguments.
Parameters
----------
**properties: dict of str to Any
The properties to be normalized and converted.
Returns
-------
dict of str to Any
The normalized and converted properties.
"""
for cl in type(self).mro():
if hasattr(cl, "__conversion_table__"):
properties = cl.__conversion_table__.convert(**properties)
for key, val in properties.items():
if isinstance(val, Quantity):
properties[key] = val.magnitude
return properties
def plot(
self: Feature,
input_image: np.ndarray | list[np.ndarray] | Image | list[Image] = None,
resolve_kwargs: dict = None,
interval: float = None,
**kwargs
) -> Any:
"""Visualizes the output of the feature.
This method resolves the feature and visualizes the result. If the output is
an `Image`, it displays it using `pyplot.imshow`. If the output is a list, it
creates an animation. In Jupyter notebooks, the animation is played inline
using `to_jshtml()`. In scripts, the animation is displayed using the
matplotlib backend.
Any parameters in `kwargs` are passed to `pyplot.imshow`.
Parameters
----------
input_image: np.ndarray or list np.ndarray or Image or list of Image, optional
The input image or list of images passed as an argument to the `resolve`
call. If `None`, uses previously set input values or propagates properties.
resolve_kwargs: dict, optional
Additional keyword arguments passed to the `resolve` call.
interval: float, optional
The time between frames in the animation, in milliseconds. The default
value is 33 ms.
**kwargs: dict, optional
Additional keyword arguments passed to `pyplot.imshow`.
Returns
-------
Any
The output of the feature or pipeline after execution.
"""
from IPython.display import HTML, display
# if input_image is not None:
# input_image = [Image(input_image)]
output_image = self.resolve(input_image, **(resolve_kwargs or {}))
# If a list, assume video
if not isinstance(output_image, list):
# Single image
plt.imshow(output_image, **kwargs)
return plt.gca()
else:
# Assume video
fig = plt.figure()
images = []
plt.axis("off")
for image in output_image:
images.append([plt.imshow(image, **kwargs)])
if not interval:
if isinstance(output_image[0], Image):
interval = output_image[0].get_property("interval") or (1 / 30 * 1000)
else:
interval = (1 / 30 * 1000)
anim = animation.ArtistAnimation(
fig, images, interval=interval, blit=True, repeat_delay=0
)
try:
get_ipython # Throws NameError if not in Notebook
display(HTML(anim.to_jshtml()))
return anim
except NameError:
# Not in an notebook
plt.show()
except RuntimeError:
# In notebook, but animation failed
import ipywidgets as widgets
def plotter(frame=0):
plt.imshow(output_image[frame][:, :, 0], **kwargs)
plt.show()
return widgets.interact(
plotter,
frame=widgets.IntSlider(
value=0, min=0, max=len(images) - 1, step=1
),
)
def _process_properties(
self: Feature,
propertydict: dict[str, Any],
) -> dict[str, Any]:
"""Preprocesses the input properties before calling `.get()`.
This method acts as a preprocessing hook for subclasses, allowing them
to modify or normalize input properties before the feature's main
computation.
Parameters
----------
propertydict: dict[str, Any]
The dictionary of properties to be processed before being passed
to the `.get()` method.
Returns
-------
dict[str, Any]
The processed property dictionary after normalization.
Notes
-----
- Calls `_normalize()` internally to standardize input properties.
- Subclasses may override this method to implement additional
preprocessing steps.
"""
propertydict = self._normalize(**propertydict)
return propertydict
def _activate_sources(
self: Feature,
x: Any,
) -> None:
"""Activates source items within the given input.
This method checks if `x` or its elements (if `x` is a list) are
instances of `SourceItem`, and if so, calls them to trigger their
behavior.
Parameters
----------
x: Any
The input to process. If `x` is a `SourceItem`, it is activated.
If `x` is a list, each `SourceItem` within the list is activated.
Notes
-----
- Non-`SourceItem` elements in `x` are ignored.
- This method is used to ensure that all source-dependent computations
are properly triggered when required.
"""
if isinstance(x, SourceItem):
x()
else:
if isinstance(x, list):
for source in x:
if isinstance(source, SourceItem):
source()
def __getattr__(
self: Feature,
key: str,
) -> Any:
"""Custom attribute access for the Feature class.
This method allows the properties of the `Feature` instance to be
accessed as if they were attributes. For example, `feature.my_property`
is equivalent to `feature.properties["my_property"]`.
If the requested attribute (`key`) exists in the `properties`
dictionary, the corresponding value is returned. If the attribute does
not exist, or if the `properties` attribute is not set, an
This method allows the properties of the `Feature` instance to be
accessed as if they were attributes. For example, `feature.my_property`
is equivalent to `feature.properties["my_property"]`.
If the requested attribute (`key`) exists in the `properties`
dictionary, the corresponding value is returned. If the attribute does
not exist, or if the `properties` attribute is not set, an
`AttributeError` is raised.
Parameters
----------
key: str
The name of the attribute being accessed.