-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtask_blocks.py
More file actions
2792 lines (2215 loc) · 120 KB
/
task_blocks.py
File metadata and controls
2792 lines (2215 loc) · 120 KB
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
# Task Class definitions
# March 2021: First version: Ladan Shahshahani - Maedbh King - Suzanne Witt,
# Revised 2023: Bassel Arafat, Jorn Diedrichsen, Incé Husain
# Revised 2024: Caroline Nettekoven
from pathlib import Path
import pandas as pd
import numpy as np
import random
from psychopy import prefs
prefs.hardware['audioLib'] = ['sounddevice']
from psychopy import visual, sound, core, event
from pyglet.window import key
import MultiTaskBattery.utils as ut
from ast import literal_eval
from copy import deepcopy
from moviepy.audio.io.AudioFileClip import AudioFileClip
import gc
import math
import json
class Task:
"""
Task: takes in inputs from run_experiment.py and methods
some methods are universal across all tasks. Those methods are included in the super class Task.
There are methods like display_instructions which are the same across most of the tasks.
There are, however, some tasks that have different instructions from the rest (like fingerSequence).
For those tasks, a display_instructions method is defined within the corresponding class which overrides
the universal display_instruction method.
Each of other classes runs a unique task given input from target files and from the Task class
(VisualSearch, SemanticPrediction, NBack, SocialPrediction, ActionObservation).
"""
def __init__(self, info, screen, ttl_clock, const, subj_id):
# Pointers to Screen and experimental constants
self.screen = screen
self.window = screen.window # Shortcut to window
self.const = const
self.ttl_clock = ttl_clock # This is a reference to the clock of the run
self.name = info['task_name']
self.descriptive_name = info['descriptive_name']
self.code = info['task_code']
self.task_file = info['task_file']
self.feedback_type = 'none'
# Set the instruction text height to a value defined in the constants, or use default - useful for smaller screens
self.const.instruction_text_height = getattr(self.const, 'instruction_text_height', None) or 1
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
self.trial_info = pd.read_csv(self.const.task_dir / self.name / self.task_file, sep='\t')
def display_instructions(self):
"""
displays the instruction for the task
Most tasks have the same instructions. (Tasks that have True/False responses)
Those tasks that have different instructions will have their own routine
"""
true_str = f"if True press {self.const.response_keys[1]}"
false_str = f"if False press {self.const.response_keys[2]}"
self.instruction_text = f"{self.descriptive_name} Task\n\n {true_str} \n {false_str}"
# 3.2 display the instruction text
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
# instr.size = 0.8
instr_visual.draw()
self.window.flip()
def run(self):
"""Loop over trials and collects data
Data will be stored in self.trial_data
Returns:
info (pd.DataFrame): _description_
"""
self.trial_data = [] # an empty list which will be appended with the responses from each trial
for i,trial in self.trial_info.iterrows():
t_data = trial.copy()
# Wait for the the start of next trial
t_data['real_start_time'],t_data['start_ttl'],t_data['start_ttl_time'] = self.ttl_clock.wait_until(self.start_time + trial.start_time )
# Run the trial
t_data = self.run_trial(t_data)
# Append the trial data
self.trial_data.append(t_data)
self.trial_data = pd.DataFrame(self.trial_data)
# Calculate the feedback for the run
acc = None
rt = None
if self.feedback_type[:3] == 'acc':
acc = self.trial_data['correct'].mean()
if self.feedback_type[-2:] == 'rt':
rt = self.trial_data['rt'].mean()
return acc,rt
def show_progress(self, seconds_left, show_last_seconds=5, height=1, width=10, x_pos=-5, y_pos=8):
""" Displays a progress bar for the Picture Sequence task
Args:
seconds_left (float):
The number of seconds remaining in the current trial.
If this value is greater than `show_last_seconds`, the progress bar is not shown.
show_last_seconds (float, optional):
The duration (in seconds) over which to display the progress bar at the end of a trial.
Default is 5 seconds. When `seconds_left` is less than this value, the progress bar appears.
height (float, optional):
The vertical size of the progress bar in PsychoPy window units. Default is 1.
width (float, optional):
The horizontal size of the progress bar in PsychoPy window units. Default is 10.
x_pos (float, optional):
The horizontal position of the center of the progress bar in window coordinates.
Negative values move it leftward. Default is -5.
y_pos (float, optional):
The vertical position of the center of the progress bar in window coordinates.
Positive values move it upward. Default is 8.
"""
# If we are in the last five seconds of the trial, display the remaining time
if seconds_left < show_last_seconds:
progress = visual.Progress(
win=self.window,
progress=1-(seconds_left/show_last_seconds),
size=(width, height),
pos=(x_pos, y_pos),
backColor='blue',
barColor='black',
borderColor='black',
lineWidth=5,
)
progress.draw()
def wait_response(self, start_time, max_wait_time, show_last_seconds=None, current_stimuli=None):
"""
waits for a response to be made and then returns the response
Args:
start_time (float): the time the RT-period started
max_wait_time (float): How long to wait maximally
Returns:
key (str): the key that was pressed (1-4) (0 if no key was pressed)
rt (float): the reaction time (nan if no key was pressed)
"""
response_made = False
key = 0
rt = np.nan
while (self.ttl_clock.get_time() - start_time <= max_wait_time) and not response_made:
self.ttl_clock.update()
if show_last_seconds is not None:
current_stimuli.draw()
seconds_left = max_wait_time - (self.ttl_clock.get_time() - start_time)
self.show_progress(seconds_left,
show_last_seconds=show_last_seconds,
y_pos=6)
self.window.flip()
keys=event.getKeys(keyList= self.const.response_keys, timeStamped=self.ttl_clock.clock)
if len(keys)>0:
response_made = True
key_char = keys[0][0]
key = self.const.response_keys.index(key_char) + 1
rt = keys[0][1] - start_time
return key, rt
def display_trial_feedback(self, give_feedback,correct_response):
"""
display the feedback for the current trial using the color of the fixation cross
Args:
give_feedback (bool):
If true, gives informative feedback - otherwise just shows fixation cross
correct_response (bool):
Response was correct?, False otherwise
"""
if give_feedback:
if correct_response:
self.screen.check_mark('green')
else:
self.screen.error_cross('red')
else:
self.screen.fixation_cross('white')
def save_data(self, subj_id, run_num):
"""Saves the data to the trial data file
Args:
subj_id (str): Subject id to determine name
run_num (int): Number of run - inserted as first column
"""
self.trial_data.insert(0, 'run_num', [run_num]*len(self.trial_data))
trial_data_file = self.const.data_dir / subj_id / f"{subj_id}_task-{self.code}.tsv"
ut.append_data_to_file(trial_data_file, self.trial_data)
def screen_quit(self):
""" Checks for quit or escape key presses and quits the experiment if necessary """
keys = event.getKeys()
for key in keys:
if 'q' in key or 'esc' in key:
self.window.close()
core.quit()
def get_audio_from_movie(self, movie_path, sample_rate=48000):
"""Seperates the audio from the movie file and returns the audio object (for better memory handling when playing movies with sound)"""
# Gets the movie audio
audio_clip = AudioFileClip(movie_path)
audio_array = audio_clip.to_soundarray(fps=sample_rate)
audio_clip.close()
audio = sound.Sound(audio_array,sampleRate=sample_rate, stereo=True)
return audio
class NBack(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.feedback_type = 'acc+rt'
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
trial_info_file = self.const.task_dir / self.name / self.task_file
self.trial_info = pd.read_csv(trial_info_file, sep='\t')
self.stim = []
picture_scale = self.trial_info['picture_scale'].iloc[0] if 'picture_scale' in self.trial_info.columns else 1.0
for stim in self.trial_info['stim']:
stim_path = self.const.stim_dir / self.name / stim
img = visual.ImageStim(self.window, str(stim_path))
img.size = img.size * picture_scale
self.stim.append(img)
self.corr_key = [self.trial_info['key_nomatch'].iloc[0], self.trial_info['key_match'].iloc[0]]
def display_instructions(self):
"""
displays the instruction for the task
"""
str1 = f"Compare image to the one shown 2 previously"
str2 = f"if match, press {self.corr_key[1]}"
str3 = f"if no match, press {self.corr_key[0]}"
self.instruction_text = f"{self.descriptive_name} Task\n\n {str1} \n {str2} \n {str3}"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self,trial):
"""Runs a single trial of the nback task (after it started)
Args:
trial (pd.Series):
Row of trial_info, with all information about the trial
Returns:
trial (pd.Series):
Row of trial_data with all response data added
"""
# Flush any keys in buffer
event.clearEvents()
# display stimulus
self.stim[trial['trial_num']].draw()
self.window.flip()
# collect responses 0: no response 1-4: key pressed
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['trial_dur'])
trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
# display trial feedback
self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
return trial
class Rest(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.name = 'rest'
def display_instructions(self): # overriding the display instruction routine from the parent
self.instruction_text = 'Rest: Fixate on the cross'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
# instr.size = 0.8
instr_visual.draw()
self.window.flip()
def show_stim(self):
# show fixation cross
self.screen.fixation_cross()
def run_trial(self,trial):
# get current time (self.t0)
self.screen.fixation_cross()
self.ttl_clock.wait_until(self.start_time + trial['trial_dur'])
return trial
class VerbGeneration(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
trial_info_file = self.const.task_dir / self.name / self.task_file
self.trial_info = pd.read_csv(trial_info_file, sep='\t')
self.trial_info['noun'] = self.trial_info['stim'].str.strip()
self.trial_counter = 0
def display_instructions(self): # overriding the display instruction from the parent class
self.instruction_text = f"{self.descriptive_name} Task \n\n Silently read the words presented. \n\n When GENERATE is shown, silently think of verbs that go with the words."
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def show_stim(self, noun):
""" Display a word for a fixed time. """
stim = visual.TextStim(self.window, text=noun, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=2)
stim.draw()
self.window.flip()
def display_generate_instruction(self):
""" Display the 'GENERATE' instruction. """
generate_instr = visual.TextStim(self.window, text='GENERATE', pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=2)
generate_instr.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the VerbGeneration task. """
# Display word
self.show_stim(trial['noun'])
# display GENERATE instruction at the halfway point
if self.trial_counter == len(self.trial_info) // 2:
self.display_generate_instruction()
self.trial_counter += 1
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class TongueMovement(Task):
"""
Tongue movement following Buckner et al., 2022! No particular feedback.
"""
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f"{self.descriptive_name} Task \n\n Move your tongue left to right touching your upper premolar teeth"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the tonguemovement task. """
# draw fixation cross without flipping
self.screen.fixation_cross(flip=False)
# Check the trial_type and display the corresponding stimulus
if trial['trial_type'] == 'right':
# If trial_type is 'right', show the black circle around the fixation cross
circle_visual = visual.Circle(self.window, radius=3, edges= 100, lineWidth = 20, fillColor=None, lineColor='black')
circle_visual.draw()
self.window.flip()
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class AuditoryNarrative(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f'{self.descriptive_name} Task\n\nListen to the narrative attentively.'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the AuditoryNarrative task. """
self.screen.fixation_cross()
# Load and play audio stimulus for the current trial
audio_path = self.const.stim_dir / self.name / trial['stim']
audio_stim = sound.Sound(str(audio_path))
audio_stim.play()
trial_dur = audio_stim.getDuration()
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class SpatialNavigation(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def init_task(self):
self.trial_info = pd.read_csv(self.const.task_dir / self.name / self.task_file, sep='\t')
self.corr_key = [self.trial_info['key_false'].iloc[0],self.trial_info['key_true'].iloc[0]]
def display_instructions(self):
start_location = self.trial_info.iloc[0]['location_1']
end_location = self.trial_info.iloc[0]['location_2']
self.instruction_text = (f"{self.descriptive_name} Task \n\n"
f"Imagine walking around your childhood home\n"
f"Start in the {start_location} – end in the {end_location}\n"
f"Focus on the fixation cross")
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1], wrapWidth=20)
instr_visual.draw()
self.window.flip()
def run_trial(self,trial):
self.screen.fixation_cross()
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class TheoryOfMind(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.feedback_type = 'acc+rt'
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
self.trial_info = pd.read_csv(self.const.task_dir / self.name / self.task_file, sep='\t')
self.corr_key = [self.trial_info['key_false'].iloc[0],self.trial_info['key_true'].iloc[0]]
def display_instructions(self):
"""
displays the instruction for the task
"""
task_name = visual.TextStim(self.window, text=f'{self.descriptive_name.capitalize()}', height=self.const.instruction_text_height, color=[-1, -1, -1], bold=True, pos=(0, 3))
task_name.draw()
str1 = f"You will read a story and decide if the answer to the question is True or False."
str2 = f"if true, press {self.corr_key[1]}"
str3 = f"if false, press {self.corr_key[0]}"
self.instruction_text = f"\n\n {str1} \n\n {str2} \n {str3}"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Runs a single trial of the Theory of Mind task """
event.clearEvents()
height = trial.get('text_height', 1.25)
wrapWidth=25
# Display story
story_clean = ' '.join(trial['story'].split('\n'))
story_formatted = '.\n'.join(story_clean.split('. '))
story_stim = visual.TextStim(self.window, text=story_formatted, alignHoriz='center', wrapWidth=wrapWidth, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=height)
story_stim.draw()
self.window.flip()
# wait until story duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['story_dur'])
# Flush any keys in buffer
event.clearEvents()
# Display question
question_stim = visual.TextStim(self.window, text=trial['question'], pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=height, wrapWidth=25)
question_stim.draw()
self.window.flip()
# collect responses 0: no response 1-4: key pressed
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['question_dur'])
trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
# display trial feedback
self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
return trial
class DegradedPassage(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f'{self.descriptive_name} Task \n\nListen to the audio attentively.'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the task. """
self.screen.fixation_cross()
# Load and play audio stimulus for the current trial
audio_path = self.const.stim_dir / self.name / trial['stim']
audio_stim = sound.Sound(str(audio_path))
audio_stim.play()
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class IntactPassage(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f'{self.descriptive_name} Task \n\nListen to the audio attentively.'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the task. """
self.screen.fixation_cross()
# Load and play audio stimulus for the current trial
audio_path = self.const.stim_dir / self.name / trial['stim']
audio_stim = sound.Sound(str(audio_path))
audio_stim.play()
# wait for trial duration
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
# display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
return trial
class ActionObservation(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self): # overriding the display instruction from the parent class
self.instruction_text = f"{self.descriptive_name} Task \n\n Keep your head still while watching the two clips. \n\n Try and remember the knot shown."
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Runs a single trial of the ActionObservation task """
# Assuming that 'stim' column in trial contains the file name of the video clip
movie_file_name = trial['stim']
# Construct the movie file path
movie_path = Path(self.const.stim_dir) / self.name / 'clips' / movie_file_name
# Convert Path object to string for compatibility
movie_path_str = str(movie_path)
# Create a MovieStim3 object
movie_clip = visual.MovieStim(self.window, movie_path_str, loop=False)
while movie_clip.isFinished == False:
movie_clip.play()
movie_clip.draw()
self.window.flip()
self.ttl_clock.update()
self.screen.fixation_cross()
# Display trial feedback
self.display_trial_feedback(give_feedback= trial['display_trial_feedback'], correct_response = None)
# Flush memory: This is necessary for the script to be able to run more than 1 run. Presenting movies is very memory hungry, so do not remove!
movie_clip.unload()
gc.collect() # Collect garbarge
return trial
class DemandGrid(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.square_size = 1.5
self.feedback_type = 'acc+rt'
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
trial_info_file = self.const.task_dir / self.name / self.task_file
self.trial_info = pd.read_csv(trial_info_file, sep='\t')
self.corr_key = [self.trial_info['key_left'].iloc[0],self.trial_info['key_right'].iloc[0]]
def display_instructions(self):
"""
displays the instruction for the task
"""
str1 = f"You will watch the sequence of boxes that light up and then choose the correct pattern"
str2 = f"if left, press {self.corr_key[0]}"
str3 = f"if right, press {self.corr_key[1]}"
self.instruction_text = f"{self.descriptive_name} Task\n\n {str1} \n {str2} \n {str3}"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def create_grid(self, sequence=None, position='center',grid_size=(3,4)):
"""Creates the grid of squares for the DemandGrid task, lighting up specific squares blue if a sequence is given,
and positions the grid left, right, or center."""
# Calculate offsets based on the desired position
if position == 'left':
offset_x = -5
elif position == 'right':
offset_x = 5
else: # center
offset_x = 0
# Center the grid vertically
offset_y = 0
grid = []
# Create and draw the grid
for i in range(grid_size[0]):
row = []
for j in range(grid_size[1]):
# Calculate position with the offsets
square_x = (j - grid_size[0] / 2 + 0.5) * self.square_size + offset_x
square_y = (grid_size[1] / 2 - i - 0.5) * self.square_size + offset_y
# Determine the fill color based on the sequence
fill_color = 'blue' if sequence and (i, j) in sequence else 'white'
rect = visual.Rect(self.window, width=self.square_size, height=self.square_size,
pos=(square_x, square_y), lineWidth=3,
lineColor='black', fillColor=fill_color)
rect.draw()
row.append(rect)
grid.append(row)
return grid
def run_trial(self, trial):
"""Runs a single trial of the DemandGrid task with two boxes lighting up at a time"""
# Draw the entire grid in its initial state
if 'grid_size' in trial:
grid_size = literal_eval(trial['grid_size'])
else:
grid_size = (3,4)
# Make the code adaptable to old DemandGrid implementation
if 'num_steps' in trial:
num_steps = trial['num_steps']
else:
num_steps = 3
step_dur = trial['sequence_dur']/num_steps
self.grid = self.create_grid(grid_size=grid_size)
self.window.flip()
# Display the sequence in steps
if 'original_sequence' in trial:
original_sequence = literal_eval(trial['original_sequence'])
else:
original_sequence = literal_eval(trial['grid_sequence'])
if 'num_steps' in trial: # new implementation
for i in range(num_steps):
step_sequence_name = f'original_step_{i+1}'
step_sequence = literal_eval(trial[step_sequence_name])
for tuple in step_sequence:
x, y = tuple
self.grid[x][y].fillColor = 'blue'
for row in self.grid:
for rect in row:
rect.draw()
self.window.flip()
self.ttl_clock.wait_until(self.ttl_clock.get_time() + step_dur)
for tuple in step_sequence:
x, y = tuple
self.grid[x][y].fillColor = 'white'
else: # old implementation
for i in range(0, len(original_sequence), 2): # Iterate in steps of 2
if i + 1 < len(original_sequence):
pair = [original_sequence[i], original_sequence[i + 1]]
else:
pair = [original_sequence[i]] # Handle odd-length sequences
# Highlight positions in the current pair
for x, y in pair:
self.grid[x][y].fillColor = 'blue'
# Draw and update the window
for row in self.grid:
for rect in row:
rect.draw()
self.window.flip()
self.ttl_clock.wait_until(self.ttl_clock.get_time() + step_dur)
# Reset colors after the pair
for x, y in pair:
self.grid[x][y].fillColor = 'white'
# Flush any keys in buffer
event.clearEvents()
# Determine which side the correct sequence will be displayed
correct_side = trial['correct_side']
# # Display the original and modified sequence on the left or right side
modified_sequence = literal_eval(trial['modified_sequence'])
original_grid = self.create_grid(sequence=original_sequence, position=correct_side, grid_size=grid_size)
modified_grid = self.create_grid(sequence=modified_sequence, position='left' if correct_side == 'right' else 'right', grid_size=grid_size)
self.window.flip()
# collect responses 0: no response 1-4: key pressed
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['question_dur'])
trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
# Provide feedback if necessary
self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
return trial
class SentenceReading(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f'{self.descriptive_name} Task \n\n Read each English word and press a button when the image of a hand pressing a button is displayed'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the sentence reading task. """
# get sentence and split into words by space
sentence = trial['stim']
words = sentence.split()
#show words seqeuntially each for 450ms
for word in words:
word_stim = visual.TextStim(self.window, text=word, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=2)
word_stim.draw()
self.window.flip()
self.ttl_clock.wait_until(self.ttl_clock.get_time() + 0.45)
event.clearEvents()
# show press button image
button_stim = visual.ImageStim(self.window, image=str(self.const.stim_dir / self.name / 'hand_press_transparent.png'))
button_stim.draw()
self.window.flip()
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), 0.4)
# show blank_transparent image
blank_stim = visual.ImageStim(self.window, image=str(self.const.stim_dir / self.name / 'blank_transparent.png'))
blank_stim.draw()
self.window.flip()
# flush any keys in buffer
event.clearEvents()
# not displaying crosshair to replicate the localizer
return trial
class NonwordReading(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
def display_instructions(self):
self.instruction_text = f'{self.descriptive_name} Task \n\n Read each nonword word and press a button when the image of a hand pressing a button is displayed'
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the nonword reading task. """
# get sentence and split into words by space
sentence = trial['stim']
words = sentence.split()
#show words seqeuntially each for 450ms
for word in words:
word_stim = visual.TextStim(self.window, text=word, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=2)
word_stim.draw()
self.window.flip()
self.ttl_clock.wait_until(self.ttl_clock.get_time() + 0.45)
event.clearEvents()
# show press button image
button_stim = visual.ImageStim(self.window, image=str(self.const.stim_dir / self.name / 'hand_press_transparent.png'))
button_stim.draw()
self.window.flip()
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), 0.4)
# show blank_transparent image
blank_stim = visual.ImageStim(self.window, image=str(self.const.stim_dir / self.name / 'blank_transparent.png'))
blank_stim.draw()
self.window.flip()
# clear any keys in buffer
event.clearEvents()
# not displaying crosshair to replicate the localizer
return trial
class OddBall(Task):
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.feedback_type = 'acc+rt'
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
trial_info_file = self.const.task_dir / self.name / self.task_file
self.trial_info = pd.read_csv(trial_info_file, sep='\t')
self.corr_key = [self.trial_info['key_one'].iloc[0],self.trial_info['key_two'].iloc[0]]
def display_instructions(self):
"""
displays the instruction for the task
"""
str1 = f"Press {self.corr_key[0]} when you see a red K"
self.instruction_text = f"{self.descriptive_name} Task\n\n {str1} \n"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the oddball task. """
current_trial = trial['stim']
# show stem
if current_trial == 'red_K':
word_stim = visual.TextStim(self.window, text='K', pos=(0.0, 0.0), color='red', units='deg', height=1.5)
elif current_trial == 'black_K':
word_stim = visual.TextStim(self.window, text='K', pos=(0.0, 0.0), color='black', units='deg', height=1.5)
elif current_trial == 'red_O':
word_stim = visual.TextStim(self.window, text='O', pos=(0.0, 0.0), color='red', units='deg', height=1.5)
elif current_trial == 'black_O':
word_stim = visual.TextStim(self.window, text='O', pos=(0.0, 0.0), color='black', units='deg', height=1.5)
word_stim.draw()
self.window.flip()
self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
self.display_trial_feedback(trial['display_trial_feedback'], None)
# Flush any keys in buffer
event.clearEvents()
# collect responses 0: no response 1-4: key pressed
trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['iti_dur'])
# method 2 for accuracy for oddball
if trial['trial_type'] == 1:
trial['correct'] = True if trial['response']!= 0 else False
elif trial['trial_type'] == 0:
trial['correct'] = np.nan
return trial
class FingerSequence(Task):
"""
Finger sequence task
"""
def __init__(self, info, screen, ttl_clock, const, subj_id):
super().__init__(info, screen, ttl_clock, const, subj_id)
self.feedback_type = 'acc+rt'
def init_task(self):
"""
Initialize task - default is to read the target information into the trial_info dataframe
"""
trial_info_file = self.const.task_dir / self.name / self.task_file
self.trial_info = pd.read_csv(trial_info_file, sep='\t')
self.corr_key = [self.trial_info['key_one'].iloc[0],self.trial_info['key_two'].iloc[0],self.trial_info['key_three'].iloc[0],self.trial_info['key_four'].iloc[0]]
def display_instructions(self):
self.instruction_text = f"{self.descriptive_name} Task \n\n Using your four fingers, press the keys in the order shown on the screen\n Use all four fingers for this task"
instr_visual = visual.TextStim(self.window, text=self.instruction_text, height=self.const.instruction_text_height, color=[-1, -1, -1])
instr_visual.draw()
self.window.flip()
def run_trial(self, trial):
""" Run a single trial of the finger sequence task. """
#clear buffer
event.clearEvents()
# Display the sequence
sequence = trial['stim'].split()
# Calculate the start position for the sequence and determine the spacing between numbers
num_items = len(sequence)
spacing = 2.0
start_x = -(num_items - 1) * spacing / 2
# Show the numbers in the sequence next to each other ( using the spacing and start_x calculated above)
for i, number in enumerate(sequence):
pos = (start_x + i * spacing, 0.0) # Horizontal position is adjusted based on index
stim = visual.TextStim(self.window, text=number, pos=pos, color='black', units='deg', height=1.5)
stim.draw()
self.window.flip()
sequence_start_time = self.ttl_clock.get_time() # Needed for knowing when to stop looking for key presses
digit_start_time = sequence_start_time # Updated with each key press for calculating RT
rt_list = np.full(num_items,np.nan)
correct_list = np.zeros((num_items,)) # List of booleans indicating whether each press was correct needed for overall trial accuracy
num_presses =0
# Initialize the color for each digit in the sequence as black
digit_colors = ['black'] * num_items
while self.ttl_clock.get_time() - sequence_start_time < trial['trial_dur'] and num_presses < num_items:
self.ttl_clock.update()
keys = event.getKeys(keyList=self.const.response_keys, timeStamped=self.ttl_clock.clock)
if keys:
key_char, key_press_time = keys[0]
key = self.const.response_keys.index(key_char) + 1
rt = key_press_time - digit_start_time
rt_list[num_presses]=rt
digit_start_time = key_press_time
# Check if key pressed is correct
correct_list[num_presses] = key == int(sequence[num_presses])
# Update color based on correctness
digit_colors[num_presses] = 'green' if correct_list[num_presses] else 'red'
num_presses += 1
# Draw all digits with their adjusted colors
for i, (number, color) in enumerate(zip(sequence, digit_colors)):
pos = (start_x + i * spacing, 0.0)
stim = visual.TextStim(self.window, text=number, pos=pos, color=color, units='deg', height=1.5)
stim.draw()
self.window.flip()
else:
# If the sequence is completed, wait until the end of the trial
self.ttl_clock.wait_until(sequence_start_time + trial['trial_dur'])
# if any press is wrong trial['correct'] needs to be false, this is for post trial feedback
trial['correct'] = correct_list.sum()/num_items
if np.all(np.isnan(rt_list)):
# calculate mean rt across presses
trial['rt'] = np.nan
else:
trial['rt'] = np.nanmean(rt_list)
# display trial feedback (for whole trial)
self.display_trial_feedback(trial['display_trial_feedback'], trial['correct']== 1)