-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubOptimalChoiceWithCommitment.py
1536 lines (1202 loc) · 47.3 KB
/
SubOptimalChoiceWithCommitment.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
from sys import platform as _platform
from psychopy import visual, core, parallel, gui, event
import time, csv, random, datetime, os, logging, sys
import readPort
#Determine which OS is being used, and calculate the screen size
if _platform == "linux" or _platform == "linux2":
# Linux
import Tkinter
root = Tkinter.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
print("_width: " + str(screen_width) + "\n" + "height: " + str(screen_height))
elif _platform == "win32":
# Windows...
from win32api import GetSystemMetrics
print "width =", GetSystemMetrics (0)
print "height =",GetSystemMetrics (1)
screen_width = GetSystemMetrics (0)
screen_height = GetSystemMetrics (1)
# Constants
# -------------------------------------------------------------------------------
L_X = (-1*(screen_width/3))
R_X = (screen_width/3)
I_STIM_Y = (-1*(screen_width/16))
CHOICE_Y = (screen_width/16)
# Time (in seconds) the hopper will stay up if the beam is not broken.
TIMEOUT_PERIOD = 60
#Time (in seconds) the hopper will stay up when the beam is broken
REWARD_TIME = 1
#Width of border around stimuli
LINE_WIDTH = 4
# Time of day at which experiment will start
# First element represents hours (24hr format)
# Second element represents minutes
# Set to 09:15
EXPERIMENT_START_TIME = [9, 15]
#Time (in seconds) the experiment will run
EXPERIMENT_TIME = 6300 #seconds = 105min
#A stimulus which can lead to one of two other stimuli
class ChoiceStim:
def __init__(self, name):
self.x = 0
self.y = CHOICE_Y
self.width = 100
self.height = 100
self.fillColour = "Gray"
self.outlineColour = "Silver"
self.name = name
self.initStims = []
def set_fill (self, fillCol):
self.fillColour = fillCol
def set_x (self, x):
self.x = x
def set_y (self, y):
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def set_outline (self, outlineCol):
self.outlineColour = outlineCol
def add_initStim (self, stim):
self.initStims.append(stim)
def draw(self):
global win
if self.name == "ChoiceA":
self.boundingBox = visual.Rect(win, lineWidth = LINE_WIDTH, width = self.width, height = self.height, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = "White")
CCInnerCirc = visual.Circle(win, lineWidth = LINE_WIDTH, radius = 15, pos = (self.x, self.y), units = "pix", lineColor = "Black", fillColor = "Black")
self.boundingBox.draw()
CCInnerCirc.draw()
elif self.name == "ChoiceB":
self.boundingBox = visual.Rect(win, lineWidth = LINE_WIDTH, width = self.width, height = self.height, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = "White")
CBInnerRect = visual.Rect(win, lineWidth = LINE_WIDTH, width = 30, height = 30, pos = (self.x, self.y), units = "pix", lineColor = "Black", fillColor = "White")
self.boundingBox.draw()
CBInnerRect.draw()
elif self.name == "ChoiceC":
topRight = (self.x + (self.width/2), self.y + (self.height/2))
bottomLeft = (self.x - (self.width/2), self.y - (self.height/2))
topLeft = (self.x - (self.width/2), self.y + (self.height/2))
bottomRight = (self.x + (self.width/2), self.y - (self.height/2))
self.boundingBox = visual.Rect(win, lineWidth = LINE_WIDTH, width = self.width, height = self.height, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = "White")
CALine1 = visual.Line(win, start = (topRight), end = (bottomLeft), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
CALine2 = visual.Line(win, start = (bottomRight), end = (topLeft), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
self.boundingBox.draw()
CALine1.draw()
CALine2.draw()
else:
self.boundingBox = visual.Rect(win, lineWidth = 4, width = self.width, height = self.height, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = self.fillColour)
self.boundingBox.draw()
#A stimulus which leads to one other stimulus, directly below it
class InitialLinkStim:
def __init__(self, name):
self.x = 0
self.y = I_STIM_Y
self.radius = 50
self.fillColour = "Gray"
self.outlineColour = "Silver"
self.name = name
self.termStims = []
self.subOpt = False
def set_subOpt(self, value):
self.subOpt = value
def get_subOpt():
return self.subOpt
def set_fill (self, fillCol):
self.fillColour = fillCol
def set_outline (self, outlineCol):
self.outlineColour = outlineCol
def add_termStim (self, stim):
self.termStims.append(stim)
def set_x (self, x):
self.x = x
def set_y (self, y):
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def draw(self):
global win
if self.name == "InitA":
self.boundingBox = visual.Circle(win, lineWidth = LINE_WIDTH, radius = self.radius, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = "White")
InitAVertLine = visual.Line(win, start = (self.x, (self.y + self.radius)), end = (self.x, (self.y - self.radius)), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
self.boundingBox.draw()
InitAVertLine.draw()
elif self.name == "InitB":
topStart = ((self.x - 35), (self.y + 20))
topEnd = ((self.x + 35), (self.y + 20))
midStart = ((self.x - self.radius), (self.y))
midEnd = ((self.x + self.radius), (self.y))
bottomStart = ((self.x - 35), (self.y - 20))
bottomEnd = ((self.x + 35), (self.y - 20))
self.boundingBox = visual.Circle(win, lineWidth = LINE_WIDTH, radius = self.radius, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = "White")
InitBTopLine = visual.Line(win, start = (topStart), end = (topEnd), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
InitBMidLine = visual.Line(win, start = (midStart), end = (midEnd), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
InitBBottomLine = visual.Line(win, start = (bottomStart), end = (bottomEnd), lineWidth = LINE_WIDTH, units = "pix", lineColor = "Black")
self.boundingBox.draw()
InitBTopLine.draw()
InitBMidLine.draw()
InitBBottomLine.draw()
else:
self.boundingBox = visual.Circle(win, lineWidth = LINE_WIDTH, radius = self.radius, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = self.fillColour)
self.boundingBox.draw()
def drawTermLinks(self):
result = rollForTermResult(self)
drawBlanksNoFlip(listOfBlanks)
if result == 0:
termStimShown = self.termStims[0]
self.termStims[0].draw()
else:
termStimShown = self.termStims[1]
self.termStims[1].draw()
return termStimShown
#A stimulus which is presented and then holds for a particular period of time, regardless of input
class TerminalLinkStim:
def __init__(self, name):
self.x = 0
self.y = I_STIM_Y
self.radius = 50
self.fillColour = "Gray"
self.outlineColour = "Silver"
self.name = name
self.chanceOfReinforcement = 0
def set_fill (self, fillCol):
self.fillColour = fillCol
def get_fill(self):
return self.fillColour
def set_outline (self, outlineCol):
self.outlineColour = outlineCol
def set_chanceOfReinforcement(self, chance):
self.chanceOfReinforcement = chance
def set_x (self, x):
self.x = x
def set_y (self, y):
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y
def draw(self):
global win
if self.name == "TermA":
self.fillColour = "Green"
elif self.name == "TermB":
self.fillColour = "Orange"
elif self.name == "TermC":
self.fillColour = "Red"
elif self.name == "TermD":
self.fillColour = "Purple"
self.boundingBox = visual.Circle(win, lineWidth = LINE_WIDTH, radius = self.radius, pos = (self.x, self.y), units = "pix", lineColor = self.outlineColour, fillColor = self.fillColour)
self.boundingBox.draw()
#Determine which terminal link is shown
def rollForTermResult(initialLink):
global termResults1, termResults2, rolledABefore, rolledBBefore, index1, index2
#reset the chance output array for stims of InitA
if not rolledABefore:
termResults1 = [0,0,1,1,1,
1,1,1,1,1]
random.shuffle(termResults1)
index1 = 0
#reset the chance output array for stims of InitB
if not rolledBBefore:
termResults2 = [0,0,1,1,1,
1,1,1,1,1]
random.shuffle(termResults2)
index2 = 0
rolledABefore = True
rolledBBefore = True
if initialLink.name == "InitA":
result = termResults1[index1]
index1 += 1
if index1 == len(termResults1):
rolledABefore = False
elif initialLink.name == "InitB":
result = termResults2[index2]
index2 += 1
if index2 == len(termResults2):
rolledBBefore = False
return result
# A rigged function for returning "1" or "0" 50% of the time.
# Save whether the function has been called before.
def rollDiceForFiftyFifty():
global rolledFFBefore, FFResults, FFIndex
if not rolledFFBefore:
FFResults = [0,0,0,0,0,
1,1,1,1,1]
random.shuffle(FFResults)
FFIndex = -1
rolledFFBefore = True
FFIndex += 1
if FFIndex == len(FFResults):
random.shuffle(FFResults)
FFIndex = -1
return FFResults[FFIndex]
#Starts logging for admin purposes
def initialize_logger(output_dir):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create console handler and set level to info
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# create error file handler and set level to error
handler = logging.FileHandler(os.path.join(output_dir, "error.log"),"w", encoding=None, delay="true")
handler.setLevel(logging.ERROR)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# create debug file handler and set level to debug
handler = logging.FileHandler(os.path.join(output_dir, "all.log"),"w")
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
#Creates window, sets up mouse, etc.
def setup():
global win, mouse, rolledABefore, rolledBBefore, subjectNumber, datafile, writer, parallelPort, portValue, rolledFiftyFiftyBefore, trialNumber, birdAte
logging.debug("Setting up...")
#initialize the window
win = visual.Window(fullscr = True, rgb = [-1.000,-1.000,-1.000], units = "pix", winType = "pyglet")
#setup input from the mouse
mouse = event.Mouse(visible = True)
core.checkPygletDuringWait = True
parallelPort = parallel.ParallelPort(address=0x0378)
portValue = 0x0000
turnOnFan()
birdAte = False
rolledABefore = False
rolledBBefore = False
rolledFFBefore = False
rolledFiftyFiftyBefore = False
trialNumber = 0
dataFolderPath = os.getcwd() + "\SubOptimal_Data_Logs"
logging.debug(dataFolderPath)
if not os.path.exists(dataFolderPath):
os.makedirs(dataFolderPath)
filename = dataFolderPath + '/' + (time.strftime("%d_%m_%Y")) + '_' + (time.strftime("%H_%M")) + '_' + 'Subject_' + str(subjectNumber) + '_data.csv'
datafile = open(filename, 'wb')
writer = csv.writer(datafile, delimiter=',')
if condition == "Autoshaping (FR1)" or condition == "Operant Training (FR1)" or condition == "Operant Training (FR3)" or condition == "Operant Training (FR5)":
writer.writerow(["ResearchAssistant", "SubjectNumber", "SetNumber",
"SessionNumber", "DateStarted", "Contingency",
"Condition", "PeckstoReward", "ProgramName", "TrialNumber",
"ProgramLoadTime", "BirdInBoxTime", "StartTime",
"ExperimentEndTime", "ApparatusPresent",
"TimeoutPeriod", "RewardTime", "StimulusPresented",
"StimulusSide", "ReactionTimes", "PeckNum",
"ITI", "BirdAte"])
else:
writer.writerow(['ResearchAssistant', 'SubjectNumber', 'SetNumber',
'SessionNumber', 'DateandTimeRun', 'Contingency',
'Condition', 'NumberofPecksRequired', 'ProgramName',
'TrialNumber', 'ProgramLoadTime', 'BirdInBoxTime',
'ExperimentStartTime', 'ExperimentEndTime',
'ApparatusPresent', 'TimeoutPeriod', 'RewardTime',
'ChoiceStimulus', 'Initial-Link', 'Terminal-Link', 'Terminal-LinkColour',
'ChoiceStimulusSidePecked', 'Initial-LinkSidePecked',
'ChoiceStimulusPecked',
'ChoiceStimulusReactionTime', 'Initial-LinkReactionTime',
'Terminal-LinkPeckLog', 'TerminalLinkLatency',
'Terminal-LinkFinalResponse', 'Terminal-LinkDuration',
'Inter-TrialInterval(ITI)',
'ChoiceStimulusScreenPeckCount',
'InitialLinkScreenPeckCount',
'Terminal-LinkScreenPeckCount', 'Sub-OptimalLinkChosen', 'BirdAte'])
# Creates all stimuli required, and sets them as global values
def createStimuli():
global blankLeftChoiceStim, blankCentreChoiceStim, blankRightChoiceStim
global blankLeftTermStim, blankRightTermStim, choiceA, choiceB, choiceC
global initA, initB, termLinkA, termLinkB, termLinkC, termLinkD
global listOfBlanks
logging.debug("Creating stimuli...")
listOfBlanks = []
blankLeftChoiceStim = ChoiceStim("BlankL")
blankCentreChoiceStim = ChoiceStim("BlankC")
blankRightChoiceStim = ChoiceStim("BlankR")
blankLeftChoiceStim.set_x(L_X)
blankCentreChoiceStim.set_x(0)
blankRightChoiceStim.set_x(R_X)
blankLeftTermStim = TerminalLinkStim("BlankL")
blankRightTermStim = TerminalLinkStim("BlankR")
blankLeftTermStim.set_x(L_X)
blankRightTermStim.set_x(R_X)
listOfBlanks.append(blankLeftChoiceStim)
listOfBlanks.append(blankCentreChoiceStim)
listOfBlanks.append(blankRightChoiceStim)
listOfBlanks.append(blankLeftTermStim)
listOfBlanks.append(blankRightTermStim)
choiceA = ChoiceStim("ChoiceA")
choiceB = ChoiceStim("ChoiceB")
choiceC = ChoiceStim("ChoiceC")
initA = InitialLinkStim("InitA")
initB = InitialLinkStim("InitB")
termLinkA = TerminalLinkStim("TermA")
termLinkB = TerminalLinkStim("TermB")
termLinkC = TerminalLinkStim("TermC")
termLinkD = TerminalLinkStim("TermD")
# Matches initial links with choice stimuli,
# based on contingency.
def matchStimuli(contingency, reversal):
logging.debug("Matching Stimuli...")
if contingency == "1":
choiceA.set_x(L_X)
choiceB.set_x(R_X)
initA.set_x(L_X)
initB.set_x(R_X)
termLinkA.set_x(L_X)
termLinkB.set_x(L_X)
termLinkC.set_x(R_X)
termLinkD.set_x(R_X)
if reversal == False:
termLinkA.set_chanceOfReinforcement(1)
termLinkB.set_chanceOfReinforcement(0)
termLinkC.set_chanceOfReinforcement(0.5)
termLinkD.set_chanceOfReinforcement(0.5)
elif reversal == True:
termLinkA.set_chanceOfReinforcement(0.5)
termLinkB.set_chanceOfReinforcement(0.5)
termLinkC.set_chanceOfReinforcement(1)
termLinkD.set_chanceOfReinforcement(0)
choiceA.add_initStim(initA)
choiceB.add_initStim(initB)
choiceC.add_initStim(initA)
choiceC.add_initStim(initB)
initA.add_termStim(termLinkA)
initA.add_termStim(termLinkB)
initB.add_termStim(termLinkC)
initB.add_termStim(termLinkD)
elif contingency == "2":
choiceA.set_x(R_X)
choiceB.set_x(L_X)
initA.set_x(L_X)
initB.set_x(R_X)
termLinkA.set_x(L_X)
termLinkB.set_x(R_X)
termLinkC.set_x(R_X)
termLinkD.set_x(L_X)
if reversal == False:
termLinkA.set_chanceOfReinforcement(0)
termLinkB.set_chanceOfReinforcement(0.5)
termLinkC.set_chanceOfReinforcement(0.5)
termLinkD.set_chanceOfReinforcement(1)
elif reversal == True:
termLinkA.set_chanceOfReinforcement(0.5)
termLinkB.set_chanceOfReinforcement(1)
termLinkC.set_chanceOfReinforcement(0)
termLinkD.set_chanceOfReinforcement(0.5)
choiceA.add_initStim(initB)
choiceB.add_initStim(initA)
choiceC.add_initStim(initA)
choiceC.add_initStim(initB)
initA.add_termStim(termLinkD)
initA.add_termStim(termLinkA)
initB.add_termStim(termLinkB)
initB.add_termStim(termLinkC)
elif contingency == "3":
choiceA.set_x(L_X)
choiceB.set_x(R_X)
initA.set_x(R_X)
initB.set_x(L_X)
termLinkA.set_x(R_X)
termLinkB.set_x(R_X)
termLinkC.set_x(L_X)
termLinkD.set_x(L_X)
if reversal == False:
termLinkA.set_chanceOfReinforcement(0.5)
termLinkB.set_chanceOfReinforcement(0.5)
termLinkC.set_chanceOfReinforcement(1)
termLinkD.set_chanceOfReinforcement(0)
elif reversal == True:
termLinkA.set_chanceOfReinforcement(1)
termLinkB.set_chanceOfReinforcement(0)
termLinkC.set_chanceOfReinforcement(0.5)
termLinkD.set_chanceOfReinforcement(0.5)
choiceA.add_initStim(initB)
choiceB.add_initStim(initA)
choiceC.add_initStim(initA)
choiceC.add_initStim(initB)
initA.add_termStim(termLinkA)
initA.add_termStim(termLinkB)
initB.add_termStim(termLinkC)
initB.add_termStim(termLinkD)
elif contingency == "4":
choiceA.set_x(R_X)
choiceB.set_x(L_X)
initA.set_x(R_X)
initB.set_x(L_X)
termLinkA.set_x(R_X)
termLinkB.set_x(L_X)
termLinkC.set_x(L_X)
termLinkD.set_x(R_X)
if reversal == False:
termLinkA.set_chanceOfReinforcement(0.5)
termLinkB.set_chanceOfReinforcement(1)
termLinkC.set_chanceOfReinforcement(0)
termLinkD.set_chanceOfReinforcement(0.5)
elif reversal == True:
termLinkA.set_chanceOfReinforcement(1)
termLinkB.set_chanceOfReinforcement(0.5)
termLinkC.set_chanceOfReinforcement(0.5)
termLinkD.set_chanceOfReinforcement(0)
choiceA.add_initStim(initA)
choiceB.add_initStim(initB)
choiceC.add_initStim(initA)
choiceC.add_initStim(initB)
initA.add_termStim(termLinkD)
initA.add_termStim(termLinkA)
initB.add_termStim(termLinkB)
initB.add_termStim(termLinkC)
# Makes a list of choice stimuli, returns the list
def makeChoiceStimList():
logging.debug("Randomizing choice stimuli...")
choiceList = []
choiceList1 = [choiceA, choiceB]
choiceList2 = [choiceA, choiceC]
choiceList3 = [choiceB, choiceC]
for i in range(0,20):
# 20 of each type of forced choice
choiceList.append([choiceA])
choiceList.append([choiceB])
choiceList.append([choiceC])
# 40 of each type of choice
choiceList.append(choiceList1)
choiceList.append(choiceList2)
choiceList.append(choiceList3)
choiceList.append(choiceList1)
choiceList.append(choiceList2)
choiceList.append(choiceList3)
random.shuffle(choiceList)
return choiceList
# Draws blank stimuli, but doesn't present them.
# Must be used in conjunction with another stimulus
# presentation function
def drawBlanksNoFlip(stimuli):
for i in range(0,len(stimuli)):
stimuli[i].draw()
# Draws each stimuli in "stimuli"
def drawStims(stimuli):
logging.debug("Drawing stimuli...")
if len(stimuli) != len(listOfBlanks):
drawBlanksNoFlip(listOfBlanks)
for i in range(0,len(stimuli)):
stimuli[i].draw()
win.flip()
# Waits for input on any object provided in "Stimuli"
# Returns after "targetPeckRequired" number of clicks on
# stimuli is reached.
def waitForClicks(targetPeckRequired, stimuli, duration):
logging.debug("Waiting for clicks...")
peckNum = 0
targetPeckNum = 0
targetPecked = ""
oldMouseIsDown = True
targetFlag = False
reactionTimes = []
reactionTimer = core.Clock()
stimTimer = core.CountdownTimer(duration)
while ((stimTimer.getTime() > 0) and (targetFlag == False)):
#event.clearEvents('mouse')
#mouse.clickReset()
mouseIsDown = mouse.getPressed()[0]
mouse.clickReset()
if mouseIsDown and not oldMouseIsDown:
# Add click reaction times to list.
reactionTimes.append(reactionTimer.getTime())
pos = mouse.getPos()
logging.debug(pos)
for i in range (0,len(stimuli)):
if stimuli[i].getBoundingBox().contains(pos):
targetPeckNum += 1
if targetPeckNum >= targetPeckRequired:
targetFlag = True
targetPecked = stimuli[i]
break
reactionTimer.reset()
peckNum += 1
oldMouseIsDown = mouseIsDown
if event.getKeys(["escape"]):
logging.debug("User pressed escape")
exit()
return targetPecked, targetFlag, peckNum, reactionTimes
# Waits for the user to press the escape key
# Used for ITI waiting
# When time is 0, loop will go infinitely
# Every other value of time will start a counter for that length of time (in s)
def waitForExitPress(time = 0):
logging.debug("Waiting for exit key to be pressed")
if time == 0:
while True:
if event.getKeys(["escape"]):
logging.debug("User pressed escape")
exit()
else:
waitTimer = core.CountdownTimer(time)
while (waitTimer.getTime() > 0):
if event.getKeys(["escape"]):
logging.debug("User pressed escape")
exit()
# Displays a blank screen and waits for the escape key
def displayEndScreen():
logging.debug("Displaying end screen")
drawBlanksNoFlip(listOfBlanks)
spacebarText = visual.TextStim(win, text='Experiment Ended. Press ESC to exit.', alignHoriz = 'center', alignVert = 'bottom')
spacebarText.draw()
win.flip()
waitForExitPress()
# Probabilities:
# 1 = 100%
# 0.5 = 50%
# 0 = no reward
def giveReward(probability):
global fiftyFifty, fiftyFiftyIndex, rolledFiftyFiftyBefore, birdAte
hopperDropped = ""
if apparatusPresent:
if probability == 1:
logging.debug("Reward given with probability of: ", probability)
hopperDropped = dropHoppersAtRandom()
elif probability == 0.5:
if not rolledFiftyFiftyBefore:
fiftyFifty = [0,0,0,0,0,
1,1,1,1,1]
random.shuffle(fiftyFifty)
rolledFiftyFiftyBefore = True
fiftyFiftyIndex = -1
fiftyFiftyIndex += 1
if fiftyFifty[fiftyFiftyIndex] == 1:
hopperDropped = dropHoppersAtRandom()
logging.debug("Reward given with probability of: " + str(probability))
else:
logging.debug("Reward not given")
probability = 0
# In place of 1 second of hopper access
core.wait(REWARD_TIME)
else:
logging.debug("Reward not given")
# In place of 1 second of hopper access
core.wait(REWARD_TIME)
if probability > 0:
birdAte = False
hopperTimer = core.CountdownTimer(TIMEOUT_PERIOD)
# Read IR beam
if hopperDropped == "L":
while (hopperTimer.getTime() > 0):
core.wait(0.1)
irValue = readLeftHopperBeam()
if irValue == 0:
birdAte = True
break
## 1 second of hopper access
core.wait(REWARD_TIME)
dropLeftHopper()
else:
# Assume right hopper was dropped
while (hopperTimer.getTime() > 0):
core.wait(0.1)
irValue = readRightHopperBeam()
if irValue == 0:
birdAte = True
break
## 1 second of hopper access
core.wait(REWARD_TIME)
dropRightHopper()
else:
logging.debug("Apparatus not present")
## FIX: MAKE THIS CODE MORE CONDENSED.
if probability == 1:
logging.debug("Reward given with probability of: " + str(probability))
elif probability == 0.5:
if not rolledFiftyFiftyBefore:
fiftyFifty = [0,0,0,0,0,
1,1,1,1,1]
random.shuffle(fiftyFifty)
rolledFiftyFiftyBefore = True
fiftyFiftyIndex = -1
fiftyFiftyIndex += 1
if fiftyFiftyIndex == (len(fiftyFifty) -1):
rolledFiftyFiftyBefore = False
if fiftyFifty[fiftyFiftyIndex] == 1:
logging.debug("Reward given with probability of: " + str(probability))
else:
logging.debug("Reward not given")
probability = 0
else:
logging.debug("Reward not given")
# In place of 1 second of hopper access
core.wait(REWARD_TIME)
if probability > 0:
birdAte = True
# Randomly chooses a hopper to drop.
# Call this function when it doesn't matter which hopper is dropped
def dropHoppersAtRandom():
chanceArray = [0,1]
random.shuffle(chanceArray)
if chanceArray[0] == 1:
raiseLeftHopper()
hopperDropped = "L"
else:
raiseRightHopper()
hopperDropped = "R"
logging.debug("Hopper dropped: " + str(hopperDropped))
return hopperDropped
# Raises the hopper and turns the light on.
def raiseLeftHopper():
global portValue
portValue = portValue | (0x0010)
portValue = portValue | (0x0004)
parallelPort.setData(portValue)
# Raises the hopper and turns the light on.
def dropLeftHopper():
global portValue
portValue = portValue & ~(0x0010)
portValue = portValue & ~(0x0004)
parallelPort.setData(portValue)
def raiseRightHopper():
global portValue
portValue = portValue | (0x0020)
portValue = portValue | (0x0008)
parallelPort.setData(portValue)
def dropRightHopper():
global portValue
portValue = portValue & ~(0x0020)
portValue = portValue & ~(0x0008)
parallelPort.setData(portValue)
def turnOnHouseLight():
global portValue
portValue = portValue | (0x0001)
parallelPort.setData(portValue)
def turnOffHouseLight():
global portValue
portValue = portValue & ~(0x0001)
parallelPort.setData(portValue)
def turnOnFan():
global portValue
portValue = portValue | (0x0002)
parallelPort.setData(portValue)
def turnOffFan():
global portValue
portValue = portValue & ~(0x0002)
parallelPort.setData(portValue)
# Reads from left IR beam. Called after hopper is dropped
def readLeftHopperBeam():
#return if beam broken
value = readPort.readPort(0x0201) & (0x20)
logging.debug("LEFT IR: " + str(value))
return value
# Reads from right IR beam. Called after hopper is dropped
def readRightHopperBeam():
#return if beam broken
value = readPort.readPort(0x0201) & (0x10)
logging.debug("RIGHT IR: " + str(value))
return value
#Reads IR beam status on port 0x0201 (GamePort)
def checkForApparatus():
#return True if apparatus present, False otherwise
logging.debug("Checking for apparatus")
value = readPort.readPort(0x0201)
logging.debug("Apparatus value " + str(value))
if value == 0x00ff:
return True
else:
return False
def waitForTermLinks():
logging.debug("Waiting for terminal clicks...")
peckNum = 0
oldMouseIsDown = True
reactionTimes = []
reactionTimer = core.Clock()
stimTimer = core.CountdownTimer(TERM_DUR)
stimTimer.reset()
while (stimTimer.getTime() > 0):
mouseIsDown = mouse.getPressed()[0]
mouse.clickReset()
if mouseIsDown and not oldMouseIsDown:
# Add click reaction times to list.
reactionTimes.append(reactionTimer.getTime())
reactionTimer.reset()
pos = mouse.getPos()
logging.debug(pos)
peckNum += 1
oldMouseIsDown = mouseIsDown
if event.getKeys(["escape"]):
logging.debug("User pressed escape")
exit()
return peckNum, reactionTimes
# Main experimental phase. Reversal changes chance of reinforcement.
def doExperimentalPhase():
logging.debug("Starting experimental phase...")
global birdAte
createStimuli()
matchStimuli(contingency, reversal)
stimList = makeChoiceStimList()
startTime = time.time()
expTimer = core.CountdownTimer(EXPERIMENT_TIME)
trialNumber = 0
print("StimList Len: " + str(len(stimList)))
logging.debug("StimList Length " + str(len(stimList)))
for i in range(0,len(stimList)):
choicePeckNum = 0
initPeckNum = 0
trialNumber += 1
if (expTimer.getTime() <= 0):
break
drawStims(stimList[i])
cStimPecked, cClickFlag, cPeckNum, cReactionTimes = waitForClicks(1, stimList[i], expTimer.getTime())
if cClickFlag == True:
drawStims(cStimPecked.initStims)
iStimPecked, iClickFlag, iPeckNum, iReactionTimes = waitForClicks(1, cStimPecked.initStims, expTimer.getTime())
if iClickFlag == True:
termStimShown = iStimPecked.drawTermLinks()
win.flip()
tPeckNum, tReactionTimes = waitForTermLinks()
drawStims(listOfBlanks) #Display blank stimuli for duration of ITI
birdAte = False
giveReward(termStimShown.chanceOfReinforcement)
cStimSide = ""
iStimSide = ""
if cClickFlag == True:
if cStimPecked.get_x() == L_X:
cStimSide = "LEFT"
elif cStimPecked.get_x() == R_X:
cStimSide = "RIGHT"
elif cStimPecked.get_x() == 0:
cStimSide = "CENTRE"
else:
cStimSide = "NO STIM PECKED"
if cClickFlag == True: