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

"""Implementation of the I-DT algorithm as described in:
        
    **Dario D. Salvucci and Joseph H. Goldberg (2000).**  
    *Identifying fixations and saccades in eye-tracking protocols.*  
    Proceedings of the 2000 symposium on Eye tracking research & applications (ETRA'00, 71-78).  
    [https://doi.org/10.1145/355017.355028](https://doi.org/10.1145/355017.355028)
"""

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

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

from argaze import GazeFeatures

import numpy
import cv2

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

FixationType = TypeVar('Fixation', bound="Fixation")
# Type definition for type annotation convenience

SaccadeType = TypeVar('Saccade', bound="Saccade")
# Type definition for type annotation convenience

@dataclass(frozen=True)
class Fixation(GazeFeatures.Fixation):
    """Define dispersion based fixation."""

    deviation_max: float = field(init=False)
    """Maximal gaze position distance to the centroïd."""

    def __post_init__(self):

        super().__post_init__()

        points = self.positions.values()
        points_x, points_y = [p[0] for p in points], [p[1] for p in points]
        points_array = numpy.column_stack([points_x, points_y])
        centroid_array = numpy.array([numpy.mean(points_x), numpy.mean(points_y)])
        deviations_array = numpy.sqrt(numpy.sum((points_array - centroid_array)**2, axis=1))

        # Update frozen focus attribute using centroid
        object.__setattr__(self, 'focus', (centroid_array[0], centroid_array[1]))

        # Update frozen deviation_max attribute
        object.__setattr__(self, 'deviation_max', max(deviations_array))

    def point_deviation(self, gaze_position) -> float:
        """Get distance of a point from the fixation's centroïd."""

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

    def overlap(self, fixation) -> bool:
        """Does a gaze position from another fixation having a deviation to this fixation centroïd smaller than maximal deviation?"""

        points = fixation.positions.values()
        points_x, points_y = [p[0] for p in points], [p[1] for p in points]
        points_array = numpy.column_stack([points_x, points_y])
        centroid_array = numpy.array([self.focus[0], self.focus[1]])
        deviations_array = numpy.sqrt(numpy.sum((points_array - centroid_array)**2, axis=1))

        return min(deviations_array) <= self.deviation_max

    def merge(self, fixation) -> FixationType:
        """Merge another fixation into this fixation."""

        self.positions.append(fixation.positions)
        self.__post_init__()

        return self

    def draw(self, frame: numpy.array, color=(127, 127, 127), border_color=(255, 255, 255)):
        """Draw fixation into frame."""

        cv2.circle(frame, (int(self.focus[0]), int(self.focus[1])), int(self.deviation_max), color, -1)
        cv2.circle(frame, (int(self.focus[0]), int(self.focus[1])), int(self.deviation_max), border_color, len(self.positions))

@dataclass(frozen=True)
class Saccade(GazeFeatures.Saccade):
    """Define dispersion based saccade."""

    def __post_init__(self):
        super().__post_init__()

    def draw(self, frame: numpy.array, color=(255, 255, 255)):
        """Draw saccade into frame."""

        _, start_position = self.positions.first
        _, last_position = self.positions.last

        cv2.line(frame, (int(start_position[0]), int(start_position[1])), (int(last_position[0]), int(last_position[1])), color, 2)

@dataclass
class GazeMovementIdentifier(GazeFeatures.GazeMovementIdentifier):

    deviation_max_threshold: int|float
    """Maximal distance allowed to consider a gaze movement as a fixation."""

    duration_min_threshold: int|float
    """Minimal duration allowed to consider a gaze movement as a fixation.
    It is also used as maximal duration allowed to consider a gaze movement as a saccade."""

    def __post_init__(self):

        self.__valid_positions = GazeFeatures.TimeStampedGazePositions()
        self.__fixation_positions = GazeFeatures.TimeStampedGazePositions()
        self.__saccade_positions = GazeFeatures.TimeStampedGazePositions()

    def identify(self, ts, gaze_position, terminate=False) -> GazeMovementType:
        """Identify gaze movement from successive timestamped gaze positions.

            The optional *terminate* argument allows to notify identification algorithm that given gaze position will be the last one.
        """

        # Ignore non valid gaze position
        if not gaze_position.valid:

            return None if not terminate else self.current_fixation
            
        # Check if too much time elapsed since last gaze position
        if len(self.__valid_positions) > 0:

            ts_last, _ = self.__valid_positions.last

            if (ts - ts_last) > self.duration_min_threshold:

                # Get last movement
                last_movement = self.current_saccade if len(self.__fixation_positions) == 0 else self.current_fixation

                # Clear all former gaze positions
                self.__valid_positions = GazeFeatures.TimeStampedGazePositions()
                self.__fixation_positions = GazeFeatures.TimeStampedGazePositions()
                self.__saccade_positions = GazeFeatures.TimeStampedGazePositions()

                # Store valid gaze position
                self.__valid_positions[ts] = gaze_position

                # Return last valid movement if exist
                return last_movement

        # Store gaze positions until a minimal duration 
        self.__valid_positions[ts] = gaze_position

        first_ts, _ = self.__valid_positions.first
        last_ts, _ = self.__valid_positions.last

        # Once the minimal duration is reached
        if last_ts - first_ts >= self.duration_min_threshold:

            # Calculate the deviation of valid gaze positions
            deviation = Fixation(self.__valid_positions).deviation_max

            # Valid gaze positions deviation small enough
            if deviation <= self.deviation_max_threshold:

                # Store last saccade
                last_saccade = self.current_saccade

                # Clear saccade positions
                self.__saccade_positions = GazeFeatures.TimeStampedGazePositions()

                # Copy valid gaze positions into fixation positions
                self.__fixation_positions = self.__valid_positions.copy()

                # Output last saccade
                return last_saccade if not terminate else self.current_fixation
                
            # Valid gaze positions deviation too wide while identifying fixation
            elif len(self.__fixation_positions) > 0:

                # Store last fixation
                last_fixation = self.current_fixation

                # Start saccade positions with current gaze position
                self.__saccade_positions[ts] = gaze_position

                # Clear fixation positions
                self.__fixation_positions = GazeFeatures.TimeStampedGazePositions()

                # Clear valid positions
                self.__valid_positions = GazeFeatures.TimeStampedGazePositions()

                # Output last fixation
                return last_fixation if not terminate else self.current_saccade

            # Valid gaze positions deviation too wide while identifying saccade (or not)
            else:

                # Move oldest valid position into saccade positions
                first_ts, first_position = self.__valid_positions.pop_first()
                self.__saccade_positions[first_ts] = first_position

    @property
    def current_fixation(self) -> FixationType:

        if len(self.__fixation_positions) > 0:

            return Fixation(self.__fixation_positions)

    @property
    def current_saccade(self) -> SaccadeType:

        if len(self.__saccade_positions) > 0:
            
            return Saccade(self.__saccade_positions)