def calibrateEyeTrackerPyGaze():
    """
        Runs the callibration process using PyGaze and tobii eye trackers.
    """

    disp = Display()
    tracker = EyeTracker(disp,resolution=(1600,900),  trackertype='tobii')
    
    tracker.calibrate()
    
    #tracker.close() 
    disp.close()
    return tracker
Example #2
0
    def run(self):
        """The run phase of the plug-in goes here."""

        if hasattr(self.experiment, u'pygaze_eyetracker'):
            raise osexception( \
             u'You should have only one instance of `pygaze_init` in your experiment')
        self.set_item_onset()
        # Determine the tracker type and perform certain tracker-specific
        # operations.
        if self.tracker_type == u'Simple dummy':
            tracker_type = u'dumbdummy'
        elif self.tracker_type == u'Advanced dummy (mouse simulation)':
            tracker_type = u'dummy'
        elif self.tracker_type == u'EyeLink':
            tracker_type = u'eyelink'
            if self.get(u'eyelink_calbeep'):
                from openexp.synth import synth
                self.beep = synth(self.experiment)
        elif self.tracker_type == u'Tobii':
            tracker_type = u'tobii'
        elif self.tracker_type == u'SMI':
            tracker_type = u'smi'
        else:
            raise osexception(u'Unknown tracker type: %s' % self.tracker_type)
        # Determine logfile
        if self.get(u'_logfile') == u'automatic':
            logfile = os.path.splitext(self.get(u'logfile'))[0]
            if tracker_type == u'eyelink':
                logfile = logfile + u'.edf'
        else:
            logfile = self.get(u'_logfile')
        # Determine event detection
        if tracker_type == u'eyelink':
            event_detection = u'native'
        else:
            event_detection = u'pygaze'
        # Initialize pygaze and the eye-tracker object
        self.experiment.pygaze_display = Display(u'opensesame')
        self.experiment.pygaze_eyetracker = EyeTracker( \
         self.experiment.pygaze_display, trackertype=tracker_type, \
         data_file=logfile, eventdetection=event_detection, \
         saccade_velocity_threshold=self.get(u'sacc_vel_thr'), \
         saccade_acceleration_threshold=self.get(u'sacc_acc_thr'), \
         ip=self.get(u'smi_ip'), sendport=self.get(u'smi_send_port'), \
         receiveport=self.get(u'smi_recv_port'), logfile=logfile,
         eyelink_force_drift_correct= \
         self.get(u'eyelink_force_drift_correct'))
        self.experiment.pygaze_eyetracker.set_draw_calibration_target_func( \
         self.draw_calibration_canvas)
        self.experiment.cleanup_functions.append(self.close)
        if self.calibrate == u'yes':
            self.experiment.pygaze_eyetracker.calibrate()
Example #3
0
from pygaze.logfile import Logfile
import pygaze.libtime as timer

import cv2
import numpy
if DISPTYPE == 'psychopy':
    from psychopy.visual import ImageStim
elif DISPTYPE == 'pygame':
    import pygame

# # # # #
# INITIALISE

# Start a new Display instance to be able to show things on the monitor.
# The important parameters will automatically be loaded from the constants.
disp = Display()

# Initialise a Keyboard instance to detect key presses. Again, important
# parameters will be loaded from the constants.
kb = Keyboard()

# Initialise the EyeTracker and let it know which Display instance to use by
# passing it to the EyeTracker.
tracker = EyeTracker(disp)

# Create a Logfile instance that keeps track of when videos start.
log = Logfile()
# Write a header to the log file.
log.write(['date', 'time', 'trialnr', 'video', 'timestamp'])

# # # # #
Example #4
0
from pygaze.screen import Screen
from pygaze.keyboard import Keyboard
from pygaze.mouse import Mouse
from pygaze.logfile import Logfile
from pygaze.eyetracker import EyeTracker
import pygaze.libtime as timer

from scansync.mri import MRITriggerBox


##############
# INITIALISE #
##############

# Initialise a new Display instance.
disp = Display()

# Present a start-up screen.
scr = Screen()
scr.draw_text("Loading, please wait...", fontsize=24)
disp.fill(scr)
disp.show()

# Open a new log file.
log = Logfile()
# TODO: Write header.
log.write(["trialnr", "block", "run","stim", "keypress", "go_nogo", "face_onset", "signal_onset","resp_onset", "RT", "accuracy", "respmap", "block_type"])

# Open a new log file to log events.
event_log = Logfile(filename=EVENT_LOG)
event_log.write(["time", "event"])
Example #5
0
	def run(self):

		"""
		desc:
			The run phase of the plug-in goes here.
		"""

		if hasattr(self.experiment, u'pygaze_eyetracker'):
			raise osexception( \
				u'You should have only one instance of `pygaze_init` in your experiment')
		self.set_item_onset()
		# Determine the tracker type and perform certain tracker-specific
		# operations.
		if self.tracker_type == u'Simple dummy':
			tracker_type = u'dumbdummy'
		elif self.tracker_type == u'Advanced dummy (mouse simulation)':
			tracker_type = u'dummy'
		elif self.tracker_type == u'EyeLink':
			tracker_type = u'eyelink'
		elif self.tracker_type == u'Tobii':
			tracker_type = u'tobii'
		elif self.tracker_type == u'SMI':
			tracker_type = u'smi'
		elif self.tracker_type == u'EyeTribe':
			tracker_type = u'eyetribe'
		else:
			raise osexception(u'Unknown tracker type: %s' % self.tracker_type)
		# Determine logfile
		if self.get(u'_logfile') == u'automatic':
			logfile = os.path.splitext(self.get(u'logfile'))[0]
			if tracker_type == u'eyelink':
				# Automatically shorten filenames like 'subject-0', because
				# these are too long. This avoids having to rename logfiles
				# all the time.
				basename = os.path.basename(logfile)
				dirname = os.path.dirname(logfile)
				if len(basename) > 8 and basename.startswith(u'subject-'):
					basename = u'sub_' + basename[8:]
					logfile = os.path.join(dirname, basename)
					print(u'Attention: EyeLink logfile renamed to %s.edf' \
						% logfile)
				elif basename == u'defaultlog':
					logfile = u'default'
					print(u'Attention: EyeLink logfile renamed to %s.edf' \
						% logfile)
				logfile = logfile + u'.edf'
		else:
			logfile = self.get(u'_logfile')
		# Determine event detection
		if tracker_type == u'eyelink':
			event_detection = u'native'
		else:
			event_detection = u'pygaze'
		# Initialize pygaze and the eye-tracker object
		self.experiment.pygaze_display = Display(u'opensesame')
		self.experiment.pygaze_eyetracker = EyeTracker(
			self.experiment.pygaze_display, trackertype=tracker_type,
			data_file=logfile, eventdetection=event_detection,
			saccade_velocity_threshold=self.get(u'sacc_vel_thr'),
			saccade_acceleration_threshold=self.get(u'sacc_acc_thr'),
			ip=self.get(u'smi_ip'), sendport=self.get(u'smi_send_port'),
			receiveport=self.get(u'smi_recv_port'), logfile=logfile,
			eyelink_force_drift_correct=self.get(
			u'eyelink_force_drift_correct'),pupil_size_mode=self.get(
			u'eyelink_pupil_size_mode'))
		if self.get(u'calbeep') == 'yes':
			from openexp.synth import synth
			self.beep = synth(self.experiment)
		self.experiment.pygaze_eyetracker.set_draw_calibration_target_func(
			self.draw_calibration_canvas)
		self.experiment.pygaze_eyetracker.set_draw_drift_correction_target_func(
			self.draw_calibration_canvas)
		self.experiment.cleanup_functions.append(self.close)
		if self.calibrate == u'yes':
			self.experiment.pygaze_eyetracker.calibrate()
import random

from constants import *

from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.sound import Sound
from pygaze.keyboard import Keyboard
from pygaze.logfile import Logfile
import pygaze.libtime as timer

# Create a new Display instance.
disp = Display()

# Create a new Keyboard instance.
kb = Keyboard()

# Create a new Logfile instance.
log = Logfile()
log.write(["trialnr", "trial_type", "stimulus", \
    "fix_onset", "stim_onset", "response", "RT", \
    "correct"])

# Create a BAD sound.
bad_sound = Sound(osc="whitenoise", length=200)
bad_sound.set_volume(1)
good_sound = Sound(osc="sine", freq=440, length=200)
good_sound.set_volume(0.5)

# Create a new Screen instance.
scr = Screen()
Example #7
0
from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.eyetracker import EyeTracker

disp = Display()
tracker = EyeTracker(disp)

scr.draw_text(text="Resetting connection to %s tracker" % (TRACKERTYPE), \
    fontsize=24)
disp.fill(scr)
disp.show()

try:
    tracker.stop_recording()
except:
    print("Could not stop recording")

tracker.close()
disp.close()
import os

# PyGaze
from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.eyetracker import EyeTracker
from pygaze.keyboard import Keyboard
from pygaze.libtime import clock


# # # # #
# SETUP

# visuals
disp = Display()
scr = Screen()

# input
tracker = EyeTracker(disp)
kb = Keyboard(keylist=None, timeout=None)

# calibrate
tracker.calibrate()

# starting screen
scr.clear()
scr.draw_text(text="Press Space to start")
disp.fill(scr)
disp.show()
kb.get_key(keylist=['space'], timeout=None, flush=True)
Example #9
0
"""
Created on Thu Nov 10 15:42:29 2016

@author: adam
"""

import pygaze
from pygaze.display import Display
from pygaze.screen import Screen
import pygaze.libtime as timer
import numpy
from psychopy.visual import GratingStim

# Initialize a new Display instance (specifications are in
# constants.py).
disp = Display()

# Create a new GratingStim. The sinusoidal texture and the
# Gaussian mask will make it into a Gabor. The spatial
# frequency of 0.05 cycles per pixel will make it have
# 1 cycle every 20 pixels.
gabor = GratingStim(pygaze.expdisplay, tex='sin', mask='gauss', \
    sf=0.05, size=200)

# Initialize a new Screen instance for the Gabor.
gaborscreen = Screen()
# Add the GratingStim to the gaborscreen's screen property
# (a list of all PsychoPy stimuli in the screen).
gaborscreen.screen.append(gabor)

# Create random numbers between 0 and 1 (numpy.random.rand),
Example #10
0
    hand_pattern = 'LRLRLRLR'

if testing:
    allTrials = allTrials[0:8]
    blockLen = 2
    nT = 14
    train = 2

# if which_monitor == "eyetracker":
# win = visual.Window([1280,1024], monitor="tobii", units="deg",color='white',fullscr=False)
# elif which_monitor == "haley_small":
# win = visual.Window([1080, 675], monitor="haleys", units="deg",color='white',fullscr=False)

# Initialise a new Display instance
disp = Display(disptype='psychopy',
               dispsize=(1280, 1024),
               bgc=(255, 255, 255, 255))

# Initialise a new EyeTracker instance
tracker = EyeTracker(disp, trackertype='tobii')
tracker.fixtresh = 1.5
tracker.calibrate()

win = pygaze.expdisplay
win.mouseVisible = False

fixation = visual.ShapeStim(win,
                            vertices=((0, -15), (0, 15), (0, 0), (-15, 0),
                                      (15, 0)),
                            lineWidth=5,
                            closeShape=False,
Example #11
0
from pygaze.screen import Screen
from pygaze.keyboard import Keyboard
from pygaze.mouse import Mouse
from pygaze.logfile import Logfile
from pygaze.eyetracker import EyeTracker
import pygaze.libtime as timer

from libmeg import *

#%%

# # # # #
# INITIALISE

# Initialise a new Display instance.
disp = Display()

# Present a start-up screen.
scr = Screen()
scr.draw_text("Loading, please wait...", fontsize=MAIN_FONTSIZE)
disp.fill(scr)
disp.show()



# Open a new log file.
log = Logfile(filename = LOGFILE)
log_det = Logfile(filename = DETAILED_LOGFILE)
log_events = Logfile(filename = EVENT_LOGFILE)
# TODO: Write header.
log.write(["trialnr","left_ang","right_ang", "cue_dir", "targ", "targ_ang", "resp_ang", "perc_diff", "resp_onset", "resp_duration", "iti", "iti_onset", "stim_onset","delay_onset", "cue_onset", "postcue_onset","probe_onset", "prac"])
Example #12
0
'''
Código para Pygaze
'''

from constants import *
from pygaze.display import Display
from pygaze.screen import Screen
from pygaze.keyboard import Keyboard
import pygaze.libtime as timer
from pygaze.logfile import Logfile
import random

# Criando todas as instâncias (display, screen e coleta de tecla)

# Criando display que será apresentado no monitor do PC
disp = Display()

# Criando a keyboard para coleta de respostas
kb = Keyboard()
# Após kb - Criando o logfile para armazenar e salvar os dados coletados
log = Logfile()

# Tela de instruções do experimento


instructions = 'Seja bem vindo(a)!\n' \
               'Neste experimento as letras F e J apareceraão em ambos os lados da tela.\n' \
               'Se você ver a letra F, então pressione a tecla F.\n' \
               'Se você ver a letra J, então pressione a tecla J.\n' \
               'Tente ser tão rápido e preciso quanto possível durante os ensaios.\n\n' \
                'Aperte a barra de espaço do teclado para começar.\n\n' \
logfolderpath = os.path.join(
    c.LOGDIR, "{0}_{1}_{2}".format(subjectNumber, newSubject.subject_code,
                                   fulltimenow))
if not os.path.exists(logfolderpath):
    os.makedirs(logfolderpath)
logfilepath = os.path.join(
    logfolderpath, "s{0}_{1}_{2}".format(subjectNumber,
                                         newSubject.subject_code, datenow))

# initialize a Timer
timer = Time()

# initialize the display for stimuli
disp = Display(disptype="psychopy",
               dispsize=c.TOBII_DISPSIZE,
               screennr=0,
               bgc="grey")

# initialize a tobiitracker
tracker = InfantTobiiTracker(disp, logfilepath)

# create a new logfile (for TESTing purposes only)
eventlog = Logfile(filename="{0}\subj{1}_caliblog_{2}".format(
    logfolderpath, subjectNumber, datenow))
eventlog.write([
    "\nDate and time of experiment: {0}".format(
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
])
eventlog.write(["Subject number: {0}".format(subjectNumber)])
eventlog.write([
    "Test positions: 1. interesting: {0}, 2. interesting: {1}".format(
xax = DISPSIZE[0]
yax = DISPSIZE[1]

cy = yax / 2
cx = xax / 2

### Set size of game matrix relative to screen with 'margin'.
margin = 0.7
side = yax * margin
t_side = side / p1
tloc = t_side / p1

owncol = (255, 255, 255)
othercol = (255, 255, 255)

disp = Display(dispsize=DISPSIZE, screennr=2)
mse = Mouse(visible=False, timeout=10)

gamescreen = Screen(dispsize=DISPSIZE)

#tracker = EyeTracker(disp)

fixscr = Screen(dispsize=DISPSIZE)
fixscr.draw_fixation(fixtype='cross', diameter=8)

introscreen = Screen(dispsize=DISPSIZE)
introscreen.draw_text("Welcome to the experiment", fontsize=30)
introscreen.draw_text("\n\n\n (To proceed, press any key)", fontsize=25)

istrscreen = Screen(dispsize=DISPSIZE)
istrscreen.draw_text(
Example #15
0
				RUMBLE = False
	# set up function argument types and return type
	XInputSetState = xinput.XInputSetState
	XInputSetState.argtypes = [ctypes.c_uint, ctypes.POINTER(XINPUT_VIBRATION)]
	XInputSetState.restype = ctypes.c_uint
	# define helper function
	def set_vibration(controller, left_motor, right_motor):
	    vibration = XINPUT_VIBRATION(int(left_motor * 65535), int(right_motor * 65535))
	    XInputSetState(controller, ctypes.byref(vibration))


# # # # #
# PYGAZE INSTANCES

# visual
disp = Display()
scr = Screen()
# input
js = Joystick()


# # # # #
# RUN

# run until a minute has passed
t0 = timer.get_time()
t1 = timer.get_time()
text = "Test the joystick!"
while t1 - t0 < 60000:
	# get joystick input
	event, value, t1 = js.get_joyinput(timeout=10)
Example #16
0
from pygaze.display import Display
import pygaze.libtime as timer
from pygaze.screen import Screen
from constants import *

fixscreen = Screen()
fixscreen.draw_fixation(fixtype='dot')

disp = Display()
timer.pause(2000)
disp.close()
Example #17
0
    # sd.setup_mic()

    t = threading.Thread(target=run_server)
    t.daemon = True

    eye_lock = threading.Lock()
    eye_event = threading.Event()
    eye_thread = threading.Thread(name='eye_tracking',
                                  target=eye_tracker,
                                  args=(
                                      eye_lock,
                                      eye_event,
                                  ))
    eye_thread.daemon = True

    disp = Display(disptype='psychopy')
    scr = Screen(disptype='psychopy')
    disp.close()
    tracker = EyeTracker(disp, trackertype='eyetribe')

    EYE_DATA = Queue.Queue(500)

    try:
        t.start()

        eye_thread.start()

        with Listener(on_click=on_click) as listener:
            listener.join()

        # listener.start()
Example #18
0
    def run(self):
        """
		desc:
			The run phase of the plug-in goes here.
		"""

        if hasattr(self.experiment, u'pygaze_eyetracker'):
            raise osexception(
                u'You should have only one instance of `pygaze_init` in your experiment'
            )
        self.set_item_onset()
        # Determine the tracker type and perform certain tracker-specific
        # operations.
        kwdict = {}
        if self.var.tracker_type == u'Simple dummy':
            tracker_type = u'dumbdummy'
        elif self.var.tracker_type == u'Advanced dummy (mouse simulation)':
            tracker_type = u'dummy'
        elif self.var.tracker_type == u'EyeLink':
            tracker_type = u'eyelink'
            kwdict[u'eyelink_force_drift_correct'] = \
             self.var.eyelink_force_drift_correct == u'yes'
            kwdict[u'pupil_size_mode'] = self.var.eyelink_pupil_size_mode
        elif self.var.tracker_type == u'SMI':
            tracker_type = u'smi'
            kwdict[u'ip'] = self.var.smi_ip
            kwdict[u'sendport'] = self.var.smi_send_port
            kwdict[u'receiveport'] = self.var.smi_recv_port
        elif self.var.tracker_type == u'EyeTribe':
            tracker_type = u'eyetribe'
        elif self.var.tracker_type == u'OpenGaze':
            tracker_type = u'opengaze'
        elif self.var.tracker_type == u'Alea':
            tracker_type = u'alea'
            kwdict[u'alea_key'] = self.var.alea_api_key
            kwdict[u'animated_calibration'] = \
             self.var.alea_animated_calibration == u'yes'
        elif self.var.tracker_type == u'Tobii':
            tracker_type = u'tobii'
        elif self.var.tracker_type == u'Tobii-legacy':
            tracker_type = u'tobii-legacy'
        elif self.var.tracker_type == u'Tobii Pro Glasses 2':
            tracker_type = u'tobiiglasses'
            kwdict[u'address'] = self.var.tobiiglasses_address
            kwdict[u'udpport'] = self.var.tobiiglasses_udpport
        else:
            raise osexception(u'Unknown tracker type: %s' %
                              self.var.tracker_type)
        # Determine logfile
        if self.var._logfile == u'automatic':
            logfile = os.path.splitext(self.var.logfile)[0]
            if tracker_type == u'eyelink':
                # Automatically shorten filenames like 'subject-0', because
                # these are too long. This avoids having to rename logfiles
                # all the time.
                basename = os.path.basename(logfile)
                dirname = os.path.dirname(logfile)
                if len(basename) > 8 and basename.startswith(u'subject-'):
                    basename = u'sub_' + basename[8:]
                    logfile = os.path.join(dirname, basename)
                    print(u'Attention: EyeLink logfile renamed to %s.edf' \
                     % logfile)
                elif basename == u'defaultlog':
                    logfile = u'default'
                    print(u'Attention: EyeLink logfile renamed to %s.edf' \
                     % logfile)
                logfile = logfile + u'.edf'
                kwdict[u'data_file'] = logfile
        else:
            logfile = self.var._logfile
        # Register the logfile with OpenSesame
        self.experiment.data_files.append(logfile)
        # Determine event detection. Currently, only the EyeLink has native
        # event detection.
        if tracker_type == u'eyelink':
            event_detection = u'native'
        else:
            event_detection = u'pygaze'
        # Initialize pygaze and the eye-tracker object
        self.experiment.pygaze_display = Display(u'opensesame')
        self.experiment.pygaze_eyetracker = EyeTracker(
            self.experiment.pygaze_display,
            trackertype=tracker_type,
            eventdetection=event_detection,
            saccade_velocity_threshold=self.var.sacc_vel_thr,
            saccade_acceleration_threshold=self.var.sacc_acc_thr,
            logfile=logfile,
            **kwdict)
        if self.var.calbeep == u'yes':
            from openexp.synth import synth
            self.beep = synth(self.experiment)
        self.experiment.pygaze_eyetracker.set_draw_calibration_target_func(
            self.draw_calibration_canvas)
        self.experiment.pygaze_eyetracker.set_draw_drift_correction_target_func(
            self.draw_calibration_canvas)
        self.experiment.cleanup_functions.append(self.close)
        if self.var.calibrate == u'yes':
            self.experiment.pygaze_eyetracker.calibrate()
        self.python_workspace[
            u'eyetracker'] = self.experiment.pygaze_eyetracker
Example #19
0
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 10 13:29:48 2016

@author: adam
"""

from pygaze.display import Display
from pygaze.screen import Screen
import pygaze.libtime as timer

# disp = Window(size=DISPSIZE, units='pix', fullscr=True)
disp = Display()
fixscreen = Screen()
fixscreen.draw_fixation(fixtype='dot')

imgscreen = Screen()
imgscreen.draw_image('/home/adam/Desktop/experiment0/Example.png')

disp.fill(fixscreen)
disp.show()
timer.pause(1000)

disp.fill(imgscreen)
disp.show()
timer.pause(2000)

disp.close()
from pygaze.screen import Screen
from pygaze.keyboard import Keyboard
from pygaze.mouse import Mouse
from pygaze.logfile import Logfile
import pygaze.libtime as timer

from custom import calc_angular_dist, generate_oris, generate_locs, pol2car, StimScreen

import numpy


# # # # #
# PREPARATION

# Intialise the Display.
disp = Display()

# Initialise the basic input devices.
kb = Keyboard(keylist=None, timeout=None)
mouse = Mouse(mousebuttonlist=None, timeout=None)

# Initialise a log.
log = Logfile()
header = ['trialnr', 'nstim', 'fixonset', 'stimonset', 'maintenanceonset', \
    'probeonset', 'RT', 'response']
for i in range(max(NSTIM)):
    header.extend(['stimx%d' % (i), 'stimy%d' % (i), 'stimori%d' % (i), \
        'stimerror%d' % (i)])
header.extend(['E', 'X', 'T'])
for i in range(max(NSTIM)-1):
    header.append('NT%d' % i)
    multicast_ip = int(multicast_ip[1:])
    _print("Multicast IP = %s" % multicast_ip)
else:
    multicast_ip = 0
    _print("No multicast IP found.")

# GENERAL
# Total number of points.
total = 0.0

# Create a colour wheel to select colours from for the stimuli.
cw = create_colourwheel(STIML, STIMR, savefile='colourwheel.png')

# PYGAZE
# Initialise a new Display instance
disp = Display()

# Initialise a Screen instance for arbitrary drawing.
scr = Screen()
scr.draw_text(text="Initialising the experiment...", fontsize=FONTSIZE)
disp.fill(scr)
disp.show()

# Initialise the ka-ching sound.
kaching = Sound(soundfile=KACHING)

# Initialise a Keyboard and a Mouse instance for participant interaction.
kb = Keyboard()
mouse = Mouse()

# COMMUNICATIONS