-
Notifications
You must be signed in to change notification settings - Fork 5
/
bandwidth_masking.py
813 lines (742 loc) · 47.2 KB
/
bandwidth_masking.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
'''
Create a comodulation masking release 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 numpy as np
from taskontrol.settings import rigsettings
from taskontrol.core import paramgui
from PySide import QtGui
from taskontrol.core import arraycontainer
from taskontrol.core import utils
from taskontrol.core import statematrix
from taskontrol.plugins import templates
reload(templates)
from taskontrol.plugins import performancedynamicsplot
from taskontrol.plugins import soundclient
reload(soundclient)
from taskontrol.plugins import speakercalibration
import time
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,enabled=False,
units='s',group='Water delivery')
self.params['baseWaterValveL'] = paramgui.NumericParam('Base time left',value=0.03,
units='s',group='Water delivery')
self.params['factorWaterValveL'] = paramgui.NumericParam('Factor left',value=1,
units='s',group='Water delivery')
self.params['timeWaterValveR'] = paramgui.NumericParam('Time valve right',value=0.03,enabled=False,
units='s',group='Water delivery')
self.params['baseWaterValveR'] = paramgui.NumericParam('Base time right',value=0.03,
units='s',group='Water delivery')
self.params['factorWaterValveR'] = paramgui.NumericParam('Factor right',value=1,
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['soundMode'] = paramgui.MenuParam('Sound presentation mode',
['full_duration', 'off_on_withdrawal'],
value=0,group='Choice parameters')
self.params['toneSide'] = paramgui.MenuParam('Tone side',
['left', 'right'],
value=1,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.04,
units='s',group='Timing parameters')
self.params['delayToTargetHalfRange'] = paramgui.NumericParam('+/-',value=0.0,
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.5,
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')
timingParams = self.params.layout_group('Timing parameters')
self.params['automationMode'] = paramgui.MenuParam('Automation Mode',
['off','increase_delay','same_left_right','same_right_left','left_right_left'],
value=0,group='Automation')
automationParams = self.params.layout_group('Automation')
self.params['threshMode'] = paramgui.MenuParam('Threshold Mode',
['max_only','linear','exponential'],
value=0,group='Threshold detection parameters')
# -- tone intensity refers to difference between tone and masking noise --
self.params['minSNR'] = paramgui.NumericParam('Minimum signal to noise',value=2, decimals=1,
units='dB',group='Threshold detection parameters')
self.params['maxSNR'] = paramgui.NumericParam('Maximum signal to noise',value=20,decimals=0,
units='dB',group='Threshold detection parameters')
self.params['numSNRs'] = paramgui.NumericParam('Number of SNRs', value=2, decimals=0, units='dB', group='Threshold detection parameters')
threshParams = self.params.layout_group('Threshold detection parameters')
self.params['bandMode'] = paramgui.MenuParam('Bandwidth Mode', ['white_only', 'max_only', 'uniform'], value=0, group='Bandwidth parameters')
self.params['minBand'] = paramgui.NumericParam('Minimum bandwidth',value=0.25,decimals=2,
units='octaves',group='Bandwidth parameters')
self.params['maxBand'] = paramgui.NumericParam('Maximum bandwidth',value=4.0,decimals=2,
units='octaves',group='Bandwidth parameters')
self.params['numBands'] = paramgui.NumericParam('Number of bandwidths',
value=5, decimals=0, group='Bandwidth parameters')
self.params['includeWhite'] = paramgui.MenuParam('Include white noise?', ['yes', 'no'], value=0, group='Bandwidth parameters')
bandParams = self.params.layout_group('Bandwidth parameters')
self.params['noiseMode'] = paramgui.MenuParam('Masker amplitude mode', ['max_only', 'uniform'], value=1, group='Masker amplitude parameters')
# -- power refers to average power of noise stimulus
self.params['minNoiseAmp'] = paramgui.NumericParam('Minimum noise power',value=30,decimals=0,
units='dB',group='Masker amplitude parameters')
self.params['maxNoiseAmp'] = paramgui.NumericParam('Maximum noise power',value=40,decimals=0,
units='dB',group='Masker amplitude parameters')
self.params['numAmps'] = paramgui.NumericParam('Number of noise amplitudes',
value=2, decimals=0, group='Masker amplitude parameters')
noiseParams = self.params.layout_group('Masker amplitude parameters')
self.params['toneFreq'] = paramgui.NumericParam('Tone frequency',value=8000,
units='Hz',group='Sound parameters')
self.params['modRate'] = paramgui.NumericParam('Modulation Rate',value=8,
units='Hz',group='Sound parameters')
soundParams = self.params.layout_group('Sound parameters')
self.params['currentBand'] = paramgui.NumericParam('Trial bandwidth',value=0.0,decimals=2,
units='octaves', enabled=False, group='Current Trial')
self.params['currentNoiseAmp'] = paramgui.NumericParam('Trial noise power',value=0.0,decimals=0,
units='dB', enabled=False, group='Current Trial')
self.params['currentSNR'] = paramgui.NumericParam('Trial SNR',value=0.0,decimals=1,
units='dB', enabled=False, group='Current Trial')
self.params['laserSide'] = paramgui.MenuParam('Laser side', ['none', 'left', 'right', 'bilateral'],
value=0, enabled=False, group='Current Trial')
trialParams = self.params.layout_group('Current Trial')
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')
# Photostim params
self.params['laserMode'] = paramgui.MenuParam('Laser Mode',
['none','random'],
value=0,group='Laser Stimulation')
self.params['laserOnset'] = paramgui.NumericParam('Laser onset (from sound)',value=0.0,
units='s',group='Laser Stimulation')
self.params['laserOffset'] = paramgui.NumericParam('Laser offset (from sound)',value=0.1,
units='s',group='Laser Stimulation')
# -- Percent trials with laser. Remaining trials will be no laser.
self.params['fractionTrialsLaser'] = paramgui.NumericParam('Fraction trials with laser',value=0.25,
units='',group='Laser Stimulation')
self.params['stimMode'] = paramgui.MenuParam('Stimulation Mode',
['unilateral_left','unilateral_right', 'bilateral', 'mixed_unilateral', 'mixed_all'],
value=2,group='Laser Stimulation')
photostimParams = self.params.layout_group('Laser Stimulation')
#
self.params['experimenter'].set_value('santiago')
self.params['subject'].set_value('test')
# -- Add graphical widgets to main window --
self.centralWidget = QtGui.QWidget()
layoutMain = QtGui.QVBoxLayout()
layoutTop = QtGui.QVBoxLayout()
layoutBottom = QtGui.QHBoxLayout()
layoutCol1 = QtGui.QVBoxLayout()
layoutCol2 = QtGui.QVBoxLayout()
layoutCol3 = QtGui.QVBoxLayout()
layoutCol4 = QtGui.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.dispatcherView)
layoutCol2.addWidget(self.manualControl)
layoutCol2.addStretch()
layoutCol2.addWidget(waterDelivery)
layoutCol2.addStretch()
layoutCol2.addWidget(choiceParams)
layoutCol2.addStretch()
layoutCol2.addWidget(automationParams)
layoutCol2.addStretch()
layoutCol3.addWidget(timingParams)
layoutCol3.addStretch()
layoutCol3.addWidget(photostimParams)
layoutCol3.addStretch()
layoutCol3.addWidget(trialParams)
layoutCol3.addStretch()
layoutCol4.addWidget(soundParams)
layoutCol4.addStretch()
layoutCol4.addWidget(threshParams)
layoutCol4.addStretch()
layoutCol4.addWidget(bandParams)
layoutCol4.addStretch()
layoutCol4.addWidget(noiseParams)
layoutCol4.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 = arraycontainer.Container()
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 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)
# -- Load parameters from a file --
self.params.from_file(paramfile,paramdictname)
# -- 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()
self.soundClient.start()
# -- Specify state matrix with extratimer --
self.sm = statematrix.StateMatrix(inputs=rigsettings.INPUTS,
outputs=rigsettings.OUTPUTS,
readystate='ready_next_trial')
#extratimers=['laserTimer'])
# -- Prepare first trial --
#self.prepare_next_trial(0)
def prepare_target_sound(self, band, noiseInt, toneInt):
spkCal = speakercalibration.Calibration(rigsettings.SPEAKER_CALIBRATION_SINE)
# FIXME: currently I am averaging calibration from both speakers (not good)
stimDur = self.params['targetDuration'].get_value()
modRate = self.params['modRate'].get_value()
noiseCal = speakercalibration.NoiseCalibration(rigsettings.SPEAKER_CALIBRATION_NOISE)
toneFreq = self.params['toneFreq'].get_value()
noiseAmp = noiseCal.find_amplitude(noiseInt, type='narrowband')
if np.isinf(band):
s1 = {'type':'AM', 'modFrequency': modRate, 'duration':stimDur, 'amplitude': noiseAmp}
else:
s1 = {'type':'band_AM', 'modRate': modRate, 'frequency': toneFreq, 'octaves': band, 'duration': stimDur, 'amplitude': noiseAmp}
toneAmp = spkCal.find_amplitude(toneFreq, noiseInt+toneInt)
s2 = {'type':'tone', 'frequency': toneFreq, 'duration':stimDur, 'amplitude': toneAmp}
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()
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 --
nValid = self.params['nValid'].get_value()
###print '{0} {1} {2}'.format(nValid,trialsPerBlock,np.mod(nValid,trialsPerBlock)) ### DEBUG
#import pdb; pdb.set_trace() ### DEBUG
# === Prepare next trial ===
self.execute_automation()
nextCorrectChoice = self.results['rewardSide'][nextTrial]
# -- Define reward for each side --
factorL = 1
factorR = 1
self.params['timeWaterValveL'].set_value(factorL*self.params['baseWaterValveL'].get_value())
self.params['timeWaterValveR'].set_value(factorR*self.params['baseWaterValveR'].get_value())
# -- Prepare sound --
threshMode = self.params['threshMode'].get_string()
toneSide = self.params['toneSide'].get_string()
if threshMode=='max_only':
if nextCorrectChoice==self.results.labels['rewardSide'][toneSide]:
currentToneInt = self.params['maxSNR'].get_value()
else:
currentToneInt = -np.inf
# if nextCorrectChoice==self.results.labels['rewardSide']['left']:
# currentToneInt = -np.inf
# elif nextCorrectChoice==self.results.labels['rewardSide']['right']:
# currentToneInt = self.params['maxSNR'].get_value()
elif threshMode=='linear':
if nextCorrectChoice==self.results.labels['rewardSide'][toneSide]:
numSNRs = self.params['numSNRs'].get_value()
minSNR = self.params['minSNR'].get_value()
maxSNR = self.params['maxSNR'].get_value()
allSNRs = np.linspace(minSNR, maxSNR, numSNRs)
currentToneInt = np.random.choice(allSNRs)
else:
currentToneInt = -np.inf
if self.params['bandMode'].get_string()=='white_only':
currentBand = np.inf
elif self.params['bandMode'].get_string()=='max_only':
currentBand = self.params['maxBand'].get_value()
else:
numBands = self.params['numBands'].get_value()
minBand = self.params['minBand'].get_value()
maxBand = self.params['maxBand'].get_value()
allBands = np.logspace(np.log2(minBand), np.log2(maxBand), numBands, base=2.0)
if self.params['includeWhite'].get_string()=='yes':
allBands = np.append(allBands, np.inf)
currentBand = float(np.random.choice(allBands))
if self.params['noiseMode'].get_string()=='max_only':
currentNoiseAmp = self.params['maxNoiseAmp'].get_value()
else:
allNoiseAmps = np.linspace(self.params['minNoiseAmp'].get_value(), self.params['maxNoiseAmp'].get_value(), self.params['numAmps'].get_value())
currentNoiseAmp = np.random.choice(allNoiseAmps)
self.params['currentBand'].set_value(currentBand)
self.params['currentNoiseAmp'].set_value(currentNoiseAmp)
self.params['currentSNR'].set_value(currentToneInt)
self.prepare_target_sound(currentBand, currentNoiseAmp, currentToneInt)
# -- Prepare state matrix --
self.set_state_matrix(nextCorrectChoice)
self.dispatcherModel.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()
noiseID = 1 # The appropriate sound has already been prepared and sent to server with ID=1
toneID = 2
targetDuration = self.params['targetDuration'].get_value()
if rigsettings.OUTPUTS.has_key('outBit1'):
trialStartOutput = ['outBit1'] # Sync signal for trial-start.
else:
trialStartOutput = []
if rigsettings.OUTPUTS.has_key('outBit0'):
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()
# -- Define the type of trial to present --
laserMode = self.params['laserMode'].get_string()
if laserMode=='none':
laserOutput = []
self.params['laserSide'].set_string('none')
else:
fractionTrialsLaser = self.params['fractionTrialsLaser'].get_value()
#print fractionTrialsEachLaserOnset
fractionNoLaser = 1-fractionTrialsLaser
fractionTrials = np.array([fractionNoLaser,fractionTrialsLaser])
trialTypeInd = np.random.choice(2, size=1, p=fractionTrials)[0]
stimMode = self.params['stimMode'].get_string()
if trialTypeInd>0:
if stimMode == 'unilateral_left':
laserOutput = ['stim1']
self.params['laserSide'].set_string('left')
elif stimMode == 'unilateral_right':
laserOutput = ['stim2']
self.params['laserSide'].set_string('right')
elif stimMode == 'bilateral':
laserOutput = ['stim1', 'stim2']
self.params['laserSide'].set_string('bilateral')
elif stimMode == 'mixed_unilateral':
possOutputs = [['stim1'], ['stim2']]
possSide = ['left', 'right']
sideThisTrial = np.random.choice(2)
laserOutput = possOutputs[sideThisTrial]
self.params['laserSide'].set_string(possSide[sideThisTrial])
elif stimMode == 'mixed_all':
possOutputs = [['stim1'], ['stim2'], ['stim1', 'stim2']]
possSide = ['left', 'right', 'bilateral']
sideThisTrial = np.random.choice(3)
laserOutput = possOutputs[sideThisTrial]
self.params['laserSide'].set_string(possSide[sideThisTrial])
else:
laserOutput = []
self.params['laserSide'].set_string('none')
# -- Set state matrix --
soundMode = self.params['soundMode'].get_string()
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':'playNoiseStimulus'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput, serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'}, serialOut=toneID)
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':'playNoiseStimulus',correctSidePort:'playNoiseStimulus'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput,serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'}, serialOut=toneID)
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':'playNoiseStimulus'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput,serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Tup':'reward'}, serialOut=toneID)
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])
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':'playNoiseStimulus','Cout':'waitForCenterPoke'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput,serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Cout':'stopStimulus', 'Tup':'stopStimulus'},serialOut=toneID)
if soundMode == 'full_duration':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePoke'},
outputsOff=stimOutput)
elif soundMode == 'off_on_withdrawal':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePoke'},
outputsOff=stimOutput, serialOut=soundclient.STOP_ALL_SOUNDS)
self.sm.add_state(name='waitForSidePoke', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'})
self.sm.add_state(name='keepWaitForSide', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'})
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'})
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='punish', 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'}, outputsOff=laserOutput)
if laserMode == 'none':
self.sm.add_state(name='delayPeriod', statetimer=delayToTarget,
transitions={'Tup':'playNoiseStimulus','Cout':'waitForCenterPoke'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput, serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Cout':'stopStimulus', 'Tup':'stopStimulus'}, serialOut=toneID)
if soundMode == 'full_duration':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePoke'},
outputsOff=stimOutput)
elif soundMode == 'off_on_withdrawal':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePoke'},
outputsOff=stimOutput, serialOut=soundclient.STOP_ALL_SOUNDS)
self.sm.add_state(name='waitForSidePoke', statetimer=rewardAvailability,
transitions={'Lin':'choiceLeft','Rin':'choiceRight',
'Tup':'noChoice'})
else:
laserOnset = self.params['laserOnset'].get_value()
laserOffset = self.params['laserOffset'].get_value()
if laserOnset > 0:
self.sm.add_state(name='delayPeriod', statetimer=delayToTarget,
transitions={'Tup':'playNoiseStimulus','Cout':'waitForCenterPoke'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput, serialOut=noiseID,
outputsOff=trialStartOutput)
#restart trial if mouse withdraws before laser comes on
self.sm.add_state(name='playToneStimulusBeforeLaser', statetimer=laserOnset,
transitions={'Cout':'waitForCenterPoke', 'Tup':'laserOn'})
self.sm.add_state(name='laserOn', statetimer=0, transitions={'Tup':'playToneStimulus'},
outputsOn=laserOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration-laserOnset,
transitions={'Cout':'stopStimulus', 'Tup':'stopStimulus'})
elif laserOnset <= 0:
self.sm.add_state(name='delayPeriod', statetimer=delayToTarget+laserOnset,
transitions={'Tup':'laserOn','Cout':'waitForCenterPoke'})
self.sm.add_state(name='laserOn', statetimer=0, transitions={'Tup':'delayPeriodWithLaser'},
outputsOn=laserOutput)
self.sm.add_state(name='delayPeriodWithLaser', statetimer=-laserOnset,
transitions={'Tup':'playNoiseStimulus','Cout':'waitForCenterPoke'})
self.sm.add_state(name='playNoiseStimulus', statetimer=0,
transitions={'Tup':'playToneStimulus'},
outputsOn=stimOutput, serialOut=noiseID,
outputsOff=trialStartOutput)
self.sm.add_state(name='playToneStimulus', statetimer=targetDuration,
transitions={'Cout':'stopStimulus', 'Tup':'stopStimulus'},
serialOut=toneID)
if soundMode == 'full_duration':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePokeWithLaser'},
outputsOff=stimOutput)
elif soundMode == 'off_on_withdrawal':
self.sm.add_state(name='stopStimulus', statetimer=0,
transitions={'Tup':'waitForSidePokeWithLaser'},
outputsOff=stimOutput, serialOut=soundclient.STOP_ALL_SOUNDS)
self.sm.add_state(name='waitForSidePokeWithLaser', statetimer=laserOffset,
transitions={'Lin':'choiceLeft','Rin':'choiceRight', 'Tup':'laserOff'})
self.sm.add_state(name='laserOff', statetimer=0, transitions={'Tup':'waitForSidePoke'},
outputsOff=laserOutput)
self.sm.add_state(name='waitForSidePoke', statetimer=rewardAvailability-laserOffset,
transitions={'Lin':'choiceLeft','Rin':'choiceRight', 'Tup':'noChoice'})
if correctSidePort=='Lin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'reward'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'punish'})
elif correctSidePort=='Rin':
self.sm.add_state(name='choiceLeft', statetimer=0,
transitions={'Tup':'punish'})
self.sm.add_state(name='choiceRight', statetimer=0,
transitions={'Tup':'reward'})
self.sm.add_state(name='reward', statetimer=rewardDuration,
transitions={'Tup':'stopReward'},
outputsOn=[rewardOutput],
outputsOff=laserOutput)
self.sm.add_state(name='stopReward', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=[rewardOutput]+stimOutput)
self.sm.add_state(name='punish', statetimer=punishTimeError,
transitions={'Tup':'ready_next_trial'},
outputsOff=laserOutput)
self.sm.add_state(name='noChoice', statetimer=0,
transitions={'Tup':'ready_next_trial'},
outputsOff=laserOutput)
else:
raise TypeError('outcomeMode={0} has not been implemented'.format(outcomeMode))
###print self.sm ### DEBUG
self.dispatcherModel.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.dispatcherModel.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,:]
secondToLastEvent = eventsThisTrial[-2,:] #sometimes extratimer is the last event so we need to check this too
if (lastEvent[1]==-1 and lastEvent[2]==0) or (lastEvent[1]==7 and secondToLastEvent[1]==-1 and secondToLastEvent[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['playNoiseStimulus']
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['playNoiseStimulus']]
# elif outcomeModeString in ['simulated','sides_direct','direct']:
# seqCin = [self.sm.statesNameToIndex['waitForCenterPoke'],
# self.sm.statesNameToIndex['playNoiseStimulus']]
# 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
# print timeValue
cInInds = np.flatnonzero(eventsThisTrial[:targetEventInd,1]==self.sm.eventsDict['Cin'])
timeValue = eventsThisTrial[cInInds[-1],0] if len(cInInds) else np.nan
self.results['timeCenterIn'][trialIndex] = timeValue
print 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
# print timeValue
cOutInd = np.flatnonzero(eventsThisTrial[cInInds[-1]:,1]==self.sm.eventsDict['Cout']) if len(cInInds) else np.zeros(0)
timeValue = eventsThisTrial[cOutInd[0]+cInInds[-1],0] if len(cOutInd) else np.nan
self.results['timeCenterOut'][trialIndex] = timeValue
print 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
# print timeValue
if outcomeModeString in ['on_next_correct','only_if_correct']:
leftInInds = np.flatnonzero(statesThisTrial==self.sm.statesNameToIndex['choiceLeft'])
rightInInds = np.flatnonzero(statesThisTrial==self.sm.statesNameToIndex['choiceRight'])
if len(leftInInds):
timeValue = eventsThisTrial[leftInInds[0],0]
elif len(rightInInds):
timeValue = eventsThisTrial[rightInInds[0],0]
else:
timeValue = np.nan
elif outcomeModeString in ['simulated','sides_direct','direct']:
timeValue = np.nan
self.results['timeSideIn'][trialIndex] = timeValue
print timeValue
# ===== Calculate choice and outcome =====
# -- Check if it's an aborted trial --
if (lastEvent[1]==-1 and lastEvent[2]==0) or (lastEvent[1]==7 and secondToLastEvent[1]==-1 and secondToLastEvent[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']
if self.sm.statesNameToIndex['punish'] in eventsThisTrial[:,2]:
self.results['outcome'][trialIndex] = \
self.results.labels['outcome']['error']
# -- Check if it was a valid trial --
if self.sm.statesNameToIndex['playNoiseStimulus'] in eventsThisTrial[:,2]:
self.params['nValid'].add(1)
self.results['valid'][trialIndex] = 1
def execute_automation(self):
'''This executes only some modes. Other modes are use outside this method'''
automationMode = self.params['automationMode'].get_string()
nValid = self.params['nValid'].get_value()
if automationMode=='increase_delay':
if nValid>0 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 QtGui.QMainWindow, which explains
its camelCase naming.
'''
self.soundClient.shutdown()
self.dispatcherModel.die()
event.accept()
if __name__ == '__main__':
(app,paradigm) = paramgui.create_app(Paradigm)