-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_recorder.py
More file actions
385 lines (286 loc) · 13.8 KB
/
functions_recorder.py
File metadata and controls
385 lines (286 loc) · 13.8 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
import matplotlib
matplotlib.use('TkAgg')
from pypixxlib.propixx import PROPixxCTRL, PROPixx
import numpy as np
import time
import matplotlib.pyplot as plt
import pypixxlib._libdpx as libd
import keyboard
from datetime import timedelta
import csv
import os.path
from functions_osc import create_server
import paths
def initialize_projector():
"""Initialize the projector controller"""
# get the device object for the controller
my_device = PROPixxCTRL()
# enable pixel mode
libd.DPxEnableDoutPixelMode()
return my_device
# libd.DPxDisableDoutPixelMode()
# libd.DPxSetMarker()
# libd.DPxWriteRegCacheAfterVideoSync()
def record_inputs_frames(my_device, number_frames):
"""Record a given number of samples from the Propixx controller to a list"""
# allocate a list to store the frames
frame_list = []
t_start = time.time()
my_device.updateRegisterCache()
# for several frames
for frames in np.arange(number_frames):
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
proj_trigger = din_state & 2**10
bonsai_trigger = din_state & 2**4
miniscope_trigger = din_state & 2**6
optitrack_trigger = din_state & 2**2
t = time.time() - t_start
frame_list.append([t, proj_trigger, bonsai_trigger, miniscope_trigger, optitrack_trigger])
# turn the list into an array
frame_list = np.array(frame_list)
return frame_list
def record_inputs_key(my_device):
"""Record sync data on a list until escape is pressed"""
# allocate a list to store the frames
frame_list = []
t_start = time.time()
my_device.updateRegisterCache()
# for several frames
while True:
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
proj_trigger = (din_state & 2**10 + 1)/(2**10 + 1)
bonsai_trigger = (din_state & 2**4 + 1)/(2**4 + 1)
miniscope_trigger = (din_state & 2**6 + 1)/(2**6 + 1)
optitrack_trigger = (din_state & 2**2 + 1)/(2**2 + 1)
t = time.time() - t_start
frame_list.append([t, proj_trigger, bonsai_trigger, miniscope_trigger, optitrack_trigger])
if keyboard.is_pressed('Escape'):
break
# turn the list into an array
frame_list = np.array(frame_list)
return frame_list
def record_vr_trial_experiment(session, my_device, path_in, name_in, exp_type):
"""Handle the trial communication structure and write the sync data to a text file"""
# define the file to save the path to
file_name = os.path.join(path_in, name_in + "_sync" + exp_type + '_suffix.csv')
my_device.updateRegisterCache()
# launch OSC server with Unity
unity_osc = create_server()
# Create thread/socket to listen
unity_sock = unity_osc.listen(address=paths.unity_ip, port=paths.unity_out_port, default=True)
# Triggers a callback to the 'unity_ready' function
unity_osc.bind(b'/UnityReady', session.unity_ready, sock=unity_sock)
# Triggers a callback to the 'received_trial' function
unity_osc.bind(b'/TrialReceived', session.received_trial, sock=unity_sock)
# The EndTrial message triggers a callback to the 'end_trial' function
unity_osc.bind(b'/EndTrial', session.end_trial, sock=unity_sock)
my_device.updateRegisterCache()
# Send the setup instructions to Unity
print('Setting up experiment...')
setup_message = session.assemble_setup_message()
unity_osc.simple_send(b'/SetupExperiment', setup_message, paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# open the file
with open(file_name, mode='w') as f:
# initialize the writer
f_writer = csv.writer(f, delimiter=',')
t_start = time.time()
# for several frames
while session.in_experiment:
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
proj_trigger = (din_state & 2 ** 10 + 1) / (2 ** 10 + 1)
bonsai_trigger = (din_state & 2 ** 4 + 1) / (2 ** 4 + 1)
optitrack_trigger = (din_state & 2 ** 6 + 1) / (2 ** 6 + 1)
miniscope_trigger = (din_state & 2 ** 2 + 1) / (2 ** 2 + 1)
t = time.time() - t_start
# write to the file
f_writer.writerow([t, proj_trigger, bonsai_trigger, optitrack_trigger, miniscope_trigger])
if session.ready:
if not session.is_started:
# Send a message to unity to begin the session
print('Starting session...\n')
unity_osc.simple_send(b'/SessionStart', [""], paths.unity_ip, paths.unity_in_port, sock=unity_sock)
session.is_started = True
# Process the OSC communication - trial structure is handled by Unity
if session.setup_trial:
# Reset setup trial bool
session.setup_trial = False
# Generate a message to be sent via OSC client
message = session.assemble_trial_message()
# Send trial string to Unity
print('Trial {} sent'.format(message[0]))
print(message)
unity_osc.simple_send(b'/SetupTrial', message, paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# Received OSC messages are automatically picked up by a separate thread
# session.end_trial is called buy the OSC listener automatically. It increments to the next trial
# and resets the session.start_trial boolean
if keyboard.is_pressed('Escape'):
break
unity_osc.stop_all()
unity_osc.terminate_server()
return 'Total duration: ' + str(timedelta(seconds=(time.time() - t_start))), file_name
def record_vr_screen_experiment(session, my_device, path_in, name_in, exp_type):
"""Handle the trial communication structure and write the sync data to a text file"""
# launch OSC server with Unity
unity_osc = create_server()
# Create thread/socket to listen
unity_sock = unity_osc.listen(address=paths.unity_ip, port=paths.unity_out_port, default=True)
# Triggers a callback to the 'unity_ready' function
unity_osc.bind(b'/UnityReady', session.unity_ready, sock=unity_sock)
# Triggers a callback to the 'received_trial' function
unity_osc.bind(b'/TrialReceived', session.received_trial, sock=unity_sock)
# The EndTrial message triggers a callback to the 'end_trial' function
unity_osc.bind(b'/EndTrial', session.end_trial, sock=unity_sock)
# allocate a list to store the frames
# frame_list = []
my_device.updateRegisterCache()
# define the file to save the path to
file_name = os.path.join(path_in, name_in + "_sync" + exp_type + '_suffix.csv')
# Send the setup instructions to Unity
print('Setting up experiment...')
setup_message = session.assemble_setup_message()
unity_osc.simple_send(b'/SetupExperiment', setup_message, paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# Send a message to unity to begin the setup sequence
unity_osc.simple_send(b'/SessionStart', "", paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# open the file
with open(file_name, mode='w') as f:
# initialize the writer
f_writer = csv.writer(f, delimiter=',')
t_start = time.time()
# for several frames
while session.in_experiment:
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
proj_trigger = (din_state & 2 ** 10 + 1) / (2 ** 10 + 1)
bonsai_trigger = (din_state & 2 ** 4 + 1) / (2 ** 4 + 1)
optitrack_trigger = (din_state & 2 ** 6 + 1) / (2 ** 6 + 1)
miniscope_trigger = (din_state & 2 ** 2 + 1) / (2 ** 2 + 1)
t = time.time() - t_start
# write to the file
f_writer.writerow([t, proj_trigger, bonsai_trigger, optitrack_trigger, miniscope_trigger])
if session.ready:
if not session.is_started:
# Send a message to unity to begin the session
print('Starting session...\n')
unity_osc.simple_send(b'/SessionStart', [""], paths.unity_ip, paths.unity_in_port, sock=unity_sock)
session.is_started = True
# Process the trial structure
if not session.in_trial:
session.check_ISI()
if session.start_trial:
# Mark that we are in a trial
session.in_trial = True
# Reset start trial bool
session.start_trial = False
# Generate a message to be sent via OSC client
message = session.assemble_trial_message()
print(message)
# Send trial string to Unity
print('Trial {} started'.format(message[0]))
unity_osc.simple_send(b'/TrialStart', message, paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# Received OSC messages are automatically picked up by a separate thread
if keyboard.is_pressed('Escape'):
break
unity_osc.stop_all()
unity_osc.terminate_server()
return 'Total duration: ' + str(timedelta(seconds=(time.time() - t_start))), file_name
def record_vr_rig(session, my_device, path_in, name_in, exp_type):
"""Write the sync data to a text file"""
# allocate a list to store the frames
# frame_list = []
my_device.updateRegisterCache()
# define the file to save the path to
# file_name = os.path.join(path_in, datetime.now().strftime("%d_%m_%Y_%H_%M_%S") + '_syncVR.csv')
file_name = os.path.join(path_in, name_in + "_sync" + exp_type + '_suffix.csv')
# launch OSC server with Unity
unity_osc = create_server()
# Create thread/socket to listen
unity_sock = unity_osc.listen(address=paths.unity_ip, port=paths.unity_out_port, default=True)
# Triggers a callback to the 'unity_ready' function
unity_osc.bind(b'/UnityReady', session.unity_ready, sock=unity_sock)
my_device.updateRegisterCache()
# Send the setup instructions to Unity
print('Setting up experiment...')
unity_osc.simple_send(b'/SetupExperiment', [""], paths.unity_ip, paths.unity_in_port, sock=unity_sock)
# open the file
with open(file_name, mode='w') as f:
# initialize the writer
f_writer = csv.writer(f, delimiter=',')
t_start = time.time()
# for several frames
while session.in_experiment:
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
proj_trigger = (din_state & 2**10 + 1)/(2**10 + 1)
bonsai_trigger = (din_state & 2**4 + 1)/(2**4 + 1)
optitrack_trigger = (din_state & 2**6 + 1)/(2**6 + 1)
miniscope_trigger = (din_state & 2**2 + 1)/(2**2 + 1)
t = time.time() - t_start
# write to the file
f_writer.writerow([t, proj_trigger, bonsai_trigger, optitrack_trigger, miniscope_trigger])
if session.ready:
if not session.is_started:
# Send a message to unity to begin the session
print('Starting session...\n')
unity_osc.simple_send(b'/SessionStart', [""], paths.unity_ip, paths.unity_in_port, sock=unity_sock)
session.is_started = True
if keyboard.is_pressed('Escape'):
break
unity_osc.stop_all()
unity_osc.terminate_server()
return 'Total duration: ' + str(time.time() - t_start), file_name
def record_miniscope_rig(my_device, path_in, name_in):
"""Write the sync data to a text file"""
# allocate a list to store the frames
# frame_list = []
t_start = time.time()
my_device.updateRegisterCache()
# define the file to save the path to
# file_name = os.path.join(path_in, datetime.now().strftime("%d_%m_%Y_%H_%M_%S") + '_syncMini.csv')
file_name = os.path.join(path_in, name_in + '_syncMini_suffix.csv')
# open the file
with open(file_name, mode='w') as f:
# initialize the writer
f_writer = csv.writer(f, delimiter=',')
# for several frames
while True:
my_device.updateRegisterCache()
din_state = my_device.din.getValue()
miniscope_trigger = (din_state & 2**2 + 1)/(2**2 + 1)
bonsai2_trigger = (din_state & 2**8 + 1)/(2**8 + 1)
t = time.time() - t_start
# write to the file
f_writer.writerow([t, miniscope_trigger, bonsai2_trigger])
if keyboard.is_pressed('Escape'):
break
return 'Total duration: ' + str(time.time() - t_start), file_name
def plot_inputs_vr(frame_list):
"""Plot the sync data"""
fig = plt.figure()
ax = fig.add_subplot(111)
ax1, = ax.plot(frame_list[:, 0], frame_list[:, 1], marker='o')
ax2, = ax.plot(frame_list[:, 0], frame_list[:, 2] + 2, marker='o')
ax3, = ax.plot(frame_list[:, 0], frame_list[:, 3] + 4, marker='o')
ax4, = ax.plot(frame_list[:, 0], frame_list[:, 4] + 6, marker='o')
ax.legend((ax1, ax2, ax3, ax4), ('Projector', 'Bonsai', 'Optitrack', 'Miniscope'))
plt.show()
# calculate frame rates
# for all the signals
# for signal in np.arange(5):
# print()
def plot_inputs_miniscope(frame_list):
"""Plot the sync data"""
fig = plt.figure()
ax = fig.add_subplot(111)
ax1, = ax.plot(frame_list[:, 0], frame_list[:, 1], marker='o')
ax2, = ax.plot(frame_list[:, 0], frame_list[:, 2] + 2, marker='o')
ax.legend((ax1, ax2), ('Miniscope', 'Bonsai'))
plt.show()
def load_csv(path):
"""Load csv data from a file path"""
with open(path) as f:
csv_reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)
frame_list = [row for row in csv_reader]
return np.array(frame_list)