aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/DataFeatures.py
blob: 501968765246dfbb5e2fa1f69d5464b1334e6db9 (plain)
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
"""Miscellaneous data features."""

__author__ = "Théo de la Hogue"
__credits__ = []
__copyright__ = "Copyright 2023, Ecole Nationale de l'Aviation Civile (ENAC)"
__license__ = "BSD"

from typing import TypeVar, Tuple, Any
import os
import sys
import traceback
import importlib
from inspect import getmembers, getmodule
import collections
import json
import ast
import bisect
import threading
import math
import time

import pandas
import numpy
import matplotlib.pyplot as mpyplot
import matplotlib.patches as mpatches
from colorama import Style, Fore

TimeStampType = TypeVar('TimeStamp', int, float)
"""Type definition for timestamp as integer or float values."""

TimestampedObjectType = TypeVar('TimestampedObject', bound="TimestampedObject")
# Type definition for type annotation convenience

TimestampedObjectsListType = TypeVar('TimestampedObjectsList', bound="TimestampedObjectsList")
# Type definition for type annotation convenience

def module_path(obj) -> str:
    """
    Get object module path.

    Returns:
        module path
    """
    return obj.__class__.__module__

def properties(cls) -> list:
    """get class properties name."""

    properties = [name for name, item in cls.__dict__.items() if isinstance(item, property)]
    
    for base in cls.__bases__:

        for name, item in base.__dict__.items(): 

            if isinstance(item, property):

                properties.append(name)

    return properties

def as_dict(obj, filter: bool=True) -> dict:
    """Export object as dictionary.

    Parameters:
        filter: remove None attribute values.
    """
    _dict = {}

    for p in properties(obj.__class__):

        v = getattr(obj, p)

        if not filter or v is not None:

            _dict[p] = v

    return _dict

class JsonEncoder(json.JSONEncoder):
    """Specific ArGaze JSON Encoder."""

    def default(self, obj):
        """default implementation to serialize object."""

        # numpy cases
        if isinstance(obj, numpy.integer):
            return int(obj)

        elif isinstance(obj, numpy.floating):
            return float(obj)

        elif isinstance(obj, numpy.ndarray):
            return obj.tolist()

        # default case
        try:

            return json.JSONEncoder.default(self, obj)

        # class case
        except:

            # ignore attribute starting with _
            public_dict = {}

            for k, v in vars(obj).items():
                
                if not k.startswith('_'):
                    
                    # numpy cases
                    if isinstance(v, numpy.integer):
                        v = int(v)

                    elif isinstance(v, numpy.floating):
                        v = float(v)

                    elif isinstance(v, numpy.ndarray):
                        v = v.tolist()

                    public_dict[k] = v

            return public_dict

class DataDictionary(dict):
    """Enable dot.notation access to dictionary attributes"""

    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

class TimestampedObject():
    """Abstract class to enable timestamp management."""

    def __init__(self, timestamp: int|float = math.nan):
        """Initialize TimestampedObject."""
        self._timestamp = timestamp

    def __repr__(self):
        """String representation."""
        return json.dumps(as_dict(self))

    @property
    def timestamp(self) -> int|float:
        """Get object timestamp."""
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp: int|float):
        """Set object timestamp."""
        self._timestamp = timestamp

    def untimestamp(self):
        """Reset object timestamp."""
        self._timestamp = math.nan

    def is_timestamped(self) -> bool:
        """Is the object timestamped?"""
        return not math.isnan(self._timestamp)

class TimestampedObjectsList(list):
    """Handle timestamped object into a list.

    !!! warning "Timestamped objects are not sorted internally"
        
        Timestamped objects are considered to be stored according at their coming time.
    """

    def __init__(self, ts_object_type: type, ts_objects: list = []):

        self.__object_type = ts_object_type
        self.__object_properties = properties(self.__object_type)

        for ts_object in ts_objects:

            self.append(ts_object)

    @property
    def object_type(self):
        """Get object type handled by the list."""
        return self.__object_type

    def append(self, ts_object: TimestampedObjectType|dict):
        """Append timestamped object."""
        
        # Convert dict into GazePosition
        if type(ts_object) == dict:

            ts_object = self.__object_type.from_dict(ts_object)

        # Check object type
        if type(ts_object) != self.__object_type:

            if not issubclass(ts_object.__class__, self.__object_type):

                raise TypeError(f'{type(ts_object)} object is not {self.__object_type} instance')
        
        if not ts_object.is_timestamped():

            raise ValueError(f'object is not timestamped')
        
        super().append(ts_object)

    def look_for(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Look for object at given timestamp."""
        for ts_object in self:
            
            if ts_object.timestamp == timestamp:

                return ts_object

    def __add__(self, ts_objects: list = []) -> TimestampedObjectsListType:
        """Append timestamped objects list."""

        for ts_object in ts_objects:

            self.append(ts_object)

        return self

    @property
    def duration(self):
        """Get inferred duration from first and last timestamps."""
        if self:

            return self[-1].timestamp - self[0].timestamp

        else:

            return 0

    def timestamps(self):
        """Get all timestamps in list."""
        return [ts_object.timestamp for ts_object in self]

    def tuples(self) -> list:
        """Get all timestamped objects as list of tuple."""
        return [tuple(as_dict(ts_object, filter=False).values()) for ts_object in self]

    @classmethod
    def from_dataframe(self, ts_object_type: type, dataframe: pandas.DataFrame, exclude=[]) -> TimestampedObjectsListType:
        """Create a TimestampedObjectsList from [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html)."""

        dataframe.drop(exclude, inplace=True, axis=True)

        assert(dataframe.index.name == 'timestamp')

        object_list = [ts_object_type(timestamp=timestamp, **object_dict) for timestamp, object_dict in dataframe.to_dict('index').items()]

        return TimestampedObjectsList(ts_object_type, object_list)

    def as_dataframe(self, exclude=[], split={}) -> pandas.DataFrame:
        """Convert as [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html).  
        
        The optional *split* argument allows tuple values to be stored in dedicated columns.  
        For example: to convert {"point": (0, 0)} data as two separated "x" and "y" columns, use split={"point": ["x", "y"]}  

        !!! warning "Values must be dictionaries"
        
            Each key is stored as a column name.

        !!! note

            Timestamps are stored as index column called 'timestamp'.
        """

        df = pandas.DataFrame(self.tuples(), columns=self.__object_properties)

        # Exclude columns
        df.drop(exclude, inplace=True, axis=True)

        # Split columns
        if len(split) > 0:

            splited_columns = []
            
            for column in df.columns:

                if column in split.keys():

                    df[split[column]] = pandas.DataFrame(df[column].tolist(), index=df.index)
                    df.drop(column, inplace=True, axis=True)

                    for new_column in split[column]:

                        splited_columns.append(new_column)

                else:

                    splited_columns.append(column)

            # Reorder splited columns
            df = df[splited_columns]

        # Append timestamps as index column
        df['timestamp'] = self.timestamps()
        df.set_index('timestamp', inplace=True)

        return df

    @classmethod
    def from_json(self, ts_object_type: type, json_filepath: str) -> TimestampedObjectsListType:
        """Create a TimestampedObjectsList from .json file."""

        with open(json_filepath, encoding='utf-8') as ts_objects_file:

            json_ts_objects = json.load(ts_objects_file)

            return TimestampedObjectsList(ts_object_type, [ts_object_type(**ts_object_dict) for ts_object_dict in json_ts_objects])

    def to_json(self, json_filepath: str):
        """Save a TimestampedObjectsList to .json file."""

        with open(json_filepath, 'w', encoding='utf-8') as ts_objects_file:

            json.dump(self, ts_objects_file, ensure_ascii=False, default=(lambda obj: as_dict(obj)), indent='   ')

    def __repr__(self):
        """String representation"""
        return json.dumps([as_dict(ts_object) for ts_object in self], ensure_ascii=False,)

    def __str__(self):
        """String representation"""
        return json.dumps([as_dict(ts_object) for ts_object in self], ensure_ascii=False,)

    def pop_last_until(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Pop all item until a given timestamped value and return the first after."""

        # get last item before given timestamp
        earliest_value = self.get_last_until(timestamp)

        while self[0].timestamp < earliest_value.timestamp:

            self.pop(0)
            
        return self[0]

    def pop_last_before(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Pop all item before a given timestamped value and return the last one."""

        # get last item before given timestamp
        earliest_value = self.get_last_before(timestamp)

        poped_value = self.pop(0)

        while poped_value.timestamp != earliest_value.timestamp:

            poped_value = self.pop(0)

        return poped_value

    def get_first_from(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Retreive first item timestamp from a given timestamp value."""

        ts_list = self.timestamps()
        first_from_index = bisect.bisect_left(ts_list, timestamp)

        if first_from_index < len(self):

            return self[ts_list[first_from_index]]
            
        else:
            
            raise KeyError(f'No data stored after {timestamp} timestamp.')

    def get_last_before(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Retreive last item timestamp before a given timestamp value."""

        ts_list = self.timestamps()
        last_before_index = bisect.bisect_left(ts_list, timestamp) - 1

        if last_before_index >= 0:

            return self[ts_list[last_before_index]]
            
        else:
            
            raise KeyError(f'No data stored before {timestamp} timestamp.')
        
    def get_last_until(self, timestamp: TimeStampType) -> TimestampedObjectType:
        """Retreive last item timestamp until a given timestamp value."""

        ts_list = self.timestamps()
        last_until_index = bisect.bisect_right(ts_list, timestamp) - 1

        if last_until_index >= 0:

            return self[ts_list[last_until_index]]
            
        else:
            
            raise KeyError(f'No data stored until {timestamp} timestamp.')

    def plot(self, names=[], colors=[], split={}, samples=None) -> list:
        """Plot as [matplotlib](https://matplotlib.org/) time chart."""

        df = self.as_dataframe(split=split)
        legend_patches = []

        # decimate data
        if samples != None:

            if samples < len(df):

                step = int(len(df) / samples) + 1
                df = df.iloc[::step, :]

        for name, color in zip(names, colors):

            markerline, stemlines, baseline = mpyplot.stem(df.index, df[name])
            mpyplot.setp(markerline, color=color, linewidth=1, markersize = 1)
            mpyplot.setp(stemlines, color=color, linewidth=1)
            mpyplot.setp(baseline, color=color, linewidth=1)

            legend_patches.append(mpatches.Patch(color=color, label=name.upper()))

        return legend_patches

class SharedObject(TimestampedObject):
    """Abstract class to enable multiple threads sharing for timestamped object."""

    def __init__(self, timestamp: int|float = math.nan):

        TimestampedObject.__init__(self, timestamp)
        self._lock = threading.Lock()
        self._execution_times = {}
        self._exceptions = {}

class PipelineStepObject():
    """
    Define class to assess pipeline step methods execution time and observe them.
    """

    def __init__(self, name: str = None, working_directory: str = None, observers: dict = None):
        """Initialize PipelineStepObject

        Parameters:
            name: object name
            working_directory: folder path to use for relative file path.
            observers: dictionary with observers objects.

        """

        # Init private attribute
        self.__name = name
        self.__working_directory = working_directory
        self.__observers = observers if observers is not None else {}
        self.__execution_times = {}
        self.__properties = {}

        # parent attribute will be setup later by parent it self
        self.__parent = None

    def __enter__(self):
        """At with statement start."""

        # Start children pipeline step objects
        for child in self.children:

            child.__enter__()

        # Start observers
        for observer_name, observer in self.__observers.items():

            observer.__enter__()

        return self

    def __exit__(self, exception_type, exception_value, exception_traceback):
        """At with statement end."""

        # End observers
        for observer_name, observer in self.__observers.items():

            observer.__exit__(exception_type, exception_value, exception_traceback)

        # End children pipeline step objects
        for child in self.children:

            child.__exit__(exception_type, exception_value, exception_traceback)

    @property
    def name(self) -> str:
        """Get pipeline step object's name."""
        return self.__name

    @property
    def working_directory(self) -> str:
        """Get pipeline step object's working_directory."""
        return self.__working_directory

    @property
    def parent(self) -> object:
        """Get pipeline step object's parent object."""
        return self.__parent

    @parent.setter
    def parent(self, parent: object):
        """Set layer's parent object."""
        self.__parent = parent

    @property
    def observers(self) -> dict:
        """Get pipeline step object observers dictionary."""
        return self.__observers

    @property
    def execution_times(self):
        """Get pipeline step object observers execution times dictionary."""
        return self.__execution_times
    
    def as_dict(self) -> dict:
        """Export PipelineStepObject attributes as dictionary.

        Returns:
            object_data: dictionary with pipeline step object attributes values.
        """
        return {
            "name": self.__name,
            "observers": self.__observers
        }

    @classmethod
    def from_dict(cls, object_data: dict, working_directory: str = None) -> object:
        """Load PipelineStepObject attributes from dictionary.

        Returns:
            object_data: dictionary with pipeline step object attributes values.
            working_directory: folder path where to load files when a dictionary value is a relative filepath.
        """

        # Append working directory to the Python path
        if working_directory is not None:

            sys.path.append(working_directory)

        # Load name
        try:

            new_name = object_data.pop('name')

        except KeyError:

            new_name = None
        
        # Load observers
        new_observers = {}

        try:

            new_observers_value = object_data.pop('observers')

            # str: relative path to file
            if type(new_observers_value) == str:

                filepath = os.path.join(working_directory, new_observers_value)
                file_format = filepath.split('.')[-1]

                # Python file format
                if file_format == 'py':

                    observer_module_path = new_observers_value.split('.')[0]

                    observer_module = importlib.import_module(observer_module_path)

                    new_observers = observer_module.__observers__

             # dict: instanciate ready-made argaze observers
            elif type(new_observers_value) == dict:

                for observer_type, observer_data in new_observers_value.items():

                    new_observers[observer_type] = eval(f'{observer_type}(**observer_data)')

        except KeyError:

            pass

        # Create pipeline step object
        return PipelineStepObject(\
            new_name, \
            working_directory, \
            new_observers \
            )

    @classmethod
    def from_json(cls, configuration_filepath: str, patch_filepath: str = None) -> object:
        """
        Load pipeline step object from .json file.

        Parameters:
            configuration_filepath: path to json configuration file
            patch_filepath: path to json patch file to modify any configuration entries
        """
        with open(configuration_filepath) as configuration_file:

            object_data = json.load(configuration_file)
            working_directory = os.path.dirname(configuration_filepath)

            # Apply patch to configuration if required
            if patch_filepath is not None:

                with open(patch_filepath) as patch_file:

                    patch_data = json.load(patch_file)

                    import collections.abc

                    def update(d, u):

                        for k, v in u.items():

                            if isinstance(v, collections.abc.Mapping):

                                d[k] = update(d.get(k, {}), v)

                            elif v is None:

                                del d[k]

                            else:

                                d[k] = v

                        return d

                    object_data = update(object_data, patch_data)

            return cls.from_dict(object_data, working_directory)

    def to_json(self, json_filepath: str = None):
        """Save pipeline step object into .json file."""

        # Remember file path to ease rewriting
        if json_filepath is not None:

            self.__json_filepath = json_filepath

        # Open file
        with open(self.__json_filepath, 'w', encoding='utf-8') as object_file:

            json.dump({module_path(self):as_dict(self)}, object_file, ensure_ascii=False, indent=4)

            # QUESTION: maybe we need two saving mode?
            #json.dump(self, object_file, ensure_ascii=False, indent=4, cls=DataFeatures.JsonEncoder)

    def __str__(self) -> str:
        """
        String representation of pipeline step object.
        
        Returns:
            String representation
        """
        
        tabs = self.tabulation  
        output = f'{Fore.GREEN}{Style.BRIGHT}{self.__class__.__module__}.{self.__class__.__name__}{Style.RESET_ALL}\n'

        if self.__name is not None:
            output += f'{tabs}\t{Style.BRIGHT}name{Style.RESET_ALL}: {self.__name}\n'

        if self.__parent is not None:
            output += f'{tabs}\t{Style.BRIGHT}parent{Style.RESET_ALL}: {self.__parent.name}\n'

        if len(self.__observers):
            output += f'{tabs}\t{Style.BRIGHT}observers{Style.RESET_ALL}:\n'
            for name, observer in self.__observers.items():
                output += f'{tabs}\t  - {Fore.RED}{name}{Style.RESET_ALL}: {Fore.GREEN}{Style.BRIGHT}{observer.__class__.__module__}.{observer.__class__.__name__}{Style.RESET_ALL}\n'

        for name, value in self.properties:

            output += f'{tabs}\t{Style.BRIGHT}{name}{Style.RESET_ALL}: '

            if type(value) == dict:

                output += '\n'

                for k, v in value.items():

                    output += f'{tabs}\t  - {Fore.RED}{k}{Style.RESET_ALL}: {v}\n'

            elif type(value) == numpy.ndarray:

                output += f'numpy.array{value.shape}\n'

            elif type(value) == pandas.DataFrame:

                output += f'pandas.DataFrame{value.shape}\n'

            else:

                output += f'{value}'

                if output[-1] != '\n':

                    output += '\n'

        return output

    @property
    def tabulation(self) -> str:
        """Edit tabulation string according parents number."""

        tabs = ''
        parent = self.__parent

        while (parent is not None):

            tabs += '\t'
            parent = parent.parent

        return tabs

    @property
    def properties(self) -> Tuple[name, any]:
        """Iterate over pipeline step properties values."""

        for name, item in self.__class__.__dict__.items(): 

            if isinstance(item, property):

                yield name, getattr(self, name)
        
        for base in self.__class__.__bases__:

            if base != PipelineStepObject and base != SharedObject:

                for name, item in base.__dict__.items(): 

                    if isinstance(item, property):

                        yield name, getattr(self, name)

    @property
    def children(self) -> object:
        """Iterate over children pipeline step objects."""

        for name, item in self.__class__.__dict__.items(): 

            if isinstance(item, property):

                attr = getattr(self, name)

                if PipelineStepObject in attr.__class__.__bases__:

                    yield attr

def PipelineStepMethod(method):
    """Define a decorator use into PipelineStepObject class to declare pipeline method.

    !!! danger
        PipelineStepMethod must have a timestamp as first argument.
    """

    def wrapper(self, *args, timestamp: int|float = None, unwrap: bool = False, **kwargs):
        """Wrap pipeline step method to measure execution time.

        Parameters:
            args: Any arguments defined by PipelineStepMethod.
            timestamp: Optional method call timestamp (unit does'nt matter) if first args parameter is not a TimestampedObject instance.
            unwrap: Extra arguments used in wrapper function to call wrapped method directly.
        """
        if timestamp is None:

            if isinstance(args[0], TimestampedObject):

                timestamp = args[0].timestamp

        if unwrap:

            return method(self, *args, **kwargs)

        # Initialize execution time assessment
        start = time.perf_counter()
        exception = None
        result = None
        
        try:

            # Execute wrapped method
            result = method(self, *args, **kwargs)

        except Exception as e:

            exception = e

        finally:

            # Measure execution time
            self.execution_times[method.__name__] = (time.perf_counter() - start) * 1e3

        # Notify observers that method has been called
        subscription_name = f'on_{method.__name__}'

        for observer_name, observer in self.observers.items():

            # Does the observer cares about this method?
            if subscription_name in dir(observer): 

                subscription = getattr(observer, subscription_name)

                # Call subscription
                subscription(timestamp, self, exception)

        # Raise exception
        if exception is not None:

            raise exception

        return result

    return wrapper

class PipelineStepObserver():
    """Define abstract class to observe pipeline step object use.

    !!! note
        To subscribe to a method call, the inherited class simply needs to define 'on_<method_name>' functions with timestamp, object and traceback argument.
    """

    def __enter__(self):
        """
        Define abstract __enter__ method to use observer as a context.

        !!! warning
            This method is called provided that the observed PipelineStepObject is created as a context using a with statement.
        """
        return self

    def __exit__(self, type, value, traceback):
        """
        Define abstract __exit__ method to use observer as a context.

        !!! warning
            This method is called provided that the observed PipelineStepObject is created as a context using a with statement.
        """
        pass