-
Notifications
You must be signed in to change notification settings - Fork 0
/
ABnStream.py
executable file
·1307 lines (1195 loc) · 76.3 KB
/
ABnStream.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Alex Holcombe alex.holcombe@sydney.edu.au
#See the README.md for more information: https://github.com/alexholcombe/attentional-blink/blob/master/README.md
#git remote add origin https://github.com/alexholcombe/nStream
from __future__ import print_function, division
from psychopy import monitors, visual, event, data, logging, core, sound, gui
import psychopy.info
import numpy as np
from math import atan, log, ceil, cos, sin, pi, atan2
from copy import deepcopy
import time, sys, os#, pylab
import string, random
#Eyetracking stuff
eyetrackingOption = True #Include this so can turn it off, because Psychopy v1.83.01 mistakenly included an old version of pylink which prevents EyelinkEyetrackerForPsychopySUPA3 stuff from importing
if eyetrackingOption:
from EyelinkEyetrackerForPsychopySUPA3 import Tracker_EyeLink #Chris Fajou integration
eyetracking = False
getEyeTrackingFileFromEyetrackingMachineAtEndOfExperiment = False #If True, can take up to 1.5 hrs in certain conditions
#End eyetracking stuff
try:
from noiseStaircaseHelpers import printStaircase, toStaircase, outOfStaircase, createNoise, plotDataAndPsychometricCurve
except ImportError:
print('Could not import from noiseStaircaseHelpers.py (you need that file to be in the same directory)')
try: import stringResponse
except ImportError: print('Could not import strongResponse.py (you need that file to be in the same directory)')
try: import letterLineupResponse
except ImportError: print('Could not import letterLineupResponse.py (you need that file to be in the same directory)')
descendingPsycho = True
#THINGS THAT COULD PREVENT SUCCESS ON A STRANGE MACHINE
#same screen or external screen? Set scrn=0 if one screen. scrn=1 means display stimulus on second screen.
#widthPix, heightPix
quitFinder = False #if checkRefreshEtc, quitFinder becomes True
autopilot=False
demo=False #False
exportImages= False #quits after one trial
subject='Hubert' #user is prompted to enter true subject name
if autopilot: subject='auto'
if os.path.isdir('.'+os.sep+'rawData'):
dataDir='rawData'
else:
print('"rawData" directory does not exist, so saving data in present working directory')
dataDir='.'
timeAndDateStr = time.strftime("%d%b%Y_%H-%M", time.localtime())
showRefreshMisses=True #flicker fixation at refresh rate, to visualize if frames missed
feedback=False
autoLogging=False
refreshRate = 60
if demo:
refreshRate = 60.; #100 LN: refresh rate for previous AB and RSVP task for gamers was 60
font = 'sloan'
staircaseTrials = 25
prefaceStaircaseTrialsN = 20 #22
prefaceStaircaseNoise = np.array([5,20,20,20, 50,50,50,5,80,80,80,5,95,95,95]) #will be recycled / not all used, as needed
threshCriterion = 0.58
bgColor = [-.7,-.7,-.7] # [-1,-1,-1]
cueColor = [1.,1.,1.]
cueType = 'exogenousRing' #'endogenous':
if cueType == 'endogenous':
cueColor = [1,-1,-1]
letterColor = [1.,1.,1.]
cueRadius = 2.5 #6 deg, as in Martini E2 Letters should have height of 2.5 deg
widthPix= 1024 #monitor width in pixels of Agosta
heightPix= 768 #800 #monitor height in pixels
monitorwidth = 40.5 #monitor width in cm
scrn=0 #0 to use main screen, 1 to use external screen connected to computer
fullscr=False #True to use fullscreen, False to not. Timing probably won't be quite right if fullscreen = False
allowGUI = False
if demo: monitorwidth = 23#18.0
if exportImages:
widthPix = 400; heightPix = 400
monitorwidth = 13.0
fullscr=False; scrn=0
if demo:
scrn=0; fullscr=False
widthPix = 800; heightPix = 600
monitorname='testMonitor'
allowGUI = True
viewdist = 57. #cm
pixelperdegree = widthPix/ (atan(monitorwidth/viewdist) /np.pi*180)
msg= 'pixelperdegree=' + str( round(pixelperdegree,2) )
logging.info(pixelperdegree)
# create a dialog from dictionary
infoFirst = { 'Do staircase (only)': False, 'Check refresh etc':True, 'Fullscreen (timing errors if not)': fullscr, 'Screen refresh rate': refreshRate }
OK = gui.DlgFromDict(dictionary=infoFirst,
title='AB or dualstream experiment OR staircase to find thresh noise level for T1 performance criterion',
order=['Do staircase (only)', 'Check refresh etc', 'Fullscreen (timing errors if not)'],
tip={'Check refresh etc': 'To confirm refresh rate and that can keep up, at least when drawing a grating'},
#fixed=['Check refresh etc'])#this attribute can't be changed by the user
)
if not OK.OK:
print('User cancelled from dialog box'); core.quit()
doStaircase = infoFirst['Do staircase (only)']
checkRefreshEtc = infoFirst['Check refresh etc']
fullscr = infoFirst['Fullscreen (timing errors if not)']
refreshRate = infoFirst['Screen refresh rate']
if checkRefreshEtc:
quitFinder = True
if quitFinder:
import os
applescript="\'tell application \"Finder\" to quit\'"
shellCmd = 'osascript -e '+applescript
os.system(shellCmd)
#letter size 2.5 deg
numLettersToPresent = 24
#For AB, minimum SOAms should be 84 because any shorter, I can't always notice the second ring when lag1. 71 in Martini E2 and E1b (actually he used 66.6 but that's because he had a crazy refresh rate of 90 Hz)
SOAms = 82.35 #82.35 Battelli, Agosta, Goodbourn, Holcombe mostly using 133
letterDurMs = 60 #60
ISIms = SOAms - letterDurMs
letterDurFrames = int( np.floor(letterDurMs / (1000./refreshRate)) )
cueDurFrames = letterDurFrames
ISIframes = int( np.floor(ISIms / (1000./refreshRate)) )
#have set ISIframes and letterDurFrames to integer that corresponds as close as possible to originally intended ms
rateInfo = 'total SOA=' + str(round( (ISIframes + letterDurFrames)*1000./refreshRate, 2)) + ' or ' + str(ISIframes + letterDurFrames) + ' frames, comprising\n'
rateInfo+= 'ISIframes ='+str(ISIframes)+' or '+str(ISIframes*(1000./refreshRate))+' ms and letterDurFrames ='+str(letterDurFrames)+' or '+str(round( letterDurFrames*(1000./refreshRate), 2))+'ms'
logging.info(rateInfo); print(rateInfo)
trialDurFrames = int( numLettersToPresent*(ISIframes+letterDurFrames) ) #trial duration in frames
monitorname = 'testmonitor'
waitBlank = False
mon = monitors.Monitor(monitorname,width=monitorwidth, distance=viewdist)#relying on monitorwidth cm (39 for Mitsubishi to do deg calculations) and gamma info in calibratn
mon.setSizePix( (widthPix,heightPix) )
units='deg' #'cm'
def openMyStimWindow(): #make it a function because have to do it several times, want to be sure is identical each time
myWin = visual.Window(monitor=mon,size=(widthPix,heightPix),allowGUI=allowGUI,units=units,color=bgColor,colorSpace='rgb',fullscr=fullscr,screen=scrn,waitBlanking=waitBlank,
winType='pyglet' ) #pygame doesn't work, don't know why. Works in textLocationTest.py
return myWin
myWin = openMyStimWindow()
refreshMsg2 = ''
if not checkRefreshEtc:
refreshMsg1 = 'REFRESH RATE WAS NOT CHECKED'
refreshRateWrong = False
else: #checkRefreshEtc
runInfo = psychopy.info.RunTimeInfo(
# if you specify author and version here, it overrides the automatic detection of __author__ and __version__ in your script
#author='<your name goes here, plus whatever you like, e.g., your lab or contact info>',
#version="<your experiment version info>",
win=myWin, ## a psychopy.visual.Window() instance; None = default temp window used; False = no win, no win.flips()
refreshTest='grating', ## None, True, or 'grating' (eye-candy to avoid a blank screen)
verbose=True, ## True means report on everything
userProcsDetailed=True ## if verbose and userProcsDetailed, return (command, process-ID) of the user's processes
)
#print(runInfo)
logging.info(runInfo)
print('Finished runInfo- which assesses the refresh and processes of this computer')
#check screen refresh is what assuming it is ##############################################
Hzs=list()
myWin.flip(); myWin.flip();myWin.flip();myWin.flip();
myWin.setRecordFrameIntervals(True) #otherwise myWin.fps won't work
print('About to measure frame flips')
for i in range(50):
myWin.flip()
Hzs.append( myWin.fps() ) #varies wildly on successive runs!
myWin.setRecordFrameIntervals(False)
# end testing of screen refresh########################################################
Hzs = np.array( Hzs ); Hz= np.median(Hzs)
msPerFrame= 1000./Hz
refreshMsg1= 'Frames per second ~='+ str( np.round(Hz,1) )
refreshRateTolerancePct = 3
pctOff = abs( (np.median(Hzs)-refreshRate) / refreshRate)
refreshRateWrong = pctOff > (refreshRateTolerancePct/100.)
if refreshRateWrong:
refreshMsg1 += ' BUT'
refreshMsg1 += ' program assumes ' + str(refreshRate)
refreshMsg2 = 'which is off by more than' + str(round(refreshRateTolerancePct,0)) + '%!!'
else:
refreshMsg1 += ', which is close enough to desired val of ' + str( round(refreshRate,1) )
myWinRes = myWin.size
myWin.allowGUI =True
myWin.close() #have to close window to show dialog box
defaultNoiseLevel = 0#90.0 #to use if no staircase, can be set by user
dlgLabelsOrdered = list()
if doStaircase:
myDlg = gui.Dlg(title="Staircase to find appropriate noisePercent", pos=(200,400))
else:
myDlg = gui.Dlg(title="RSVP experiment", pos=(200,400))
if not autopilot:
myDlg.addField('Subject name (default="Hubert"):', 'Hubert', tip='or subject code')
dlgLabelsOrdered.append('subject')
if doStaircase:
easyTrialsCondText = 'Num preassigned noise trials to preface staircase with (default=' + str(prefaceStaircaseTrialsN) + '):'
myDlg.addField(easyTrialsCondText, tip=str(prefaceStaircaseTrialsN))
dlgLabelsOrdered.append('easyTrials')
myDlg.addField('Staircase trials (default=' + str(staircaseTrials) + '):', tip="Staircase will run until this number is reached or it thinks it has precise estimate of threshold")
dlgLabelsOrdered.append('staircaseTrials')
else:
myDlg.addField('\tPercent noise dots=', defaultNoiseLevel, tip=str(defaultNoiseLevel))
dlgLabelsOrdered.append('defaultNoiseLevel')
#myDlg.addField('Trials per condition (default=' + str(trialsPerCondition) + '):', trialsPerCondition, tip=str(trialsPerCondition))
#dlgLabelsOrdered.append('trialsPerCondition')
myDlg.addText(refreshMsg1, color='Black')
if refreshRateWrong:
myDlg.addText(refreshMsg2, color='Red')
if refreshRateWrong:
logging.error(refreshMsg1+refreshMsg2)
else: logging.info(refreshMsg1+refreshMsg2)
if checkRefreshEtc and (not demo) and (myWinRes != [widthPix,heightPix]).any():
msgWrongResolution = 'Screen apparently NOT the desired resolution of '+ str(widthPix)+'x'+str(heightPix)+ ' pixels!!'
myDlg.addText(msgWrongResolution, color='Red')
logging.error(msgWrongResolution)
print(msgWrongResolution)
dimGreyForDlgBox = 'DimGrey'
from distutils.version import LooseVersion
if LooseVersion(psychopy.__version__) < LooseVersion("1.84.2"):
dimGreyForDlgBox = [-1.,1.,-1.] #color names stopped working along the way, for unknown reason
myDlg.addText('Note: to abort press ESC at a trials response screen', color=dimGreyForDlgBox)
myDlg.show()
if myDlg.OK: #unpack information from dialogue box
thisInfo = myDlg.data #this will be a list of data returned from each field added in order
if not autopilot:
name=thisInfo[dlgLabelsOrdered.index('subject')]
if len(name) > 0: #if entered something
subject = name #change subject default name to what user entered
if doStaircase:
if len(thisInfo[dlgLabelsOrdered.index('staircaseTrials')]) >0:
staircaseTrials = int( thisInfo[ dlgLabelsOrdered.index('staircaseTrials') ] ) #convert string to integer
print('staircaseTrials entered by user=',staircaseTrials)
logging.info('staircaseTrials entered by user=',staircaseTrials)
if len(thisInfo[dlgLabelsOrdered.index('easyTrials')]) >0:
prefaceStaircaseTrialsN = int( thisInfo[ dlgLabelsOrdered.index('easyTrials') ] ) #convert string to integer
print('prefaceStaircaseTrialsN entered by user=',thisInfo[dlgLabelsOrdered.index('easyTrials')])
logging.info('prefaceStaircaseTrialsN entered by user=',prefaceStaircaseTrialsN)
else: #not doing staircase
#trialsPerCondition = int( thisInfo[ dlgLabelsOrdered.index('trialsPerCondition') ] ) #convert string to integer
#print('trialsPerCondition=',trialsPerCondition)
defaultNoiseLevel = int (thisInfo[ dlgLabelsOrdered.index('defaultNoiseLevel') ])
else:
print('User cancelled from dialog box.')
logging.flush()
core.quit()
if not demo:
allowGUI = False
myWin = openMyStimWindow()
#set up output data file, log file, copy of program code, and logging
infix = ''
if doStaircase:
infix = 'staircase_'
fileName = os.path.join(dataDir, subject + '_' + infix+ timeAndDateStr)
if not demo and not exportImages:
dataFile = open(fileName+'.txt', 'w')
saveCodeCmd = 'cp \'' + sys.argv[0] + '\' '+ fileName + '.py'
os.system(saveCodeCmd) #save a copy of the code as it was when that subject was run
logFname = fileName+'.log'
ppLogF = logging.LogFile(logFname,
filemode='w',#if you set this to 'a' it will append instead of overwriting
level=logging.INFO)#errors, data and warnings will be sent to this logfile
if demo or exportImages:
dataFile = sys.stdout; logF = sys.stdout
logging.console.setLevel(logging.ERROR) #only show this level messages and higher
logging.console.setLevel(logging.ERROR) #DEBUG means set console to receive nearly all messges, INFO next level, EXP, DATA, WARNING and ERROR
if fullscr and not demo and not exportImages:
runInfo = psychopy.info.RunTimeInfo(
# if you specify author and version here, it overrides the automatic detection of __author__ and __version__ in your script
#author='<your name goes here, plus whatever you like, e.g., your lab or contact info>',
#version="<your experiment version info>",
win=myWin, ## a psychopy.visual.Window() instance; None = default temp window used; False = no win, no win.flips()
refreshTest='grating', ## None, True, or 'grating' (eye-candy to avoid a blank screen)
verbose=False, ## True means report on everything
userProcsDetailed=True, ## if verbose and userProcsDetailed, return (command, process-ID) of the user's processes
#randomSeed='set:42', ## a way to record, and optionally set, a random seed of type str for making reproducible random sequences
## None -> default
## 'time' will use experimentRuntime.epoch as the value for the seed, different value each time the script is run
##'set:time' --> seed value is set to experimentRuntime.epoch, and initialized: random.seed(info['randomSeed'])
##'set:42' --> set & initialize to str('42'), and will give the same sequence of random.random() for all runs of the script
)
logging.info(runInfo)
logging.flush()
#create click sound for keyboard
try:
click=sound.Sound('406__tictacshutup__click-1-d.wav')
except: #in case file missing, create inferiro click manually
logging.warn('Could not load the desired click sound file, instead using manually created inferior click')
click=sound.Sound('D',octave=4, sampleRate=22050, secs=0.015, bits=8)
if showRefreshMisses:
fixSizePix = 18 #2.6 #make fixation bigger so flicker more conspicuous
else: fixSizePix = 6
fixColor = [1,1,1]
fixatnPtSize = 4
if exportImages: fixColor= [0,0,0]
fixatnTextureWidth = np.round(fixSizePix/4).astype(int)
fixatnNoiseTexture = np.round( np.random.rand(fixatnTextureWidth,fixatnTextureWidth) ,0 ) *2.0-1 #Can counterphase flicker noise texture to create salient flicker if you break fixation
fixatn= visual.PatchStim(myWin, tex=fixatnNoiseTexture, size=(fixSizePix,fixSizePix), units='pix', mask='circle', interpolate=False, autoLog=False)
fixatnCounterphase= visual.PatchStim(myWin, tex= -1*fixatnNoiseTexture, size=(fixSizePix,fixSizePix), units='pix', mask='circle', interpolate=False, autoLog=False) #reverse contrast
fixatnPoint= visual.Circle(myWin,fillColorSpace='rgb',fillColor=(1,1,1),radius=fixatnPtSize,pos=[0,0],units='pix',autoLog=autoLogging)
respPromptStim = visual.TextStim(myWin,pos=(0, -.8),colorSpace='rgb',color=(1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
acceptTextStim = visual.TextStim(myWin,pos=(0, -.7),colorSpace='rgb',color=(1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
acceptTextStim.setText('Hit ENTER to accept. Backspace to edit')
respStim = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color=(1,1,0),alignHoriz='center', alignVert='center',height=.16,units='norm',autoLog=autoLogging)
clickSound, badKeySound = stringResponse.setupSoundsForResponse()
requireAcceptance = False
nextText = visual.TextStim(myWin,pos=(0, .1),colorSpace='rgb',color = (1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
NextRemindCountText = visual.TextStim(myWin,pos=(0,.2),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
screenshot= False; screenshotDone = False
instructions1 = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.5,units='deg',autoLog=autoLogging)
instructions2 = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.5,units='deg',autoLog=autoLogging)
instructionText1 = """
This experiment is made up of 200 trials. On each trial you will fixate your eyes on a central point on the screen.Then several rapid, randomly-ordered sequences of letters will appear at two or 8 locations on the screen.You must not move your eyes from the fixation point while these sequences are playing.
One of the letters will appear with a white ring around it.Your job is to tell us which of the letters appeared within the white ring. Again, you must not move your eyes from the fixation point in the centre of the screen while the letter streams are shown.
Press space to read more instructions
"""
instructionText2 ="""
At the end of each trial you will see a screen in which the whole alphabet is displayed. You should click on the letter that you saw within the circle.
However, you may have been UNSURE about the letter that you saw. If you were UNSURE about the letter you saw, click the letter using the LEFT mouse button. The letter you selected will turn YELLOW. If you were SURE about the letter that you saw, click the letter with the RIGHT mouse button. The letter you clicked will turn GREEN.\n
Please tell the experimenter you have read the instructions. Be sure to ask him if you have any questions.
"""
instructions1.text = instructionText1
instructions2.text = instructionText2
def roundToNearestY(x,y): #round x to nearest y, e.g. rounding 65 to nearest 30 = 60
ans = round (x*1.0 / y) * y
return ans
#SETTING THE CONDITIONS
#For the optional attentional blink
#For the dual-stream simultaneous target
stimListDualStream=[]
possibleCueTemporalPositions = np.array([6,7,8,9,10]) #debugAH np.array([6,7,8,9,10])
tasks=['T1','T1T2','allCued','oneCued']
numResponsesWanted=1; maxNumRespsWanted=1
numRings = 1 # 3
streamsPerRingPossibilities = np.array([2,8]) #this needs to be listed here so when print header can work out the maximum value
for streamsPerRing in streamsPerRingPossibilities:
for task in [ tasks[3] ]: #T1 task is just for the single-target tasks, but both streams are presented
if task=='T1T2':
numResponsesWanted=2; numToCue=-999
elif task=='allCued':
numToCue = streamsPerRing
elif task=='oneCued':
numToCue = 1
print('task=',task)
#setting targetLeftRightIfOne constant because which stream randomisation taken care of by baseAngle. Stream0 will always be the one cued, but it'll be in a random position
for targetLeftRightIfOne in ['right']: # ['left','right']: #If single target, should it be on the left or the right?
anglesMustBeMultipleOf = int( round(360 / max(streamsPerRingPossibilities) ) )
randomlyAssignCuesToStreams = True
for baseAngleCWfromEast in range(0,360,anglesMustBeMultipleOf): #cued stream will always be stream0. Its position is randomized by baseAngleCWfromEast
for cueTemporalPos in possibleCueTemporalPositions:
for firstRespLRifTwo in ['left','right']: #If dual target and lineup response, should left one or right one be queried first?
# if streamsPerRing == max(streamsPerRingPossibilities):
# baseAngleCWfromEast = 0
# else: #change base angle so that in the 2 streams condition, they equally often occupy each of the possible angles of the nStreams condition
# baseAngleCWfromEast= random.random()*360
# #round baseAngle to the nearest multiple of 360/max(streamsPerRingPossibilities)
# anglesMustBeMultipleOf = 360/max(streamsPerRingPossibilities)
# baseAngleCWfromEast = roundToNearestY(baseAngleCWfromEast, anglesMustBeMultipleOf)
stimListDualStream.append(
{'numRings':numRings, 'streamsPerRing':streamsPerRing, 'numRespsWanted':numResponsesWanted, 'task':task, 'targetLeftRightIfOne':targetLeftRightIfOne,
'cue0temporalPos':cueTemporalPos, 'firstRespLRifTwo': firstRespLRifTwo, 'cue1lag':0,'numToCue':numToCue,
'baseAngleCWfromEast':baseAngleCWfromEast}
) #cue1lag = 0, meaning simultaneous targets
trialsPerConditionDualStream = 2
trialsDualStream = data.TrialHandler(stimListDualStream,trialsPerConditionDualStream) #constant stimuli method
logging.info( ' each trialDurFrames='+str(trialDurFrames)+' or '+str(trialDurFrames*(1000./refreshRate))+ \
' ms' )
def numberToLetter(number): #0 = A, 25 = Z
#if it's not really a letter, return @
#if type(number) != type(5) and type(number) != type(np.array([3])[0]): #not an integer or numpy.int32
# return ('@')
alpha = [i for i in string.ascii_uppercase]
#print('Inside numberToLetter, number = ' + str(number))
if number < 0 or number > len(alpha) or number == 2 or number == 22:
return '@'
else:
return alpha[number]
def letterToNumber(letter): #A = 0, Z = 25
#if it's not really a letter, return -999
#HOW CAN I GENERICALLY TEST FOR LENGTH. EVEN IN CASE OF A NUMBER THAT' SNOT PART OF AN ARRAY?
alpha = [i for i in string.ascii_uppercase]
alpha.remove('C')
alpha.remove('W')
if letter == 'C' or letter == 'W':
return '@'
else:
return alpha.index(letter)
#print header for data file
print('experimentPhase\ttrialnum\tsubject\ttask\t',file=dataFile,end='')
print('noisePercent\t',end='',file=dataFile)
print('targetLeftRightIfOne\t',end='',file=dataFile)
print('streamsPerRing\t',end='',file=dataFile)
print('baseAngleCWfromEast\t',end='',file=dataFile)
printInOrderOfResponses = True
assert (printInOrderOfResponses==True), "Sorry, feature not supported"
if printInOrderOfResponses:
for i in range(maxNumRespsWanted):
dataFile.write('resp'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('button'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('cuePos'+str(i)+'\t')
dataFile.write('answer'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('correct'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('whichStream'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('whichRespCue'+str(i)+'\t') #have to use write to avoid ' ' between successive text, at least until Python 3
dataFile.write('responsePosRelative'+str(i)+'\t')
for i in range(numRings * max(streamsPerRingPossibilities)):
dataFile.write('streamLtrSequence'+str(i)+'\t')
print('timingBlips',file=dataFile)
#end of header
def calcStreamPos(numRings,streamsPerRing,baseAngleCWfromEast,cueOffsets,streami,streamOrNoise):
#streamOrNoise because noise coordinates have to be in deg, stream in pix
#cueOffsets are in deg, for instance indicating the eccentricity of the streams/cues
noiseOffsetKludge = 0.9 #Because the noise coords were drawn in pixels but the cue position is specified in deg, I must convert pix to deg for noise case
thisRingNum = int( streami / streamsPerRing )
ringStreami = streami % streamsPerRing
if streamsPerRing ==0:
pos = np.array([0,0])
else:
#assume want them evenly spaced, counterclockwise starting from directly east
halfAngle = 360/streamsPerRing/2.0
thisRingAngleOffset = (thisRingNum % 2) * halfAngle #offset odd-numbered rings by half the angle
thisAngle = baseAngleCWfromEast + ringStreami/streamsPerRing * 360 + thisRingAngleOffset
x = cueOffsets[thisRingNum]*cos(thisAngle/180*pi)
y = cueOffsets[thisRingNum]*sin(thisAngle/180*pi)
pos = np.array([x,y])
if streamOrNoise: #Because the noise coords were drawn in pixels but the cue position is specified in deg, I must convert pix to deg
pos *= noiseOffsetKludge*pixelperdegree
#pos = np.round(pos) #rounding or integer is a bad idea. Then for small radii, not equally spaced
#pos = pos.astype(int)
return pos
def oneFrameOfStim( n,cues,streamLtrSequences,cueDurFrames,letterDurFrames,ISIframes,cuesTemporalPos,whichStreamEachCue,
numRings,streamsPerRing,ltrStreams,baseAngleThisTrial,
noiseEachStream,proportnNoise,noiseCoordsEachStream,numNoiseDotsEachStream):#draw letter and possibly cue and noise on top
#defining a function to draw each frame of stim.
SOAframes = letterDurFrames+ISIframes
cueFrames = cuesTemporalPos*SOAframes
letterN = int( np.floor(n/SOAframes) )
frameOfThisLetter = n % SOAframes #every SOAframes, new letter
showLetter = frameOfThisLetter < letterDurFrames #if true, it's not time for the blank ISI. it's still time to draw the letter
#print 'n=',n,' SOAframes=',SOAframes, ' letterDurFrames=', letterDurFrames, ' (n % SOAframes) =', (n % SOAframes) #DEBUGOFF
#so that any timing problems occur just as often for every frame, always draw the letter and the cue, but simply draw it in the bgColor when it's not meant to be on
cuesTimeToDraw = list([False])*len(cues) #if don't use this, for AB task, bg color T2 cue will be drawn on top of T1 cue
#cue graphics objects for all possible streams should be drawn (in bgColor or cueColor) in E N W S order
for cue in cues: #might be at same time, or different times
cue.setLineColor( bgColor )
for cueN in xrange(len(cuesTemporalPos)): #For each cue, see whether it is time to draw it
thisCueFrameStart = cueFrames[cueN]
if n>=thisCueFrameStart and n<thisCueFrameStart+cueDurFrames:
thisCue = whichStreamEachCue[cueN]
if cueType=='endogenous':
cues[thisCue].setFillColor( cueColor )
else:
cues[thisCue].setLineColor( cueColor )
cuesTimeToDraw[thisCue] = True
for cueN in xrange(len(cues)):
if cuesTimeToDraw[cueN] == True: ##if don't use this, for AB task, bg color T2 cue will be drawn on top of T1 cue
cues[cueN].draw()
for streami in xrange(numRings*streamsPerRing):
thisStream = ltrStreams[streami]
thisLtrIdx = streamLtrSequences[streami][letterN] #which letter of the predecided sequence should be shown
#setting the letter size (height) takes a lot of time, so each stream must be drawn in correct height before the trial starts
if showLetter:
thisStream[thisLtrIdx].setColor( letterColor )
else: thisStream[thisLtrIdx].setColor( bgColor )
posThis = calcStreamPos(numRings,streamsPerRing,baseAngleThisTrial,cueOffsets,streami,streamOrNoise=0)
thisStream[thisLtrIdx].pos = posThis
thisStream[thisLtrIdx].draw()
#noise
refreshNoise = False #Not recommended because takes longer than a frame, even to shuffle apparently. Or may be setXYs step
if proportnNoise>0:
if refreshNoise:
if frameOfThisLetter ==0: #refresh it if it's the first frame of the noise, so each letter gets a different noise but noise not dynamic within a letter
np.random.shuffle(noiseCoordsEachStream[streami]) #refresh the noise by shuffling the possible locations of noise dots
numNoiseDotsThis = numNoiseDotsEachStream[streami]
dotCoords = noiseCoordsEachStream[streami][0:numNoiseDotsThis] #Take the first numNoiseDots random locations to plot the dots
posThisDeg = calcStreamPos(numRings,streamsPerRing,cueOffsets,streami,streamOrNoise=1)
#print('streami=',streami,'posThisDeg=',posThisDeg,'cueOffsets=',cueOffsets,'numStream=',numStreams)
#Displace the noise to present it over the letter stream
dotCoords[:,0] += posThisDeg[0]
dotCoords[:,1] += posThisDeg[1]
noiseEachStream[streami].setXYs(dotCoords)
noiseEachStream[streami].draw()
return True
# #######End of function definition that displays the stimuli!!!! #####################################
#############################################################################################################################
cues = list()
for cueN in xrange(numRings * max(streamsPerRingPossibilities)):
if cueType == 'exogenousRing':
cue = visual.Circle(myWin,
radius=cueRadius,#Martini used circles with diameter of 12 deg
lineColorSpace = 'rgb',
lineColor=bgColor,
lineWidth=2.0, #in pixels
units = 'deg',
fillColorSpace = 'rgb',
fillColor=None, #beware, with convex shapes fill colors don't work
pos= [-5,-5], #the anchor (rotation and vertices are position with respect to this)
interpolate=True,
autoLog=False)#this stim changes too much for autologging to be useful
elif cueType =='endogenous': #tiny dot at fixation point
cue = visual.Circle(myWin,
units='pix',
radius=1, #4
fillColorSpace='rgb',
fillColor=bgColor,
lineWidth=0,
interpolate=False,
autoLog = False)
cues.append(cue)
def calcLtrHeightSize( ltrHeight, cueOffsets, ringNum ):
ltrHeightBase = 1/2.*ltrHeight
#eccentricity scale including exponent. Check Strasburger
mFactor = 1/5.
ltrHeightThis = ltrHeightBase * mFactor*cueOffsets[ringNum]
return ltrHeightThis
#In each stream, predraw all 26 letters
ltrHeight = 3 #Martini letters were 2.5deg high
cueOffsets = [3,7,11.5]
maxStreams = numRings * max(streamsPerRingPossibilities)
ltrStreams = list()
for streami in xrange(maxStreams):
streamThis = list()
#calc desired eccentricity and size
#currently assumes streamsPerRing and numRings and cueOffsets doesn't change
thisRingNum = int( streami / streamsPerRing )
ltrHeightThis = calcLtrHeightSize( ltrHeight, cueOffsets, thisRingNum )
#print('thisRingNum = ',thisRingNum,'streamsPerRing=',streamsPerRing, ' ltrHeightThis=',ltrHeightThis)
for i in range(0,26):
if i is not 2 and i is not 22:
ltr = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb', font = font, color=letterColor,alignHoriz='center',alignVert='center',units='deg',autoLog=autoLogging)
ltr.setHeight( ltrHeightThis )
letter = numberToLetter(i)
#print(letter)
ltr.setText(letter,log=False)
ltr.setColor(bgColor)
streamThis.append( ltr )
ltrStreams.append( streamThis )
#All noise dot coordinates ultimately in pixels, so can specify each dot is one pixel
noiseFieldWidthDeg=ltrHeight *0.9 #1.0 makes noise sometimes intrude into circle
noiseFieldWidthPix = int( round( noiseFieldWidthDeg*pixelperdegree ) )
def timingCheckAndLog(ts,trialN):
#check for timing problems and log them
#ts is a list of the times of the clock after each frame
interframeIntervs = np.diff(ts)*1000
#print ' interframe intervs were ',around(interframeIntervs,1) #DEBUGOFF
frameTimeTolerance=.2 #proportion longer than refreshRate that will not count as a miss
longFrameLimit = np.round(1000/refreshRate*(1.0+frameTimeTolerance),2)
idxsInterframeLong = np.where( interframeIntervs > longFrameLimit ) [0] #frames that exceeded 150% of expected duration
numCasesInterframeLong = len( idxsInterframeLong )
if numCasesInterframeLong >0 and (not demo):
longFramesStr = 'ERROR,'+str(numCasesInterframeLong)+' frames were longer than '+str(longFrameLimit)+' ms'
if demo:
longFramesStr += 'not printing them all because in demo mode'
else:
longFramesStr += ' apparently screen refreshes skipped, interframe durs were:'+\
str( np.around( interframeIntervs[idxsInterframeLong] ,1 ) )+ ' and was these frames: '+ str(idxsInterframeLong)
if longFramesStr != None:
logging.error( 'trialnum='+str(trialN)+' '+longFramesStr )
if not demo:
flankingAlso=list()
for idx in idxsInterframeLong: #also print timing of one before and one after long frame
if idx-1>=0:
flankingAlso.append(idx-1)
else: flankingAlso.append(np.NaN)
flankingAlso.append(idx)
if idx+1<len(interframeIntervs): flankingAlso.append(idx+1)
else: flankingAlso.append(np.NaN)
flankingAlso = np.array(flankingAlso)
flankingAlso = flankingAlso[np.negative(np.isnan(flankingAlso))] #remove nan values
flankingAlso = flankingAlso.astype(np.integer) #cast as integers, so can use as subscripts
logging.info( 'flankers also='+str( np.around( interframeIntervs[flankingAlso], 1) ) ) #because this is not an essential error message, as previous one already indicates error
#As INFO, at least it won't fill up the console when console set to WARNING or higher
return numCasesInterframeLong
#end timing check
trialClock = core.Clock()
numTrialsCorrect = 0;
numTrialsApproxCorrect = 0;
numTrialsEachRespCorrect= np.zeros( maxNumRespsWanted )
numTrialsEachApproxCorrect= np.zeros( maxNumRespsWanted )
if eyetracking:
if getEyeTrackingFileFromEyetrackingMachineAtEndOfExperiment:
eyeMoveFile=('EyeTrack_'+subject+'_'+timeAndDateStr+'.EDF')
tracker=Tracker_EyeLink(myWin,trialClock,subject,1, 'HV5',(255,255,255),(0,0,0),False,(widthPix,heightPix))
def shuffleArraysIdentically(a, b):
assert len(a) == len(b)
aList = False; bList = False
if type(a).__name__=='list':
a = np.array(a)
aList = True
if type(b).__name__=='list':
b = np.array(b)
bList = True
p = np.random.permutation(len(a))
a = a[p]
b = b[p]
if aList:
a = list(a)
if bList:
b = list(b)
return a, b
def do_RSVP_stim(numRings,streamsPerRing, trial, proportnNoise,trialN):
#relies on global variables:
# logging, bgColor
#
streamsPerRing = trial['streamsPerRing']
print("streamsPerRing = ",trial['streamsPerRing'], 'task=',task)
if task != 'allCued':
print('targetLeftRightIfOne=',trial['targetLeftRightIfOne'], 'cue0temporalPos=',trial['cue0temporalPos'])
#set up which temporal positions are cued
cuesTemporalPos = [] #will contain the positions of all the cues (targets)
if task=='T1T2': #AB
cuesTemporalPos.append(trial['cue0temporalPos'])
cuesTemporalPos.append(trial['cue0temporalPos']+thisTrial['cue1lag'])
numTargets = 2
elif task =='T1': #target on only one side will be task 'T1' so only one cue
numTargets = 1
cuesTemporalPos.append(trial['cue0temporalPos'])
else: #generic task
numTargets = trial['numToCue'] #numToCue is global variable
for streami in xrange(trial['numToCue']):
cuesTemporalPos.append(trial['cue0temporalPos']) #all cues at the same time
cuesTemporalPos = np.array(cuesTemporalPos) #convert to np array
#assign the letters to be shown in each stream
streamLtrSequences = list()
for streami in xrange(numRings * streamsPerRing):
letterSeqThisStream = np.arange(0,24)
#letterSeqThisStream = np.delete(letterSeqThisStream, [2,22])
np.random.shuffle(letterSeqThisStream)
streamLtrSequences.append( letterSeqThisStream )
avoidDuplicates = False
if avoidDuplicates: #between first two streams
while (streamLtrSequences[0]==streamLtrSequences[1]).any():
np.random.shuffle(streamLtrSequences[0])
#set up corrAnsEachResp, whichStreamEachResp, whichStreamEachCue, whichRespEachCue, and cues' positions
#change corrAnswers to answerEachResp everywhere. To recover stream, could use whichStreamEachResp. Sensible if only one stream is queried and just want to print out that on each trial.
#whichStreamEachCue indicate which stream each cue refers to. These can be in different order than whichStreamEachResp, because randomised which queried first
#whichStreamEachResp is which stream each response refers to (which stream was queried for 0th response, 1st response, etc)
corrAnsEachResp = list(); whichStreamEachCue = list(); whichStreamEachResp = list(); whichRespEachCue = list()
if trial['task'] == 'T1':
if trial['targetLeftRightIfOne']=='right':
corrAnsEachResp.append( np.array( streamLtrSequences[0][cuesTemporalPos[0]] ) )
whichStreamEachResp.append(0) #first drawn is East
whichStreamEachCue.append(0)
whichRespEachCue.append(0)
stream=0
cues[0].setPos( calcStreamPos(numRings,streamsPerRing,cueOffsets,stream,streamOrNoise=0) )
elif trial['targetLeftRightIfOne']=='left':
corrAnsEachResp.append( np.array( streamLtrSequences[1][cuesTemporalPos[0]] ) ) #which streams are targets? Need variable for that.
whichStreamEachResp.append(1)
whichStreamEachCue.append(0)
whichRespEachCue.append(0)
stream=1
cues[0].setPos( calcStreamPos(numRings,streamsPerRing,cueOffsets,stream,streamOrNoise=0) )
else:
print("UNEXPECTED targetLeftRightIfOne value!")
elif trial['task'] =='T1T2': #attentional blink
if streamsPerRing==1 and numRings==1:
corrAnsEachResp.append( np.array( streamLtrSequences[0][cuesTemporalPos[0]] ) )
whichStreamEachCue.append(0)
whichStreamEachResp.append(0)
whichRespEachCue.append(0)
corrAnsEachResp.append( np.array( streamLtrSequences[0][cuesTemporalPos[1]] ) )
whichStreamEachCue.append(0)
whichStreamEachResp.append(0)
whichRespEachCue.append(1)
if len(cuesTemporalPos) > 2:
print("WARNING: Expected only 2 temporal positions for cues with T1T2 task, but have ", len(cuesTemporalPos))
cues[0].setPos([0,0])
cues[1].setPos([0,0])
elif numRings==1 and streamsPerRing==2: #2 streams with targets in different streams
print("ERROR: Not set up for 2-stream AB currently, but seems like that's what you are asking for")
#stream=1
#cues[0].setPos( calcStreamPos(numStreams,stream,cueOffset,streamOrNoise=0) )
#stream=0
#cues[1].setPos( calcStreamPos(numStreams,stream,cueOffset,streamOrNoise=0) )
whichRespEachCue.append(0)
whichRespEachCue.append(1)
else: #assume all len(cuesTemporalPos) streams cued at same time, with numRespsWanted to be reported, in random order.
#For instance, if numRespsWanted = 1, then a random one is queried.
if len(set(cuesTemporalPos)) > 1:
print('ERROR: Expected for this task that all cues would cue the same temporal position. Randomisation of whichResp will be wrong, need to randomise within each temporalPos')
core.quit()
#For each cue, work out correct answer, what stream it is
corrAnsEachCue = [] #because order of responses will be different than order of cues
numCues = len(cuesTemporalPos)
#Randomly assign cues to streams (with no repeats, because assuming all cues identical)
whichStreamEachCue = range(numRings*streamsPerRing)
if randomlyAssignCuesToStreams: #not doing it in nStreams versus 2 streams, because position stream 0, cued is randomised by baseAngle
random.shuffle(whichStreamEachCue)
whichStreamEachCue = whichStreamEachCue[:numCues] #Now will be random subset of streams, numCues long
whichStreamEachResp = deepcopy(whichStreamEachCue)
for streamI in xrange( numRings*streamsPerRing ): #Drawing the cues in the location they're supposed to be in
#assume each cue the succeeding stream (usually all cues same temporal position)
#assume only one response per time (Only one stream queried per temporalPos). Cut this down to one below.
posThis = calcStreamPos(numRings,streamsPerRing,trial['baseAngleCWfromEast'],cueOffsets,streamI,streamOrNoise=0)
if cueType =='endogenous': #reduce radius to bring it right next to fixation center
# angleRad = streamI/numStreams * 2*pi
desiredDistFromFixatn=2 #pixels
# newX = desiredDistFromFixatn*cos(angleRad)
# newY = desiredDistFromFixatn*sin(angleRad)
# print('newX=',newX,'newY=',newY)
# posThis = [newX,newY]
desiredDistFromFixatnEachRing = [ desiredDistFromFixatn ] * numRings
posThis = calcStreamPos(numRings,streamsPerRing,desiredDistFromFixatnEachRing,streamI,streamOrNoise=0)
cues[streamI].setPos( posThis )
cueRadiusThis = 1.05*calcLtrHeightSize( ltrHeight, cueOffsets, ringNum=int(streamI/streamsPerRing) )
cues[streamI].setRadius( cueRadiusThis )
for cuei in xrange(numCues): #work out correct answer for each cue
whichStreamThisCue = whichStreamEachCue[cuei]
letterIdxThisStream = streamLtrSequences[whichStreamThisCue][cuesTemporalPos[cuei]]
corrAnsEachCue.append( letterIdxThisStream )
corrAnsEachResp.append( letterIdxThisStream )
whichRespEachCue.append(cuei) #assume that responses are queried in the order of the cues. Note that above, which stream each cue corresponds to is random
#Need to shuffle which stream is queried first, second, etc. Remember, we're assuming there's only one temporalPos
#reduce whichStreamEachResp to numRespsWanted. Also whichRespEachCue. Leave corrAnsEachResp same length so can do error analysis checking for swaps.
whichRespEachCue = np.array(whichRespEachCue) #so that behaves correctly with np.where
#whichRespEachCue can be longer than number of responses. Otherwise may never get to cue (stream) corresponding to the single response cued.
#So, go through and replace all that are greater than numRespsWanted with -999
cuesNotQueriedIdxs= np.where( whichRespEachCue > trial['numRespsWanted']-1 )[0] #these streams were not to be responded to
#print('cuesNotQueriedIdxs=',cuesNotQueriedIdxs,'whichRespEachCue=',whichRespEachCue, 'where output= ', np.where( whichRespEachCue > trial['numRespsWanted']-1 ), 'numRespsWanted=', trial['numRespsWanted'] ) #AHdebug
if len( cuesNotQueriedIdxs ) > 0:
whichRespEachCue[ cuesNotQueriedIdxs ] = -999 #Leaving those that actually were queried.
whichStreamEachResp = whichStreamEachResp[ :trial['numRespsWanted'] ] #reduce to actual number of responses
corrAnsEachResp = corrAnsEachResp[ :trial['numRespsWanted'] ] #reduce to actual number of responses.
whichRespEachCue = whichRespEachCue[ :trial['numRespsWanted'] ] #reduce to actual number of responses.
#print('whichStreamEachCue=',whichStreamEachCue,' whichStreamEachResp=',whichStreamEachResp,'whichRespEachCue=',whichRespEachCue, ' corrAnsEachResp=',corrAnsEachResp)
#debug printouts
#print( 'streamLtrSequences[0]=',[numberToLetter(x) for x in streamLtrSequences[0]] )
#if trial['numStreams']>1:
# print( 'streamLtrSequences[1]=',[numberToLetter(x) for x in streamLtrSequences[1]] )
firstCueStream = whichStreamEachCue[0]
firstCueItem = streamLtrSequences[firstCueStream][cuesTemporalPos[0]]
#print( "corrAnsEachResp=", [numberToLetter(x) for x in corrAnsEachResp], "First cue cues stream",firstCueStream, " and letter ",numberToLetter(firstCueItem), end='')
if trial['numToCue'] > 1:
secondCueStream = whichStreamEachCue[1]
secondCueItem = streamLtrSequences[secondCueStream][cuesTemporalPos[1]]
print( " while second cue cues stream",secondCueStream, " and letter ",numberToLetter(secondCueItem) )
else: print('')
#end debug printouts
noiseEachStream = list(); noiseCoordsEachStream = list(); numNoiseDotsEachStream = list()
if proportnNoise > 0: #generating noise is time-consuming, so only do it once per trial. Then shuffle noise coordinates for each letter
for streami in xrange(numRings*streamsPerRing):
(noiseThis,allFieldCoordsThis,numNoiseDotsThis) = createNoise(proportnNoise,myWin,noiseFieldWidthPix, bgColor) #for the left stream, or the only stream
noiseEachStream.append(noiseThis)
numNoiseDotsEachStream.append(numNoiseDotsThis)
noiseCoordsEachStream.append(allFieldCoordsThis)
#Work out how to displace the noise so it will be on top of the streams, and then displace it
for streami in xrange(numRings*streamsPerRing):
numNoiseDotsThis = numNoiseDotsEachStream[streami]
dotCoords = noiseCoordsEachStream[streami][0:numNoiseDotsThis] #Take the first numNoiseDots random locations to plot the dots
posThisPix = calcStreamPos(numRings,streamsPerRing,trial['baseAngleCWfromEast'],cueOffsets,streami,streamOrNoise=1)
#Displace the noise to present it over the letter stream
dotCoords[:,0] += posThisPix[0]
dotCoords[:,1] += posThisPix[1]
noiseEachStream[streami].setXYs(dotCoords)
#end prep of cuesTemporalPos, streamLtrSequences, corrAnsEachResp, noiseEachStream, numNoiseDotsEachStream, noiseCoordsEachStream
preDrawStimToGreasePipeline = list() #I don't know why this works, but without drawing it I have consistent timing blip first time that draw ringInnerR for phantom contours
for cue in cues:
if cueType == 'endogenous':
cue.setFillColor(bgColor)
else:
cue.setLineColor(bgColor)
preDrawStimToGreasePipeline.extend([cue])
for stim in preDrawStimToGreasePipeline:
stim.draw()
myWin.flip(); myWin.flip()
#end preparation of stimuli
core.wait(.1);
trialClock.reset()
fixatnPeriodMin = 0.3
fixatnPeriodFrames = int( (np.random.rand(1)/2.+fixatnPeriodMin) *refreshRate) #random interval between 800ms and 1.3s (changed when Fahed ran outer ring ident)
ts = list(); #to store time of each drawing, to check whether skipped frames
if (fixatnPeriodFrames-1) % 2 ==0:
fixatnPeriodFrames +=1 #make it odd so that phase will be correct for transitioning to fixation flicker during the trial
for i in range(fixatnPeriodFrames): #prestim fixation interval
if showRefreshMisses: #flicker fixation on and off at framerate to see when skip frame
if i%2 or demo or exportImages:
fixatn.draw()
else: fixatnCounterphase.draw()
fixatnPoint.draw() #small circle on top
myWin.flip() #end fixation interval
#myWin.setRecordFrameIntervals(True); #can't get it to stop detecting superlong frames
t0 = trialClock.getTime()
for n in range(trialDurFrames): #this is the loop for this trial's stimulus!
if showRefreshMisses: #flicker fixation on and off at framerate to see when skip frame
if n%2 or demo or exportImages:
fixatn.draw()
else: fixatnCounterphase.draw()
fixatnPoint.draw()
worked = oneFrameOfStim( n,cues,streamLtrSequences,cueDurFrames,letterDurFrames,ISIframes,cuesTemporalPos,whichStreamEachCue,
numRings,streamsPerRing,ltrStreams,thisTrial['baseAngleCWfromEast'],
noiseEachStream,proportnNoise,noiseCoordsEachStream,numNoiseDotsEachStream) #draw letter and possibly cue and noise on top
if exportImages:
myWin.getMovieFrame(buffer='back') #for later saving
framesSaved +=1
myWin.flip()
t=trialClock.getTime()-t0; ts.append(t);
#end of big stimulus loop
myWin.setRecordFrameIntervals(False);
if task=='T1':
respPromptStim.setText('Which letter was circled?',log=False)
elif task=='T1T2':
respPromptStim.setText('Which two letters were circled?',log=False)
else: respPromptStim.setText('Error: unexpected task',log=False)
postCueNumBlobsAway=-999 #doesn't apply to non-tracking and click tracking task
return streamLtrSequences,cuesTemporalPos,corrAnsEachResp,whichStreamEachCue,whichStreamEachResp,whichRespEachCue,ts
def handleAndScoreResponse(passThisTrial,responses,responsesAutopilot,task,streamLtrSequences,
cuesTemporalPos,whichStreamEachCue,whichStreamEachResp,corrAnsEachResp,whichRespEachCue):
#Handle response, calculate whether correct, ########################################
#global printInOrderOfResponses
if autopilot or passThisTrial:
responses = responsesAutopilot
if autopilot: print("autopilot and fake responses are:",responses)
print( "Inside handleAndScoreResponse corrAnsEachResp=", [numberToLetter(x) for x in corrAnsEachResp], " whichRespEachCue=",whichRespEachCue)
#for eachRespCorrect etc., tension between calculating %corr for each response position and separating them out by target
#assume it's single- or multi-target thing where each target in a different stream
eachRespCorrect = np.zeros( len(responses) ) #number of responses
eachApproxCorrect = np.zeros( len(responses) )
posEachResponse = np.zeros( len(responses) )
responsePosRelative = np.zeros( len(responses) )
for respI in range(len(responses)): #score each response
if corrAnsEachResp[respI] == letterToNumber( responses[respI] ):
eachRespCorrect[respI] = 1 #doesn't compensate for different response query orders
thisStream = whichStreamEachResp[respI]
thisRespLetterSeq = np.array([ltrStreams[thisStream][item].text for item in streamLtrSequences[thisStream]])
#print(thisRespLetterSeq)
thisResponse = responses[respI]
#print('thisResponse: '+ str(thisResponse))
posThisResponse= np.where( thisResponse==thisRespLetterSeq ) #what position in the stream is the letter the person reported
#print('posThisResponse: ' + str(posThisResponse))
posThisResponse= posThisResponse[0] #list with potentially two entries, want first which will be array of places where the response was found in the letter sequence
if len(posThisResponse) > 1:
logging.error('Expected response to have occurred in only one position in stream')
if np.alen(posThisResponse)==0: #response not found in letter sequence
posThisResponse = -999
logging.warn('Response was not present in the stimulus stream')
else:
posThisResponse = posThisResponse[0]
posEachResponse[respI]= posThisResponse
#determine which cue cued thisStream
thisCue = np.where( thisStream == np.array(whichStreamEachCue) )[0]
print("thisStream = ",thisStream, " whichStreamEachCue =", whichStreamEachCue, " thisCue=", thisCue) #AHdebug
if len(thisCue) > 1:
logging.error('Expected thisStream to have been cued only once')
if np.alen(thisCue)==0: #thisStream seemingly not cued
posThisResponse = -999
logging.error('thisStream seemingly not cued'); print("ERROR: thisStream seemingly not cued")
else:
thisCue = thisCue[0]
cueTemporalPos = cuesTemporalPos[ thisCue ]
responsePosRelative[respI] = posThisResponse - cueTemporalPos
print(" thisCue idx=", thisCue, " cueTemporalPos = ",cueTemporalPos, " temporal posThisResponse= ", posThisResponse, "responsePosRelative[respI]=",responsePosRelative[respI])
eachApproxCorrect[respI] += abs(responsePosRelative[respI]) <= 3 #Vul efficacy measure of getting it right to within plus/minus
print("eachRespCorrect=",eachRespCorrect,"posEachResponse=",posEachResponse,"responsePosRelative=",responsePosRelative)
if printInOrderOfResponses: #Trying to print each response, whether correct, and which stream it corresponds to. Also cue temporal pos
#Too hard because mapping between response and eachRespCorrect and cuesTemporalPos a bit complicated, don't have whichRespEachCue variable
for respI in range(len(responses)): #give info about each response. responses seem to be in the order they are made
#header should be resp0, eachRespCorrect0, whichStream0,
print(responses[respI], '\t', end ='', file=dataFile) #respN
print(buttons[respI],'\t', end='', file=dataFile) #buttonN
answerCharacter = thisRespLetterSeq[cueTemporalPos]
print(cueTemporalPos, '\t', end = '', file = dataFile)
print(answerCharacter, '\t', end='', file=dataFile) #answer0
print(eachRespCorrect[respI],'\t', end='', file=dataFile) #eachRespCorrect0. This is in order of responses
print(whichStreamEachResp[respI], '\t', end='', file=dataFile) #whichStream0
print(whichRespEachCue[respI], '\t', end='', file=dataFile) #whichRespEachCue0
#Ideally, determine temporal position of cue corresponding to this response, with help of whichStreamEachCue
#But maybe there is not necessarily any unique mapping between them and the cuesTemporalPos. But, can rely on experiment design nums (cue1lag, etc.)
#Are cuesTemporalPos always in the order of the responses? (with the proviso that those with same temporal pos will be different streams)
while respI < maxNumRespsWanted-1:
respI+=1
print('-999','\t', end='', file=dataFile) #response N/A for this trial
print('-999','\t', end='', file=dataFile) #button N/A for this trial
if respI < len(corrAnsEachResp): #more answers than responses stored, to correspond to other streams to allow analysis of swaps, using whichStreamEachResp
answerCharacter = numberToLetter( corrAnsEachResp[respI] )
print(answerCharacter, '\t', end='', file=dataFile) #answerN
else: print('-999','\t', end='', file=dataFile) #answer0 N/A
print('-999','\t', end='', file=dataFile) #eachRespCorrectN N/A
if respI < len(whichStreamEachResp):
print(whichStreamEachResp[respI], '\t', end='', file=dataFile) #whichStreamN
else: print('-999','\t', end='', file=dataFile) #whichStreamN N/A
print('-999','\t', end='', file=dataFile) #whichRespEachCue N/A
else: #print in order of cues
#print('whichStreamEachCue=',whichStreamEachCue,' whichStreamEachResp=',whichStreamEachResp,' corrAnsEachResp=',corrAnsEachResp, ' whichStreamEachCue=',whichStreamEachCue,'whichRespEachCue same as whichStreamEachResp')
#responses, corrAnsEachResp, whichStreamEachResp will still line up
uniquethTemporalPosThisCue = 0
for cueI in range(len(cuesTemporalPos)): #print response stuff to dataFile
#header was answerPos0, answer0, response0, correct0, responsePosRelative0
#header should be answerStream0, answer0
print(cuesTemporalPos[cueI],'\t', end='', file=dataFile)
thisCueLetterSeq = streamLtrSequences[cueI]
answerCharacter = numberToLetter( corrAnsEachResp[cueI] )
print(answerCharacter, '\t', end='', file=dataFile) #answer0
thisStream = whichStreamEachCue[cueI]
print(thisStream,'\t', end='', file=dataFile) #stream0
#Find this stream in whichStreamEachResp to reveal which response this was.
#But, only consider responses from this cuesTemporalPos grouping.
#Don't have a whichRespEachCue variable
if cueI < numRespsWanted: #assuming order of responses same as order of cues. Remedy with whichStreamEachCue and whichStreamEachResp
print(responses[cueI], '\t', end='', file=dataFile) #response0 etc.
print(buttons[cueI], '\t', end='', file=dataFile) #button0 etc.
else:
print('-999\t-999','\t', end='', file=dataFile) #responseN,buttonN
whichStreamEachCue,whichStreamEachRes
for respI in range(len(responses)):
print(responsePosRelative[respI], '\t', end='',file=dataFile) #responsePosRelative0
#print('for cueI=',cueI,' cuesTemporalPos[cueI]=',cuesTemporalPos[cueI], ' answerCharacter=',answerCharacter, ' responses[cueI]=',responses[cueI],
# ' responsePosRelative[cueI]= ',responsePosRelative[cueI], ' eachCorrect[cueI]=',eachCorrect[cueI], 'eachApproxCorrect[cueI]=', eachApproxCorrect[cueI])
if len(eachRespCorrect)>1:
allCorrect = eachRespCorrect.all()
else:
allCorrect = eachRespCorrect[0]
T1approxCorrect = eachApproxCorrect[0]
return allCorrect,eachRespCorrect,eachApproxCorrect,T1approxCorrect,passThisTrial,expStop
#end handleAndScoreResponses
def play_high_tone_correct_low_incorrect(correct, passThisTrial=False):
highA = sound.Sound('G',octave=5, sampleRate=6000, secs=.3, bits=8)
low = sound.Sound('F',octave=3, sampleRate=6000, secs=.3, bits=8)
highA.setVolume(0.9)
low.setVolume(1.0)
if correct:
highA.play()
elif passThisTrial:
high= sound.Sound('G',octave=4, sampleRate=2000, secs=.08, bits=8)
for i in range(2):
high.play(); low.play();
else: #incorrect
low.play()
expStop=False
instructions1.draw()
myWin.flip()
waiting = True