-
Notifications
You must be signed in to change notification settings - Fork 0
/
experiment-fixed-demo.py
434 lines (361 loc) · 17.5 KB
/
experiment-fixed-demo.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy2 Experiment Builder (v1.79.01), Thu Feb 20 15:58:25 2014
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, monitors
from psychopy.constants import * # things like STARTED, FINISHED
import numpy as np # whole numpy lib is available, prepend 'np.'
import random
import os # handy system and path functions
# Utility methods
# Divdes list into N chunks
def chunk(xs, n):
ys = list(xs)
random.shuffle(ys)
ylen = len(ys)
size = int(ylen / n)
chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)]
leftover = ylen - size*n
edge = size*n
for i in xrange(leftover):
chunks[i%n].append(ys[edge+i])
return chunks
# Store info about the experiment session
expName = u'experiment' # from the Builder filename that created this script
expInfo = {u'session': u'001', u'participant': u''}
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
# Setup files for saving
if not os.path.isdir('data'):
os.makedirs('data') # if this fails (e.g. permissions) we will get error
filename = 'data' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath=None,
savePickle=True, saveWideText=True,
dataFileName=filename)
# Start Code - component code to be run before the window creation
# Setup variables
width = 1280
height = 720
mon = monitors.Monitor('testMonitor')
primary = visual.Window(size=[width, height], fullscr=True, screen=0, allowGUI=True, units='pix', monitor=mon)
# store frame rate of monitor if we can measure it successfully
expInfo['frameRate']=primary.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 "instructions"
instructionsClock = core.Clock()
instructionsTextStr = u'You will see a number of circles in the center of the screen, some will be red. The red circles will turn white after 5 seconds and all the circles will start moving. \r\n\nAfter the motion stops, please use the mouse to indicate which circles were the \u201ctargets\u201d in red at the beginning. The next trial will automatically begin.\r\n\nPress any key to start test'
instrText = visual.TextStim(primary, ori=0, name='instrText',
text=instructionsTextStr, font=u'Arial',
pos=[0, 0], height=30, wrapWidth=None,
color=u'white', colorSpace=u'rgb', opacity=1,
depth=0.0)
# Initialize components for Routine "trial"
trialClock = core.Clock()
ISI = core.StaticPeriod(win=primary, screenHz=expInfo['frameRate'], name='ISI')
mouse = event.Mouse()
# 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 "instructions"-------
t = 0
instructionsClock.reset() # clock
frameN = -1
# update component parameters for each repeat
key_resp_2 = event.BuilderKeyResponse() # create an object of type KeyResponse
key_resp_2.status = NOT_STARTED
# keep track of which components have finished
instructionsComponents = []
instructionsComponents.append(instrText)
instructionsComponents.append(key_resp_2)
for thisComponent in instructionsComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "instructions"-------
continueRoutine = True
while continueRoutine:
# get current time
t = instructionsClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instrText* updates
if t >= 0.0 and instrText.status == NOT_STARTED:
# keep track of start time/frame for later
instrText.tStart = t # underestimates by a little under one frame
instrText.frameNStart = frameN # exact frame index
instrText.setAutoDraw(True)
primary.setMouseVisible(False)
# *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
event.clearEvents()
if key_resp_2.status == STARTED:
theseKeys = event.getKeys()
if len(theseKeys) > 0: # at least one key was pressed
# 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
routineTimer.reset() # if we abort early the non-slip timer needs reset
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instructionsComponents:
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 event.getKeys(["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
primary.flip()
else: # this Routine was not non-slip safe so reset non-slip timer
routineTimer.reset()
#-------Ending Routine "instructions"-------
for thisComponent in instructionsComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method=u'random',
extraInfo=expInfo, originPath=None,
trialList=data.importConditions(u'conditions-demo.xlsx'),
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)
screenRec = visual.Rect(primary, width=width/3.25, height=height/3.25)
screenRec.fillColor = 'black'
#screenRec.fillColor = 'grey'
#screenRec.lineWidth = 10
screenRec.lineColor = 'black'
nDots = 800
dotSize = 5
nCircles = 8
circleSize = 20
speed = 1.4
maxRotSpeed = .2
timeTargetVisible = 2.5
timeMoving = 8
for thisTrial in trials:
percentConnectedVar = thisTrial['percentConnected']
numOfTargetsVar = thisTrial['numOfTargets']
inclSecondScreenVar = int(thisTrial['inclSecondScreen'])
hidePrimaryVar = int(thisTrial['hidePrimary'])
# Randomly select some circles subject must track
print "percent connected:" + str(percentConnectedVar)
print "num of targets:" +str(numOfTargetsVar)
print "include second screen:" +str(inclSecondScreenVar)
print "hide primary:" +str(hidePrimaryVar)
circles = []
circleAngles = []
for i in range(nCircles):
circle = visual.Polygon(primary, name='circle',
edges=90, size=circleSize, units = 'pix',
ori=0, pos=[random.randint(int((-width/6.5))+10, int((width/6.5))-10), random.randint(int((-height/6.5))+10, int((height/6.5))-10)],
lineWidth=1, lineColor=[1,1,1], lineColorSpace=u'rgb',
fillColor=[1,1,1], fillColorSpace=u'rgb',
opacity=1,interpolate=True)
circleAngles.append(random.random() * 2*np.pi)
circles.append(circle)
# Randomly place dots bounded around the primary screen
coords = []
dotsAngles = []
while(len(coords) < nDots):
dotsAngles.append(random.random() * 2*np.pi)
randx = random.randint(-width/2, width/2)
randy = random.randint(-height/2, height/2)
if randy in range(int(-height/6.5), int(height/6.5)):
if randx not in range(int(-width/6.5), int(width/6.5)):
coords.append([randx, randy])
else:
coords.append([randx, randy])
dots = visual.ElementArrayStim(primary, elementTex=None, elementMask='circle', nElements=nDots,
sizes=dotSize, units = 'pix', xys = coords)
targetsNum = int(numOfTargetsVar)
targetsSelectedKeys = random.sample(circles, targetsNum)
if (percentConnectedVar >= 100):
connectedDotsIndexs = range(0, nDots)
else:
connectedDotsIndexs = random.sample(range(0, nDots), int(nDots * percentConnectedVar))
print "number of connected dots:" + str(len(connectedDotsIndexs))
connectedDotsChunkedEvenly = chunk(connectedDotsIndexs, targetsNum)
# Creates dictionary of targets mapped to its connected dots
targets = dict(zip(targetsSelectedKeys, connectedDotsChunkedEvenly))
flattened = [x for sublist in connectedDotsChunkedEvenly for x in sublist]
notConnectedDotIndexs = [i for i in range(0, nDots) if i not in flattened]
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 "trial"-------
t = 0
trialClock.reset() # clock
frameN = -1
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = []
trialComponents.append(ISI)
for circle in circles:
trialComponents.append(circle)
trialComponents.append(mouse)
for thisComponent in trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "trial"-------
continueRoutine = True
clickCount = 0
clickedCircles = []
lastPressClock = core.Clock()
while continueRoutine:
# 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
# *circle* updates
if t >= 0.0 and t <= timeTargetVisible:
primary.setMouseVisible(False)
if inclSecondScreenVar > 0:
dots.draw()
screenRec.draw()
for circle in circles:
if circle in targets: circle.fillColor = 'red'
circle.draw()
elif t >= timeTargetVisible and t <= timeMoving + timeTargetVisible :
dotXys = dots.xys
# the draw is here so drawing is in correct order and draws rec over the top of dots
if inclSecondScreenVar > 0:
dots.draw()
screenRec.draw()
for index, circle in enumerate(circles):
# Reset targets back to white
circle.fillColor = 'white'
a = circleAngles[index]
x = speed * np.cos(a)
y = speed * np.sin(a)
#print x + y
circle.pos[0] += x
circle.pos[1] += y
if hidePrimaryVar > 0 and t >= 6.0 and t <= 7.0:
pass
else:
circle.draw()
if circle in targets:
for dotIdx in targets[circle]:
dotXys[dotIdx][0] += x
dotXys[dotIdx][1] += y
if dotXys[dotIdx][0] <= (-width/2)+10:
dotXys[dotIdx][0] = (dotXys[dotIdx][0] * -1) - 5
if dotXys[dotIdx][0] >= (width/2)-10:
dotXys[dotIdx][0] = (dotXys[dotIdx][0] * -1) + 5
if dotXys[dotIdx][1] <= (-height/2)+10:
dotXys[dotIdx][1] = (dotXys[dotIdx][1] * -1) - 5
if dotXys[dotIdx][1] >= (height/2)-10:
dotXys[dotIdx][1] = (dotXys[dotIdx][1] * -1) + 5
if circle.pos[0] <= (-width/6.5)+10 or circle.pos[0] >= (width/6.5)-10 or circle.pos[1] <= (-height/6.5)+10 or circle.pos[1] >= (height/6.5)-10:
a = a + np.pi
else:
# else randomly rotate the stimulus a bit
a += (random.random()-.5) * maxRotSpeed
circleAngles[index] = a
for dotInx in notConnectedDotIndexs:
da = dotsAngles[dotInx]
dx = speed * np.cos(da)
dy = speed * np.sin(da)
da += (random.random()-.5) * maxRotSpeed
dotXys[dotInx][0] += dx
dotXys[dotInx][1] += dy
if dotXys[dotInx][0] <= (-width/2)+10:
dotXys[dotInx][0] = (dotXys[dotInx][0] * -1) - 5
elif dotXys[dotInx][0] >= (width/2)-10:
dotXys[dotInx][0] = (dotXys[dotInx][0] * -1) + 5
elif dotXys[dotInx][1] <= (-height/2)+10:
dotXys[dotInx][1] = (dotXys[dotInx][1] * -1) - 5
if dotXys[dotInx][1] >= (height/2)-10:
dotXys[dotInx][1] = (dotXys[dotInx][1] * -1) + 5
dotsAngles[index] = da
dots.setXYs(dotXys)
# *mouse* updates
if t >= timeMoving + timeTargetVisible and mouse.status == NOT_STARTED:
# Check number of dots on screen
count = 0
for pair in dots.xys:
if -width/2 <= pair[0] <= width/2 and -height/2 <= pair[1] <= height/2:
count += 1
print "count: " + str(count)
# keep track of start time/frame for later
mouse.tStart = t # underestimates by a little under one frame
mouse.frameNStart = frameN # exact frame index
mouse.status = STARTED
event.mouseButtons = [0, 0, 0] # reset mouse buttons to be 'up'
if mouse.status == STARTED: # only update if started and not stopped!
primary.setMouseVisible(True)
if inclSecondScreenVar > 0:
dots.draw()
screenRec.draw()
for circle in circles:
circle.draw()
if mouse.getPressed()[0] and lastPressClock.getTime() > 0.2:
lastPressClock.reset()
for circle in circles:
if circle.contains(mouse) and circle not in clickedCircles:
clickedCircles.append(circle)
clickCount += 1
print clickCount
print targetsNum
print clickedCircles
if clickCount >= targetsNum: # ie if any button is pressed
# abort routine on response
clickResponseTime = t - mouse.tStart
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
routineTimer.reset() # if we abort early the non-slip timer needs reset
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 event.getKeys(["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
primary.flip()
else: # this Routine was not non-slip safe so reset non-slip timer
routineTimer.reset()
#-------Ending Routine "trial"-------
for thisComponent in trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# store data for trials (TrialHandler)
targetsCorrectlyIdentified = list(set(clickedCircles).intersection(targets))
print "targetsCorrectlyIdentified: " + str(len(targetsCorrectlyIdentified))
trials.addData('targetsCorrectlyIdentified', len(targetsCorrectlyIdentified))
trials.addData('clickResponseTime', clickResponseTime)
thisExp.nextEntry()
# completed 1 repeats of 'trials'
primary.close()
core.quit()