/
stroopy.py
239 lines (193 loc) · 8.39 KB
/
stroopy.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
# -*- coding: utf-8 -*-
from psychopy import event, core, data, gui, visual
from fileHandling import *
class Experiment:
def __init__(self, win_color, txt_color):
self.stimuli_positions = [[-.2, 0], [.2, 0], [0, 0]]
self.win_color = win_color
self.txt_color = txt_color
def create_window(self, color=(1, 1, 1)):
# type: (object, object) -> object
color = self.win_color
win = visual.Window(monitor="testMonitor",
color=color, fullscr=True)
return win
def settings(self):
experiment_info = {'Subid': '', 'Age': '', 'Experiment Version': 0.1,
'Sex': ['Male', 'Female', 'Other'],
'Language': ['English', 'Swedish'], u'date':
data.getDateStr(format="%Y-%m-%d_%H:%M")}
info_dialog = gui.DlgFromDict(title='Stroop task', dictionary=experiment_info,
fixed=['Experiment Version'])
experiment_info[u'DataFile'] = u'Data' + os.path.sep + u'stroop.csv'
if info_dialog.OK:
return experiment_info
else:
core.quit()
return 'Cancelled'
def create_text_stimuli(self, text=None, pos=[0.0, 0.0], name='', color=None):
'''Creates a text stimulus,
'''
if color is None:
color = self.txt_color
text_stimuli = visual.TextStim(win=window, ori=0, name=name,
text=text, font=u'Arial',
pos=pos,
color=color, colorSpace=u'rgb')
return text_stimuli
def create_trials(self, trial_file, randomization='random'):
'''Doc string'''
data_types = ['Response', 'Accuracy', 'RT', 'Sub_id', 'Sex']
with open(trial_file, 'r') as stimfile:
_stims = csv.DictReader(stimfile)
trials = data.TrialHandler(list(_stims), 1,
method="random")
[trials.data.addDataType(data_type) for data_type in data_types]
return trials
def present_stimuli(self, color, text, position, stim):
_stimulus = stim
color = color
position = position
if settings['Language'] == "Swedish":
text = swedish_task(text)
else:
text = text
_stimulus.pos = position
_stimulus.setColor(color)
_stimulus.setText(text)
return _stimulus
def running_experiment(self, trials, testtype):
_trials = trials
testtype = testtype
timer = core.Clock()
stimuli = [self.create_text_stimuli(window) for _ in range(4)]
for trial in _trials:
# Fixation cross
fixation = self.present_stimuli(self.txt_color, '+', self.stimuli_positions[2],
stimuli[3])
fixation.draw()
window.flip()
core.wait(.6)
timer.reset()
# Target word
target = self.present_stimuli(trial['colour'], trial['stimulus'],
self.stimuli_positions[2], stimuli[0])
target.draw()
# alt1
alt1 = self.present_stimuli(self.txt_color, trial['alt1'],
self.stimuli_positions[0], stimuli[1])
alt1.draw()
# alt2
alt2 = self.present_stimuli(self.txt_color, trial['alt2'],
self.stimuli_positions[1], stimuli[2])
alt2.draw()
window.flip()
keys = event.waitKeys(keyList=['x', 'm', 'q'])
resp_time = timer.getTime()
if testtype == 'practice':
if keys[0] != trial['correctresponse']:
instruction_stimuli['incorrect'].draw()
else:
instruction_stimuli['right'].draw()
window.flip()
core.wait(2)
if testtype == 'test':
if keys[0] == trial['correctresponse']:
trial['Accuracy'] = 1
else:
trial['Accuracy'] = 0
trial['RT'] = resp_time
trial['Response'] = keys[0]
trial['Sub_id'] = settings['Subid']
trial['Sex'] = settings['Sex']
write_csv(settings[u'DataFile'], trial)
event.clearEvents()
print(f"keys: {keys}")
if 'q' in keys:
print(f"breaking because keys: {keys}")
break
def create_instructions_dict(instr):
start_n_end = [w for w in instr.split() if w.endswith('START') or w.endswith('END')]
keys = {}
for word in start_n_end:
key = re.split("[END, START]", word)[0]
if key not in keys.keys():
keys[key] = []
if word.startswith(key):
keys[key].append(word)
return keys
def create_instructions(input, START, END, color="Black"):
instruction_text = parse_instructions(input, START, END)
print(instruction_text)
text_stimuli = visual.TextStim(window, text=instruction_text, wrapWidth=1.2,
alignHoriz='center', color=color,
alignVert='center', height=0.06)
return text_stimuli
def display_instructions(start_instruction=''):
# Display instructions
if start_instruction == 'Practice':
instruction_stimuli['instructions'].pos = (0.0, 0.5)
instruction_stimuli['instructions'].draw()
positions = [[-.2, 0], [.2, 0], [0, 0]]
examples = [experiment.create_text_stimuli() for pos in positions]
example_words = ['green', 'blue', 'green']
if settings['Language'] == 'Swedish':
example_words = [swedish_task(word) for word in example_words]
for i, pos in enumerate(positions):
examples[i].pos = pos
if i == 0:
examples[0].setText(example_words[i])
elif i == 1:
examples[1].setText(example_words[i])
elif i == 2:
examples[2].setColor('Green')
examples[2].setText(example_words[i])
[example.draw() for example in examples]
instruction_stimuli['practice'].pos = (0.0, -0.5)
instruction_stimuli['practice'].draw()
elif start_instruction == 'Test':
instruction_stimuli['test'].draw()
elif start_instruction == 'End':
instruction_stimuli['done'].draw()
window.flip()
event.waitKeys(keyList=['space'])
event.clearEvents()
def swedish_task(word):
swedish = '+'
if word == "blue":
swedish = u"blå"
elif word == "red":
swedish = u"röd"
elif word == "green":
swedish = u"grön"
elif word == "yellow":
swedish = "gul"
return swedish
if __name__ == "__main__":
background = "Black"
back_color = (0, 0, 0)
textColor = "White"
# text_color = (1, 1, 1)
experiment = Experiment(win_color=background , txt_color=textColor)
settings = experiment.settings()
language = settings['Language']
instructions = read_instructions_file("INSTRUCTIONS", language, language + "End")
instructions_dict = create_instructions_dict(instructions)
instruction_stimuli = {}
window = experiment.create_window(color=back_color)
for inst in instructions_dict.keys():
instruction, START, END = inst, instructions_dict[inst][0], instructions_dict[inst][1]
instruction_stimuli[instruction] = create_instructions(instructions, START, END, color=textColor)
# We don't want the mouse to show:
event.Mouse(visible=False)
# Practice Trials
display_instructions(start_instruction='Practice')
practice = experiment.create_trials('practice_list.csv')
experiment.running_experiment(practice, testtype='practice')
# Test trials
display_instructions(start_instruction='Test')
trials = experiment.create_trials('stimuli_list.csv')
experiment.running_experiment(trials, testtype='test')
# End experiment but first we display some instructions
display_instructions(start_instruction='End')
window.close()