-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_data_1.py
More file actions
2375 lines (1664 loc) · 112 KB
/
process_data_1.py
File metadata and controls
2375 lines (1664 loc) · 112 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
import os
import pandas as pd
import numpy as np
from copy import deepcopy
import sys
import bz2
import pickle
import _pickle as cPickle
from tqdm import tqdm
import seaborn as sns
import math
# import cateyes as ce
import json
from scipy.signal import medfilt
from scipy import stats
from scipy.interpolate import interp1d
from matplotlib import pyplot as plt
import warnings
import numbers
import logging
logger = logging.getLogger(__name__)
# These lines allow me to see logging.info messages in my jupyter cell output
logger.handlers.clear() # clear from history
logger.addHandler(logging.StreamHandler(stream=sys.stdout))
logger.setLevel(logging.DEBUG)
plt.style.use('ggplot')
#os.chdir('Documents\GitHub\Driving-Sim-Analysis') # change directory to path desired other error will throw that it can't find default analysis json file
os.chdir(r'/Users/ariannagiguere/Documents/GitHub/Driving-Sim-Analysis')
class subject_data():
def __init__(self, subject_data_folder,
cbPatient = False, analyze_gaze = False,
offset_car_xz = False,
analysis_parameters_file = 'default_analysis_parameters.json',
use_cached_data = False,
gaze_contingent=False,
estimate_head_trackers = False,
session_num='S001'):
self.analysis_parameters = json.load(open(analysis_parameters_file))
self.sub_id = os.path.split(subject_data_folder)[-1]
self.cbPatient = cbPatient
self.data_parent_folder = os.path.split(subject_data_folder)[:-1][0]
self.data_folder = subject_data_folder
self.analyze_gaze = analyze_gaze
self.raw_gaze_data = False
self.gaze_contingent = gaze_contingent
self.session_num = session_num
self.estimate_head_trackers = estimate_head_trackers
#self.update_tracker_directories_using_ppid(subject_folder)
self.experiment_settings = False # Making the attribute known
self.read_experiment_settings_from_file() # self.experiment_settings is now set
self.experiment_settings['figure_out_folder'] = self.get_figure_out_folder('figs')
self.experiment_settings['analyze_gaze'] = analyze_gaze
self.results = False
self.resultsLeft = False # placeholders for data of CB patients separated by turn
self.resultsRight = False
self.time_series_results = False
self.has_gaze_in_head = False
self.has_head_pose = False
self.pickle_dir = 'pickled_data'
if self.session_num != 'S001':
self.pickle_path = os.path.join(self.pickle_dir, f'{self.sub_id}_{self.session_num}_pickle_dict.pbz2')
if estimate_head_trackers:
self.pickle_path = os.path.join(self.pickle_dir, f'{self.sub_id}_{self.session_num}_pickle_dict_estimate_head_track.pbz2')
else:
self.pickle_path = os.path.join(self.pickle_dir, f'{self.sub_id}_pickle_dict.pbz2')
if estimate_head_trackers:
self.pickle_path = os.path.join(self.pickle_dir, f'{self.sub_id}_pickle_dict_estimate_head_track.pbz2')
if os.path.isdir(self.pickle_dir) is False:
os.makedirs(self.pickle_dir)
self.trial_dict = False
self.use_cached_data = use_cached_data
if use_cached_data:
f = bz2.BZ2File(self.pickle_path, "rb")
print('self.pickle_path: ',self.pickle_path)
pickle_dict = cPickle.load(f)
f.close()
self.trial_dict = pickle_dict['trial_dict']
# self.analysis_parameters = pickle_dict['analysis_parameters']
self.results = pickle_dict['results']
self.has_gaze_in_head = pickle_dict['has_gaze_in_head']
self.has_head_pose = pickle_dict['has_head_pose']
else:
self.read_trial_results_from_file()
if '_cyclopeangaze_headPositionTracker_location_0' in self.results.columns:
row = self.results.iloc[0]
head_tracker_path = row['_cyclopeangaze_headPositionTracker_location_0'].split('/')[2:]
t1_path = os.path.join(self.data_parent_folder, row['ppid'],*head_tracker_path)
# replace "tracker" folder with "estimated_head_trackers" folder if using estimated head trackers
if self.estimate_head_trackers:
t1_path = t1_path.replace('trackers', 'estimated_head_trackers')
head_tracker_df = pd.read_csv(t1_path)
# Some subs have head tackers that lack a head pose matrix
if len(head_tracker_df.iloc[0].filter(regex='4x4')) > 0:
self.has_head_pose = True
if analyze_gaze:
# self.import_raw_gaze_data() returns false if not found
self.raw_gaze_data = self.import_raw_gaze_data()
else:
self.raw_gaze_data = None
if type(self.raw_gaze_data) is pd.DataFrame:
self.has_gaze_in_head = True
else:
self.has_gaze_in_head = False
if 'divergence' in self.results.columns:
self.results = self.results.drop(['divergence'], axis=1)
if offset_car_xz:
logger.info('Adding car xz offset ' + str(offset_car_xz) + ' for ' + self.sub_id)
self.experiment_settings['offset_car_xz'] = offset_car_xz
else:
self.experiment_settings['offset_car_xz'] = None
#self.calc_divergence_for_all_trials() # necessary to update after changing position
self.results.reset_index(drop=True)
def get_pl_export_folder(self, session):
session_parent_folder = os.path.join(self.data_folder, session, 'PupilData')
session_exports_folder_list = []
[session_exports_folder_list.append(name) for name in os.listdir(session_parent_folder) if name[0] != '.'];
indices = [int(element) for element in session_exports_folder_list]
newest_index = np.argmax(indices)
pupil_session_string = session_exports_folder_list[newest_index]
if not 'exports' in os.listdir(os.path.join(session_parent_folder, pupil_session_string)):
logger.info('\nNo export folder found in Pupil Labs session folder. No gaze data imported.')
return False
exports_parent_folder = os.path.join(session_parent_folder, pupil_session_string, 'exports')
exports_folder_list = []
[exports_folder_list.append(name) for name in os.listdir(exports_parent_folder) if name[0] != '.'];
if len(exports_folder_list) == 0:
logger.info('\nNo subfolder found in found in Pupil Labs Export folder. No gaze data imported.')
return False
indices = [int(element) for element in exports_folder_list]
newest_index = np.argmax(indices)
exports_folder_path = os.path.join(exports_parent_folder, exports_folder_list[newest_index])
print('Export path for PL data: ', exports_folder_path)
return exports_folder_path
def import_raw_gaze_data(self):
'''
:param pupil_session_idx: the index of the pupil session to use with respect to the list of folders in the
# session directoy. Typically, these start at 000 and go up from there.
:return: gaze positions
'''
def return_gaze_path(session):
exports_folder = self.get_pl_export_folder(session)
if exports_folder == False:
self.raw_gaze_data = False
return False
else: return os.path.join(exports_folder, 'gaze_positions.csv')
pupil_gazepositions_filepath = return_gaze_path(self.session_num)
if pupil_gazepositions_filepath == False: # skip gaze data if exports doesn't exists
return False
# Defaults to the most recent pupil export folder (highest number)
gaze_positions = pd.read_csv(pupil_gazepositions_filepath)
if os.path.exists(os.path.join(self.data_folder, 'S002', 'PupilData')):
pupil_gazepositions_filepath = return_gaze_path('S002')
if pupil_gazepositions_filepath != False:
new_gaze_positions = pd.read_csv(pupil_gazepositions_filepath)
gaze_positions = pd.concat((gaze_positions, new_gaze_positions), axis=0)
return gaze_positions
def get_gaze_data_slice(self, start_time, end_time):
# right now this only works if there is one exports file otherwise it throws a bool error
firstIdx = list(map(lambda i: i > start_time, self.raw_gaze_data['gaze_timestamp'])).index(True)
try:
lastIdx = list(map(lambda i: i > end_time, self.raw_gaze_data['gaze_timestamp'])).index(True)
except:
end_time = self.raw_gaze_data['gaze_timestamp'].values[-1]
lastIdx = list(map(lambda i: i >= end_time, self.raw_gaze_data['gaze_timestamp'])).index(True)
slice_of_data = self.raw_gaze_data.iloc[firstIdx:lastIdx + 1] # changed this to work for double session data -AG
return slice_of_data
def separate_calibration_trials(self):
self.calibration_trial_results = self.results.loc[self.results['trialType'] == 'CalibrationAssessment']
self.results = self.results.loc[self.results['trialType'] != 'CalibrationAssessment'] # now results will not have calibration trials
def get_figure_out_folder(self, subfolder):
# creates the dir subfolder/subID
# make directory to save figures
savePlotsPath = os.path.join(subfolder, self.sub_id)
if os.path.isdir(savePlotsPath):
pass
else:
os.makedirs(savePlotsPath)
return savePlotsPath
def update_tracker_directories_using_ppid(self, subject_folder):
'''
Update tracker directories in self.results.
'''
# make filename the ppid
self.results['ppid'] = subject_folder
list_carTransform_split = [verts.split('/') for verts in self.results['simplecar_carTransformMatrix_location_0']]
list_roadVerts_split = [verts.split('/') for verts in self.results['road_vertices_location_0']]
list_roadTransform_split = [verts.split('/') for verts in self.results['roadTransformMat_location_0']]
if '_cyclopeangaze_headPositionTracker_location_0' in self.results.columns:
list_headTransform_split = [verts.split('/') for verts in self.results['_cyclopeangaze_headPositionTracker_location_0']]
trackers = [list_carTransform_split, list_roadVerts_split, list_roadTransform_split, list_headTransform_split]
else:
trackers = [list_carTransform_split, list_roadVerts_split, list_roadTransform_split]
# takes care of case where ppid is changed after data collection
for tracker_list in trackers:
for i in range(len(tracker_list)):
tracker_list[i][2] = 'S00' + str(self.results['session_num'].iloc[i])
#print(tracker_list[i][-1])#[-7:-4])
trial_num = str(self.results['trial_num'].iloc[i])
if len(trial_num) == 2:
trial_num = '0' + trial_num
if len(trial_num) == 1:
trial_num = '00' + trial_num
tracker_list[i][-1] = tracker_list[i][-1].replace(tracker_list[i][-1][-7:-4], trial_num)
filepaths = []
for tracker_list in trackers:
filepaths.append([os.path.join('carSettings',*row[1:]).replace('\\','/') for row in tracker_list])
self.results['simplecar_carTransformMatrix_location_0'] = filepaths[0]
self.results['road_vertices_location_0'] = filepaths[1]
self.results['roadTransformMat_location_0'] = filepaths[2]
if '_cyclopeangaze_headPositionTracker_location_0' in self.results.columns:
self.results['_cyclopeangaze_headPositionTracker_location_0'] = filepaths[3]
def read_experiment_settings_from_file(self):
settings_path = os.path.join(self.data_folder, self.session_num, 'session_info', 'settings.json')
with open(settings_path) as json_data:
self.experiment_settings = json.load(json_data)
def read_trial_results_from_file(self):
trial_data_path = os.path.join(self.data_folder, self.session_num)
self.results = pd.read_csv(os.path.join(trial_data_path, 'trial_results.csv'))
if 'trialType' not in self.results.columns:
# add trial type column to avoid throwing error
self.results.loc[:,'trialType'] = np.nan
self.separate_calibration_trials()
self.update_tracker_directories_using_ppid(subject_folder=self.sub_id) # this fixes naming and trackers in case name was changed after data collection
# drop any rows that have nans in trial results (reset trials) and report number
num_reset_trials = len(self.results['turn_direction'].dropna()) - len(self.results['turn_direction'])
if num_reset_trials != 0:
indices_wo_nans = np.where(self.results['turn_direction'].notnull())[0]
self.results = self.results.iloc[indices_wo_nans, :]
print('Number of off-road reset trials for participant ' + self.sub_id + ': ' + str(abs(num_reset_trials)))
# this is where we could change self.results to have only left or right turns
# we want to run through everything twice, with all left, then all right turns
if self.cbPatient == True:
gb = self.results.groupby('turn_direction')
groups = [gb.get_group(x) for x in gb.groups]
if groups[0]['turn_direction'].iloc[0] == 'left':
self.resultsLeft, self.resultsRight = groups[0].copy(), groups[1].copy()
else:
self.resultsRight, self.resultsLeft = groups[0].copy(), groups[1].copy()
if os.path.isdir(os.path.join(self.experiment_settings['figure_out_folder'], 'LEFT')): # folders to save plots separately
pass
else:
os.makedirs(os.path.join(self.experiment_settings['figure_out_folder'],'LEFT'))
os.makedirs(os.path.join(self.experiment_settings['figure_out_folder'],'RIGHT'))
if 'trialType' not in self.resultsLeft.columns:
self.resultsLeft.loc[:,'trialType'] = np.nan
self.resultsRight.loc[:,'trialType'] = np.nan
def get_trial_from_results(self, trial_results_row_in, analyze_gaze = False):
'''
in: a row from the subject trial dataframe (e.g. sub_all_trial_data)
out: a trial_data object
Useful when iterating over rows in the dataframe to compute new variables
'''
if self.use_cached_data:
trial = self.trial_dict[trial_results_row_in.trial_num]
trial.subject_data = self
return trial
# return trial_data(trial_results_row_in, self.experiment_settings, self.data_folder)
return trial_data(trial_results_row_in, self, analyze_gaze)
def get_trial_from_index(self, trial_index, analyze_gaze = False):
'''
in: an index to a row from the subject trial dataframe (e.g. sub_all_trial_data)
out: a trial_data object
Useful when iterating over rows in the dataframe to compute new variables
'''
if self.use_cached_data:
trial = self.trial_dict[self.results.iloc[trial_index].trial_num]
trial.subject_data = self
return trial
return trial_data(self.results.iloc[trial_index], self, analyze_gaze)
def plot_car_trajectory_all_trials(self, plot_gaze_data=False):
logger.info('Plotting all car trajectories for ' + self.sub_id)
# Plot car trajectory
for trialIndex, trial_results_row in self.results.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
if a_trial.results['trialType'] != 'CalibrationAssessment':
a_trial.plot_car_trajectory(showFig=False, saveFig=True, flip_left_turns=True, saveFolder=a_trial.results['turn_direction'],plot_gaze_data=plot_gaze_data)
def plot_mean_car_trajectory(self,
trial_results_slice,
showFig=True,
saveFig=True,
interp_time_seconds = 5,
interp_res_seconds = (1 / 90),
saveFolder = ''):
interp_car_x_list = []
interp_car_z_list = []
for trialIndex, trial_results_row in trial_results_slice.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
(interp_timestamps, interp_car_x, interp_car_z) = a_trial.interpolate_car_pos_roadspace(interp_time_seconds=5, \
interp_res_seconds=(
1 / 90),
flip_left_turns=True)
interp_car_x_list.append(interp_car_x)
interp_car_z_list.append(interp_car_z)
mean_car_x = np.mean(interp_car_x_list, 0)
mean_car_z = np.mean(interp_car_z_list, 0)
plt.ioff() # prevents the fig from showing if in notebook mode
plt.figure(figsize=(8, 8))
ax = plt.subplot()
# Load the first trial to get the road trajectory
a_trial = self.get_trial_from_results(trial_results_slice.iloc[0])
a_trial.plot_road(ax, flip_left_turns=True)
for rowIdx in np.arange((np.shape(interp_car_x_list)[0])):
ax.plot(interp_car_x_list[rowIdx], interp_car_z_list[rowIdx], 'k', linewidth=0.5)
ax.plot(mean_car_x, mean_car_z, 'r', linewidth=1.5)
ax.plot(mean_car_x[0], mean_car_z[0], 'o')
ax.text(.5, .5, self.sub_id + '\n' + \
'Density: ' + str(a_trial.results['contrast']) + '\n' + \
'Radius: ' + str(a_trial.results['turn_radius']), \
horizontalalignment='center', \
verticalalignment='center', transform=ax.transAxes, fontsize=15)
ax.set_xlabel('Horizontal Distance (m)')
ax.set_ylabel('Vertical Distance (m)')
ax.axis("equal") # sets the x/y axes scales equal
plt.ion() # prevents the fig from showing if in notebook mode
if saveFig:
plotFigSubPath = os.path.join(self.experiment_settings['figure_out_folder'], saveFolder, 'mean_trajectories')
fig_name = 'mean_trajectory_' + 'D-' + str(a_trial.results['contrast']) + '_R-' + str(
a_trial.results['turn_radius'])
if os.path.isdir(plotFigSubPath) is False:
os.makedirs(plotFigSubPath)
plt.savefig(os.path.join(plotFigSubPath, fig_name + '.png'))
if showFig:
plt.show()
else:
plt.close()
def plot_time_vs_steer_bias_all_trials(self, time_start=0, interp_time_seconds=7.37, interp_res_seconds=(1 / 90), saveFolder='', turn_dir=None, collapse_across_OF=False, showFig=False, saveFig=False):
'''
By default this function returns a figures with subplots for all radii. If you only want
a figure with one radius, pass it data that has one radius only.
'''
logger.info('Plotting time vs. steering bias for ' + self.sub_id)
gb = self.results.groupby(['turn_direction'])
if turn_dir == 'left':
data = gb.get_group('left')
elif turn_dir == 'right':
data = gb.get_group('right')
else: data = self.results
placeholder_df = pd.DataFrame()
for group_key, trial_results_slice in data.groupby(['turn_radius']):
self.time_series_results = pd.DataFrame() # clear out data frame
for row_idx, row in trial_results_slice.iterrows(): # have to group by contrast after
a_trial = self.get_trial_from_results(row)
a_trial.plot_time_vs_steer_bias(showFig=False, saveFig=False, interp_time_seconds=interp_time_seconds)
# average over radii and set placeholder df
copy = self.time_series_results.copy(deep=True)
copy = copy.groupby(by=copy.columns,axis=1).mean()
copy.loc[:,'turn_radius'] = group_key[0]
placeholder_df = pd.concat((placeholder_df, copy))
self.time_series_results = placeholder_df.copy(deep=True)
if saveFig or showFig:
str_graph_title = 'Effect of Optic Flow on Steering Bias over Time \nParticipant ' + str(self.results['ppid'].values[0])
mean_time_series_df = self.time_series_results.groupby(by=self.time_series_results.columns, axis=1).apply(lambda g: g.mean(axis=1) if isinstance(g.iloc[0,0], numbers.Number) else g.iloc[:,0])
radiusList = np.unique(np.array(mean_time_series_df['turn_radius'].values,dtype=np.float64))
# plots the steering bias over time
idx = 0
fontsize=14
fig, ax = plt.subplots(1, 3, figsize=(14,6))
plt.suptitle(str_graph_title, fontsize=fontsize+2)
colors = sns.color_palette("bright")
optic_flow_density = ['Low', 'Medium', 'High']
for group_key, slices in mean_time_series_df.groupby(['turn_radius']):
# finding only divergence by optic flow columns
cols = np.array(slices.columns)
index_chop_at_ppid = slices.columns.get_loc('turn_radius')
cols = cols[1:index_chop_at_ppid]
optic_flow_lvs = []
for i in range(len(cols)):
optic_flow_lvs.append(cols[i][-3:])
plt.ioff()
if collapse_across_OF:
x = slices.iloc[:,1:len(cols)+1].mean(axis=1)
y = slices['interp_timestamps']
ax[idx].plot(x, y, linewidth=1.5, color='r') #label=optic_flow_lvs[contrast-1]) # get just density from title
else:
for contrast in range(1, len(cols)+1):
x = slices.iloc[:,contrast]
y = slices['interp_timestamps']
ax[idx].plot(x, y, linewidth=1.5, label=optic_flow_density[contrast-1], color=colors[contrast-1]) #label=optic_flow_lvs[contrast-1]) # get just density from title
ax[idx].axvline(x=2, ls = '--', color='k') # plots vertical dotted line
ax[idx].set_ylabel('Time (sec)', fontsize=fontsize)
ax[idx].set_xlabel('Distance to Inner Road Edge (m)', fontsize=fontsize)
ax[idx].set_xlim(-0.2, 4.2)
ax[idx].set_ylim(time_start, interp_time_seconds)
ax[idx].vlines(x=0,ymin=np.min(y), ymax=np.max(y), color='k')
ax[idx].vlines(x=4,ymin=np.min(y), ymax=np.max(y), color='k')
ax[idx].set_title('Radius: ' + str(radiusList[idx]) + 'm', fontsize=fontsize)
if idx == 1:
ax[idx].legend(title='Flow Density',fontsize='large', title_fontsize='large', loc='lower right')
idx = idx + 1
plt.tight_layout()
if saveFig:
save_path = str_graph_title.split(',')[0].replace(' ','-') + '-Time-' + str(time_start) + 'to' + str(interp_time_seconds) + '(s)'
if collapse_across_OF:
save_path = save_path + '-CollapseAcrossOF'
plt.savefig(os.path.join(save_path.replace('\n', '') + '.png'), dpi = 300)
print('File saved at: ', os.path.join(save_path.replace('\n', '') + '.png'))
if showFig:
plt.show()
else:
plt.close()
def plot_mean_trajectory_for_all_conditions(self, showFig=False, interp_time_seconds=5, interp_res_seconds=(1 / 90),saveFolder='', turn_dir=None):
logger.info('Plotting mean car trajectories for ' + self.sub_id)
gb = self.results.groupby(['turn_direction'])
if turn_dir == 'left':
data = gb.get_group('left')
elif turn_dir == 'right':
data = gb.get_group('right')
else: data = self.results
for group_key, trial_results_slice in data.groupby(['contrast', 'turn_radius']):
self.plot_mean_car_trajectory(trial_results_slice, showFig=False, interp_time_seconds=interp_time_seconds,
interp_res_seconds=(1 / 90),saveFolder=saveFolder)
def calc_divergence_for_all_trials(self):
self.calc_divergence_over_segment_for_all_trials(start_percent=0, end_percent=100)
def calc_divergence_over_segment_for_all_trials(self, start_percent = 0, end_percent = 100):
logger.info('Calculating divergence for ' + self.sub_id)
# lists that will be n trials long
mean_div = []
mean_abs_div = []
mean_div_from_inner_road_edge = []
if start_percent == 0 and end_percent == 100:
label_suffix = ''
else:
label_suffix = '_' + str(start_percent) + '_' + str(end_percent)
# Calculate mean divergence from road center
for trialIndex, trial_results_row in self.results.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
a_trial.calc_mean_divergence_over_segment(start_percent=start_percent, end_percent=end_percent)
def calc_mean_gaze_behavior_over_segment_for_all_trials(self, start_percent=0, end_percent=100):
logger.info('Calculating calc_mean_gaze_behavior_over_segment for ' + self.sub_id)
if start_percent == 0 and end_percent == 100:
label_suffix = ''
else:
label_suffix = '_' + str(start_percent) + '_' + str(end_percent)
# Calculate mean divergence from road center
for trialIndex, trial_results_row in self.results.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
a_trial.calc_mean_gaze_behavior_over_segment(start_percent=start_percent, end_percent=end_percent)
def offset_contrast_for_each_radius(self, magnitude=-0.05):
'''
Creates a new column, 'contrasts_offset_by_radius'.
Prevents error bars from overlapping when a values is plotted by contrast (xaxis) and radius (lines)
'''
contrastList = np.array(self.results['contrast'].values, dtype=np.float64)
radiusList = np.array(self.results['turn_radius'].values, dtype=np.float64)
# drop nans from calibration assessment
radiusList = radiusList[~np.isnan(radiusList)]
contrastList = contrastList[~np.isnan(contrastList)]
offsets_rad = [-magnitude, 0, magnitude]
np.linspace(np.mean(contrastList) - magnitude, np.mean(contrastList) + magnitude, len(contrastList))
for count, radiusValue in enumerate(np.unique(radiusList)):
idx = np.where(radiusList == radiusValue)[0]
contrastList[idx] = contrastList[idx] + offsets_rad[count]
nans_for_cal_trials = np.repeat(np.nan, len(np.where(self.results['trialType']=='CalibrationAssessment')[0]))
self.results['contrasts_offset_by_radius'] = np.concatenate((nans_for_cal_trials,contrastList),axis=0)
def plot_for_contrast_x_radius(self, varName, yLabel, showFig=False, saveFig=True, size=(6, 8), saveFolder = '', turn_dir = None):
logger.info('plot_for_contrast_x_radius: Plotting ' + varName + ' for ' + self.sub_id)
if varName not in self.results.columns:
logger.error('plot_for_contrast_x_radius: Variable ' + varName + ' not in <subject_data>.results')
return None
if 'offset_contrast_for_each_radius' not in self.results.columns:
self.offset_contrast_for_each_radius()
plt.ioff()
the_fig = plt.figure(figsize=size)
ax = plt.subplot()
sns.set(style="ticks", rc={"lines.linewidth": 3})
gb = self.results.groupby(['turn_direction'])
if turn_dir == 'left':
data = gb.get_group('left')
elif turn_dir == 'right':
data = gb.get_group('right')
else: data = self.results
sns.lineplot(
data=data, x="contrasts_offset_by_radius", y=varName, hue="turn_radius", err_style="bars",
errorbar=("ci", 95),
palette="bright")
#sns.scatterplot(self.results,x="contrasts_offset_by_radius",y=varName,hue="turn_radius",palette='bright')
# data=self.results, x="contrasts_offset_by_radius", y=varName, hue="turn_radius", err_style="bars")#,
#errorbar=("ci", 95),
#palette="bright"
#)
ax.legend(loc='best', title='Turn Radius')
ax.set_ylabel(yLabel)
ax.set_xlabel('Optic Flow Density')
xticks = np.unique(self.results['contrast'])
ax.set_xticks(xticks[~np.isnan(xticks)])
ax.set_xticklabels(['Zero', 'Low', 'High'])
plt.ion()
if saveFig:
plotFigSubPath = os.path.join(self.experiment_settings['figure_out_folder'], saveFolder)
fig_name = self.sub_id + '_' + varName + '_contrast_x_radius'
if os.path.isdir(plotFigSubPath) is False:
os.makedirs(plotFigSubPath)
plt.savefig(os.path.join(plotFigSubPath, fig_name + '.png'), bbox_inches='tight')
if showFig:
plt.show()
return the_fig
def write_fake_car_data(self):
for trialIndex, trial_results_row in self.results.iterrows():
this_trial = self.get_trial_from_results(trial_results_row)
this_trial.calculate_road_edges()
this_trial.calculate_road_vertices_in_world()
self.data_parent_folder = os.path.join(*os.path.split(self.data_folder)[:-1])
full_path_to_car_data = trial_results_row['simplecar_carTransformMatrix_location_0'].split('/')
fake_data_parent_folder = full_path_to_car_data[1:-1]
car_data_filename = full_path_to_car_data[-1]
###########################################################################
# first, align the car with the left edge of the road
fake_data_parent_folder[-1] = 'fakecartrackers_car_on_left_road_edge'
fake_car_data_parent_folder = os.path.join(self.data_parent_folder,*fake_data_parent_folder)
if os.path.isdir(fake_car_data_parent_folder) is False:
os.makedirs(fake_car_data_parent_folder)
vert_timestamps_linear = np.linspace(this_trial.car_data['time'].iloc[0],
this_trial.car_data['time'].iloc[-1],
len(this_trial.road_vertices));
interp_road_x_world = np.interp(this_trial.car_data['time'],
vert_timestamps_linear,
this_trial.road_vertices['roadedge_left_x_world'])
interp_road_z_world = np.interp(this_trial.car_data['time'],
vert_timestamps_linear,
this_trial.road_vertices['roadedge_left_z_world'])
this_trial.car_data['pos_x'] = interp_road_x_world
this_trial.car_data['pos_z'] = interp_road_z_world
this_trial.car_data['simplecar_4x4_R0C3'] = interp_road_x_world
this_trial.car_data['simplecar_4x4_R2C3'] = interp_road_z_world
this_trial.car_data.to_csv(os.path.join(fake_car_data_parent_folder,car_data_filename))
###########################################################################
# first, align the car with the right edge of the road
fake_data_parent_folder[-1] = 'fakecartrackers_car_on_right_road_edge'
fake_car_data_parent_folder = os.path.join(self.data_parent_folder,*fake_data_parent_folder)
if os.path.isdir(fake_car_data_parent_folder) is False:
os.makedirs(fake_car_data_parent_folder)
this_trial.car_data['pos_x'] = this_trial.road_vertices['roadedge_right_x_world']
this_trial.car_data['pos_z'] = this_trial.road_vertices['roadedge_right_z_world']
this_trial.car_data['simplecar_4x4_R0C3'] = this_trial.road_vertices['roadedge_right_x_world']
this_trial.car_data['simplecar_4x4_R2C3'] = this_trial.road_vertices['roadedge_right_z_world']
this_trial.car_data.to_csv(os.path.join(fake_car_data_parent_folder,car_data_filename))
def calc_s2s_rmse_wheel_angle_for_all_trials(self):
# Plot car trajectory
for trialIndex, trial_results_row in self.results.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
a_trial.calc_rmse()
# # plot the time series of wheel angle
# if trialIndex == 0:
# plt.figure()
# plt.plot(np.array(a_trial.car_data['time']), np.array(a_trial.car_data['wheelAngle']), 'o')
# plt.title('Trial ' + str(trialIndex+1) + ' Wheel Angle vs. Time')
# plt.xlabel('Time (sec)')
# plt.ylabel('Wheel Angle (deg)')
# plt.show()
def calc_mean_gaze_az_rel_car_for_all_trials(self, turn_dir=None):
print(f'Calculating gaze az_rel_car for all trials.')
mean_az_rel_car = []
median_az_rel_car = []
gb = self.results.groupby(['turn_direction'])
if turn_dir == 'left':
data = gb.get_group('left')
elif turn_dir == 'right':
data = gb.get_group('right')
else: data = self.results
# for trialIndex, trial_results_row in data.iterrows():
for trialIndex, trial_results_row in tqdm(self.results.iterrows(), desc="Processing: " + self.sub_id,
unit='trials', total=len(self.results)):
# print(f'Processing: {trialIndex}')
a_trial = self.get_trial_from_results(trial_results_row, analyze_gaze=True)
if not hasattr(a_trial, 'processed_gaze_data'):
print('Processed gaze data not present.')
mean_az_rel_car.append(np.nan)
else:
median_az = np.median(a_trial.processed_gaze_data['gaze_az_rel_car'])
median_az_rel_car.append(median_az)
mean_az = np.mean(a_trial.processed_gaze_data['gaze_az_rel_car'])
mean_az_rel_car.append(mean_az)
# a_trial.results['mean_gaze_az_rel_car'] = mean_az
# a_trial.results['median_gaze_az_rel_car'] = median_az
print(f'Done calculating gaze az_rel_car for all trials.')
# self.results['mean_az_rel_car'] = mean_az_rel_car
# self.results['median_az_rel_car'] = median_az_rel_car
def save_experiment_trials_to_pickle(self, interp_sec = 5):
'''
This does not save any calibration trials to the pickle.
This does not update your subject results file.
That will require checking if the column exists and, if not, updating it.
'''
trial_dict ={}
# for trialIndex, trial_results_row in self.results.iterrows():
for trialIndex, trial_results_row in tqdm(self.results.iterrows(), desc="Processing: " + self.sub_id, unit='trials', total=len(self.results)):
a_trial = self.get_trial_from_results(trial_results_row, analyze_gaze=self.analyze_gaze)
a_trial.interpolate_divergence_roadspace(interp_time_seconds=interp_sec)
a_trial.calc_rmse()
a_trial.subject_data = None
trial_dict[a_trial.results.trial_num] = a_trial
trial_dict['subject_results'] = self.results
trial_dict['time_series_results'] = self.time_series_results
pickle_dict = {'trial_dict': trial_dict,
'analysis_parameters': self.analysis_parameters,
'results': trial_dict['subject_results'],
'experiment_settings': self.experiment_settings,
'has_gaze_in_head': self.has_gaze_in_head,
'has_head_pose': self.has_head_pose
}
with bz2.BZ2File(self.pickle_path, "wb") as f:
cPickle.dump(pickle_dict, f)
def plot_mean_gaze_rel_car(self, saveFig=True, showFig=False, saveFolder='gaze_rel_car'):
from matplotlib.ticker import StrMethodFormatter
plt.ioff() # prevents the fig from showing if in notebook mode
plt.rcParams.update({'font.size': 15})
the_fig, ax = plt.subplots(figsize=(8, 8))
font = {'family': 'sans',
'weight': 'normal',
'size': 15,
}
l_turns = self.results[self.results['turn_direction'] == 'left']
r_turns = self.results[self.results['turn_direction'] == 'right']
h1 = sns.pointplot(data=l_turns, x="contrast", y="mean_gaze_az_rel_car", hue='turn_radius', errorbar='ci',
dodge=0.1)
h2 = sns.pointplot(data=r_turns, x="contrast", y="mean_gaze_az_rel_car", hue='turn_radius', errorbar='ci',
dodge=0.2, linestyles=':')
plt.hlines([0], -10, 10)
plt.ylim(-20, 20)
plt.xlim(-.5, 2.5)
# plt.legend(shadow=True)
# plt.xlabel('o.f. density')
plt.xlabel('flow density', fontdict=font)
plt.ylabel('gaze azimuth relative to car', fontdict=font)
plt.suptitle('left turns (solid lines) and right turns (dotted)', fontdict=font)
ax.yaxis.set_major_formatter(StrMethodFormatter(u"{x:.0f}°"))
ax.set_xticklabels(['only rotational', 'low', 'high'])
sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1), prop=font)
if saveFig:
plotFigSubPath = os.path.join(self.experiment_settings['figure_out_folder'], saveFolder)
fig_name = self.sub_id + '_' 'gaze_rel_car'
if os.path.isdir(plotFigSubPath) is False:
os.makedirs(plotFigSubPath)
plt.savefig(os.path.join(plotFigSubPath, fig_name + '.png'), bbox_inches='tight')
print(os.path.join(plotFigSubPath, fig_name + '.png'))
plt.ion() # prevents the fig from showing if in notebook mode
if showFig:
plt.show()
else:
plt.close()
return the_fig
def gaze_rel_heading_polar_plot(self, saveFig=True, showFig=False, saveFolder='gaze_rel_car'):
plt.rcParams.update({'font.size': 40})
the_fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(12, 12))
ax.set_theta_zero_location("N")
line_style = '-'
for trialIndex, trial_results_row in self.results.iterrows():
a_trial = self.get_trial_from_results(trial_results_row)
plts = a_trial.processed_gaze_data['pupilLabsTimeStamp']
a_trial.processed_gaze_data['pupil_rel_time'] = plts - plts[0]
az_rad = np.deg2rad(a_trial.processed_gaze_data['gaze_az_rel_car_filtered'])
t = a_trial.processed_gaze_data['pupil_rel_time']
if trial_results_row['turn_radius'] == 35:
line_color = 'r'
elif trial_results_row['turn_radius'] == 55:
line_color = 'g'
elif trial_results_row['turn_radius'] == 75:
line_color = 'b'
ax.plot(az_rad, t, ls=line_style, c=line_color, alpha=0.3)
ax.plot([0, 0], [0, 15], ':k', lw=3)
ax.set_rmax(np.max(t))
ax.grid(True)
ax.set_thetamin(-60)
ax.set_thetamax(60)
ax.set_theta_direction(-1)
if saveFig:
plotFigSubPath = os.path.join(self.experiment_settings['figure_out_folder'], saveFolder)
fig_name = self.sub_id + '_' 'gaze_rel_heading_polar'
if os.path.isdir(plotFigSubPath) is False:
os.makedirs(plotFigSubPath)
plt.savefig(os.path.join(plotFigSubPath, fig_name + '.png'), bbox_inches='tight')
print('Generating' + str(os.path.join(plotFigSubPath, fig_name + '.png')))
plt.ion() # prevents the fig from showing if in notebook mode
if showFig:
plt.show()
else:
plt.close()
plt.rcParams.update({'font.size': 15})
return the_fig
def draw_full_roadway(self):
plt.style.use('default')
plt.figure(figsize=(8, 8))
ax = plt.subplot()
ax.axis("equal")
for idx in np.arange(0, len(self.results) - 1):
tr = self.get_trial_from_index(idx)
ax, f_prev, l_prev = tr.draw_road_in_world(ax)
tr2 = self.get_trial_from_index(idx + 1)
ax, f_cur, l_cur = tr2.draw_road_in_world(ax)
ax.plot([f_cur[0], l_prev[0]], [f_cur[1], l_prev[1]], 'k')
ax.plot([f_cur[2], l_prev[2]], [f_cur[3], l_prev[3]], 'k')
plt.tick_params(left=False, right=False, labelleft=False,
labelbottom=False, bottom=False)
plt.axis('off')
plt.grid('off')
fig_name = self.sub_id + '_' '_roadway.png'
plt.savefig(os.path.join(self.experiment_settings['figure_out_folder'], fig_name), bbox_inches='tight', dpi=300,transparent=True)
plt.style.use('ggplot')
class trial_data():
def __init__(self, trial_results_row_in, subject_data, analyze_gaze = False):
self.left_eye_only = False
self.subject_data = subject_data
subject_data_folder = subject_data.data_folder
experiment_settings = subject_data.experiment_settings
self.data_parent_folder = os.path.join(*os.path.split(subject_data_folder)[:-1])
self.data_folder = subject_data_folder
self.results = deepcopy(trial_results_row_in)
self.interpolated_div_and_timestamps = False
# self.results = trial_results_row_in
self.experiment_settings = experiment_settings
# makes path correct, if folder name was changed after data collection
if self.results['trialType'] != 'CalibrationAssessment': # only for non-calibration trial data