forked from tkngch/pylink-wrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eyetracker.py
250 lines (198 loc) · 8.51 KB
/
eyetracker.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
#!/usr/bin/env python2
# encoding: utf-8
"""
This file provides a wrapper class to pylink, Eyetracker. This is mainly to
ease the use of EyeLink eye-tracker (SR research).
Copyright 2015 Takao Noguchi (tkngch@runbox.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import pygame
import pylink
import os
from pygame_utils import Text
class Eyetracker:
def __init__(self, subjID, dataDir):
self._init_graphics()
self._init_datafiles(subjID, dataDir)
self._init_tracker()
self._init_calibration()
pylink.flushGetkeyQueue()
self.tracker.setOfflineMode()
self.tracker.openDataFile(self.trackerDatafile)
def _init_graphics(self):
self.screen = pygame.display.get_surface()
self.screenRect = self.screen.get_rect()
pylink.openGraphics()
def _init_datafiles(self, datafilename, datadir):
# define datafiles
# trackerDatafile is a temporary file saved onto the tracker PC
self.trackerDatafile = '%s.edf' % datafilename
# localDatafile is where the trackerDatafile is saved
# on the local (presentation) PC
self.localDatafile = datadir + '\\' + self.trackerDatafile
def _init_tracker(self):
self.tracker = pylink.EyeLink()
# Gets the display surface and sends a mesage to EDF file;
self.tracker.sendCommand(
"screen_pixel_coords = 0 0 %d %d" % self.screenRect.size)
self.tracker.sendMessage(
"DISPLAY_COORDS 0 0 %d %d" % self.screenRect.size)
tracker_software_ver = 0
eyelink_ver = self.tracker.getTrackerVersion()
if eyelink_ver == 3:
tvstr = self.tracker.getTrackerVersionString()
vindex = tvstr.find("EYELINK CL")
tracker_software_ver = int(float(
tvstr[(vindex + len("EYELINK CL")):].strip()))
if eyelink_ver >= 2:
self.tracker.sendCommand("select_parser_configuration 0")
if eyelink_ver == 2: # turn off scenelink camera stuff
self.tracker.sendCommand("scene_camera_gazemap = NO")
else:
self.tracker.sendCommand("saccade_velocity_threshold = 35")
self.tracker.sendCommand(
"saccade_acceleration_threshold = 9500")
# set EDF file contents
self.tracker.sendCommand(
"file_event_filter = " +
"LEFT,RIGHT,FIXATION,SACCADE,BLINK,MESSAGE,BUTTON")
if tracker_software_ver >= 4:
self.tracker.sendCommand(
"file_sample_data = " +
"LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS,HTARGET")
else:
self.tracker.sendCommand(
"file_sample_data = " +
"LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS")
# set link data (used for gaze cursor)
self.tracker.sendCommand(
"link_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,BUTTON")
if tracker_software_ver >= 4:
self.tracker.sendCommand(
"link_sample_data = " +
"LEFT,RIGHT,GAZE,GAZERES,AREA,STATUS,HTARGET")
else:
self.tracker.sendCommand(
"link_sample_data = " +
"LEFT,RIGHT,GAZE,GAZERES,AREA,STATUS")
self.tracker.sendCommand("button_function 5 'accept_target_fixation'")
def _init_calibration(self):
# Sets the calibration target and background color
pylink.setCalibrationColors((0, 0, 0), (255, 255, 255))
# select best size for calibration target
pylink.setTargetSize(self.screenRect.width / 70,
self.screenRect.width / 300)
pylink.setCalibrationSounds("off", "off", "off")
pylink.setDriftCorrectSounds("off", "off", "off")
def checkUp(self):
# Does drift correction and handles the re-do camera setup situations
self.display_message(
'Starting drift correction. ' +
'Press ESC to enter the eyelink setup.')
try:
error = self.tracker.doDriftCorrect(self.screenRect.width / 2,
self.screenRect.height / 2,
1, 1)
if error <= 27:
pass
else:
self.calibrate()
except:
self.calibrate()
self.resume_recording()
self.display_message('Resuming the experiment...')
def calibrate(self):
self.display_message('Starting the eyelink setup...')
self.tracker.doTrackerSetup()
self.eye_used = self.tracker.eyeAvailable()
self.resume_recording()
def resume_recording(self):
error = self.tracker.startRecording(1, 1, 1, 1)
if error:
self.display_message('Error occured.')
print error
raise RuntimeError(error)
else:
# introduce 100 millisecond delay after recording begins
# to ensure that no data is missed before the trial starts.
pylink.beginRealTimeMode(100)
def start_recording(self):
self.calibrate()
self.resume_recording()
self.display_message('Recording started.')
# determine which eye(s) are available
self.eye_used = self.tracker.eyeAvailable()
if self.eye_used in (1, "RIGHT_EYE"):
self.tracker.sendMessage("EYE_USED 1 RIGHT")
elif self.eye_used in (0, "LEFT_EYE"):
self.tracker.sendMessage("EYE_USED 0 LEFT")
def stop_recording(self):
'''Ends recording: adds 100 msec of data to catch final events'''
pylink.endRealTimeMode()
pylink.pumpDelay(100)
self.tracker.stopRecording()
# self.display_message('Recording stopped.')
while self.tracker.getkey():
pass
def terminate(self):
# File transfer and cleanup!
self.tracker.setOfflineMode()
pylink.msecDelay(500)
# Close the file and transfer it to Display PC
self.tracker.closeDataFile()
self.tracker.receiveDataFile(self.trackerDatafile, self.localDatafile)
self.tracker.close()
self.display_message('Eyelink disconnected.')
# Close the experiment graphics
pylink.closeGraphics()
# convert the edf file to asc file
self.edf2asc()
def send_message(self, message):
self.tracker.sendMessage(message)
def edf2asc(self):
command = 'edf2asc ' + self.localDatafile
os.system(command)
def display_message(self, message):
self.screen.fill((255, 255, 255))
Text(message, self.screen).write(self.screenRect.center)
pygame.display.flip()
pygame.time.wait(2000)
def get_gazePosition(self):
dt = self.tracker.getNewestSample()
if (dt is not None):
# Gets the gaze position of the latest sample,
if self.eye_used in (1, "RIGHT_EYE") and dt.isRightSample():
gaze_position = dt.getRightEye().getGaze()
elif self.eye_used in (0, "LEFT_EYE") and dt.isLeftSample():
gaze_position = dt.getLeftEye().getGaze()
else:
gaze_position = None
return gaze_position
def wait_startfixation(self):
waiting = True
while waiting:
event = self.tracker.getNextData()
if event == pylink.STARTFIX:
gaze_position = self.get_gazePosition()
# getStartGaze gives me a negative values (not sure why)
# gaze_position = self.tracker.getFloatData().getStartGaze()
waiting = False
return gaze_position
def wait_endfixation(self):
waiting = True
while waiting:
event = self.tracker.getNextData()
if event == pylink.ENDFIX:
gaze_position = self.get_gazePosition()
# getAverageGaze gives me a strange values...
# gaze_position = self.tracker.getFloatData().getAverageGaze()
waiting = False
return gaze_position