-
Notifications
You must be signed in to change notification settings - Fork 2
/
stpy.py
2838 lines (2191 loc) · 99.6 KB
/
stpy.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
__author__ = 'bramzandbelt'
# Import packages
from psychopy import visual, monitors, core, event, iohub, info, gui
from psychopy.hardware.emulator import launchScan
print 'psychopy version: %s' % info.psychopyVersion
import os
import time
import random # for setting random number generator seed
import calendar
from itertools import chain, compress
import numpy as np
print 'numpy version: %s' % np.__version__
import pandas as pd
print 'pandas version: %s' % pd.__version__
from pandas import DataFrame
# This is to enable printing of all data frame columns
pd.set_option('display.max_columns', None)
import serial
from pprint import pprint
import re
# To Do:
#
# ADD PAUSE KEY FUNCTIONALITY
# =============================================================================
# if pauseKey.keys:
# td = win._toDraw
# win._toDraw = [] # hides whatever was being auto-drawn
# txt = visual.TextStim(win,text='(paused, p to continue)')
# while not event.getKeys(keyList=['p']):
# txt.draw()
# win.flip()
# win._toDraw = td # restore auto-draw
# pauseKey.status = NOT_STARTED
# pauseKey.keys = []
# Some general stuff
# =============================================================================
# Do not monitor for key presses during wait periods
core.checkPygletDuringWait = False
def check_df_from_csv_file(df):
"""
<SUMMARY LINE>
<EXTENDED DESCRIPTION>
Parameters
----------
<NAME> : <TYPE>
<DESCRIPTION>
Returns
-------
<NAME> : <TYPE>
<DESCRIPTION>
Raises
------
<EXCEPTIONS>
Usage
-----
<USAGE>
Example
-------
<EXAMPLE THAT CAN IDEALLY BE COPY PASTED>
"""
# Index (*Ix) and keycount (keycount*) columns should be of type object
# This is to guarantee that NA and integers can be represented. Floats would
# cause problems.
# cols = [col for col in df.select_dtypes(exclude = ['int'])
# if col.endswith('Ix') or col.startswith('keyCount')]
# for col in cols:
# df[col] = df[col].astype('object')
# if os.path.isfile(trialListFile):
# trialList = pd.read_csv(trialListFile)
# ixCols = [col for col in trialList if re.search('Ix$',col)]
#
#
# # Assertions
# # ---------------------------------------------------------------------
# for col in ixCols:
# assert trialList[col].dtype == np.int or \
# all(trialList['cueIx'].isnull()), \
# 'column {} in file {} contains data other than integers'.format(col,trialListFile)
#
#
#
# config['practice']['trialList'] = trialList
return df
def collect_response(rd,kb, *args, **kwargs):
"""
Collect responses from response device and keyboard
This function is called at two stages in the experiment:
1. Instruction
Returns count of response keys, escape keys, and other keys to monitor
2. Experiment
Updates the log variable with key count and key time information
Parameters
----------
rd : dict
specifies response device properties
kb : dict
specifies keyboard properties
log : pandas.core.frame.DataFrame
trial log
otherKeys : list (optional)
specifies which other keys (from response device or keyboard)
to monitor
Returns
-------
log : pandas.core.frame.DataFrame (optional)
trial log; collect_responses fills in values for keyCount and
keyTime variables.
Usage
-----
# For collecting experimental data
log = collect_response(rd,kb,log)
# For instruction screens
keyCount = collect_response(rd,kb)
"""
triggered = None
otherKeysPressed = None
otherKeys = None
log = None
if len(args) == 0:
if kwargs:
if 'log' in kwargs:
log = kwargs.get('log')
if 'otherKeys' in kwargs:
otherKeys = kwargs.get('otherKeys')
elif len(args) == 1:
otherKeys = args[0]
elif len(args) == 2:
otherKeys = args[0]
log = args[1]
elif len(args) > 2:
# TODO: Add error message
pass
# Process inputs
# -------------------------------------------------------------------------
rspKeys = [item
for sublist in rd['settings']['rspKeys']
for item in sublist]
keyKey = rd['settings']['keyKey']
timeKey = rd['settings']['timeKey']
rdClass = rd['settings']['class']
escKeys = kb['settings']['escKeys']
# Define dynamic variables
# -------------------------------------------------------------------------
keyCount = {key: 0 for key in rspKeys}
keyTime = {key: [] for key in rspKeys}
# Determine response identity and response
# -------------------------------------------------------------------------
rdEvents = rd['client'].getEvents()
for ev in rdEvents:
evKeys = ev._asdict()[keyKey]
evTime = ev._asdict()[timeKey]
print 'Key pressed: %s at time %f' % (evKeys, evTime)
# If response device is keyboard and escape keys are in event data
if rdClass == 'Keyboard':
if any([re.findall(key,ev._asdict()['key']) for key in escKeys]):
print('Warning: Escape key pressed - Experiment is terminated')
core.quit()
if otherKeys:
if any([re.findall(key,ev._asdict()['key']) for key in otherKeys]):
otherKeysPressed = ev._asdict()['key']
print otherKeysPressed
return keyCount, otherKeysPressed
# If any of the event keys are in event data
if any([re.findall(key,evKeys) for key in rspKeys]):
for key in rspKeys:
keyCount[key] += evKeys.count(key)
if isinstance(log,pd.DataFrame):
keyTime[key].extend([evTime - log.iloc[0]['trialOns']] * evKeys.count(key))
# Check if any escape or other keys have been pressed
# -------------------------------------------------------------------------
if rdClass != 'Keyboard':
for ev in kb['client'].getEvents():
if any([re.findall(key,ev._asdict()['key']) for key in escKeys]):
print('Warning: Escape key pressed - Experiment is terminated')
core.quit()
if otherKeys:
if any([re.findall(key,ev._asdict()['key']) for key in otherKeys]):
otherKeysPressed = ev._asdict()['key']
return keyCount, otherKeysPressed
# For each key, only response times of first two events are stored
if isinstance(log,pd.DataFrame):
for key in rspKeys:
if keyCount[key] >= 2:
# In case of multiple keystrokes of the same key, only keep
# events that follow a previous keystroke > 50 ms. Smaller
# intervals likely reflect contact bounces
toKeep = [True]
toKeep.extend((np.diff(keyTime[key]) > 0.05).tolist())
# Adjust keyCount and keyTime
keyCount[key] = toKeep.count(True)
keyTime[key] = list(compress(keyTime[key],toKeep))
for key in rspKeys:
if keyCount[key] > 2:
keyTime[key] = keyTime[key][0:2]
elif keyCount[key] < 2:
keyTime[key].extend([float('NaN')] * (2 - keyCount[key]))
# Convert to numpy ndarray
keyTime[key] = np.array(keyTime[key])
# Log response events
for key in rspKeys:
log.iloc[0]['keyCount_'+key] = keyCount[key]
log.iloc[0]['keyTime1_'+key] = keyTime[key][0]
log.iloc[0]['keyTime2_'+key] = keyTime[key][1]
return log
else:
return keyCount, otherKeysPressed
def compute_trial_statistics(trialStats,rd,log):
"""
Computes and writes trial descriptive statistics
Descriptive statistics categories include response time (rt), response time
difference (rtDiff), and raw processing time (rpt)
Parameters
----------
trialStats : dict
specifies which of the following descriptive statistics need to
be computed:
rt : bool
whether or not to compute statistics related to
response time (RT): RT of first and second key press
(for each key), as well as mean, min, and max across
keys
rtDiff : bool
whether or not to compute statistics related to
response time difference: this is only of interest for
situations in which a stimulus is associated with
multiple key presses
rpt : bool
whether or not to compute statistics related to
raw processing time (rpt), the time between s2 and RT
onset: RPT for first and second key press
(for each key), as well as mean, min, and max across
keys
rd : dict
specifies response device properties
log : pandas.core.frame.DataFrame
trial log
Returns
-------
log : pandas.core.frame.DataFrame
trial log; compute_trial_statistics fills in values based on
the key-value pairs in trialStats:
if trialStats['rt']:
rt1_*, rt2_*, rt1_mean, rt2_mean, rt1_min, rt2_min,
rt1_max, rt2_max
if trialStats['rtDiff']:
rtDiff1_*, rtDiff2_*, rtDiff1_mean, rtDiff2_mean
if trialStats['rpt']:
rpt1_*, rpt2_*, rpt1_mean, rpt2_mean, rpt1_min, rpt2_min,
rpt1_max, rpt2_max
"""
rspKeys = [item for sublist in rd['settings']['rspKeys'] for item in sublist]
rspKeyPairs = rd['settings']['rspKeys']
s1Ons = log.iloc[0]['s1Ons']
s2Ons = log.iloc[0]['s2Ons']
# Response time
# -------------------------------------------------------------------------
# Compute response times relative to primary (go) signal for first (rt1)
# and second (rt2) key strokes plus their min (fastest), max (slowest),
# and mean across keys
rt1 = {key: np.nan for key in rspKeys}
rt2 = rt1.copy()
for key in rspKeys:
rt1[key] = log.iloc[0]['keyTime1_'+key] - s1Ons
rt2[key] = log.iloc[0]['keyTime2_'+key] - s1Ons
if trialStats['rt']:
log.iloc[0]['rt1_'+key] = rt1[key]
log.iloc[0]['rt2_'+key] = rt2[key]
if trialStats['rt']:
log.iloc[0]['rt1_mean'] = np.nanmean(rt1.values())
log.iloc[0]['rt2_mean'] = np.nanmean(rt2.values())
log.iloc[0]['rt1_min'] = np.nanmin(rt1.values())
log.iloc[0]['rt2_min'] = np.nanmin(rt2.values())
log.iloc[0]['rt1_max'] = np.nanmax(rt1.values())
log.iloc[0]['rt2_max'] = np.nanmax(rt2.values())
# Response time difference
# -------------------------------------------------------------------------
if trialStats['rtDiff']:
for pair in rspKeyPairs:
pairStr = pair[0] + '-' + pair[1]
log.iloc[0]['rtDiff1_' + pairStr] = rt1[pair[0]] - rt1[pair[1]]
log.iloc[0]['rtDiff2_' + pairStr] = rt2[pair[0]] - rt2[pair[1]]
rtDiff1Cols = [col for col in log.columns if col.startswith('rtDiff1_')]
rtDiff2Cols = [col for col in log.columns if col.startswith('rtDiff2_')]
log.iloc[0]['rtDiff1_mean'] = log.iloc[0][rtDiff1Cols].abs().mean()
log.iloc[0]['rtDiff2_mean'] = log.iloc[0][rtDiff2Cols].abs().mean()
# Raw processing time
# -------------------------------------------------------------------------
# Compute response times relative to secondary signal for first (rt1) and
# second (rt2) key strokes plus their min (fastest), max (slowest), and
# mean across keys
if trialStats['rpt']:
for key in rspKeys:
log.iloc[0]['rpt1_' + key] = log.iloc[0]['keyTime1_'+key] - s2Ons
log.iloc[0]['rpt2_' + key] = log.iloc[0]['keyTime2_'+key] - s2Ons
rpt1Cols = [col for col in log.columns if col.startswith('rpt1_')]
rpt2Cols = [col for col in log.columns if col.startswith('rpt2_')]
log.iloc[0]['rpt1_mean'] = log.iloc[0][rpt1Cols].mean()
log.iloc[0]['rpt2_mean'] = log.iloc[0][rpt2Cols].mean()
log.iloc[0]['rpt1_min'] = log.iloc[0][rpt1Cols].min()
log.iloc[0]['rpt2_min'] = log.iloc[0][rpt2Cols].min()
log.iloc[0]['rpt1_max'] = log.iloc[0][rpt1Cols].max()
log.iloc[0]['rpt2_max'] = log.iloc[0][rpt2Cols].max()
return log
def evaluate_block(config,df,blockId,blockLog,trialOnsNextBlock):
"""
Evaluate block performance
Parameters
----------
config : dict
specifies StPy experiment properties
df : pandas.core.frame.DataFrame
trial log
blockId : str or unicode
identifier of the block
blockLog : pandas.core.frame.DataFrame
block log
trialOnsNextBlock : numpy.int64
time when next block should start; this is used to
determine duration of block feedback
Returns
-------
allCritMet : bool
whether or not all predefined task performance criteria
have been met
"""
# Subfunctions
def assess_performance(stat,lo,hi):
"""
Evaluates whether statistic is withing lower and upper bounds
Parameters
----------
stat : dict
statistical value to be evaluated
lo : int or float
lower bound
hi : int or float
upper bound
Returns
-------
critMet : bool
specifies whether or not criterion is met
"""
if lo <= stat <= hi:
critMet = True
else:
critMet = False
return critMet
def get_bounds(config,stat,ix):
"""
Get lower and upper bounds for a given statistic
Parameters
----------
config : dict
specifies StPy experiment properties
stat : str or unicode
descriptive statistic name
ix : int
stimulus index (only used if bounds vary across stimulus
indices)
Returns
-------
lo : int or float
lower bound of criterion
hi : int or float
upper bound of criterion
"""
crit = config['feedback']['block']['features'][stat]['criterion']
if isinstance(crit[0],list):
return min(crit[ix]), max(crit[ix])
else:
return min(crit), max(crit)
def get_data(df,statType,trialType,stimType,stimIx):
"""
Obtain data from DataFrame based on which descriptive statistics are computed
Parameters
----------
df : pandas.core.series.DataFrame
trial log
statType : str or unicode
statistic on which feedback is presented
trialType : pandas.core.series.Series
boolean array acting as selector of trials (rows)
stimType : pandas.core.series.Series
array of stimulus indices
stimIx : int
stimulus index
Returns
-------
data : pandas.core.series.Series
data on which descriptive statistic are computed
"""
bla = {'s1Accuracy': df.trialCorrect[trialType & (stimType == stimIx)].value_counts(),
's2Accuracy': df.trialCorrect[trialType & (stimType == stimIx)].value_counts(),
's1MeanRt': df.rt1_mean[trialType & (stimType == ix)],
's1MeanRtDiff': df.rtDiff1_mean[trialType & (stimType == ix)]}
data = bla[statType]
return data
def get_desc_stat(data,statType):
"""
Compute descriptive statistic on data
Parameters
----------
data : int or float
data on which descriptive statistic is computed
statType : str or unicode
statistic on which feedback is presented
Returns
-------
descStat : int or float
descriptive statistic
"""
# Assertions
knownStatTypes = ['s1Accuracy','s2Accuracy','s1MeanRt','s1MeanRtDiff']
assert statType in knownStatTypes, 'unknown statType %s' % statType
if statType == 's1Accuracy' or statType == 's2Accuracy':
if True in data.index:
nTrue = data[True].astype(float)
nTrial = data.sum().astype(float)
pCorrect = nTrue / nTrial
descStat = (pCorrect * 100).round()
else:
descStat = 0
elif statType == 's1MeanRt':
if data.empty:
descStat = np.nan
else:
meanRt = data.mean() * 1000
if np.isnan(meanRt):
descStat = np.nan
else:
descStat = meanRt.round()
elif statType == 's1MeanRtDiff':
if data.empty:
descStat = np.nan
else:
meanRtDiff = data.abs().mean() * 1000
if np.isnan(meanRtDiff):
descStat = np.nan
else:
descStat = meanRtDiff.round()
else:
descStat = np.nan
return descStat
def get_feedback_message(config,stat,ix):
"""
Determine what feedback should be presented
Parameters
----------
config : dict
specifies StPy experiment properties
stat : str or unicode
descriptive statistic name
ix : int
list index
Returns
-------
posMes : str, unicode, or list
feedback message if performance criterion is met
negMes : str, unicode, or list
feedback message if performance criterion is not met
"""
posMes = config['feedback']['block']['features'][stat]['feedbackPos']
negMes = config['feedback']['block']['features'][stat]['feedbackNeg']
if isinstance(posMes,list):
if len(posMes) == 1:
pos = posMes[0]
elif len(posMes) > 1:
pos = posMes[ix]
else:
pos = posMes
if isinstance(negMes,list):
if len(negMes) == 1:
neg = negMes[0]
elif len(negMes) > 1:
neg = negMes[ix]
else:
neg = negMes
return str(pos), str(neg)
def update_feedback_log(log,stimIx,stat,statType,critMet):
"""
Update block log
Logs performance level and whether or not preset performance criterion
is met.
Parameters
----------
log : pandas.core.frame.DataFrame
block log
stimIx : int
stimulus index
stat : numpy.float64 or numpy.int
performance
statType : str or unicode
statistic on which feedback is presented
critMet : bool
whether or not performance criterion is met
Returns
-------
log : pandas.core.frame.DataFrame
block log
"""
# Dict of formatted strings, referring to columns in log
strStatCol = {'s1Accuracy': 's1Acc_%.2d',
's2Accuracy': 's2Acc_%.2d',
's1MeanRt': 's1MeanRt_%.2d',
's1MeanRtDiff': 's1MeanRtDiff_%.2d'}
strCritCol = {'s1Accuracy': 's1AccCritMet_%.2d',
's2Accuracy': 's2AccCritMet_%.2d',
's1MeanRt': 's1MeanRtCritMet_%.2d',
's1MeanRtDiff': 's1MeanRtDiffCritMet_%.2d'}
# Column names for statistic and criterion
colStat = strStatCol[statType] % stimIx
colCrit = strCritCol[statType] % stimIx
# Update the log
log[colStat] = stat
log[colCrit] = critMet
return log
def update_feedback_screen(win,feedbackStim,stim,stat,statType,critMet,posMes,negMes):
"""
Update feedback stimulus
Parameters
----------
win : psychopy.visual.window.Window
PsychoPy window object, in which stimuli are presented
feedbackStim : dict
Specifies aspects of the feedback: stimulus identity,
performance, and feedback message
stim : psychopy.visual.text.TextStim or psychopy.visual.text.ImageStim
PsychoPy stimulus to which feedback relates
stat : numpy.float64 or numpy.int
performance
statType : str or unicode
statistic on which feedback is presented
critMet : bool
whether or not performance criterion is met
posMes : str or unicode
feedback message if performance criterion is met
negMes : str or unicode
feedback message if performance criterion is not met
Returns
-------
feedbackStim : dict
Specifies aspects of the feedback: stimulus identity,
performance, and feedback message
"""
# Define some variables
# -----------------------------------------------------------------
stimName = stim.name[stim.name.find('_')+1:]
stimNameText = get_empty_text_stim(win)
performText = get_empty_text_stim(win)
feedbackText = get_empty_text_stim(win)
posFeedbackColor = (255, 255, 255)
negFeedbackColor = (255, 0, 0)
# Stimulus
# -----------------------------------------------------------------
stimNameText.setText(stimName)
feedbackStim['stim'].append(stimNameText)
# Performance
# -----------------------------------------------------------------
statStr = {'s1Accuracy': 'accuracy: %0.f%% correct',
's2Accuracy': 'accuracy: %0.f%% correct',
's1MeanRt': 'speed: %0.f ms',
's1MeanRtDiff': 'synchrony: %0.f ms difference'}
performText.setText(statStr[statType] % stat)
if critMet:
performText.setColor(posFeedbackColor,'rgb255')
else:
performText.setColor(negFeedbackColor, 'rgb255')
feedbackStim['performance'].append(performText)
# Feedback
# -----------------------------------------------------------------
if critMet:
feedbackText.setText(posMes)
feedbackText.setColor(posFeedbackColor,'rgb255')
else:
feedbackText.setText(negMes)
feedbackText.setColor(negFeedbackColor, 'rgb255')
feedbackStim['feedback'].append(feedbackText)
return feedbackStim
window = config['window']['window']
trialStats = config['statistics']['trial']
s1 = df.s1Ix
s2 = df.s2Ix
s1Trial = (s1.notnull()) & (s2.isnull())
s2Trial = s2.notnull()
anyS1Trial = any(s1Trial)
anyS2Trial = any(s2Trial)
trialTypeExist = {'s1Accuracy': anyS1Trial,
's2Accuracy': anyS2Trial,
's1MeanRt': anyS1Trial,
's1MeanRtDiff': anyS1Trial}
trialType = {'s1Accuracy': s1Trial,
's2Accuracy': s2Trial,
's1MeanRt': s1Trial,
's1MeanRtDiff': s1Trial}
# Unique indices of relevant stimulus present in data frame
uniqueStimIxs = {'s1Accuracy': sorted(s1[s1.notnull()].unique().tolist()),
's2Accuracy': sorted(s2[s2.notnull()].unique().tolist()),
's1MeanRt': sorted(s1[s1.notnull()].unique().tolist()),
's1MeanRtDiff': sorted(s1[s1.notnull()].unique().tolist())}
# Relevent stimulus type to select on
stimType = {'s1Accuracy': s1,
's2Accuracy': s2,
's1MeanRt': s1,
's1MeanRtDiff': s1}
# Stimulus
stimulus = {'s1Accuracy': config['stimuli']['s1'],
's2Accuracy': config['stimuli']['s2'],
's1MeanRt': config['stimuli']['s1'],
's1MeanRtDiff': config['stimuli']['s1']}
# Task performance features to provide feedback on
features = config['feedback']['block']['features']
feedbackFeat = [key for key in features.keys() if features[key]['enable'] and trialTypeExist[key]]
blockFeedback = config['feedback']['block']['features']
blockFeedbackStim = {'stim': [],
'performance': [],
'feedback': []}
criteriaMet = []
for feat in sorted(feedbackFeat):
for ix in uniqueStimIxs[feat]:
lowerBound, upperBound = get_bounds(config=config,
stat=feat,
ix=ix)
posMessage, negMessage = get_feedback_message(config=config,
stat=feat,
ix=ix)
data = get_data(df=df,
statType=feat,
trialType=trialType[feat],
stimType=stimType[feat],
stimIx=ix)
if not data.empty:
descStat = get_desc_stat(statType=feat,
data=data)
thisCritMet = assess_performance(stat=descStat,
lo=lowerBound,
hi=upperBound)
criteriaMet.append(thisCritMet)
# Update feedback screen
blockFeedbackStim = update_feedback_screen(win=window,
feedbackStim=blockFeedbackStim,
stim=stimulus[feat][ix],
stat=descStat,
statType=feat,
critMet=thisCritMet,
posMes=posMessage,
negMes=negMessage)
# Update feedback log
blockLog = update_feedback_log(log=blockLog,
stimIx=ix,
stat=descStat,
statType=feat,
critMet=thisCritMet)
allCritMet = all(criteriaMet)
# Display feedback
# -------------------------------------------------------------------------
# Count how lines feedback
nLines = len(blockFeedbackStim['stim'])
# Feedback title, containing block ID
blockTitleStim = get_empty_text_stim(window)
yPos = (float(nLines) - 1)/2 + 2
xPos = 0
blockTitleStim.setText('Block %s' % (blockId))
blockTitleStim.setPos((xPos,yPos))
blockTitleStim.setHeight(1)
blockTitleStim.alignHoriz = 'center'
blockTitleStim.setAutoDraw(True)
# Loop over feedback lines
for iStim in range(nLines):
# Set position of the stimulus
yPos = (float(nLines) - 1)/2 - iStim
xPos = -12
blockFeedbackStim['stim'][iStim].setPos((xPos,yPos))
blockFeedbackStim['stim'][iStim].setHeight(0.75)
blockFeedbackStim['stim'][iStim].alignHoriz = 'left'
blockFeedbackStim['stim'][iStim].setAutoDraw(True)
# Set position of performance stimulus
xPos = -5
blockFeedbackStim['performance'][iStim].setPos((xPos,yPos))
blockFeedbackStim['performance'][iStim].setHeight(0.75)
blockFeedbackStim['performance'][iStim].alignHoriz = 'left'
blockFeedbackStim['performance'][iStim].setAutoDraw(True)
# Set position of feedback stimulus
xPos = 5
blockFeedbackStim['feedback'][iStim].setPos((xPos,yPos))
blockFeedbackStim['feedback'][iStim].setHeight(0.75)
blockFeedbackStim['feedback'][iStim].alignHoriz = 'left'
blockFeedbackStim['feedback'][iStim].setAutoDraw(True)
window.flip()
tNow = config['clock'].getTime()
feedbackDuration = config['feedback']['block']['duration']
if trialOnsNextBlock == 0:
core.wait(feedbackDuration)
elif tNow + feedbackDuration < trialOnsNextBlock:
core.wait(feedbackDuration)
elif tNow < trialOnsNextBlock:
core.wait(5)
else:
core.wait(trialOnsNextBlock - tNow - 2)
blockTitleStim.setAutoDraw(False)
for iStim in range(nLines):
blockFeedbackStim['stim'][iStim].setAutoDraw(False)
blockFeedbackStim['performance'][iStim].setAutoDraw(False)
blockFeedbackStim['feedback'][iStim].setAutoDraw(False)
window.flip()
return allCritMet
def evaluate_trial(evalData,feedbackDur,window,stimuli,log):
"""
Evaluate trial performance and present trial feedback
Parameters
----------
evalData : dict
specifies information about how trial should be evaluated,
this includes:
evalDataFile : dict
specifies trial evaluation data files for each
of the possible response devices
evalData : pandas.core.frame.DataFrame
all stimulus-response combinations specified
in the trial evaluation data file
correct : pandas.core.series.Series
accuracy for each of the stimulus-response
combinations
responseType : pandas.core.series.Series
response type for each of the stimulus-response
combinations
feedback : pandas.core.series.Series
feedback for each of the stimulus-response
combinations
trialType : pandas.core.series.Series
trial type for each of the stimulus-response
combinations
feedbackDur : float
trial feedback duration (in seconds)
window : psychopy.visual.window.Window
PsychoPy window object, in which stimuli are presented
stimuli : dict
specifies PsychoPy stimuli, including the feedback and inter-
trial interval stimulus
log : pandas.core.frame.DataFrame
trial log
Returns
-------
log : pandas.core.frame.DataFrame
trial log; evaluate_trial fills in values for the following
variables: trialCorrect, trialType, responseType, and
trialFeedback
"""
# Process inputs
# =========================================================================
# Assertions
# -------------------------------------------------------------------------
# specific to evalData and log (window and stimulis should have been
# checked already and not have been updated
# Define dynamic variables
# -------------------------------------------------------------------------
trialCorrect = []
trialLabel = []
trialFeedback = []
# Trial evaluation
# =========================================================================
ix = log.index.tolist()[0]
# Match pattern, using stimulus and response data
source = evalData['evalData'].fillna(float('inf'))
patternDict= log[source.columns].fillna(float('inf')).to_dict()
pattern = {key: [value[ix]] for key,value in patternDict.iteritems()}
iRow = source.isin(pattern).all(1)
if sum(iRow) == 0:
trialCorrect = False
# If no match, try to match using stimulus data only to determine trialType
sourceStim = evalData['evalData'][['s1Ix','s2Ix']].fillna(float('inf'))
patternDictStim = log[sourceStim.columns].fillna(float('inf')).to_dict()
patternStim = {key: [value[ix]] for key,value in patternDictStim.iteritems()}
iRow = sourceStim.isin(patternStim).all(1)
uniqueTrialTypes = evalData['trialType'].loc[iRow].unique()
if len(uniqueTrialTypes) == 0:
trialType = 'NOC' # Not otherwise classified
elif len(uniqueTrialTypes) == 1:
trialType = uniqueTrialTypes.tolist()[0]