aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/GazeFeatures.py
blob: e5dfdf0abf8ec016de9b19698c9f15dd87327799 (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
#!/usr/bin/env python

from typing import TypeVar, Tuple
from dataclasses import dataclass, field
import math
import json

from argaze import DataStructures
from argaze.AreaOfInterest import AOIFeatures

import numpy
import pandas
import cv2 as cv

@dataclass(frozen=True)
class GazePosition():
    """Define gaze position as a tuple of coordinates with precision."""

    value: tuple[int | float] = field(default=(0, 0))
    """Position's value."""

    precision: float = field(default=0., kw_only=True)
    """Position's precision represents the radius of a circle around \
    this gaze position value where other same gaze position measurements could be."""

    def __getitem__(self, axis: int) -> int | float:
        """Get position value along a particular axis."""

        return self.value[axis]

    def __iter__(self) -> iter:
        """Iterate over each position value axis."""

        return iter(self.value)
    
    def __len__(self) -> int:
        """Number of axis in position value."""

        return len(self.value)

    def __repr__(self):
        """String representation"""

        return json.dumps(self, ensure_ascii = False, default=vars)

    def __array__(self):
        """Cast as numpy array."""

        return numpy.array(self.value)

    @property
    def valid(self) -> bool:
        """Is the precision not None?"""

        return self.precision is not None

    def overlap(self, gaze_position, both=False) -> float:
        """Does this gaze position overlap another gaze position considering its precision?
        Set both to True to test if the other gaze position overlaps this one too."""

        dist = (self.value[0] - gaze_position.value[0])**2 + (self.value[1] - gaze_position.value[1])**2
        dist = numpy.sqrt(dist)

        if both:
            return dist < min(self.precision, gaze_position.precision)
        else:
            return dist < self.precision

    def draw(self, frame, color=(0, 255, 255)):
        """Draw gaze position point and precision circle."""

        if self.valid:

            int_value = (int(self.value[0]), int(self.value[1]))

            # Draw point at position
            cv.circle(frame, int_value, 2, color, -1)

            # Draw precision circle
            if self.precision > 0:
                cv.circle(frame, int_value, round(self.precision), color, 1)

class UnvalidGazePosition(GazePosition):
    """Unvalid gaze position."""

    def __init__(self):

        super().__init__((None, None), precision=None)

class TimeStampedGazePositions(DataStructures.TimeStampedBuffer):
    """Define timestamped buffer to store gaze positions."""

    def __setitem__(self, key, value: GazePosition|dict):
        """Force GazePosition storage."""

        # Convert dict into GazePosition
        if type(value) == dict:

            assert(set(["value", "precision"]).issubset(value.keys()))

            value = GazePosition(value["value"], precision=value["precision"])

        assert(type(value) == GazePosition or type(value) == UnvalidGazePosition)

        super().__setitem__(key, value)

GazeMovementType = TypeVar('GazeMovement', bound="GazeMovement")
# Type definition for type annotation convenience

@dataclass(frozen=True)
class GazeMovement():
    """Define abstract gaze movement class as a buffer of timestamped positions."""

    positions: TimeStampedGazePositions
    """All timestamp gaze positions."""

    duration: float = field(init=False)
    """Inferred duration from first and last timestamps."""

    def __post_init__(self):

        start_position_ts, start_position = self.positions.first
        end_position_ts, end_position = self.positions.last

        # Update frozen duration attribute
        object.__setattr__(self, 'duration', end_position_ts - start_position_ts)

    def __str__(self) -> str:
        """String display"""

        output = f'{type(self)}:\n\tduration={self.duration}\n\tsize={len(self.positions)}'

        for ts, position in self.positions.items():

            output += f'\n\t{ts}:\n\t\tvalue={position.value},\n\t\taccurracy={position.precision}'

        return output

class Fixation(GazeMovement):
    """Define abstract fixation as gaze movement."""

    def __post_init__(self):

        super().__post_init__()

class Saccade(GazeMovement):
    """Define abstract saccade as gaze movement."""

    def __post_init__(self):

        super().__post_init__()

class UnknownGazeMovement(GazeMovement):
    """Define abstract unknown gaze movement."""

    def __post_init__(self):

        super().__post_init__()

TimeStampedGazeMovementsType = TypeVar('TimeStampedGazeMovements', bound="TimeStampedGazeMovements")
# Type definition for type annotation convenience

class TimeStampedGazeMovements(DataStructures.TimeStampedBuffer):
    """Define timestamped buffer to store gaze movements."""

    def __setitem__(self, key, value: GazeMovement):
        """Force value to inherit from GazeMovement."""

        assert(type(value).__bases__[0] == Fixation or type(value).__bases__[0] == Saccade or type(value).__bases__[0] == UnknownGazeMovement)

        super().__setitem__(key, value)

    def __str__(self):

        output = ''
        for ts, item in self.items():

            output += f'\n{item}'

        return output

GazeStatusType = TypeVar('GazeStatus', bound="GazeStatus")
# Type definition for type annotation convenience

@dataclass(frozen=True)
class GazeStatus(GazePosition):
    """Define gaze status as a gaze position belonging to an identified and indexed gaze movement."""

    movement_type: str = field(kw_only=True)
    """GazeMovement type to which gaze position belongs."""

    movement_index: int = field(kw_only=True)
    """GazeMovement index to which gaze positon belongs."""

    @classmethod
    def from_position(cls, gaze_position: GazePosition, movement_type: str, movement_index: int) -> GazeStatusType:
        """Initialize from a gaze position instance."""

        return cls(gaze_position.value, precision=gaze_position.precision, movement_type=movement_type, movement_index=movement_index)

TimeStampedGazeStatusType = TypeVar('TimeStampedGazeStatus', bound="TimeStampedGazeStatus")
# Type definition for type annotation convenience

class TimeStampedGazeStatus(DataStructures.TimeStampedBuffer):
    """Define timestamped buffer to store gaze status."""

    def __setitem__(self, key, value: GazeStatus):
        super().__setitem__(key, value)

class GazeMovementIdentifier():
    """Abstract class to define what should provide a gaze movement identifier."""

    def __iter__(self) -> GazeMovementType:
        raise NotImplementedError('__iter__() method not implemented')

    def __next__(self):
        raise NotImplementedError('__next__() method not implemented')

    def __call__(self, ts_gaze_positions: TimeStampedGazePositions):

        assert(type(ts_gaze_positions) == TimeStampedGazePositions)

        # process identification on a copy
        self.__ts_gaze_positions = ts_gaze_positions.copy()

        return self

    def identify(self, ts_gaze_positions: TimeStampedGazePositions) -> Tuple[TimeStampedGazeMovementsType, TimeStampedGazeMovementsType, TimeStampedGazeStatusType]:
        """Identifiy fixations and saccades from timestamped gaze positions."""

        assert(type(ts_gaze_positions) == TimeStampedGazePositions)

        ts_fixations = TimeStampedGazeMovements()
        ts_saccades = TimeStampedGazeMovements()
        ts_unknown = TimeStampedGazeMovements()
        ts_status = TimeStampedGazeStatus()

        for gaze_movement in self(ts_gaze_positions):

            if isinstance(gaze_movement, Fixation):

                start_ts, start_position = gaze_movement.positions.first

                ts_fixations[start_ts] = gaze_movement

                for ts, position in gaze_movement.positions.items():

                    ts_status[ts] = GazeStatus.from_position(position, 'Fixation', len(ts_fixations))

            elif isinstance(gaze_movement, Saccade):

                start_ts, start_position = gaze_movement.positions.first
                end_ts, end_position = gaze_movement.positions.last
                
                ts_saccades[start_ts] = gaze_movement

                ts_status[start_ts] = GazeStatus.from_position(start_position, 'Saccade', len(ts_saccades))
                ts_status[end_ts] = GazeStatus.from_position(end_position, 'Saccade', len(ts_saccades))

            else:

                start_ts, start_position = gaze_movement.positions.first

                ts_unknown[start_ts] = gaze_movement

                for ts, position in gaze_movement.positions.items():

                    ts_status[ts] = GazeStatus.from_position(position, 'UnknownGazeMovement', len(ts_unknown))

        return ts_fixations, ts_saccades, ts_unknown, ts_status

@dataclass
class VisualScanStep():
    """Define a visual scan step as a start timestamp, duration, the name of the area of interest and where gaze looked at in each frame during the step."""

    timestamp: int
    duration: float
    area: str
    look_at: DataStructures.TimeStampedBuffer

class VisualScanGenerator():
    """Abstract class to define when an aoi starts to be looked and when it stops."""

    visual_scan_steps: list

    def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes):

        if type(ts_aoi_scenes) != AOIFeatures.TimeStampedAOIScenes:
            raise ValueError('argument must be a TimeStampedAOIScenes')

        self.visual_scan_steps = []

        for step in self:

            if step == None:
                continue

            self.visual_scan_steps.append(step)

    def __iter__(self):
        raise NotImplementedError('__iter__() method not implemented')

    def steps(self) -> list:
        """Get visual scan steps."""

        return self.visual_scan_steps

    def as_dataframe(self) -> pandas.DataFrame:
        """Convert buffer as pandas dataframe."""

        df = pandas.DataFrame.from_dict(self.visual_scan_steps)
        df.set_index('timestamp', inplace=True)
        df.sort_values(by=['timestamp'], inplace=True)

        return df

    def save_as_csv(self, filepath):
        """Write buffer content into a csv file."""
        
        try:

            self.as_dataframe().to_csv(filepath, index=True)

        except:
            raise RuntimeError(f'Can\' write {filepath}')

class PointerBasedVisualScan(VisualScanGenerator):
    """Build visual scan on the basis of which AOI are looked."""

    def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes, ts_gaze_positions: TimeStampedGazePositions):

        # process identification on a copy
        self.__ts_aoi_scenes = ts_aoi_scenes.copy()
        self.__ts_gaze_positions = ts_gaze_positions.copy()

        # a dictionary to store when an aoi starts to be looked
        self.__step_dict = {}

        # build visual scan
        super().__init__(ts_aoi_scenes)

    def __iter__(self):
        """Visual scan generator function."""

        # while there is aoi scene to process
        while len(self.__ts_aoi_scenes) > 0:

            (ts_current, aoi_scene_current) = self.__ts_aoi_scenes.pop_first()

            # is aoi scene a missing exception ?
            try: 

                raise aoi_scene_current

            # when aoi scene is missing
            except AOIFeatures.AOISceneMissing as e:
                pass

            # when aoi scene is not missing
            except:

                try: 

                    gaze_position = self.__ts_gaze_positions[ts_current]

                     # is aoi scene a missing exception ?
                    raise gaze_position

                # when gaze position is missing
                except GazePositionMissing as e:
                    pass

                # when there is no gaze position at current time
                except KeyError as e:
                    pass

                # when gaze position is not missing
                except:

                    for name, aoi in aoi_scene_current.items():

                        looked = aoi.contains_point(gaze_position)

                        if looked:

                            if not name in self.__step_dict.keys():

                                # aoi starts to be looked
                                self.__step_dict[name] = {
                                    'start': ts_current,
                                    'look_at': DataStructures.TimeStampedBuffer()
                                }

                            # store where the aoi is looked for 4 corners aoi
                            if len(aoi) == 4:
                                self.__step_dict[name]['look_at'][round(ts_current)] = aoi.inner_axis(gaze_position)

                        elif name in self.__step_dict.keys():

                            ts_start = self.__step_dict[name]['start']

                            # aoi stops to be looked
                            yield VisualScanStep(round(ts_start), round(ts_current - ts_start), name, self.__step_dict[name]['look_at'])

                            # forget the aoi
                            del self.__step_dict[name]

        # close started steps
        for name, step in self.__step_dict.items():

            ts_start = step['start']

            # aoi stops to be looked
            yield VisualScanStep(round(ts_start), round(ts_current - ts_start), name, step['look_at'])

class FixationBasedVisualScan(VisualScanGenerator):
    """Build visual scan on the basis of timestamped fixations."""

    def __init__(self, ts_aoi_scenes: AOIFeatures.TimeStampedAOIScenes, ts_fixations: TimeStampedGazeMovements):

        super().__init__(ts_aoi_scenes)

        if type(ts_fixations) != TimeStampedGazeMovements:
            raise ValueError('second argument must be a GazeFeatures.TimeStampedGazeMovements')

        # process identification on a copy
        self.__ts_aoi_scenes = ts_aoi_scenes.copy()
        self.__ts_fixations = ts_fixations.copy()

    def __iter__(self):
        """Visual scan generator function."""

        yield -1, None