forked from damascenodiego/pygame-logitechG29_wheel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexperiment_mtb_learning.py
265 lines (238 loc) · 7.89 KB
/
experiment_mtb_learning.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
####################
####################
#### __ IMPORTS ____
####################
# General libraries
import os
from datetime import datetime
import pandas as pd
import numpy as np
import subprocess
from psychopy import visual, event, core
from psychopy.hardware import keyboard
defaultKeyboard = keyboard.Keyboard(backend='iohub')
# Special functions
def countdown_timer(duration, window):
countdown_text = visual.TextStim(window, text='', pos=(0, 0), height=50)
for time_remaining in range(duration, 0, -1):
countdown_text.text = str(time_remaining)
countdown_text.draw()
window.flip()
core.wait(1)
countdown_text.text = '0'
countdown_text.draw()
window.flip()
core.wait(1)
##############################
#### __ EXPERIMENT CONFIG ____
##############################
# PARTICIPANT INFO
participant = 'Giorgia' # name of subject
output_path = os.path.join('./results', participant)
os.makedirs(output_path, exist_ok=True)
# PARAMETERS DEBUGGING
full_screen = True # set to True for real experiment
ACCUMULATED_RESULTS_FILENAME = 'accumulated_results.csv'
# PARAMETERS EXP
# presentation
driving_time_limit = 60
nr_trials = 10
do_rest = False
time_slide_intro_trial = 1
time_slide_outro_trial = 1
countdown_duration = 3
conditions = ['play', 'motor', 'playback']
base_command = ['python', 'mountain_biking_all_conds.py']
# visual
ratio_text_size = 40
ratio_text_width=2
ratio_cross = 40
contrast = 0.1
# # Command to activate Conda environment on Windows
# activate_cmd = f'conda activate mtb'
# subprocess.run(activate_cmd, shell=True)
# print('Conda environment activated!')
############################
#### __ PSYCHOPY CONFIG ____
############################
win = visual.Window(
size=[800, 600],
units="pix",
fullscr=full_screen,
color=[-1, -1, -1]
)
win.mouseVisible = False
fixation = visual.shape.ShapeStim(win=win,
vertices="cross",
color='white',
fillColor='white',
contrast=contrast,
size=max(win.size)/ratio_cross)
############################
#### __ EXPERIMENT ____
############################
# INTRODUCTION
# Slide 1
text = visual.TextStim(win=win, text="Hi "+ str(participant) + "\
\n\nDuring you will have to control a mountain bike and keep it on track on a downhill pathway.\
\n\nEach game lasts " + str(driving_time_limit) + " seconds and you can play up to " + str(nr_trials) + " games.\
\n\nPress a key on the keyboard to continue!",\
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# Slide 2
text = visual.TextStim(win=win, text="You can use the left and right arrows of the keyboard to play.\
\n\nWihile playing, please minimize unnecessary movements (eye blinks, face or any other unnecessary body movement).\
\n\nPress a key on the keyboard to continue!",\
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# Slide 3
text = visual.TextStim(win=win, text="You will also have to other two conditions:\
\n\n- motor: where you press left and right arrows as if you where playin.\
\n\n- sensory: where you will just watch the game",\
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# Slide 4
text = visual.TextStim(win=win, text="The experiment is about to start."\
"\n\nIf you need to move or to take a break, that's the time!"
"\n\nWhen you're ready, press a key to start the experiment.",
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# Stimuli presentation begins
for i in range(nr_trials):
for cond in conditions:
# Slide intro of each trial
text = visual.TextStim(win=win, text="Game " + str(i+1) + "/" + str(nr_trials) + '\n'
+ " condition: " + cond,
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
core.wait(time_slide_intro_trial)
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# # COUNTDOWN
# countdown_timer(countdown_duration, win)
# PLAY GAME
fixation.autoDraw = True
win.flip()
win.winHandle.set_visible(False) # Hide the PsychoPy window
# Run the command and capture the output
trial_str = "trial_" + str(i)
command = base_command + [f'--driver_name={participant}',
f'--trial={trial_str}',
f'--condition={cond}']
print(f"Command to execute: {' '.join(command)}")
output = subprocess.run(command, capture_output=True, text=True)
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
win.winHandle.set_visible(True) # Show the PsychoPy window
# Check the return code to see if the script ran successfully
if output.returncode == 0:
print("Script executed successfully.")
print(output.stdout)
else:
print("Script execution failed.")
# Remove fixaxtion cross
fixation.autoDraw = False
win.flip()
# Slide with leaderboard
if cond == "play":
d = pd.read_csv(ACCUMULATED_RESULTS_FILENAME, comment='#')
drivers = d['driver']
errors = d['error']
epoch_times=d['epoch_time']
# get the last element of the leaderboard
avg_err=errors.iloc[-1]
idxs_error= np.argsort(errors)
sorted_errors=errors[idxs_error]
sorted_drivers=drivers[idxs_error]
sorted_epoch_times=epoch_times[idxs_error]
rank=np.searchsorted(sorted_errors.to_numpy(),avg_err)+1
# Slide intro of each trial
text = visual.TextStim(win=win, text=f"Your error of {avg_err:.3f} ranks you #{rank} out of {len(sorted_errors)}",
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
core.wait(time_slide_outro_trial)
text.autoDraw = False
## REST
if do_rest:
# Slide for the breaks
text = visual.TextStim(win=win, text="Trial " + str(i+1) + "/" + str(nr_trials) + ' has ended.'\
"\n\nYou can rest now for a minute, but please look at the countdown and minimize your movements." + \
"\n\nPress a key on the keyboard to continue!",
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
if defaultKeyboard.getKeys(keyList=["escape"]):
core.quit()
text.autoDraw = False
# Call the countdown_timer function
countdown_timer(countdown_duration, win)
leaderboard_text='Leaderboard (Rank-Driver-Error-When)\n\n'
top10_counter=1
for d,e,t in zip(sorted_drivers,sorted_errors,sorted_epoch_times):
datetime_obj = datetime.utcfromtimestamp(t)
when=datetime_obj.strftime('%Y-%m-%d %H:%M')
txt=f'{top10_counter}\t\t{d}\t\t{e:.3f}\t\t\t{when}'
leaderboard_text+=txt+'\n'
top10_counter+=1
if top10_counter>10:
break
### LEADERBOARD
text = visual.TextStim(win=win, text=leaderboard_text + \
"\n\nThank you for your participation!",
color="white",
contrast=contrast,
wrapWidth=max(win.size)/ratio_text_width,
height= max(win.size)/ratio_text_size)
text.autoDraw = True
win.flip()
event.waitKeys()
text.autoDraw = False
win.close()