-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitch.py
3091 lines (2462 loc) · 111 KB
/
itch.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
# !/Users/bramzandbelt/anaconda/envs/psychopyenv/bin python
# -*- coding: utf-8 -*-
__author__ = "bramzandbelt"
# Import packages
# from psychopy import visual, monitors, core, event, iohub, info, gui
import psychopy as pp
from psychopy import info as ppinfo
import numpy as np
import pandas as pd
import calendar
import monthdelta
import os
import random # for setting random number generator seed
import re
import serial
import time
import itertools as it
import warnings
from pprint import pprint
from psychopy.hardware.emulator import launchScan
print 'psychopy version: %s' % ppinfo.psychopyVersion
print 'numpy version: %s' % np.__version__
print 'pandas version: %s' % pd.__version__
# This is to enable printing of all data frame columns
pd.set_option('display.max_columns', None)
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.Series
trial log
other_keys : list (optional)
specifies which other keys (from response device or keyboard)
to monitor
t0 : float (optional)
event time relative to which RT should be calculated
min_rt : float (optional)
minimum response time, in seconds
max_rt : float (optional)
maximum response time, in seconds
Returns
-------
log : pandas.core.frame.Series (optional)
trial log; collect_responses fills in values for key_count and
key_time variables.
Usage
-----
# For collecting experimental data
log = collect_response(rd,kb,log)
# For instruction screens
key_count = collect_response(rd,kb)
"""
triggered = None
other_keys = None
ev_keys_pressed = None
other_keys_pressed = None
log = None
if len(args) == 0:
if kwargs:
if 'log' in kwargs:
log = kwargs.get('log')
if 'other_keys' in kwargs:
other_keys = kwargs.get('other_keys')
if 't0' in kwargs:
t0 = kwargs.get('t0')
else:
t0 = True
if 'min_rt' in kwargs:
min_rt = kwargs.get('min_rt')
else:
min_rt = 0
if 'max_rt' in kwargs:
max_rt = kwargs.get('max_rt')
else:
max_rt = np.inf
elif len(args) == 1:
other_keys = args[0]
t0 = True
min_rt = 1.5
max_rt = np.inf
elif len(args) == 2:
other_keys = args[0]
log = args[1]
t0 = True
min_rt = 1.5
max_rt = np.inf
elif len(args) == 3:
other_keys = args[0]
log = args[1]
t0 = args[2]
min_rt = 1.5
max_rt = np.inf
elif len(args) == 4:
other_keys = args[0]
log = args[1]
t0 = args[2]
min_rt = args[3]
max_rt = np.inf
elif len(args) == 4:
other_keys = args[0]
log = args[1]
t0 = args[2]
min_rt = args[3]
max_rt = args[4]
elif len(args) > 5:
# TODO: Add error message
pass
# Process inputs
# -------------------------------------------------------------------------
rsp_keys = []
for item in rd['settings']['rsp_keys']:
rsp_keys.append(item)
key_key = rd['settings']['key_key']
time_key = rd['settings']['time_key']
rd_class = rd['settings']['class']
esc_keys = kb['settings']['esc_keys']
# Define dynamic variables
# -------------------------------------------------------------------------
key_count = {key: 0 for key in rsp_keys}
key_time = {key: [] for key in rsp_keys}
# Determine response identity and response
# -------------------------------------------------------------------------
while sum([key_count[key] for key in rsp_keys]) == 0 and \
pp.core.getTime() < t0 + max_rt:
rd_events = rd['client'].getEvents()
for ev in rd_events:
if rd_class == 'Keyboard':
# Have any abort keys been pressed?
if any([re.findall('^'+key+'$', ev.key) for key in esc_keys]):
print('Warning: Escape key pressed - Experiment is terminated')
pp.core.quit()
# Have any other keys been pressed (e.g. toggle keys for moving
# between instruction screens)
if other_keys:
if any([re.findall('^'+key+'$', ev.key) for key in
other_keys]):
other_keys_pressed = ev.key
print other_keys_pressed
return key_count, other_keys_pressed
# If any of the event keys are in event data
if any([re.findall('^'+key+'$', ev.key) for key in rsp_keys]):
key_count[ev.key] += 1
if isinstance(log, pd.core.series.Series):
# Only log time of first response key event
if not any([key_time[key] for key in rsp_keys]):
rt = ev.time - t0
key_time[ev.key] = rt
break
elif rd_class == 'Serial':
for kbev in kb['client'].getEvents():
# Have any abort keys been pressed?
if any([re.findall('^'+key+'$', kbev.key) for key in esc_keys]):
print(
'Warning: Escape key pressed - Experiment is '
'terminated')
pp.core.quit()
if other_keys:
if any([re.findall('^'+key+'$', kbev.key) for key in
other_keys]):
other_keys_pressed = kbev.key
return key_count, other_keys_pressed
# If any of the event keys are in event data
if any([re.findall('^'+key+'$', ev.data) for key in rsp_keys]):
key_count[ev.data] += 1
# Only log time of first response key event
if not any([key_time[key] for key in rsp_keys]):
rt = ev.time - t0
key_time[ev.key] = rt
break
# For each key, only response times of first two events are stored
if isinstance(log, pd.core.series.Series):
# # Determine choice
# try:
# choice_key, choice_time = \
# next((k, v) for k, v in key_time.items() if v)
# except StopIteration:
# print 'The generator was empty'
# choice_key = None
# choice_time = float('inf')
if log['ll_side'] == 'left':
key_mapping = dict(zip(rsp_keys, ('ll', 'ss', 'avoid_choice')))
elif log['ll_side'] == 'right':
key_mapping = dict(zip(rsp_keys, ('ss', 'll', 'avoid_choice')))
# Log events
for key in rsp_keys:
log['key_count_' + key] = key_count[key]
if 'ev' in locals():
log['choice'] = key_mapping.get(ev.key, 'NA')
log['rt'] = rt
if rt < min_rt:
log['too_fast'] = True
else:
log['too_fast'] = False
else:
# If no response is given, variable ev does not exist
log['choice'] = 'NA'
log['rt'] = np.inf
log['too_fast'] = False
return log
else:
return key_count, other_keys_pressed
def copy_series_values(var_names, source_series, target_series):
assert isinstance(source_series, pd.core.frame.Series), \
'source_series should be of type pandas.core.frame.Series'
assert isinstance(target_series, pd.core.frame.Series), \
'target_series should be of type pandas.core.frame.Series'
for item in var_names:
target_series[item] = source_series[item]
return target_series
def define_stimulus(window, stim_info, *args):
# type: (object, object, object) -> object
"""
Make PsychoPy stimuli based on user input
Currently, only stimuli of type TextStim and ImageStim are supported.
Parameters
----------
window : psychopy.visual.window.Window
PsychoPy window object, in which stimuli are presented
stim_info : dict
stimulus information specified by user in experiment
configuration file
stim_type : str or unicode (optional)
stimulus type
Returns
-------
stimulus : dict
specifies properties of the stimuli
"""
# Process inputs
# -------------------------------------------------------------------------
# TODO: See if assertions require __debug__ variable
assert type(window) is pp.visual.window.Window, \
'window is not of class visual.window.Window'
assert type(stim_info) is dict, \
'stim_info is not of type dict'
for key in ['type', 'name']:
assert stim_info.has_key(key), \
'stim_info does not contain key {0:s}'.format(key)
if len(args) == 1:
stim_type = args[0]
else:
stim_type = ''
if 'content' in stim_info:
n_stimulus = len(stim_info['content'])
else:
n_stimulus = 1
# Initialize list of stimuli
stimulus = [None] * n_stimulus
for i in range(n_stimulus):
stimulus[i] = init_stimulus(window,stim_info['type'])
assert (type(stimulus[i]) is
pp.visual.text.TextStim or
pp.visual.rect.Rect or
pp.visual.image.ImageStim), \
"stimulus is neither a TextStim, nor a Rect, nor an ImageStim"
# Set stimulus name
stimulus[i].name = stim_type
# if isinstance(stim_info['name'],list):
# stimulus[i].name = ''.join([stim_type,'_',stim_info['name'][i]])
# else:
# stimulus[i].name = ''.join([stim_type,'_',stim_info['name']])
# Text stimuli
# ---------------------------------------------------------------------
if type(stimulus[i]) is pp.visual.text.TextStim:
# Set stimulus content
# TODO: Include function here that defines stimulus content
# based on input
# Set other parameters, if provided
if 'font_file' in stim_info:
if stim_info['font_file']:
stimulus[i].fontFiles = stim_info['font_file']
if 'font' in stim_info:
if stim_info['font']:
stimulus[i].setFont(stim_info['font'])
if 'ori' in stim_info:
if stim_info['ori']:
stimulus[i].setOri(stim_info['ori'])
if 'height' in stim_info:
if stim_info['height']:
stimulus[i].setHeight(stim_info['height'])
if 'pos' in stim_info:
if stim_info['pos']:
stimulus[i].setPos(stim_info['pos'])
if 'color' in stim_info:
if stim_info['color']:
stimulus[i].setColor(stim_info['color'], 'rgb255')
if 'opacity' in stim_info:
if stim_info['opacity']:
stimulus[i].setOpacity(stim_info['opacity'])
# Set general TextStimulus parameters
stimulus[i].alignHoriz = 'center'
stimulus[i].alignVert = 'center'
stimulus[i].wrapWidth = 1000
# Rectangles
# ---------------------------------------------------------------------
elif type(stimulus[i]) is pp.visual.Rect:
if 'height' in stim_info:
if stim_info['height']:
stimulus[i].setHeight(stim_info['height'])
if 'width' in stim_info:
if stim_info['width']:
stimulus[i].setWidth(stim_info['width'])
if 'pos' in stim_info:
if stim_info['pos']:
stimulus[i].setPos(stim_info['pos'])
if 'ori' in stim_info:
if stim_info['ori']:
stimulus[i].setOri(stim_info['ori'])
if 'fill_color' in stim_info:
if stim_info['fill_color']:
stimulus[i].setFillColor(stim_info['fill_color'], 'rgb255')
if 'line_color' in stim_info:
if stim_info['line_color']:
stimulus[i].setLineColor(stim_info['line_color'], 'rgb255')
if 'line_width' in stim_info:
if stim_info['line_width']:
stimulus[i].setLineWidth(stim_info['line_width'])
if 'opacity' in stim_info:
if stim_info['opacity']:
stimulus[i].setOpacity(stim_info['opacity'])
# Image stimuli
# ---------------------------------------------------------------------
elif type(stimulus[i]) is pp.visual.ImageStim:
# Set stimulus content
stimulus[i].setImage(stim_info['content'][i])
# Set other parameters
if 'ori' in stim_info:
if stim_info['ori']:
stimulus[i].setOri(stim_info['ori'])
if 'pos' in stim_info:
if stim_info['pos']:
stimulus[i].setPos(stim_info['pos'])
return stimulus
def evaluate_block(config,df,block_id,block_log):
"""
Evaluate block performance
Parameters
----------
config : dict
specifies ItchPy experiment properties
df : pandas.core.frame.DataFrame
trial log
block_id : str or unicode
identifier of the block
block_log : pandas.core.frame.DataFrame
block log
Returns
-------
all_crit_met : bool
whether or not all predefined task performance
criteria
have been met
"""
# Subfunctions
# =========================================================================
def assess_performance(stat, *args, **kwargs):
"""
Evaluates whether statistic is within 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
-------
crit_met : bool
specifies whether or not criterion is met
"""
if len(args) == 0:
if kwargs:
if 'lo' in kwargs:
lo = kwargs.get('lo')
if 'hi' in kwargs:
hi= kwargs.get('hi')
if 'max_dev' in kwargs:
max_dev = kwargs.get('max_dev')
elif len(args) == 1:
max_dev = args[0]
elif len(args) == 2:
lo = args[0]
hi = args[1]
if 'max_dev' in kwargs:
if all(stat <= max_dev):
crit_met = True
else:
crit_met = False
else:
if lo <= stat <= hi:
crit_met = True
else:
crit_met = False
return crit_met
def get_bounds(config, stat):
"""
Get lower and upper bounds for a given statistic
Parameters
----------
config : dict
specifies StPy experiment properties
stat : str or unicode
descriptive statistic name
Returns
-------
lo : int or float
lower bound of criterion
hi : int or float
upper bound of criterion
"""
crit = config['feedback']['block']['features'][stat]['criterion']
return min(crit), max(crit)
def get_data(df, stat_type):
"""
Obtain data from DataFrame based on which descriptive statistics
are computed
Parameters
----------
df : pandas.core.series.DataFrame
trial log
stat_type : str or unicode
statistic on which feedback is presented
Returns
-------
data : pandas.core.series.Series
data on which descriptive statistic are computed
"""
tt = {'catch_ss_accuracy': 'catch_ss',
'catch_ll_accuracy': 'catch_ll',
'check_instr_accuracy': 'instr_check',
'too_fast_responses': 'standard',
'monotonicity': 'standard',
'discounting': 'standard'
}[stat_type]
if stat_type.endswith('accuracy'):
data = df.trial_correct[df.trial_type == tt].value_counts()
elif stat_type in ['monotonicity', 'discounting']:
# Indifference points
data = \
df.loc[df.trial_type == tt, ['trial_ix','t_l', 'm_s']]. \
sort(columns=['trial_ix', 't_l']). \
groupby(by='t_l')['m_s']. \
agg('last')
elif stat_type == 'too_fast_responses':
data = df.too_fast[df.trial_type == tt].value_counts()
else:
data = None
return data
def get_desc_stat(config, data, stat_type):
"""
Compute descriptive statistic on data
Parameters
----------
config : dict
specifies ItchPy experiment properties
data : int or float
data on which descriptive statistic is computed
stat_type : str or unicode
statistic on which feedback is presented
Returns
-------
desc_stat : int or float
descriptive statistic
"""
# Assertions
known_stat_types = ['catch_ss_accuracy', 'catch_ll_accuracy',
'check_instr_accuracy', 'too_fast_responses',
'monotonicity', 'discounting']
assert stat_type in known_stat_types, 'unknown stat_type %s' % \
stat_type
if stat_type.endswith('accuracy') or stat_type == 'too_fast_responses':
if True in data.index:
n_true = data[True].astype(float)
n_trial = data.sum().astype(float)
p_correct = n_true / n_trial
desc_stat = (p_correct * 100).round()
else:
desc_stat = 0
elif stat_type == 'monotonicity':
if data.empty:
desc_stat = np.nan
else:
# The differences in indifference point across delays are
# computed; an indifference point cannot be higher than the
# previous indifference point by 20% of the LL amount.
# This is criterion 1 from Johnson & Bickel (2008)
desc_stat = np.diff(data) / config['ip_procedure']['m_l'] * 100
elif stat_type == 'discounting':
if data.empty:
desc_stat = np.nan
else:
# The indifference point of the longest delay is used to
# evaluate whether indifference points decrease with delay
# at all
# This is criterion 2 from Johnson & Bickel (2008)
desc_stat = data.iloc[-1] / config['ip_procedure']['m_l'] * 100
else:
desc_stat = np.nan
return desc_stat
def get_feedback_message(config, stat):
"""
Determine what feedback should be presented
Parameters
----------
config : dict
specifies StPy experiment properties
stat : str or unicode
descriptive statistic name
Returns
-------
pos_mes : str, unicode, or list
feedback message if performance criterion is met
neg_mes : str, unicode, or list
feedback message if performance criterion is not met
"""
pos_mes = config['feedback']['block']['features'][stat][
'feedbackPos']
neg_mes = config['feedback']['block']['features'][stat][
'feedbackNeg']
pos = pos_mes
neg = neg_mes
return str(pos), str(neg)
def update_feedback_log(log, stat, stat_type, crit_met):
"""
Update block log
Logs performance level and whether or not preset performance
criterion is met.
Parameters
----------
log : pandas.core.frame.DataFrame
block log
stat : numpy.float64 or numpy.int
performance
stat_type : str or unicode
statistic on which feedback is presented
crit_met : 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
str_stat_col = {'catch_ss_accuracy': 'catch_ss_accuracy',
'catch_ll_accuracy': 'catch_ll_accuracy',
'check_instr_accuracy': 'check_instr_accuracy',
'too_fast_responses': 'too_fast_responses',
'monotonicity': 'monotonicity',
'discounting': 'discounting'
}
str_crit_col = {'catch_ss_accuracy': 'catch_ss_accuracy_crit_met',
'catch_ll_accuracy': 'catch_ll_accuracy_crit_met',
'check_instr_accuracy': 'check_instr_accuracy_crit_met',
'too_fast_responses': 'too_fast_responses_crit_met',
'monotonicity': 'monotonicity_crit_met',
'discounting': 'discounting_crit_met'
}
# Column names for statistic and criterion
col_stat = str_stat_col[stat_type]
col_crit = str_crit_col[stat_type]
# Update the log
if col_stat == 'monotonicity':
log[col_stat] = max(stat)
else:
log[col_stat] = stat
log[col_crit] = crit_met
return log
def update_feedback_screen(win, feedback_stim, stim, stat, stat_type,
crit_met, pos_mes, neg_mes):
"""
Update feedback stimulus
Parameters
----------
win : psychopy.visual.window.Window
PsychoPy window object, in which stimuli are
presented
feedback_stim : 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
stat_type : str or unicode
statistic on which feedback is presented
crit_met : bool
whether or not performance criterion is met
pos_mes : str or unicode
feedback message if performance criterion is met
neg_mes : str or unicode
feedback message if performance criterion is not
met
Returns
-------
feedback_stim : dict
Specifies aspects of the feedback: stimulus
identity,
performance, and feedback message
"""
# Define some variables
# -----------------------------------------------------------------
# stimName = stim.name[stim.name.find('_') + 1:]
stim_name_text = get_empty_text_stim(win)
perform_text = get_empty_text_stim(win)
feedback_text = get_empty_text_stim(win)
pos_feedback_color = (0, 191, 0)
neg_feedback_color = (255, 128, 0)
# Stimulus
# -----------------------------------------------------------------
stim_str = {'catch_ss_accuracy': "accuracy on catch scenarios with a €0.00 option",
'catch_ll_accuracy': 'accuracy on catch scenarios with equal amount options',
'check_instr_accuracy': 'accuracy on catch scenarios requiring return key press',
'too_fast_responses': 'proportion of fast responses',
'monotonicity': 'max. difference between indifference '
'points (%)',
'discounting': 'degree of discounting at longest delay'
}
stim_name_text.setText(stim_str[stat_type])
feedback_stim['stim'].append(stim_name_text)
# Performance
# -----------------------------------------------------------------
stat_str = {'catch_ss_accuracy': '%0.f%%',
'catch_ll_accuracy': '%0.f%%',
'check_instr_accuracy': '%0.f%%',
'too_fast_responses': '%0.f%%',
'monotonicity': '%0.f%%',
'discounting': '%0.f%%'
}
if stat_type == 'monotonicity':
perform_text.setText(stat_str[stat_type] % max(stat))
else:
perform_text.setText(stat_str[stat_type] % stat)
if crit_met:
perform_text.setColor(pos_feedback_color, 'rgb255')
else:
perform_text.setColor(neg_feedback_color, 'rgb255')
feedback_stim['performance'].append(perform_text)
# Feedback
# -----------------------------------------------------------------
if crit_met:
feedback_text.setText(pos_mes)
feedback_text.setColor(pos_feedback_color, 'rgb255')
else:
feedback_text.setText(neg_mes)
feedback_text.setColor(neg_feedback_color, 'rgb255')
feedback_stim['feedback'].append(feedback_text)
return feedback_stim
# Criteria
# =========================================================================
# Practice
# -------------------------------------------------------------------------
# - Responses on all trials
# Indifference point procedure
# -------------------------------------------------------------------------
# - Responses on all trials
# - Accuracy on catch trials
# trial_types = ['catch_ss', 'catch_ll', 'instr_check']
# accuracies = {'catch_ss': None,
# 'catch_ll': None,
# 'instr_check': None}
# #########################################################################
window = config['window']['window']
trial_stats = config['statistics']['trial']
tt = df.trial_type
trial_type_exist = {'catch_ss_accuracy': any(tt == 'catch_ss'),
'catch_ll_accuracy': any(tt == 'catch_ll'),
'check_instr_accuracy': any(tt == 'instr_check'),
'too_fast_responses': any(tt == 'standard'),
'monotonicity': any(tt == 'standard'),
'discounting': any(tt == 'standard')
}
# Stimulus
stimulus = {'catch_ss_accuracy': 'catch_ss',
'catch_ll_accuracy': 'catch_ll',
'check_instr_accuracy': 'instr_check',
'too_fast_responses': 'too_fast_responses',
'monotonicity': 'ip_decrease',
'discounting': 'discounting'}
# Task performance features to provide feedback on
features = config['feedback']['block']['features']
feedback_feat = [key for key in features.keys() if
features[key]['enable'] and trial_type_exist[key]]
block_feedback = config['feedback']['block']['features']
block_feedback_stim = {'stim': [],
'performance': [],
'feedback': []}
criteria_met = []
for feat in sorted(feedback_feat):
if feat == 'monotonicity':
max_dev = config['feedback']['block']['features'][feat]['criterion']
else:
lower_bound, upper_bound = get_bounds(config=config,
stat=feat)
pos_message, neg_message = get_feedback_message(config=config,
stat=feat)
data = get_data(df=df,
stat_type=feat)
if not data.empty:
desc_stat = get_desc_stat(config=config,
stat_type=feat,
data=data)
if feat == 'monotonicity':
this_crit_met = assess_performance(stat=desc_stat,
max_dev=max_dev)
else:
this_crit_met = assess_performance(stat=desc_stat,
lo=lower_bound,
hi=upper_bound)
criteria_met.append(this_crit_met)
# Update feedback screen
# TODO: implement this
block_feedback_stim = update_feedback_screen(win=window,
feedback_stim=block_feedback_stim,
stim=stimulus[feat],
stat=desc_stat,
stat_type=feat,
crit_met=this_crit_met,
pos_mes=pos_message,
neg_mes=neg_message)
# Update feedback log
block_log = update_feedback_log(log=block_log,
stat=desc_stat,
stat_type=feat,
crit_met=this_crit_met)
all_crit_met = all(criteria_met)
# Display feedback
# -------------------------------------------------------------------------
# Count how lines feedback
n_lines = len(block_feedback_stim['stim'])
# Feedback title, containing block ID
block_title_stim = get_empty_text_stim(window)
y_pos = (float(n_lines) - 1) / 2 + 2
x_pos = 0
block_title_stim.setText('Block %s' % (block_id))
block_title_stim.setPos((x_pos, y_pos))
block_title_stim.setHeight(1)
block_title_stim.alignHoriz = 'center'
block_title_stim.setAutoDraw(True)
# Loop over feedback lines
for i_stim in range(n_lines):
# Set position of the stimulus