-
Notifications
You must be signed in to change notification settings - Fork 5
/
adaptive_freq_discrim.py
765 lines (691 loc) · 42.4 KB
/
adaptive_freq_discrim.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
"""
Create a frequency discrimination 2AFC paradigm.
* TO DO:
- Check that all parameters are saved
- Check that all times are saved
- Note that outcomeMode (menu) is saved different from labels (e.g., outcome)
- Verify that the choice of last trial is saved properly
"""
import time
import numpy as np
import sys
from qtpy import QtWidgets
from taskontrol import rigsettings
from taskontrol import dispatcher
from taskontrol import statematrix
from taskontrol import savedata
from taskontrol import paramgui
from taskontrol import utils
from taskontrol.plugins import templates
from taskontrol.plugins import performancedynamicsplot
from taskontrol.plugins import soundclient
from taskontrol.plugins import speakercalibration
LONGTIME = 100
class Paradigm(templates.Paradigm2AFC):
def __init__(self,parent=None, paramfile=None, paramdictname=None):
super(Paradigm, self).__init__(parent)
# -- Performance dynamics plot --
performancedynamicsplot.set_pg_colors(self)
self.myPerformancePlot = performancedynamicsplot.PerformanceDynamicsPlot(nTrials=400,winsize=10)
# -- Add parameters --
self.params['timeWaterValveL'] = paramgui.NumericParam('Time valve left',value=0.03,
units='s',group='Water delivery')
self.params['timeWaterValveC'] = paramgui.NumericParam('Time valve center',value=0.03,
units='s',group='Water delivery')
self.params['timeWaterValveR'] = paramgui.NumericParam('Time valve right',value=0.03,
units='s',group='Water delivery')
waterDelivery = self.params.layout_group('Water delivery')
self.params['outcomeMode'] = paramgui.MenuParam('Outcome mode',
['sides_direct','direct','on_next_correct',
'only_if_correct','simulated'],
value=3,group='Choice parameters')
self.params['allowEarlyWithdrawal'] = paramgui.MenuParam('Allow early withdraw',
['off','on'],
value=0,group='Choice parameters')
self.params['antibiasMode'] = paramgui.MenuParam('Anti-bias mode',
['off','repeat_mistake'],
value=0,group='Choice parameters')
choiceParams = self.params.layout_group('Choice parameters')
self.params['delayToTargetMean'] = paramgui.NumericParam('Mean delay to target',value=0.3,
units='s',group='Timing parameters')
self.params['delayToTargetHalfRange'] = paramgui.NumericParam('+/-',value=0.05,
units='s',group='Timing parameters')
self.params['delayToTarget'] = paramgui.NumericParam('Delay to target',value=0.3,
units='s',group='Timing parameters',
enabled=False,decimals=3)
self.params['targetDuration'] = paramgui.NumericParam('Target duration',value=0.1,
units='s',group='Timing parameters')
self.params['rewardAvailability'] = paramgui.NumericParam('Reward availability',value=4,
units='s',group='Timing parameters')
self.params['punishTimeError'] = paramgui.NumericParam('Punishment (error)',value=0,
units='s',group='Timing parameters')
self.params['punishTimeEarly'] = paramgui.NumericParam('Punishment (early)',value=0,
units='s',group='Timing parameters')
timingParams = self.params.layout_group('Timing parameters')
self.params['trialsPerBlock'] = paramgui.NumericParam('Trials per block',value=300,
units='trials (0=no-switch)',
group='Switching parameters')
self.params['currentBlock'] = paramgui.MenuParam('Current block',
['mid_boundary','low_boundary','high_boundary'],
value=0,group='Switching parameters')
switchingParams = self.params.layout_group('Switching parameters')
self.params['psycurveMode'] = paramgui.MenuParam('PsyCurve Mode',
['off','uniform'],
value=0,group='Psychometric parameters')
self.params['psycurveNfreq'] = paramgui.NumericParam('N frequencies',value=8,decimals=0,
group='Psychometric parameters')
psychometricParams = self.params.layout_group('Psychometric parameters')
self.params['automationMode'] = paramgui.MenuParam('Automation Mode',
['off','increase_delay'],
value=0,group='Automation')
automationParams = self.params.layout_group('Automation')
# 5000, 7000, 9800 (until 2014-03-19)
self.params['soundActionMode'] = paramgui.MenuParam('Sound-action mode',
['low_left','high_left'],
value=0,group='Sound parameters')
self.params['highFreq'] = paramgui.NumericParam('High freq',value=16000,
units='Hz',group='Sound parameters')
self.params['midFreq'] = paramgui.NumericParam('Middle freq',value=7000,
units='Hz',group='Sound parameters')
self.params['lowFreq'] = paramgui.NumericParam('Low freq',value=3000,
units='Hz',group='Sound parameters')
self.params['targetFrequency'] = paramgui.NumericParam('Target freq',value=0,decimals=0,
units='Hz',enabled=False,group='Sound parameters')
self.params['targetIntensityMode'] = paramgui.MenuParam('Intensity mode',
['fixed','randMinus20'],
value=1,group='Sound parameters')
# This intensity corresponds to the intensity of each component of the chord
self.params['targetMaxIntensity'] = paramgui.NumericParam('Max intensity',value=50,
units='dB-SPL',group='Sound parameters')
self.params['targetIntensity'] = paramgui.NumericParam('Intensity',value=0.0,units='dB-SPL',
enabled=False,group='Sound parameters')
'''
self.params['targetAmplitudeHigh'] = paramgui.NumericParam('AmplitudeHigh',value=0.0,units='[0-1]',
enabled=False,decimals=4,group='Sound parameters')
self.params['targetAmplitudeMid'] = paramgui.NumericParam('AmplitudeMid',value=0.0,units='[0-1]',
enabled=False,decimals=4,group='Sound parameters')
self.params['targetAmplitudeLow'] = paramgui.NumericParam('AmplitudeLow',value=0.0,units='[0-1]',
enabled=False,decimals=4,group='Sound parameters')
'''
self.params['targetAmplitude'] = paramgui.NumericParam('Target amplitude',value=0.0,units='[0-1]',
enabled=False,decimals=4,group='Sound parameters')
self.params['punishSoundIntensity'] = paramgui.NumericParam('Punish intensity',value=50,
units='dB-SPL',enabled=True,
group='Sound parameters')
self.params['punishSoundAmplitude'] = paramgui.NumericParam('Punish amplitude',value=0.01,
units='[0-1]',enabled=False, decimals=4,
group='Sound parameters')
'''
self.params['highFreq'] = paramgui.NumericParam('High freq',value=500,
units='Hz',group='Sound parameters')
self.params['midFreq'] = paramgui.NumericParam('Middle freq',value=440,
units='Hz',group='Sound parameters')
self.params['lowFreq'] = paramgui.NumericParam('Low freq',value=400,
units='Hz',group='Sound parameters')
#4200, 9200, 20200
'''
soundParams = self.params.layout_group('Sound parameters')
self.params['nValid'] = paramgui.NumericParam('N valid',value=0,
units='',enabled=False,
group='Report')
self.params['nRewarded'] = paramgui.NumericParam('N rewarded',value=0,
units='',enabled=False,
group='Report')
reportParams = self.params.layout_group('Report')
#
#self.params['experimenter'].set_value('santiago')
#self.params['subject'].set_value('test')
# -- Add graphical widgets to main window --
self.centralWidget = QtWidgets.QWidget()
layoutMain = QtWidgets.QVBoxLayout()
layoutTop = QtWidgets.QVBoxLayout()
layoutBottom = QtWidgets.QHBoxLayout()
layoutCol1 = QtWidgets.QVBoxLayout()
layoutCol2 = QtWidgets.QVBoxLayout()
layoutCol3 = QtWidgets.QVBoxLayout()
layoutCol4 = QtWidgets.QVBoxLayout()
layoutMain.addLayout(layoutTop)
#layoutMain.addStretch()
layoutMain.addSpacing(0)
layoutMain.addLayout(layoutBottom)
layoutTop.addWidget(self.mySidesPlot)
layoutTop.addWidget(self.myPerformancePlot)
layoutBottom.addLayout(layoutCol1)
layoutBottom.addLayout(layoutCol2)
layoutBottom.addLayout(layoutCol3)
layoutBottom.addLayout(layoutCol4)
layoutCol1.addWidget(self.saveData)
layoutCol1.addWidget(self.sessionInfo)
layoutCol1.addWidget(self.dispatcher.widget)
layoutCol2.addWidget(self.manualControl)
layoutCol2.addStretch()
layoutCol2.addWidget(waterDelivery)
layoutCol2.addStretch()
layoutCol2.addWidget(choiceParams)
layoutCol2.addStretch()
layoutCol3.addWidget(timingParams)
layoutCol3.addStretch()
layoutCol3.addWidget(switchingParams)
layoutCol3.addStretch()
layoutCol3.addWidget(psychometricParams)
layoutCol3.addStretch()
layoutCol4.addWidget(automationParams)
layoutCol3.addStretch()
layoutCol4.addWidget(soundParams)
layoutCol3.addStretch()
layoutCol4.addWidget(reportParams)
layoutCol4.addStretch()
self.centralWidget.setLayout(layoutMain)
self.setCentralWidget(self.centralWidget)
# -- Add variables for storing results --
maxNtrials = 4000 # Preallocating space for each vector makes things easier
self.results = utils.EnumContainer()
self.results.labels['rewardSide'] = {'left':0,'right':1}
self.results['rewardSide'] = np.random.randint(2,size=maxNtrials)
self.results.labels['choice'] = {'left':0,'right':1,'none':2}
self.results['choice'] = np.empty(maxNtrials,dtype=int)
self.results.labels['outcome'] = {'correct':1,'error':0,'invalid':2,
'free':3,'nochoice':4,'aftererror':5,'aborted':6}
self.results['outcome'] = np.empty(maxNtrials,dtype=int)
# Saving outcome as bool creates an 'enum' vector, so I'm saving as 'int'
self.results['valid'] = np.zeros(maxNtrials,dtype='int8') # redundant but useful
self.results['timeTrialStart'] = np.empty(maxNtrials,dtype=float)
self.results['timeTarget'] = np.empty(maxNtrials,dtype=float)
self.results['timeCenterIn'] = np.empty(maxNtrials,dtype=float)
self.results['timeCenterOut'] = np.empty(maxNtrials,dtype=float)
self.results['timeSideIn'] = np.empty(maxNtrials,dtype=float)
# -- Define first block --
import datetime
if (datetime.datetime.now().day%2):
self.params['currentBlock'].set_string('low_boundary')
else:
self.params['currentBlock'].set_string('high_boundary')
# -- Load parameters from a file --
self.params.from_file(paramfile,paramdictname)
# -- Load speaker calibration --
#self.spkCal = speakercalibration.Calibration(rigsettings.SPEAKER_CALIBRATION)
self.spkCal = speakercalibration.Calibration(rigsettings.SPEAKER_CALIBRATION_CHORD)
#self.spkNoiseCal = speakercalibration.NoiseCalibration(rigsettings.SPEAKER_NOISE_CALIBRATION)
self.spkNoiseCal = speakercalibration.NoiseCalibration(rigsettings.SPEAKER_CALIBRATION_NOISE)
# -- Connect to sound server and define sounds --
print('Conecting to soundserver...')
#print('***** FIXME: HARDCODED TIME DELAY TO WAIT FOR SERIAL PORT! *****') ### DEBUG
#time.sleep(0.2)
self.soundClient = soundclient.SoundClient()
'''
highFreq = self.params['highFreq'].get_value()
lowFreq = self.params['lowFreq'].get_value()
stimDur = self.params['targetDuration'].get_value()
s1 = {'type':'tone', 'frequency':lowFreq, 'duration':stimDur, 'amplitude':0.01}
s2 = {'type':'tone', 'frequency':highFreq, 'duration':stimDur, 'amplitude':0.01}
self.soundClient.set_sound(1,s1)
self.soundClient.set_sound(2,s2)
'''
'''
# This code was moved to the method prepare_punish_sound()
punishSoundAmplitude = self.params['punishSoundAmplitude'].get_value()
sNoise = {'type':'noise', 'duration':0.5, 'amplitude':punishSoundAmplitude}
self.punishSoundID = 127
self.soundClient.set_sound(self.punishSoundID,sNoise)
'''
self.targetSoundID = 1
self.punishSoundID = 127
self.soundClient.start()
# -- Prepare first trial --
#self.prepare_next_trial(0)
def prepare_punish_sound(self):
punishSoundIntensity = self.params['punishSoundIntensity'].get_value()
punishSoundAmplitude = self.spkNoiseCal.find_amplitude(punishSoundIntensity).mean()
self.params['punishSoundAmplitude'].set_value(punishSoundAmplitude)
sNoise = {'type':'noise', 'duration':0.5, 'amplitude':punishSoundAmplitude}
self.soundClient.set_sound(self.punishSoundID,sNoise)
def prepare_target_sound(self,targetFrequency):
if self.params['targetIntensityMode'].get_string() == 'randMinus20':
possibleIntensities = self.params['targetMaxIntensity'].get_value()+\
np.array([-20,-15,-10,-5,0])
targetIntensity = possibleIntensities[np.random.randint(len(possibleIntensities))]
else:
targetIntensity = self.params['targetMaxIntensity'].get_value()
self.params['targetIntensity'].set_value(targetIntensity)
# FIXME: currently I am averaging calibration from both speakers (not good)
targetAmp = self.spkCal.find_amplitude(targetFrequency,targetIntensity).mean()
self.params['targetAmplitude'].set_value(targetAmp)
stimDur = self.params['targetDuration'].get_value()
s1 = {'type':'chord', 'frequency':targetFrequency, 'duration':stimDur,
'amplitude':targetAmp, 'ntones':12, 'factor':1.2}
self.soundClient.set_sound(self.targetSoundID,s1)
'''
#amplitudeFactor = [0.25,0.5,1]
#possibleAmplitudes = self.params['targetMaxAmplitude'].get_value()*np.array(amplitudeFactor)
#targetAmplitude = possibleAmplitudes[np.random.randint(len(possibleAmplitudes))]
#targetAmplitude = 0.01
#self.params['targetAmplitude'].set_value(targetAmplitude)
highFreq = self.params['highFreq'].get_value()
midFreq = self.params['midFreq'].get_value()
lowFreq = self.params['lowFreq'].get_value()
stimDur = self.params['targetDuration'].get_value()
spkCal = speakercalibration.Calibration(rigsettings.SPEAKER_CALIBRATION)
ampLow = spkCal.find_amplitude(lowFreq,targetIntensity).mean()
ampMid = spkCal.find_amplitude(midFreq,targetIntensity).mean()
ampHigh = spkCal.find_amplitude(highFreq,targetIntensity).mean()
self.params['targetAmplitudeLow'].set_value(ampLow)
self.params['targetAmplitudeMid'].set_value(ampMid)
self.params['targetAmplitudeHigh'].set_value(ampHigh)
#s1 = {'type':'tone', 'frequency':lowFreq, 'duration':stimDur, 'amplitude':ampLow}
#s2 = {'type':'tone', 'frequency':highFreq, 'duration':stimDur, 'amplitude':ampHigh}
s1 = {'type':'chord', 'frequency':lowFreq, 'duration':stimDur,
'amplitude':ampLow, 'ntones':12, 'factor':1.2}
#s2 = {'type':'chord', 'frequency':highFreq, 'duration':stimDur,
# 'amplitude':ampHigh, 'ntones':12, 'factor':1.2}
self.soundClient.set_sound(1,s1)
#self.soundClient.set_sound(2,s2)
'''
def prepare_next_trial(self, nextTrial):
import time
TicTime = time.time()
# -- Calculate results from last trial (update outcome, choice, etc) --
if nextTrial>0:
self.params.update_history(nextTrial-1)
self.calculate_results(nextTrial-1)
# -- Apply anti-bias --
if self.params['antibiasMode'].get_string()=='repeat_mistake':
if self.results['outcome'][nextTrial-1]==self.results.labels['outcome']['error']:
self.results['rewardSide'][nextTrial] = self.results['rewardSide'][nextTrial-1]
# -- Set current block if switching --
trialsPerBlock = self.params['trialsPerBlock'].get_value()
nValid = self.params['nValid'].get_value()
###print '{0} {1} {2}'.format(nValid,trialsPerBlock,np.mod(nValid,trialsPerBlock)) ### DEBUG
if (nValid>0) and not (np.mod(nValid,trialsPerBlock)):
if self.results['valid'][nextTrial-1]:
if self.params['currentBlock'].get_string()=='low_boundary':
newBlock = 'high_boundary'
elif self.params['currentBlock'].get_string()=='high_boundary':
newBlock = 'low_boundary'
else:
newBlock = 'mid_boundary' # No switch
self.params['currentBlock'].set_string(newBlock)
#import pdb; pdb.set_trace() ### DEBUG
# === Prepare next trial ===
self.execute_automation(nextTrial)
nextCorrectChoice = self.results['rewardSide'][nextTrial]
# -- Prepare sound --
highFreq = self.params['highFreq'].get_value()
midFreq = self.params['midFreq'].get_value()
lowFreq = self.params['lowFreq'].get_value()
currentBlock = self.params['currentBlock'].get_string()
psycurveMode = self.params['psycurveMode'].get_string()
soundActionMode = self.params['soundActionMode'].get_string()
if psycurveMode=='off':
if currentBlock=='mid_boundary':
freqsLH = [lowFreq,highFreq]
elif currentBlock=='low_boundary':
freqsLH = [lowFreq,midFreq]
elif currentBlock=='high_boundary':
freqsLH = [midFreq,highFreq]
if soundActionMode=='low_left':
if nextCorrectChoice==self.results.labels['rewardSide']['left']:
targetFrequency = freqsLH[0]
elif nextCorrectChoice==self.results.labels['rewardSide']['right']:
targetFrequency = freqsLH[1]
elif soundActionMode=='high_left':
if nextCorrectChoice==self.results.labels['rewardSide']['left']:
targetFrequency = freqsLH[1]
elif nextCorrectChoice==self.results.labels['rewardSide']['right']:
targetFrequency = freqsLH[0]
elif psycurveMode=='uniform':
if currentBlock=='mid_boundary':
nFreqs = self.params['psycurveNfreq'].get_value()
freqsAll = np.logspace(np.log10(lowFreq),np.log10(highFreq),nFreqs)
freqBoundary = np.sqrt(lowFreq*highFreq)
# -- NOTE: current implementation does not present points at the psych boundary --
if soundActionMode=='low_left':
leftFreqInds = np.flatnonzero(freqsAll<freqBoundary)
rightFreqInds = np.flatnonzero(freqsAll>freqBoundary)
elif soundActionMode=='high_left':
leftFreqInds = np.flatnonzero(freqsAll>freqBoundary)
rightFreqInds = np.flatnonzero(freqsAll<freqBoundary)
else:
print('WARNING! PsyCurve for this block type has not been implemented')
if nextCorrectChoice==self.results.labels['rewardSide']['left']:
randindex = np.random.randint(len(freqsAll[leftFreqInds]))
targetFrequency = freqsAll[leftFreqInds][randindex]
#targetFrequency = np.random.choice(freqsAll[leftFreqInds])
elif nextCorrectChoice==self.results.labels['rewardSide']['right']:
randindex = np.random.randint(len(freqsAll[rightFreqInds]))
targetFrequency = freqsAll[rightFreqInds][randindex]
#targetFrequency = np.random.choice(freqsAll[rightFreqInds])
pass
self.params['targetFrequency'].set_value(targetFrequency)
self.prepare_target_sound(targetFrequency)
self.prepare_punish_sound()
# -- Prepare state matrix --
self.set_state_matrix(nextCorrectChoice)
self.dispatcher.ready_to_start_trial()
###print 'Elapsed Time (preparing next trial): ' + str(time.time()-TicTime) ### DEBUG
# -- Update sides plot --
self.mySidesPlot.update(self.results['rewardSide'],self.results['outcome'],nextTrial)
# -- Update performance plot --
self.myPerformancePlot.update(self.results['rewardSide'],self.results.labels['rewardSide'],
self.results['outcome'],self.results.labels['outcome'],
nextTrial)
def set_state_matrix(self,nextCorrectChoice):
self.sm.reset_transitions()
soundID = 1 # The appropriate sound has already been prepared and sent to server with ID=1
targetDuration = self.params['targetDuration'].get_value()
if 'outBit1' in rigsettings.OUTPUTS:
trialStartOutput = ['outBit1'] # Sync signal for trial-start.
else:
trialStartOutput = []
if 'outBit0' in rigsettings.OUTPUTS:
stimOutput = ['outBit0'] # Sync signal for stimulus
else:
stimOutput = []
if nextCorrectChoice==self.results.labels['rewardSide']['left']:
rewardDuration = self.params['timeWaterValveL'].get_value()
ledOutput = 'leftLED'
#fromChoiceL = 'reward'
#fromChoiceR = 'punish'
rewardOutput = 'leftWater'
correctSidePort = 'Lin'
#soundID = 1
elif nextCorrectChoice==self.results.labels['rewardSide']['right']:
rewardDuration = self.params['timeWaterValveR'].get_value()
ledOutput = 'rightLED'
#fromChoiceL = 'punish'
#fromChoiceR = 'reward'
rewardOutput = 'rightWater'
correctSidePort = 'Rin'
#soundID = 2
else:
raise ValueError('Value of nextCorrectChoice is not appropriate')
randNum = (2*np.random.random(1)[0]-1) # In range [-1,1)
delayToTarget = self.params['delayToTargetMean'].get_value() + \
self.params['delayToTargetHalfRange'].get_value()*randNum
self.params['delayToTarget'].set_value(delayToTarget)
rewardAvailability = self.params['rewardAvailability'].get_value()
punishTimeError = self.params['punishTimeError'].get_value()
punishTimeEarly = self.params['punishTimeEarly'].get_value()
allowEarlyWithdrawal = self.params['allowEarlyWithdrawal'].get_string()
# -- Set state matrix --
outcomeMode = self.params['outcomeMode'].get_string()
if outcomeMode=='simulated':
stimOutput.append(ledOutput)
self.sm.add_state(name='startTrial', statetimer=0,
transitions={'Tup':'waitForCenterPoke'},
outputsOn=trialStartOutput)
self.sm.add_state(name='waitForCenterPoke', statetimer=1,
transitions={'Tup':'playStimulus'})
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'},
outputsOn=stimOutput,serialOut=soundID,
outputsOff=trialStartOutput)
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput],
outputsOff=stimOutput)
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput])
elif outcomeMode=='sides_direct':
self.sm.add_state(name='startTrial', statetimer=0,
transitions={'Tup':'waitForCenterPoke'},
outputsOn=trialStartOutput)
self.sm.add_state(name='waitForCenterPoke', statetimer=LONGTIME,
transitions={'Cin':'playStimulus',correctSidePort:'playStimulus'})
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'},
outputsOn=stimOutput,serialOut=soundID,
outputsOff=trialStartOutput)
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput],
outputsOff=stimOutput)
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput])
elif outcomeMode=='direct':
self.sm.add_state(name='startTrial', statetimer=0,
transitions={'Tup':'waitForCenterPoke'},
outputsOn=trialStartOutput)
self.sm.add_state(name='waitForCenterPoke', statetimer=LONGTIME,
transitions={'Cin':'playStimulus'})
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'},
outputsOn=stimOutput,serialOut=soundID,
outputsOff=trialStartOutput)
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput],
outputsOff=stimOutput)
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput])
elif outcomeMode=='on_next_correct':
self.sm.add_state(name='startTrial', statetimer=0,
transitions={'Tup':'waitForCenterPoke'},
outputsOn=trialStartOutput)
self.sm.add_state(name='waitForCenterPoke', statetimer=LONGTIME,
transitions={'Cin':'delayPeriod'})
self.sm.add_state(name='delayPeriod', statetimer=delayToTarget,
transitions={'Tup':'playStimulus','Cout':'waitForCenterPoke'})
if allowEarlyWithdrawal=='on':
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'waitForSidePoke','Cout':'waitForSidePoke'},
outputsOn=stimOutput, serialOut=soundID,
outputsOff=trialStartOutput)
else:
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'waitForSidePoke','Cout':'earlyWithdrawal'},
outputsOn=stimOutput, serialOut=soundID,
outputsOff=trialStartOutput)
self.sm.add_state(name='waitForSidePoke', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'},
outputsOff=stimOutput)
self.sm.add_state(name='keepWaitForSide', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'},
outputsOff=stimOutput)
if correctSidePort=='Lin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'reward'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'keepWaitForSide'})
elif correctSidePort=='Rin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'keepWaitForSide'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'reward'})
if allowEarlyWithdrawal=='on':
self.sm.add_state(name='earlyWithdrawal', statetimer=punishTimeEarly,
transitions={'Tup':'ready_next_trial'},
outputsOff=stimOutput)
else:
self.sm.add_state(name='earlyWithdrawal', statetimer=punishTimeEarly,
transitions={'Tup':'ready_next_trial'},
outputsOff=stimOutput,serialOut=self.punishSoundID)
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput])
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput])
self.sm.add_state(name='punishError', statetimer=punishTimeError,
transitions={'Tup':'ready_next_trial'})
self.sm.add_state(name='noChoice', statetimer=0,
transitions={'Tup':'ready_next_trial'})
elif outcomeMode=='only_if_correct':
self.sm.add_state(name='startTrial', statetimer=0,
transitions={'Tup':'waitForCenterPoke'},
outputsOn=trialStartOutput)
self.sm.add_state(name='waitForCenterPoke', statetimer=LONGTIME,
transitions={'Cin':'delayPeriod'})
self.sm.add_state(name='delayPeriod', statetimer=delayToTarget,
transitions={'Tup':'playStimulus','Cout':'waitForCenterPoke'})
# Note that 'delayPeriod' may happen several times in a trial, so
# trialStartOutput off here would only meaningful for the first time in the trial.
if allowEarlyWithdrawal=='on':
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'waitForSidePoke','Cout':'waitForSidePoke'},
outputsOn=stimOutput, serialOut=soundID,
outputsOff=trialStartOutput)
else:
self.sm.add_state(name='playStimulus', statetimer=targetDuration,
transitions={'Tup':'waitForSidePoke','Cout':'earlyWithdrawal'},
outputsOn=stimOutput, serialOut=soundID,
outputsOff=trialStartOutput)
self.sm.add_state(name='waitForSidePoke', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'},
outputsOff=stimOutput)
if correctSidePort=='Lin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'reward'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'punishError'})
elif correctSidePort=='Rin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'punishError'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'reward'})
self.sm.add_state(name='earlyWithdrawal', statetimer=punishTimeEarly,
transitions={'Tup':'ready_next_trial'},
outputsOff=stimOutput,serialOut=self.punishSoundID)
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput])
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput]+stimOutput)
self.sm.add_state(name='punishError', statetimer=punishTimeError,
transitions={'Tup':'ready_next_trial'})
self.sm.add_state(name='noChoice', statetimer=0,
transitions={'Tup':'ready_next_trial'})
else:
raise TypeError('outcomeMode={0} has not been implemented'.format(outcomeMode))
###print self.sm ### DEBUG
self.dispatcher.set_state_matrix(self.sm)
def calculate_results(self,trialIndex):
# -- Find outcomeMode for this trial --
outcomeModeID = self.params.history['outcomeMode'][trialIndex]
outcomeModeString = self.params['outcomeMode'].get_items()[outcomeModeID]
eventsThisTrial = self.dispatcher.events_one_trial(trialIndex)
#print eventsThisTrial
statesThisTrial = eventsThisTrial[:,2]
# -- Find beginning of trial --
startTrialStateID = self.sm.statesNameToIndex['startTrial']
# FIXME: Next line seems inefficient. Is there a better way?
startTrialInd = np.flatnonzero(statesThisTrial==startTrialStateID)[0]
self.results['timeTrialStart'][trialIndex] = eventsThisTrial[startTrialInd,0]
#print 'TrialStart : {0}'.format(self.results['timeTrialStart'][trialIndex]) ### DEBUG
# ===== Calculate times of events =====
# -- Check if it's an aborted trial --
lastEvent = eventsThisTrial[-1,:]
if lastEvent[1]==-1 and lastEvent[2]==0:
self.results['timeTarget'][trialIndex] = np.nan
self.results['timeCenterIn'][trialIndex] = np.nan
self.results['timeCenterOut'][trialIndex] = np.nan
self.results['timeSideIn'][trialIndex] = np.nan
# -- Otherwise evaluate times of important events --
else:
# -- Store time of stimulus --
targetStateID = self.sm.statesNameToIndex['playStimulus']
targetEventInd = np.flatnonzero(statesThisTrial==targetStateID)[0]
self.results['timeTarget'][trialIndex] = eventsThisTrial[targetEventInd,0]
# -- Find center poke-in time --
if outcomeModeString in ['on_next_correct','only_if_correct']:
seqCin = [self.sm.statesNameToIndex['waitForCenterPoke'],
self.sm.statesNameToIndex['delayPeriod'],
self.sm.statesNameToIndex['playStimulus']]
elif outcomeModeString in ['simulated','sides_direct','direct']:
seqCin = [self.sm.statesNameToIndex['waitForCenterPoke'],
self.sm.statesNameToIndex['playStimulus']]
else:
print('CenterIn time cannot be calculated for this Outcome Mode.')
seqPos = np.flatnonzero(utils.find_state_sequence(statesThisTrial,seqCin))
timeValue = eventsThisTrial[seqPos[0]+1,0] if len(seqPos) else np.nan
self.results['timeCenterIn'][trialIndex] = timeValue
# -- Find center poke-out time --
if len(seqPos):
cInInd = seqPos[0]+1
cOutInd = np.flatnonzero(eventsThisTrial[cInInd:,1]==self.sm.eventsDict['Cout'])
timeValue = eventsThisTrial[cOutInd[0]+cInInd,0] if len(cOutInd) else np.nan
else:
timeValue = np.nan
self.results['timeCenterOut'][trialIndex] = timeValue
# -- Find side poke time --
if outcomeModeString in ['on_next_correct','only_if_correct']:
leftInInd = utils.find_transition(statesThisTrial,
self.sm.statesNameToIndex['waitForSidePoke'],
self.sm.statesNameToIndex['choiceLeft'])
rightInInd = utils.find_transition(statesThisTrial,
self.sm.statesNameToIndex['waitForSidePoke'],
self.sm.statesNameToIndex['choiceRight'])
if len(leftInInd):
timeValue = eventsThisTrial[leftInInd[0],0]
elif len(rightInInd):
timeValue = eventsThisTrial[rightInInd[0],0]
else:
timeValue = np.nan
elif outcomeModeString in ['simulated','sides_direct','direct']:
timeValue = np.nan
self.results['timeSideIn'][trialIndex] = timeValue
# ===== Calculate choice and outcome =====
# -- Check if it's an aborted trial --
lastEvent = eventsThisTrial[-1,:]
if lastEvent[1]==-1 and lastEvent[2]==0:
self.results['outcome'][trialIndex] = self.results.labels['outcome']['aborted']
self.results['choice'][trialIndex] = self.results.labels['choice']['none']
# -- Otherwise evaluate 'choice' and 'outcome' --
else:
if outcomeModeString in ['simulated','sides_direct','direct']:
self.results['outcome'][trialIndex] = self.results.labels['outcome']['free']
self.results['choice'][trialIndex] = self.results.labels['choice']['none']
self.params['nValid'].add(1)
self.params['nRewarded'].add(1)
self.results['valid'][trialIndex] = 1
if outcomeModeString=='on_next_correct' or outcomeModeString=='only_if_correct':
if self.sm.statesNameToIndex['choiceLeft'] in eventsThisTrial[:,2]:
self.results['choice'][trialIndex] = self.results.labels['choice']['left']
elif self.sm.statesNameToIndex['choiceRight'] in eventsThisTrial[:,2]:
self.results['choice'][trialIndex] = self.results.labels['choice']['right']
else:
self.results['choice'][trialIndex] = self.results.labels['choice']['none']
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['nochoice']
if self.sm.statesNameToIndex['reward'] in eventsThisTrial[:,2]:
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['correct']
self.params['nRewarded'].add(1)
if outcomeModeString=='on_next_correct' and \
self.sm.statesNameToIndex['keepWaitForSide'] in eventsThisTrial[:,2]:
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['aftererror']
else:
if self.sm.statesNameToIndex['earlyWithdrawal'] in eventsThisTrial[:,2]:
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['invalid']
elif self.sm.statesNameToIndex['punishError'] in eventsThisTrial[:,2]:
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['error']
# -- Check if it was a valid trial --
if self.sm.statesNameToIndex['waitForSidePoke'] in eventsThisTrial[:,2]:
self.params['nValid'].add(1)
self.results['valid'][trialIndex] = 1
def execute_automation(self,nextTrial):
automationMode = self.params['automationMode'].get_string()
nValid = self.params['nValid'].get_value()
if automationMode=='increase_delay':
if nValid>0 and self.results['valid'][nextTrial-1] and not nValid%10:
self.params['delayToTargetMean'].add(0.010)
def closeEvent(self, event):
'''
Executed when closing the main window.
This method is inherited from QtWidgets.QMainWindow, which explains
its camelCase naming.
'''
self.soundClient.shutdown()
self.dispatcher.die()
event.accept()
if __name__ == '__main__':
(app,paradigm) = paramgui.create_app(Paradigm)