#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy2 Experiment Builder (v1.82.01), December 12, 2016, at 16:44 If you publish work using this script please cite the relevant PsychoPy publications Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13. Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008 """ from __future__ import division # so that 1/3=0.333 instead of 1/3=0 from psychopy import visual, core, data, event, logging, sound, gui from psychopy.constants import * # things like STARTED, FINISHED import numpy as np # whole numpy lib is available, prepend 'np.' from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray from numpy.random import random, randint, normal, shuffle import os # handy system and path functions # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) # Store info about the experiment session expName = 'CocktailPartyWithQuestionsWorkingAndBreakAddRandom' # from the Builder filename that created this script expInfo = {'participant':'', 'session':'001'} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + 'data/%s_%s_%s' %(expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) #save a log file for detail verbose info logFile = logging.LogFile(filename+'.log', level=logging.EXP) logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation # Setup the Window win = visual.Window(size=(1920, 1080), fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color=[0,0,0], colorSpace='rgb', blendMode='avg', useFBO=True, ) # store frame rate of monitor if we can measure it successfully expInfo['frameRate']=win.getActualFrameRate() if expInfo['frameRate']!=None: frameDur = 1.0/round(expInfo['frameRate']) else: frameDur = 1.0/60.0 # couldn't get a reliable measure so guess # Initialize components for Routine "chooseAorB" chooseAorBClock = core.Clock() #import psychopy.core # Initialize components for Routine "waitForNext" waitForNextClock = core.Clock() # BEGIN EXPERIMENT import pygaze from pygaze import libtime from pygaze.display import Display from pygaze.screen import Screen from pygaze import libscreen from pygaze.eyetracker import EyeTracker from psychopy.visual import MovieStim, ImageStim from psychopy import visual, core, event from pygaze import libinput from pygaze import liblog # Initialise a Display instance, using the default settings. # (You can add a constants.py file to set these defaults.) #disp = Display() #scr = Screen() disp = libscreen.Display(disptype='psychopy') scr = libscreen.Screen() # Get the handle to the active PsychoPy Window instance. win = pygaze.expdisplay # Initialise and calibrate an EyeTracker instance tracker = EyeTracker(disp,trackertype='eyelink') #tracker = EyeTracker(disp,trackertype='dummy') tracker.calibrate() # END BEGIN EXPERIMENT image_2 = visual.ImageStim(win=win, name='image_2',units='norm', image='message.jpg', mask=None, ori=0, pos=[0, 0], size=[2, 2], color=[1,1,1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=-1.0) # Initialize components for Routine "trial" trialClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') # Initialize components for Routine "responses" responsesClock = core.Clock() image = visual.ImageStim(win=win, name='image',units='norm', image='sin', mask=None, ori=0, pos=[0, 0], size=[2, 2], color=[1,1,1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=0.0) # Create some handy timers globalClock = core.Clock() # to track the time since experiment started routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine #------Prepare to start Routine "chooseAorB"------- t = 0 chooseAorBClock.reset() # clock frameN = -1 # update component parameters for each repeat rand = random(1) #rand= random.randint(0,1) print rand #xlsFile = "condA.xlsx" if rand<0.5: xlsFile='ExperimentAudioFileB.xlsx'#choose version B disp('B'); else: xlsFile='ExperimentAudioFileA.xlsx'#choose version A disp('A') print xlsFile # keep track of which components have finished chooseAorBComponents = [] for thisComponent in chooseAorBComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "chooseAorB"------- continueRoutine = True while continueRoutine: # get current time t = chooseAorBClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in chooseAorBComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "chooseAorB"------- for thisComponent in chooseAorBComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # the Routine "chooseAorB" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # set up handler to look after randomisation of conditions etc trials = data.TrialHandler(nReps=1, method='random', extraInfo=expInfo, originPath=None, trialList=data.importConditions(xlsFile), seed=None, name='trials') thisExp.addLoop(trials) # add the loop to the experiment thisTrial = trials.trialList[0] # so we can initialise stimuli with some values # abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb) if thisTrial != None: for paramName in thisTrial.keys(): exec(paramName + '= thisTrial.' + paramName) for thisTrial in trials: currentLoop = trials # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb) if thisTrial != None: for paramName in thisTrial.keys(): exec(paramName + '= thisTrial.' + paramName) #------Prepare to start Routine "waitForNext"------- t = 0 waitForNextClock.reset() # clock frameN = -1 # update component parameters for each repeat # BEGIN ROUTINE scr.screen.append(image_2) disp.fill(scr) disp.show() key_resp_3 = event.BuilderKeyResponse() # create an object of type KeyResponse key_resp_3.status = NOT_STARTED # keep track of which components have finished waitForNextComponents = [] waitForNextComponents.append(image_2) waitForNextComponents.append(key_resp_3) for thisComponent in waitForNextComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "waitForNext"------- continueRoutine = True while continueRoutine: # get current time t = waitForNextClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *image_2* updates if t >= 0.0 and image_2.status == NOT_STARTED: # keep track of start time/frame for later image_2.tStart = t # underestimates by a little under one frame image_2.frameNStart = frameN # exact frame index image_2.setAutoDraw(True) # *key_resp_3* updates if t >= 0.0 and key_resp_3.status == NOT_STARTED: # keep track of start time/frame for later key_resp_3.tStart = t # underestimates by a little under one frame key_resp_3.frameNStart = frameN # exact frame index key_resp_3.status = STARTED # keyboard checking is just starting key_resp_3.clock.reset() # now t=0 event.clearEvents(eventType='keyboard') if key_resp_3.status == STARTED: theseKeys = event.getKeys(keyList=['space']) # check for quit: if "escape" in theseKeys: endExpNow = True if len(theseKeys) > 0: # at least one key was pressed key_resp_3.keys = theseKeys[-1] # just the last key pressed key_resp_3.rt = key_resp_3.clock.getTime() # a response ends the routine continueRoutine = False # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in waitForNextComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "waitForNext"------- for thisComponent in waitForNextComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # check responses if key_resp_3.keys in ['', [], None]: # No response was made key_resp_3.keys=None # store data for trials (TrialHandler) trials.addData('key_resp_3.keys',key_resp_3.keys) if key_resp_3.keys != None: # we had a response trials.addData('key_resp_3.rt', key_resp_3.rt) # the Routine "waitForNext" was not non-slip safe, so reset the non-slip timer routineTimer.reset() #------Prepare to start Routine "trial"------- t = 0 trialClock.reset() # clock frameN = -1 routineTimer.add(0.500000) # update component parameters for each repeat # Initialise a PsychoPy MovieStim mov = MovieStim(win, movie, flipVert=False) # Add the MovieStim to a PyGaze Screen instance. # (The Screen object has a list of all its associated # PsychoPy stimulus instances; you can add custom # instances, like the MovieStim, and they will automatically # be drawn each time you fill and show the Display.) scr.screen.append(mov) tracker.log('movie = %s' % (movie)) # Start recording from the eye tracker. tracker.start_recording() # Record the starting time, and log it to the tracker. t1 = libtime.get_time() tracker.log('START; time=%d' % (t1)) t0 = libtime.get_time() # Run for the duration of the video while t1 - t0 < mov.duration*1000: # Fill the Display with the Screen. The right # frame from the video will automatically # be selected by PsychoPy. disp.fill(scr) # Show the Display, and record its onset t1 = disp.show() # Log the screen flip. tracker.log('FLIP; time=%d' % (t1)) if event.getKeys(keyList=['escape','q']): break print 'after loop' # keep track of which components have finished trialComponents = [] trialComponents.append(ISI) for thisComponent in trialComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "trial"------- continueRoutine = True while continueRoutine and routineTimer.getTime() > 0: # get current time t = trialClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *ISI* period if t >= 0.0 and ISI.status == NOT_STARTED: # keep track of start time/frame for later ISI.tStart = t # underestimates by a little under one frame ISI.frameNStart = frameN # exact frame index ISI.start(0.5) elif ISI.status == STARTED: #one frame should pass before updating params and completing ISI.complete() #finish the static period # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in trialComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "trial"------- for thisComponent in trialComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) print 'out of the loop' # Stop recording from the eye tracker. tracker.log('END; time=%d' % (t1)) if event.getKeys(keyList=['escape','q']): win.close() core.quit() # set up handler to look after randomisation of conditions etc trials_2 = data.TrialHandler(nReps=1, method='random', extraInfo=expInfo, originPath=None, trialList=data.importConditions(questions_file), seed=None, name='trials_2') thisExp.addLoop(trials_2) # add the loop to the experiment thisTrial_2 = trials_2.trialList[0] # so we can initialise stimuli with some values # abbreviate parameter names if possible (e.g. rgb=thisTrial_2.rgb) if thisTrial_2 != None: for paramName in thisTrial_2.keys(): exec(paramName + '= thisTrial_2.' + paramName) for thisTrial_2 in trials_2: currentLoop = trials_2 # abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb) if thisTrial_2 != None: for paramName in thisTrial_2.keys(): exec(paramName + '= thisTrial_2.' + paramName) #------Prepare to start Routine "responses"------- t = 0 responsesClock.reset() # clock frameN = -1 # update component parameters for each repeat image.setImage(question) key_resp_2 = event.BuilderKeyResponse() # create an object of type KeyResponse key_resp_2.status = NOT_STARTED #scr.draw_text(text="Press on the answer y/n.", fontsize=30) #disp.fill(scr) #disp.show() #begin routine Noa scr.screen.append(image) disp.fill(scr) disp.show() # keep track of which components have finished responsesComponents = [] responsesComponents.append(image) responsesComponents.append(key_resp_2) for thisComponent in responsesComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "responses"------- continueRoutine = True while continueRoutine: # get current time t = responsesClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *image* updates if t >= 0.0 and image.status == NOT_STARTED: # keep track of start time/frame for later image.tStart = t # underestimates by a little under one frame image.frameNStart = frameN # exact frame index image.setAutoDraw(True) # *key_resp_2* updates if t >= 0.0 and key_resp_2.status == NOT_STARTED: # keep track of start time/frame for later key_resp_2.tStart = t # underestimates by a little under one frame key_resp_2.frameNStart = frameN # exact frame index key_resp_2.status = STARTED # keyboard checking is just starting key_resp_2.clock.reset() # now t=0 event.clearEvents(eventType='keyboard') if key_resp_2.status == STARTED: theseKeys = event.getKeys(keyList=['1', '2', '3', '4', 'space']) # check for quit: if "escape" in theseKeys: endExpNow = True if len(theseKeys) > 0: # at least one key was pressed key_resp_2.keys = theseKeys[-1] # just the last key pressed key_resp_2.rt = key_resp_2.clock.getTime() # a response ends the routine continueRoutine = False #each frame Noa # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in responsesComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "responses"------- for thisComponent in responsesComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # check responses if key_resp_2.keys in ['', [], None]: # No response was made key_resp_2.keys=None # store data for trials_2 (TrialHandler) trials_2.addData('key_resp_2.keys',key_resp_2.keys) if key_resp_2.keys != None: # we had a response trials_2.addData('key_resp_2.rt', key_resp_2.rt) # end routine Noa # the Routine "responses" was not non-slip safe, so reset the non-slip timer routineTimer.reset() thisExp.nextEntry() # completed 1 repeats of 'trials_2' thisExp.nextEntry() # completed 1 repeats of 'trials' tracker.stop_recording() # Close the connection to the tracker. tracker.close() # Close the Display. disp.close win.close() core.quit()