def drift_correction(self): try: self.eyelink.doDriftCorrect((self.screen_width_px / 2), (self.screen_height_px / 2), 1, 1) except: self.eyelink.doTrackerSetup() pylink.msecDelay(50)
def shut_down(self, incomplete=False): """Terminates recording and disconnects from the eye tracker, putting it into standby mode. Will also transfer the EDF file for the current session from the tracker to the project's ``ExpAssets/EDF`` folder (or its ``incomplete`` subfolder, if incomplete = True). Called automatically whenever KLibs exits. For internal use only. Args: incomplete (bool, optional): Whether the full session was completed before the function was called. If True, the EDF file for the session will be written to an 'incomplete' subfolder of the eye tracker data directory ('ExpAssets/EDF'). Defaults to False. """ # Determine destination path for EDF (creating parent folder if needed) edf_dir = P.incomplete_edf_dir if incomplete else P.edf_dir if not os.path.isdir(edf_dir): os.makedirs(edf_dir) edf_path = os.path.join(edf_dir, self.edf_filename) self._quitting = True if self.isRecording() == 0: self.stopRecording() self.__recording = False self.setOfflineMode() msecDelay(500) self.closeDataFile() self.receiveDataFile(self.edf_filename, edf_path) return self.close()
def startEyeTracking(self, trial, calibTrial, widthPix, heightPix): #Set up each trial with the eye tracker if calibTrial: cond = "Test/Calibration Trial" else: cond = "Non-test/no calibration trial" message = "record_status_message 'Trial %d %s'" % (trial + 1, cond) self.tracker.sendCommand(message) msg = "TRIALID %s" % trial self.tracker.sendMessage(msg) #The following does drift correction at the begin of each trial if calibTrial: # Does drift correction and handles the re-do camera setup situations while True: try: error = self.tracker.doDriftCorrect( widthPix / 2, heightPix / 2, 1, 1) # 0: the fixation target must be drawn by the user if error != 27: #self.tracker.applyDriftCorrect break else: self.tracker.doTrackerSetup() except: print("Exception") break #self.tracker.sendCommand('start_drift_correction DATA =1 1 1 1') #CF - start drift correct?? #self.tracker.applyDriftCorrect() #CF - added to actually correct for drift self.tracker.setOfflineMode( ) #CF adds this to stop skipping trials due to not recording pylink.msecDelay(50) error = self.tracker.startRecording( 1, 1, 1, 1 ) #start to recording (File_samples, File_events, Link_samples, Link_events); if 1, writes something to EDF file. If 0, disables something recording. if error: return error pylink.beginRealTimeMode(100)
def start_recording(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.recording = True i = 0 while True: # params: write samples, write event, send samples, send events error = pylink.getEYELINK().startRecording(1, 1, 1, 1) if not error: break if i > self.MAX_TRY: raise Exception( \ "Error in libeyelink.libeyelink.start_recording(): Failed to start recording!") self.close() clock.expend() i += 1 print( \ "WARNING libeyelink.libeyelink.start_recording(): Failed to start recording (attempt %d of %d)" \ % (i, self.MAX_TRY)) pylink.msecDelay(100) # don't know what this is pylink.pylink.beginRealTimeMode(100) # wait a bit until samples start coming in if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise Exception( \ "Error in libeyelink.libeyelink.start_recording(): Failed to start recording (waitForBlockStart error)!")
def EyelinkCalibrate(targetloc=(1920, 1080), el=pylink.getEYELINK()): """ Performs calibration for Eyelink 1000+. **Author** : Wanja Mössing, WWU Münster | [email protected] \n *July 2017* Parameters: ---------- target : tuple two-item tuple width & height in px el : Eyelink object, optional """ el.sendMessage("STOP_REC_4_RECAL") # wait 100ms to catch final events pylink.msecDelay(100) # stop the recording el.stopRecording() # do the calibration el.doTrackerSetup(targetloc[0], targetloc[1]) # clear tracker display and draw box at center el.sendCommand("clear_screen 0") el.sendCommand("set_idle_mode") pylink.msecDelay(50) # re-start recording el.startRecording(1, 1, 1, 1) return el
def EyelinkDriftCheck(targetloc=(1920, 1080), el=pylink.getEYELINK()): """ Performs Driftcheck for Eyelink 1000+. **Author** : Wanja Mössing, WWU Münster | [email protected] \n *July 2017* Parameters: ---------- target : tuple two-item tuple width & height in px el : Eyelink object, optional """ # drift check try: el.sendMessage("STOP_REC_4_DRIFTCHECK") # wait 100ms to catch final events pylink.msecDelay(100) # stop the recording el.stopRecording() res = el.doDriftCorrect(targetloc[0], targetloc[1], 1, 1) # clear tracker display and draw box at center el.sendCommand("clear_screen 0") el.sendCommand("set_idle_mode") pylink.msecDelay(50) # re-start recording el.startRecording(1, 1, 1, 1) except: res = EyelinkCalibrate(targetloc, el) return res
def start_recording(self): """<DOC> Starts recording of gaze samples. Exceptions: Raises an exceptions.runtime_error on failure. </DOC>""" self.recording = True i = 0 while True: # Params: write samples, write event, send samples, send events error = pylink.getEYELINK().startRecording(1, 1, 1, 1) if not error: break if i > self.MAX_TRY: raise exceptions.runtime_error( \ u'Failed to start recording (startRecording error)') i += 1 print u'libeyelink.start_recording(): failed to start recording (attempt %d of %d)' \ % (i, self.MAX_TRY) pylink.msecDelay(100) # Don't know what this is pylink.pylink.beginRealTimeMode(100) # Wait for a bit until samples start coming in (I think?) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise exceptions.runtime_error( \ u'Failed to start recording (waitForBlockStart error)')
def startEyeTracking(self,trial, calibTrial,widthPix,heightPix): #Set up each trial with the eye tracker if calibTrial: cond = "Test/Calibration Trial" else: cond = "Non-test/no calibration trial" message ="record_status_message 'Trial %d %s'"%(trial+1, cond) self.tracker.sendCommand(message) msg = "TRIALID %s"%trial self.tracker.sendMessage(msg) #The following does drift correction at the begin of each trial if calibTrial:# Does drift correction and handles the re-do camera setup situations while True: try: error = self.tracker.doDriftCorrect(widthPix/2,heightPix/2,1,1) # 0: the fixation target must be drawn by the user if error != 27: #self.tracker.applyDriftCorrect break else: self.tracker.doTrackerSetup() except: print("Exception") break #self.tracker.sendCommand('start_drift_correction DATA =1 1 1 1') #CF - start drift correct?? #self.tracker.applyDriftCorrect() #CF - added to actually correct for drift self.tracker.setOfflineMode() #CF adds this to stop skipping trials due to not recording pylink.msecDelay(50) error = self.tracker.startRecording(1,1,1,1)#start to recording (File_samples, File_events, Link_samples, Link_events); if 1, writes something to EDF file. If 0, disables something recording. if error: return error; pylink.beginRealTimeMode(100)
def stop_recording(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.recording = False pylink.endRealTimeMode() pylink.getEYELINK().setOfflineMode() pylink.msecDelay(500)
def stopRecording(): """Stop eyetracker recording """ if getExperiment().recording: pylink.endRealTimeMode() pylink.msecDelay(100) getTracker().stopRecording() getExperiment().recording = False
def run_trial(params): ''' Run a trial params: image, condition in a list, e.g., ['quebec.jpg', 'no_people'] ''' # Unpacking the trial parameters pic, cond = params # Load the picture, scale the image to fill up the screen pic_path = os.path.join('images', pic) img = pygame.image.load(pic_path) img = pygame.transform.scale(img, (SCN_W, SCN_H)) # Record_status_message: show some info on the Host PC tk.sendCommand(f"record_status_message 'Picture: {pic}'") # Drift-check; re-calibrate if ESCAPE is pressed # parameters: x, y, draw_target, allow_setup tk.doDriftCorrect(int(SCN_W / 2), int(SCN_H / 2), 1, 1) # Start recording # parameters: file_event, file_sample, link_event, link_sample tk.startRecording(1, 1, 1, 1) # Wait for 100 ms to cache some samples pylink.msecDelay(100) # Present the image surf = pygame.display.get_surface() surf.blit(img, (0, 0)) pygame.display.flip() # Log a message to mark image onset tk.sendMessage('image_onset') # Log a '!V IMGLOAD' message to the EDF data file, so Data Viewer # knows where to find the image when visualizing the gaze data img_path = f'images/{pic}' tk.sendMessage(f'!V IMGLOAD FILL {img_path}') # Wait for a key response pygame.event.clear() # clear all cached events got_key = False while not got_key: for ev in pygame.event.get(): if ev.type == KEYDOWN: tk.sendMessage(f'Keypress {ev.key}') got_key = True # clear the screen surf.fill((128, 128, 128)) pygame.display.flip() # Log a message to mark image offset tk.sendMessage('image_offset') # stop recording tk.stopRecording()
def finish(self): """ Finalize the experiment """ self.setOfflineMode() pylink.msecDelay(500) self.closeDataFile() self.receiveDataFile(self._filename, self._filename) self.close()
def stop_recording(self): """ Stop recording of gaze samples """ self.recording = False pylink.endRealTimeMode() pylink.getEYELINK().setOfflineMode() pylink.msecDelay(500)
def stop_recording(self): """<DOC> Stops recording of gaze samples. </DOC>""" self.recording = False pylink.endRealTimeMode() pylink.getEYELINK().setOfflineMode() pylink.msecDelay(500)
def stop_recording(self): """ Stop recording of gaze samples """ self.recording = False pylink.endRealTimeMode(); pylink.getEYELINK().setOfflineMode(); pylink.msecDelay(500);
def End_exp(self): # Transfert et nettoyage de fichiers! self.eyelink.setOfflineMode() pylink.msecDelay(500) # Fermez le fichier et transférez-le sur Display PC self.eyelink.closeDataFile() self.eyelink.receiveDataFile(self.edfFileName, self.edfFileName_2) self.eyelink.close() # Fermer les graphiques de l'expérience pylink.closeGraphics()
def prepare_drift_correction(self, pos): """Puts the tracker in drift correction mode""" # start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50) # wait for a bit until samples start coming in (again, not sure if this # is indeed what's going on) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): print( \ "WARNING libeyelink.libeyelink.prepare_drift_correction(): Failed to perform drift correction (waitForBlockStart error)")
def closeConnection(self): '''Clean everything up, save data and close connection to tracker''' if self.tracker != None: # File transfer and cleanup! self.tracker.setOfflineMode() pylink.msecDelay(600) #Close the file and transfer it to Display PC self.tracker.closeDataFile() self.tracker.receiveDataFile(self.edfFileName, self.edfFileName) self.tracker.close() return "Eyelink connection closed successfully" else: return "Eyelink not available, not closed properly"
def retrieve(self, filename): ''' Docstring Parameters ---------- Returns ------- ''' self.tracker.setOfflineMode() pylink.msecDelay(1) self.tracker.closeDataFile() self.tracker.receiveDataFile(self.filename, filename)
def prepare_drift_correction(self, pos): """Puts the tracker in drift correction mode""" # start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50) # wait for a bit until samples start coming in (again, not sure if this # is indeed what's going on) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): print( "WARNING libeyelink.libeyelink.prepare_drift_correction(): " "Failed to perform drift correction (waitForBlockStart error)")
def close(self): """Helper method not directly called in EyeScript scripts in general Shuts down VisionEgg and writes the EventLog to a file.""" self.tracker.setOfflineMode() if self['subject'] > 0: self.log.writeLog(self.textdatafile) pylink.msecDelay(500) try: self.tracker.closeDataFile() self.tracker.receiveDataFile(self.edffile,self.eyedatafile) except RuntimeError: pass self.tracker.close() self.screen.close()
def prepare_drift_correction(self, pos): """<DOC> Puts the tracker in drift correction mode Arguments: pos -- the reference point Exceptions: Raises an exceptions.runtime_error on error </DOC>""" # Start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50)
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 startRecording(): """Commence eyetracker recording and verify that it's working. """ getTracker().resetData() getTracker().startRecording(1,1,1,1) getExperiment().recording = True pylink.beginRealTimeMode(100) try: if not getTracker().waitForBlockStart(1000,1,1): raise Exception("waitForBlockStart failed") except Exception: getTracker().drawText("LINK DATA NOT RECEIVED!",pos=(1,20)) pylink.endRealTimeMode() pylink.msecDelay(2000) getTracker().stopRecording() print "LINK DATA NOT RECEIVED!" raise TrialAbort(pylink.TRIAL_ERROR)
def terminate_task(): """ Terminate the task gracefully and retrieve the EDF data file file_to_retrieve: The EDF on the Host that we would like to download win: the current window used by the experimental script """ el_tracker = pylink.getEYELINK() if el_tracker.isConnected(): # Terminate the current trial first if the task terminated prematurely error = el_tracker.isRecording() if error == pylink.TRIAL_OK: abort_trial() # Put tracker in Offline mode el_tracker.setOfflineMode() # Clear the Host PC screen and wait for 500 ms el_tracker.sendCommand('clear_screen 0') pylink.msecDelay(500) # Close the edf data file on the Host el_tracker.closeDataFile() # Show a file transfer message on the screen msg = 'EDF data is transferring from EyeLink Host PC...' show_msg(win, msg, wait_for_keypress=False) # Download the EDF data file from the Host PC to a local data folder # parameters: source_file_on_the_host, destination_file_on_local_drive local_edf = os.path.join(session_folder, session_identifier + '.EDF') try: el_tracker.receiveDataFile(edf_file, local_edf) except RuntimeError as error: print('ERROR:', error) # Close the link to the tracker. el_tracker.close() # close the PsychoPy window win.close() # quit PsychoPy core.quit() sys.exit()
def startRecording(): """Commence eyetracker recording and verify that it's working. """ getTracker().resetData() getTracker().startRecording(1, 1, 1, 1) getExperiment().recording = True pylink.beginRealTimeMode(100) try: if not getTracker().waitForBlockStart(1000, 1, 1): raise Exception("waitForBlockStart failed") except Exception: getTracker().drawText("LINK DATA NOT RECEIVED!", pos=(1, 20)) pylink.endRealTimeMode() pylink.msecDelay(2000) getTracker().stopRecording() print "LINK DATA NOT RECEIVED!" raise TrialAbort(pylink.TRIAL_ERROR)
def prepare_drift_correction(self, pos): """ Puts the tracker in drift correction mode In: pos: the reference point """ # Start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50); # Wait for a bit until samples start coming in (I think?) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise exceptions.runtime_error("Failed to perform drift correction (waitForBlockStart error)")
def stop(self, outfile): ''' stop recording and receive the data file if outfile is not None. ''' # pumpDelay is a lower priority delay which does not block background # events. msecDelay is more aggressive. Here used to catch last bit of # data before stopping the recording pylink.pumpDelay(100) # idle mode self.tracker.setOfflineMode() pylink.msecDelay(500) # close the file on the tracker HD. Can take a while... self.tracker.closeDataFile() if outfile is not None: self.tracker.receiveDataFile(self.remotefilename, outfile) self.tracker.close() return
def prepare_drift_correction(self, pos): """ Puts the tracker in drift correction mode In: pos: the reference point """ # Start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50) # Wait for a bit until samples start coming in (I think?) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise exceptions.runtime_error( "Failed to perform drift correction (waitForBlockStart error)")
def EyelinkStop(Name, el=pylink.getEYELINK()): """ Performs stopping routines for the EyeLink 1000 Plus eyetracker. **Author** : Wanja Mössing, WWU Münster | [email protected] \n *July 2017* Parameters: ----------- Name : string filename of the edf. Doesn't have to, but can, end on '.edf' Must be the same name used during EyelinkStart() el : Eyelink Object Eyelink object returned by EyelinkStart(). By default this function tried to find it itself. """ # Check filename if '.edf' not in Name.lower(): Name += '.edf' # stop realtime mode pylink.endRealTimeMode(0) # make sure all experimental procedures finished pylink.msecDelay(1000) # stop the recording el.stopRecording() # put Eyelink back to idle el.setOfflineMode() # wait for stuff to finish pylink.msecDelay(500) # close edf el.closeDataFile() # transfer edf to display-computer try: print('Wait for EDF to be copied over LAN...') if not path.exists('./EDF'): mkdir('./EDF') el.receiveDataFile(Name, './EDF/' + Name) print('Done. EDF has been copied to ./EDF folder.') except RuntimeError: print('Error while pulling EDF file. Try to find it on Eyelink host..') el.close() pylink.closeGraphics() return
def EyelinkStop(Name, el=pylink.getEYELINK()): """ Performs stopping routines for the EyeLink 1000 Plus eyetracker. **Author** : Wanja Mössing, WWU Münster | [email protected] \n *July 2017* Parameters: ----------- Name : string filename of the edf. Doesn't have to, but can, end on '.edf' Must be the same name used during EyelinkStart() el : Eyelink Object Eyelink object returned by EyelinkStart(). By default this function tried to find it itself. """ # Check filename if '.edf' not in Name.lower(): Name += '.edf' # stop realtime mode pylink.endRealTimeMode() # make sure all experimental procedures finished pylink.msecDelay(1000) # stop the recording el.stopRecording() # put Eyelink back to idle el.setOfflineMode() # wait for stuff to finish pylink.msecDelay(500) # close edf el.closeDataFile() # transfer edf to display-computer try: print('Wait for EDF to be copied over LAN...') if not path.exists('./EDF'): mkdir('./EDF') el.receiveDataFile(Name, './EDF/'+Name) print('Done. EDF has been copied to ./EDF folder.') except RuntimeError: print('Error while pulling EDF file. Try to find it on Eyelink host..') el.close() pylink.closeGraphics() return
def prepare_drift_correction(self, pos): """<DOC> Puts the tracker in drift-correction mode. Arguments: pos -- The reference point. Exceptions: Raises an exceptions.runtime_error on error. </DOC>""" # Start collecting samples in drift correction mode self.send_command("heuristic_filter = ON") self.send_command("drift_correction_targets = %d %d" % pos) self.send_command("start_drift_correction data = 0 0 1 0") pylink.msecDelay(50) # Wait for a bit until samples start coming in (I think?) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise exceptions.runtime_error( \ u'Failed to perform drift correction (waitForBlockStart error)')
def close(self, full_close=True): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.eyelink_graphics.close() if self.recording: self.stop_recording() # close data file and transfer it to the experimental PC print(u"libeyelink.libeyelink.close(): Closing data file") pylink.getEYELINK().closeDataFile() pylink.msecDelay(500) print(u"libeyelink.libeyelink.close(): Transferring {} to {}".format( \ self.eyelink_data_file, self.local_data_file)) # During data transfer, suppress output _out = sys.stdout with open(os.devnull, 'w') as fd: sys.stdout = fd pylink.getEYELINK().receiveDataFile(self.eyelink_data_file, self.local_data_file) sys.stdout = _out pylink.msecDelay(500) print(u"libeyelink.libeyelink.close(): Closing eyelink") ### EDITED 12-08-2020 BY ALEX HOOGERBRUGGE ### ADDED THE CONDITIONAL. TO RESTORE, REMOVE THIS FILE AND RENAME ### LIBEYELINK_ORIGINAL.PY TO LIBEYELINK.PY if full_close: pylink.getEYELINK().close() pylink.msecDelay(500)
def start_recording(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.recording = True i = 0 while True: # params: write samples, write event, send samples, send events print(u'starting recording ...') error = pylink.getEYELINK().startRecording(1, 1, 1, 1) print(u'returned %s' % error) if not error: break if i > self.MAX_TRY: raise Exception( "Error in libeyelink.libeyelink.start_recording(): Failed " "to start recording!") self.close() clock.expend() i += 1 print( ("WARNING libeyelink.libeyelink.start_recording(): Failed to " "start recording (attempt %d of %d)") % (i, self.MAX_TRY)) pylink.msecDelay(100) # don't know what this is print(u'Start realtime mode ...') pylink.msecDelay(100) pylink.beginRealTimeMode(100) # wait a bit until samples start coming in print(u'Wait for block start ...') pylink.msecDelay(100) if not pylink.getEYELINK().waitForBlockStart(100, 1, 0): raise Exception( "Error in libeyelink.libeyelink.start_recording(): Failed to " "start recording (waitForBlockStart error)!") print(u'done ...')
def Start_trial(self, trial): # Titre essai en cours au bas de l'écran d'eyetracker print(trial) message = "record_status_message 'Trial %d/%d'" % (trial + 1, self.N_trials) self.eyelink.sendCommand(message) # EyeLink Data Viewer définit le début d'un essai par le message TRIALID. msg = "TRIALID %d" % trial self.eyelink.sendMessage(msg) msg = "!V TRIAL_VAR_DATA %d" % trial self.eyelink.sendMessage(msg) # Commutez le tracker sur ide et donnez-lui le temps d'effectuer un interrupteur de mode complet self.eyelink.setOfflineMode() pylink.msecDelay(50) # Commencez à enregistrer des échantillons et des événements sur le fichier edf et sur le lien. error = self.eyelink.startRecording(1, 1, 1, 1) # 0 si tout se passe bien ! if error: self.End_trial() print('error =', error) #return error #gc.disable() # Désactiver la collecte python pour éviter les retards TESTER ENLEVER !!! pylink.beginRealTimeMode(100) # Commencer le mode temps réel # Lit et supprime les événements dans la file d'attente de données jusqu'à ce qu'ils soient dans un bloc d'enregistrement. try: self.eyelink.waitForBlockStart(100, 1, 0) except RuntimeError: if pylink.getLastError( )[0] == 0: # Temps d'attente expiré sans données de lien self.End_trial() self.eyelink.sendMessage("TRIAL ERROR") print("ERROR: No link samples received!") return pylink.TRIAL_ERROR else: raise
def close(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" if self.recording: self.stop_recording() # close data file and transfer it to the experimental PC print("libeyelink.libeyelink.close(): Closing data file") pylink.getEYELINK().closeDataFile() pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Transferring %s to %s" \ % (self.eyelink_data_file, self.local_data_file)) pylink.getEYELINK().receiveDataFile(self.eyelink_data_file, \ self.local_data_file) pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Closing eyelink") pylink.getEYELINK().close() pylink.msecDelay(500)
def close(self): """ Close the connection with the eyelink """ if self.recording: self.stop_recording() # Close the datafile and transfer it to the experimental pc print "libeyelink: closing data file" pylink.getEYELINK().closeDataFile() pylink.msecDelay(100) print "libeyelink: transferring data file" pylink.getEYELINK().receiveDataFile(self.data_file, self.data_file) pylink.msecDelay(100) print "libeyelink: closing eyelink" pylink.getEYELINK().close() pylink.msecDelay(100)
def close(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.eyelink_graphics.close() if self.recording: self.stop_recording() # close data file and transfer it to the experimental PC print("libeyelink.libeyelink.close(): Closing data file") pylink.getEYELINK().closeDataFile() pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Transferring %s to %s" \ % (self.eyelink_data_file, self.local_data_file)) pylink.getEYELINK().receiveDataFile(self.eyelink_data_file, self.local_data_file) pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Closing eyelink") pylink.getEYELINK().close() pylink.msecDelay(500)
def close(self): """<DOC> Closes the connection with the eyelink. </DOC>""" if self.recording: self.stop_recording() # Close the datafile and transfer it to the experimental pc print u'libeyelink: closing data file' pylink.getEYELINK().closeDataFile() pylink.msecDelay(100) print u'libeyelink: transferring data file' pylink.getEYELINK().receiveDataFile(self.data_file, self.data_file) pylink.msecDelay(100) print u'libeyelink: closing eyelink' pylink.getEYELINK().close() pylink.msecDelay(100)
def close(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.eyelink_graphics.close() if self.recording: self.stop_recording() # close data file and transfer it to the experimental PC print("libeyelink.libeyelink.close(): Closing data file") pylink.getEYELINK().closeDataFile() pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Transferring %s to %s" % (self.eyelink_data_file, self.local_data_file)) # During data transfer, suppress output _out = sys.stdout with open(os.devnull, "w") as fd: sys.stdout = fd pylink.getEYELINK().receiveDataFile(self.eyelink_data_file, self.local_data_file) sys.stdout = _out pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Closing eyelink") pylink.getEYELINK().close() pylink.msecDelay(500)
def close(self): """See pygaze._eyetracker.baseeyetracker.BaseEyeTracker""" self.eyelink_graphics.close() if self.recording: self.stop_recording() # close data file and transfer it to the experimental PC print("libeyelink.libeyelink.close(): Closing data file") pylink.getEYELINK().closeDataFile() pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Transferring %s to %s" \ % (self.eyelink_data_file, self.local_data_file)) # During data transfer, suppress output _out = sys.stdout with open(os.devnull, 'w') as fd: sys.stdout = fd pylink.getEYELINK().receiveDataFile(self.eyelink_data_file, self.local_data_file) sys.stdout = _out pylink.msecDelay(500) print("libeyelink.libeyelink.close(): Closing eyelink") pylink.getEYELINK().close() pylink.msecDelay(500)
pylink.getEYELINK().sendCommand("file_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,MESSAGE,BUTTON") if tracker_software_ver>=4: pylink.getEYELINK().sendCommand("file_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS,HTARGET") else: pylink.getEYELINK().sendCommand("file_sample_data = LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS") pylink.setCalibrationColors( (0, 0, 0),(255, 255, 255)); #Sets the calibration target and background color pylink.setTargetSize(int(window_size[0]/40), int(window_size[0]/30)); #select best size for calibration target #----------------------------------------------------------------------------- pylink.beginRealTimeMode(0) print 'started real time mode' pylink.getEYELINK().startRecording(1, 1, 0, 0) core.wait(3) pylink.endRealTimeMode() pylink.getEYELINK().setOfflineMode() win.close() if pylink.getEYELINK() != None: # File transfer and cleanup! pylink.getEYELINK().setOfflineMode(); pylink.msecDelay(500); #Close the file and transfer it to Display PC pylink.getEYELINK().closeDataFile() pylink.getEYELINK().receiveDataFile(globvar.edf_filename, globvar.edf_filename) pylink.getEYELINK().close();
t_pars = [['lake.png', 'c'], ['lake_blur.png', 'b'], ['train.png', 'c'], ['train_blur.png', 'b']] # Step 1: connect to the tracker tk = pylink.EyeLink('100.1.1.1') # Step 2: open a Pygame window first; then call openGraphics() # to let Pylink use the Pygame window for calibration pygame.display.set_mode((scn_w, scn_h), DOUBLEBUF | FULLSCREEN) pylink.openGraphics() # Step 3: set some tracking parameters, e.g., sampling rate to 1000 Hz # put the tracker in offline mode before we change its parameters tk.setOfflineMode() # give the tracker an extra 100 ms to switch operation mode pylink.msecDelay(100) # set the sampling rate to 1000 Hz tk.sendCommand("sample_rate 1000") # Send screen resolution to the tracker tk.sendCommand("screen_pixel_coords = 0 0 %d %d" % (scn_w - 1, scn_h - 1)) # request the tracker to perform a standard 9-point calibration tk.sendCommand("calibration_type = HV9") #calibrate the central 80% of the screen tk.sendCommand('calibration_area_proportion 0.8 0.8') tk.sendCommand('validation_area_proportion 0.8 0.8') # Step 4: open EDF data file
def EyelinkStart(dispsize, Name, win, bits=32, dummy=False, colors=((0, 0, 0), (192, 192, 192))): """ Performs startup routines for the EyeLink 1000 Plus eyetracker. **Author** : Wanja Mössing, WWU Münster | [email protected] \n *July 2017* Parameters: ----------- dispsize : tuple two-item tuple width & height in px Name : string filename for the edf. Doesn't have to, but can, end on '.edf' Maximum length is 8 (without '.edf'). Possible alphanumeric input: 'a-z', 'A-Z', '0-9', '-' & '_' win : window object You necessarily need to open a psychopy window first! bits : integer color-depth, defaults to 32 dummy : boolean Run tracker in dummy mode? colors : Tuple, Optional. Tuple with two RGB triplets Returns ------- 'el' the tracker object. This can be passed to other functions, although they can use pylink.getEYELINK() to find it automatically. """ print('. ') # get filename if '.edf' not in Name.lower(): if len(Name) > 8: print('EDF filename too long! (1-8 characters/letters)') raise SystemExit else: Name += '.edf' elif '.edf' in Name.lower(): if len(Name) > 12: print('EDF filename too long! (1-8 characters/letters)') raise SystemExit print('. ') # initialize tracker object if dummy: el = pylink.EyeLink(None) else: el = pylink.EyeLink("100.1.1.1") print('. ') # Open EDF file on host el.openDataFile(Name) print('. ') # set file preamble currentdir = path.basename(getcwd()) FilePreamble = "add_file_preamble_text \'" FilePreamble += "Eyetracking Dataset AE Busch WWU Muenster Experiment: " FilePreamble += currentdir + "\'" el.sendCommand(FilePreamble) print('. ') # this function calls the custom calibration routine # "EyeLinkCoreGraphicsPsychopy.py" genv = EyeLinkCoreGraphicsPsychoPy(el, win) pylink.openGraphicsEx(genv) print('. ') # set tracker offline to change configuration el.setOfflineMode() print('. ') # flush old keys pylink.flushGetkeyQueue() print('. ') # set sampling rate el.sendCommand('sample_rate 1000') print('. ') # Sets the display coordinate system and sends mesage to that # effect to EDF file; el.sendCommand("screen_pixel_coords = 0 0 %d %d" % (dispsize[0] - 1, dispsize[1] - 1)) el.sendMessage("DISPLAY_COORDS 0 0 %d %d" % (dispsize[0] - 1, dispsize[1] - 1)) print('. ') # select parser configuration for online saccade etc detection ELversion = el.getTrackerVersion() ELsoftVer = 0 if ELversion == 3: tmp = el.getTrackerVersionString() tmpidx = tmp.find('EYELINK CL') ELsoftVer = int(float(tmp[(tmpidx + len("EYELINK CL")):].strip())) if ELversion >= 2: el.sendCommand("select_parser_configuration 0") if ELversion == 2: # turn off scenelink stuff (that's an EL2 front-cam addon...) el.sendCommand("scene_camera_gazemap = NO") else: el.sendCommand("saccade_velocity_threshold = 35") el.sendCommand("saccade_acceleration_threshold = 9500") print('. ') # set EDF file contents AREA el.sendCommand("file_event_filter = LEFT,RIGHT,FIXATION," "SACCADE,BLINK,MESSAGE,BUTTON,INPUT") if ELsoftVer >= 4: el.sendCommand("file_sample_data = LEFT,RIGHT,GAZE,HREF," "AREA,HTARGET,GAZERES,STATUS,INPUT") else: el.sendCommand("file_sample_data = LEFT,RIGHT,GAZE,HREF," "AREA,GAZERES,STATUS,INPUT") print('. ') # set link data (online interaction)AREA el.sendCommand("link_event_filter = LEFT,RIGHT,FIXATION,SACCADE," "BLINK,MESSAGE,BUTTON,INPUT") if ELsoftVer >= 4: el.sendCommand("link_sample_data = LEFT,RIGHT,GAZE,GAZERES,AREA," "HTARGET,STATUS,INPUT") else: el.sendCommand("link_sample_data = LEFT,RIGHT,GAZE,GAZERES,AREA," "STATUS,INPUT") print('. ') # run initial calibration # 13-Pt Grid calibration el.sendCommand('calibration_type = HV13') el.doTrackerSetup(dispsize[0], dispsize[1]) # put tracker in idle mode and wait 50ms, then really start it. el.sendMessage('SETUP_FINISHED') el.setOfflineMode() pylink.msecDelay(500) # set to realtime mode pylink.beginRealTimeMode(200) # start recording # note: sending everything over the link *potentially* causes buffer # overflow. However, with modern PCs and EL1000+ this shouldn't be a real # problem el.startRecording(1, 1, 1, 1) # to activate parallel port readout without modifying the FINAL.INI on the # eyelink host pc, uncomment these lines # tyical settings for straight-through TTL cable (data pins -> data pins) el.sendCommand('write_ioport 0xA 0x20') el.sendCommand('create_button 1 8 0x01 0') el.sendCommand('create_button 2 8 0x02 0') el.sendCommand('create_button 3 8 0x04 0') el.sendCommand('create_button 4 8 0x08 0') el.sendCommand('create_button 5 8 0x10 0') el.sendCommand('create_button 6 8 0x20 0') el.sendCommand('create_button 7 8 0x40 0') el.sendCommand('create_button 8 8 0x80 0') el.sendCommand('input_data_ports = 8') el.sendCommand('input_data_masks = 0xFF') # tyical settings for crossover TTL cable (data pins -> status pins) # el.sendCommand('write_ioport 0xA 0x0') # el.sendCommand('create_button 1 9 0x20 1') # el.sendCommand('create_button 2 9 0x40 1') # el.sendCommand('create_button 3 9 0x08 1') # el.sendCommand('create_button 4 9 0x10 1') # el.sendCommand('create_button 5 9 0x80 0') # el.sendCommand('input_data_ports = 9') # el.sendCommand('input_data_masks = 0xFF') # mark end of Eyelinkstart in .edf el.sendMessage('>EndOfEyeLinkStart') # return Eyelink object return el
trialComponents.append(fixL) trialComponents.append(fixR) for thisComponent in trialComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # //////////////////////////////////////////////////////////////////////////////// #win.winHandle.minimize() #drCor(el,dr,cd) #win.winHandle.maximize() #win.winHandle.activate() el.sendMessage("TRIALID " + str(nDone)) trialStartStr = datetime.now().strftime('%Y-%m-%d_%H%M%S') el.sendMessage("TIMESTAMP " + trialStartStr) el.setOfflineMode() pl.msecDelay(50) error = el.startRecording(1,1,1,1) # //////////////////////////////////////////////////////////////////////////////// #-------Start Routine "trial"------- continueRoutine = True while continueRoutine: # get current time t = trialClock.getTime() frameN = frameN + 1 # number of completed frames (0 is the first frame) # update/draw components on each frame # *windowLeft* updates if windowLeft.status == NOT_STARTED: # keep track of start time/frame for later windowLeft.tStart = t # underestimates by a little under one frame
def doSim(self, trial, road, duration, tau, doEyetrack): # Measure sample rate in order to calculate delay buffer sample_rate = self.screen.measure_refresh_rate(2.0) print "Sample rate: " + str(sample_rate) #sample_rate = 60 self.doEyetrack = doEyetrack self.pos_ring = RingBuffer(self.center, int(math.floor(tau * sample_rate)) + 1) print("Ring Buffer:: size: " + str(self.pos_ring.size)) if doEyetrack: import pylink from EyeLinkCoreGraphicsVE import EyeLinkCoreGraphicsVE self.tracker = pylink.EyeLink() if self.tracker == None: print "Error: Eyelink is not connected" sys.exit() genv = EyeLinkCoreGraphicsVE(self.screen, self.tracker) pylink.openGraphicsEx(genv) #Opens the EDF file. edfFileName = "TRIAL" + str(trial) + ".EDF" self.tracker.openDataFile(edfFileName) pylink.flushGetkeyQueue() self.tracker.sendCommand("screen_pixel_coords = 0 0 %d %d" % (VisionEgg.config.VISIONEGG_SCREEN_W, VisionEgg.config.VISIONEGG_SCREEN_H)) 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") if not self.doneSetup: self.tracker.doTrackerSetup() self.doneSetup = True else: while 1: try: error = self.tracker.doDriftCorrect( self.screen.size[0] / 2, self.screen.size[1] / 2, 1, 1) if error != 27: # ?? from example break else: self.tracker.doTrackerSetup() except: break self.screen.parameters.bgcolor = 106.0 / 255.0, 147.0 / 255.0, 0.0 # Load road data from file and create an image roadArray = numpy.loadtxt('road' + str(road) + '.txt') # Convert to a Path roadPath = ImagePath.Path( map(lambda xy: (xy[0], xy[1]), roadArray.tolist())) # Use Path to create a plot of the road im = Image.new("RGB", (2000, 100), (50, 50, 50)) draw = ImageDraw.Draw(im) # draw each side of the road separately draw.line(roadPath[:4000], fill=(200, 200, 200)) draw.line(roadPath[4000:], fill=(200, 200, 200)) del draw # Lay out a road texture in the x-z plane roadTexture = Texture(im) del im eye_height = 2.5 vertices = [(-10, -eye_height, 0), (-10, -eye_height, -1000), (10, -eye_height, 0), (10, -eye_height, -1000)] rect = TextureStimulus3D(texture=roadTexture, lowerleft=vertices[0], lowerright=vertices[1], upperleft=vertices[2], upperright=vertices[3]) # We will use these later for our camera transforms self.camera_matrix = ModelView() self.frame_timer = FrameTimer() self.outf = open( 'steersim-' + str(trial) + '-' + str(road) + '-out.txt', 'wb') # Vewport for the road viewport3D = Viewport( screen=self.screen, projection=SimplePerspectiveProjection(fov_x=75.2), camera_matrix=self.camera_matrix, stimuli=[rect]) # Construct a sky sky_l = 0 sky_r = self.screen.size[0] sky_t = self.screen.size[1] sky_b = self.screen.size[1] / 2 sky_vertices = [(sky_l, sky_t, 0), (sky_r, sky_t, 0), (sky_r, sky_b, 0), (sky_l, sky_b, 0)] sky = Rectangle3D(color=(144.0 / 255.0, 190.0 / 255.0, 1.0), vertex1=sky_vertices[0], vertex2=sky_vertices[1], vertex3=sky_vertices[2], vertex4=sky_vertices[3]) wheelTexture = Texture('wheel.png') self.wheel = TextureStimulus(texture=wheelTexture, internal_format=gl.GL_RGBA, position=(self.center, -75), anchor='center') # display the sky in its own viewport viewport2D = Viewport(screen=self.screen) viewport2D.parameters.stimuli = [sky, self.wheel] self.init_state() askText = Text(text='Press a key to start', anchor='center', position=(self.center, self.screen.size[1] / 2)) splash = Viewport(screen=self.screen) splash.parameters.stimuli = [askText] self.askForNext = Presentation(go_duration=(0.5, 'seconds'), viewports=[splash]) self.askForNext.add_controller( None, None, FunctionController(during_go_func=self.wait_for_key)) self.askForNext.parameters.enter_go_loop = True self.askForNext.run_forever() self.simPres = Presentation(go_duration=(duration, 'seconds'), viewports=[viewport3D, viewport2D], handle_event_callbacks=[ (pygame.KEYDOWN, self.check_keypress) ]) self.simPres.add_controller( None, None, FunctionController(during_go_func=self.update)) if doEyetrack: startTime = pylink.currentTime() self.tracker.sendMessage("SYNCTIME %d" % (pylink.currentTime() - startTime)) error = self.tracker.startRecording(1, 1, 1, 1) self.tracker.sendMessage("PRES %d START" % (trial)) self.simPres.go() if doEyetrack: self.tracker.sendMessage("PRES %d END" % (trial)) self.tracker.stopRecording() # 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(edfFileName, edfFileName) self.outf.close() if self.quit: raise SystemExit