-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpupilCorePipeline.py
More file actions
2818 lines (2583 loc) · 153 KB
/
pupilCorePipeline.py
File metadata and controls
2818 lines (2583 loc) · 153 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 sys
import click
import csv
import importlib
import logging
import pickle
from dotenv import load_dotenv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import scipy
@click.command()
@click.option(
"--allow_session_loading",
is_flag=True
)
@click.option(
"--skip_pupil_detection",
is_flag=True
)
@click.option(
"--vanilla_only",
is_flag=True
)
@click.option(
"--skip_vanilla",
is_flag=True
)
@click.option(
"--surpress_runtimewarnings",
is_flag=True
)
@click.option(
"--not_uxf",
is_flag=True
)
@click.option(
"--load_2d_pupils",
is_flag=True
)
@click.option(
"--min_calibration_confidence",
required=False,
type=click.FloatRange(min=0.0, max=1.0),
default=0.0
)
@click.option(
"--show_filtered_out",
is_flag=True
)
@click.option(
"--display_world_video",
is_flag=True
)
@click.option(
"--skip_eye_tracking",
is_flag=True
)
@click.option(
"--load_pandas_checkpoint",
is_flag=True
)
@click.option(
"--skip_trial_assessment",
is_flag=True
)
@click.option(
"--velocity_graphs",
is_flag=True
)
@click.option(
"--core_shared_modules_loc",
required=False,
type=click.Path(exists=True),
envvar="CORE_SHARED_MODULES_LOCATION",
)
@click.option(
"--pipeline_loc",
required=True,
type=click.Path(exists=True),
envvar="PIPELINE_LOC",
)
@click.option(
"--plugins_file",
required=False,
type=click.Path(exists=True),
envvar="PLUGINS_CSV",
)
@click.option(
"--figout_loc",
required=False,
type=click.Path(exists=False),
default="./figOut/"
)
@click.option(
"--allsessiondata_loader",
required=False,
type=click.Path(exists=False),
default="allSessionData.pickle"
)
def main(allow_session_loading, skip_pupil_detection, vanilla_only, skip_vanilla, surpress_runtimewarnings,
not_uxf, load_2d_pupils, min_calibration_confidence, show_filtered_out, display_world_video, skip_eye_tracking,
load_pandas_checkpoint, skip_trial_assessment, velocity_graphs, core_shared_modules_loc, pipeline_loc,
plugins_file, figout_loc, allsessiondata_loader):
logging.getLogger('matplotlib.font_manager').disabled = True
logging.getLogger('matplotlib.axes').disabled = True
plt.set_loglevel(level = 'warning')
if not os.path.exists(figout_loc):
os.makedirs(figout_loc)
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("numexpr").setLevel(logging.WARNING)
logging.getLogger("OpenGL").setLevel(logging.WARNING)
if surpress_runtimewarnings:
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
print(pipeline_loc)
sys.path.append(pipeline_loc)
from core.pipeline import load_intrinsics, available_mapping_methods, patch_plugin_notify_all, calibrate_and_validate, map_pupil_data, save_gaze_data, get_first_realtime_ref_data_timestamp, get_first_ref_data_timestamp, get_last_realtime_ref_data_timestamp, get_last_ref_data_timestamp, load_realtime_ref_data
from core.pupil_detection import perform_pupil_detection
from processAssessmentData import processAllData
if core_shared_modules_loc:
sys.path.append(core_shared_modules_loc)
sys.path.append(os.path.join(core_shared_modules_loc,'pupil_detector_plugins'))
else:
logging.warning("Core source location unknown. Imports might fail.")
if skip_vanilla:
plugins = []
else:
plugins = [None]
if not vanilla_only:
plugins_unpacked = []
with open(plugins_file, newline='') as f:
reader = csv.reader(filter(lambda row: row[0] != '#', f))
plugins_unpacked = list(reader)
for row in plugins_unpacked:
sys.path.append(row[0])
CurrPlugin = getattr(importlib.import_module(row[1]), row[2])
plugins.append(CurrPlugin)
if (not skip_trial_assessment) or (not skip_eye_tracking):
mapping_methods_by_label = available_mapping_methods()
mapping_method_label = click.prompt(
"Choose gaze mapping method",
type=click.Choice(mapping_methods_by_label.keys(), case_sensitive=True),
)
mapping_method = mapping_methods_by_label[mapping_method_label]
patch_plugin_notify_all(mapping_method)
skip_3d_detection = False
if mapping_method_label == "2D":
skip_3d_detection = True
if not skip_eye_tracking:
logging.debug(f"Loaded pupil detector plugins: {plugins}")
total_items = len([item for item in os.listdir("Data/") if item[0:9] == '_Pipeline'])
if total_items == 0:
logging.error("No valid data folders found. Did you make sure to start the data folder names with '_Pipeline'?")
return
i = 0
for name in [item for item in os.listdir("Data/") if item[0:9] == '_Pipeline']:
subject_loc = os.path.join("Data/", name)
rec_loc = os.path.join(subject_loc, '' if not_uxf else 'S001/PupilData/000')
logging.info(f'Proccessing {rec_loc} through pipeline...')
reference_data_loc = rec_loc+'/offline_data/reference_locations.msgpack'
total_plugins = len(plugins)
if not skip_pupil_detection:
logging.info("Performing pupil detection on eye videos. This may take a while.")
j = 0
for plugin in plugins:
j += 1
logging.info(f"---------------[{i*total_plugins + j}/{total_items*total_plugins}]----------------")
logging.info(f"Current plugin: {plugin}")
# Checking to see if we can freeze the model at the first calibration point
realtime_calib_points_loc = rec_loc+'/realtime_calib_points.msgpack';
# --__--__--__--WE ARE FREEZING THE 3D EYE MODELS--__--__--__--
if os.path.exists(realtime_calib_points_loc):
start_model_timestamp = get_first_realtime_ref_data_timestamp(realtime_calib_points_loc)
freeze_model_timestamp = get_last_realtime_ref_data_timestamp(realtime_calib_points_loc)
elif os.path.exists(reference_data_loc):
start_model_timestamp = get_first_ref_data_timestamp(reference_data_loc)
freeze_model_timestamp = get_last_ref_data_timestamp(reference_data_loc)
else:
print("No reference data found, gaze prediction may fail.")
start_model_timestamp = None
freeze_model_timestamp = None
resolution = int(name[14:17])
if resolution == 192:
eye_detector_params = [{
# eye 0 params
"intensity_range": 23,
"pupil_size_min": 10,
"pupil_size_max": 100
}, {
# eye 1 params
"intensity_range": 23,
"pupil_size_min": 10,
"pupil_size_max": 100
}]
elif resolution == 400:
eye_detector_params = [{
# eye 0 params
"intensity_range": 10,
"pupil_size_min": 10,
"pupil_size_max": 100
}, {
# eye 1 params
"intensity_range": 10,
"pupil_size_min": 10,
"pupil_size_max": 100
}]
else:
logging.error('RESOLUTION {} NOT SUPPORTED!'.format(resolution))
exit()
perform_pupil_detection(rec_loc, plugin=plugin, pupil_params=eye_detector_params,
world_file="world.mp4",
load_2d_pupils=load_2d_pupils,
start_model_timestamp=start_model_timestamp,
freeze_model_timestamp=freeze_model_timestamp,
display_world_video=display_world_video,
mapping_method=mapping_method,
skip_3d_detection=skip_3d_detection
)
logging.info("Pupil detection complete.")
j = 0
for plugin in plugins:
j += 1
logging.info(f"---------------[{i*total_plugins + j}/{total_items*total_plugins}]----------------")
logging.info(f"Exporting gaze data for plugin {plugin}")
if plugin is None:
pupil_data_loc = rec_loc + f"/offline_data/vanilla/offline_pupil.pldata"
else:
pupil_data_loc = rec_loc + f"/offline_data/{plugin.__name__}/offline_pupil.pldata"
intrinsics_loc = rec_loc + "/world.intrinsics"
realtime_calib_points_loc = rec_loc+'/realtime_calib_points.msgpack';
if os.path.exists(realtime_calib_points_loc):
print("Using exported realtime calibration points.")
try:
calibrated_gazer, pupil_data = calibrate_and_validate(reference_data_loc, pupil_data_loc, intrinsics_loc, mapping_method, realtime_ref_loc=realtime_calib_points_loc)#, min_calibration_confidence=min_calibration_confidence)
except FileNotFoundError:
print("No calibration points found.")
continue
except TypeError:
print("No calibration points found.")
continue
else:
print("Realtime calibration points have not been exported.")
try:
calibrated_gazer, pupil_data = calibrate_and_validate(reference_data_loc, pupil_data_loc, intrinsics_loc, mapping_method)#, min_calibration_confidence=min_calibration_confidence)
except FileNotFoundError:
print("No calibration points found.")
continue
except TypeError:
print("No calibration points found.")
continue
gaze, gaze_ts = map_pupil_data(calibrated_gazer, pupil_data, rec_loc)
save_gaze_data(gaze, gaze_ts, rec_loc, plugin=plugin)
i += 1
logging.info('All gaze data obtained.')
if not_uxf:
return
elif not_uxf:
logging.error('Only UXF gaze files can have fixation data graphed.')
return
if not skip_trial_assessment:
logging.info('Generating trial charts.')
targets = []
if vanilla_only:
targets.append('vanilla')
targets.append('realtime') # Realtime is technically vanilla
targets.append('vanilla_player') # Allow vanilla data exported from PL Player
allSessionData = processAllData(doNotLoad=not allow_session_loading, confidenceThresh=0.00, targets=targets, show_filtered_out=show_filtered_out, load_realtime_ref_data=load_realtime_ref_data, override_to_2d=skip_3d_detection)
with open(allsessiondata_loader, 'wb') as handle:
pickle.dump(allSessionData, handle, protocol=pickle.HIGHEST_PROTOCOL)
from pylab import savefig
if not load_pandas_checkpoint:
filehandler = open(allsessiondata_loader, "rb")
allSessionData = pickle.load(filehandler)
print(f"LOADED {allsessiondata_loader}")
if velocity_graphs:
# THIS SECTION CURRENTLY ASSUMES 2D GAZE DATA (deprojected_norm_pos rather than gaze_normal)
for subjectFolder in next(os.walk('./Data'))[1]:
print("Processing velocity data for " + subjectFolder)
session = None
for d in allSessionData:
if d['subID'] == subjectFolder[-9:]:
session = d
break
if session is None:
# contingency for accidental _01/_02 formatting
for d in allSessionData:
if d['subID'] == subjectFolder[-10:]:
session = d
break
gazeDataFolder = './Data/'+subjectFolder+'/S001/PupilData/000/Exports/'
plt.figure()
ax = plt.subplot()
detect_non_saccads(gazeDataFolder, 'vanilla', 'Native', session, 'blue', ax)
detect_non_saccads(gazeDataFolder, 'Detector2DRITnetEllsegV2AllvonePlugin', 'EllSegGen', session, 'red', ax)
plt.clf()
plt.close('all')
results_by_subject = {}
results_by_resolution = {}
results_by_eccentricity = {}
i = 1
for sessionDict in allSessionData:
print()
try:
subject = int(sessionDict['subID'][0:3])
resolution = int(sessionDict['subID'][4:7])
run = int(sessionDict['subID'][8:])
except ValueError:
subject = sessionDict['subID'][0:-4]
resolution = int(sessionDict['subID'][-3:])
run = 1
plugin = sessionDict['plExportFolder']
if subject == 4:
continue
print(f"({i}/{len(allSessionData)})SUB {subject}, {resolution}x{resolution}, run {run} ({sessionDict['plExportFolder']}):")
i += 1
ecc_targetLoc_targNum_AzEl = sessionDict['processedCalib']['targetLocalSpherical'].drop_duplicates().values
# ---------- ACCURACY ----------
"""
OLD METHOD (every point is added)
calibrationEuclideanFixErrors = sessionDict['processedSequence'][('fixError_eye2', 'euclidean')].to_numpy()
analysisEuclideanFixErrors = sessionDict['processedCalib'][('fixError_eye2', 'euclidean')].to_numpy()
"""
pupil_0_X = np.array([])
pupil_0_Y = np.array([])
pupil_0_ts = np.array([])
calibrationEuclideanFixErrors = []
targetLoc_targNum_AzEl = sessionDict['processedSequence']['targetLocalSpherical'].drop_duplicates().values
for tNum,(tX,tY) in enumerate(targetLoc_targNum_AzEl):
gbFixTrials = sessionDict['processedSequence'].groupby([('targetLocalSpherical','az'), ('targetLocalSpherical','el')])
trialsInGroup = gbFixTrials.get_group((tX,tY))
gbTrials = sessionDict['processedSequence'].groupby('trialNumber')
fixRowDataDf = gbTrials.get_group(trialsInGroup['trialNumber'].values[0])
for x in trialsInGroup['trialNumber'][1:]:
fixRowDataDf = pd.concat([fixRowDataDf,gbTrials.get_group(x)])
err_acc = np.nanmean(
fixRowDataDf['fixError_eye2']['euclidean'].to_numpy()
)
if (tX,tY) == (0.0, 0.0):
pupil_0_X = np.append(pupil_0_X, fixRowDataDf[fixRowDataDf[('pupil-centroid0', 'x')] > 0.0][('pupil-centroid0', 'x')].to_numpy())
pupil_0_Y = np.append(pupil_0_Y, fixRowDataDf[fixRowDataDf[('pupil-centroid0', 'x')] > 0.0][('pupil-centroid0', 'y')].to_numpy())
pupil_0_ts = np.append(pupil_0_ts, fixRowDataDf[fixRowDataDf[('pupil-centroid0', 'x')] > 0.0][('pupilTimestamp', '')].to_numpy())
calibrationEuclideanFixErrors.append(err_acc)
eccentricities = []
eccentricitiesAccDict = {}
analysisEuclideanFixErrors = []
fixDF = sessionDict['fixAssessmentData']
gb_h_w = fixDF.groupby([('gridSize', 'heightDegs'), ('gridSize', 'widthDegs')])
for (gHeight,gWidth) in list(gb_h_w.groups.keys()):
targetLoc_targNum_AzEl = gb_h_w.get_group((gHeight,gWidth))['fixTargetSpherical'].drop_duplicates().values
for tNum,(tX,tY) in enumerate(targetLoc_targNum_AzEl):
gbTargetType = sessionDict['trialInfo'].groupby(['targetType'])
fixTrialsDf = gbTargetType.get_group('fixation')
gbFixTrials = fixTrialsDf.groupby([('gridSize', 'heightDegs'), ('gridSize', 'widthDegs')])
fixTrialsDf = gbFixTrials.get_group((gHeight,gWidth))
gbFixTrials = fixTrialsDf.groupby([('fixTargetSpherical','az'),('fixTargetSpherical','el')])
trialsInGroup = gbFixTrials.get_group((tX,tY))
gbTrials = sessionDict['processedCalib'].groupby('trialNumber')
fixRowDataDFs = []
for x in trialsInGroup['trialNumber']:
fixRowDataDFs.append((x, gbTrials.get_group(x)))
eccentricity = np.round(np.sqrt(tX**2 + tY**2))
if eccentricity not in eccentricities and not np.isnan(eccentricity):
eccentricities.append(eccentricity)
for trialID, DFarr in fixRowDataDFs:
if (tX, tY) == (0.0, 0.0):
pupil_0_X = np.append(pupil_0_X, DFarr[DFarr[('pupil-centroid0', 'x')] > 0.0][('pupil-centroid0', 'x')].to_numpy())
pupil_0_Y = np.append(pupil_0_Y, DFarr[DFarr[('pupil-centroid0', 'x')] > 0.0][('pupil-centroid0', 'y')].to_numpy())
pupil_0_ts = np.append(pupil_0_ts, DFarr[DFarr[('pupil-centroid0', 'x')] > 0.0][('pupilTimestamp', '')].to_numpy())
nparr = DFarr['fixError_eye2']['euclidean'].to_numpy()
if eccentricity in eccentricitiesAccDict:
eccentricitiesAccDict[eccentricity].append((trialID, nparr))#(nparr[np.logical_not(np.isnan(nparr))])
else:
eccentricitiesAccDict[eccentricity] = [(trialID, nparr)]#[nparr[np.logical_not(np.isnan(nparr))]]
analysisEuclideanFixErrors.append(np.nanmean(nparr))
sessionDict['processedCalib']['eccentricity'] = np.round(np.linalg.norm(sessionDict['processedCalib']['targetLocalSpherical'].values, axis=1))
# [INTERMISSION] Plot the pupil 0 centroids of the (0.0, 0.0) targets over time
cppp_dir = f"./{figout_loc}/central_point_pupil_positions/"
if not os.path.exists(cppp_dir):
os.makedirs(cppp_dir)
fig, (ax0, ax1) = plt.subplots(2, 1)
ax0.plot(pupil_0_ts, pupil_0_X)
#ax0.set_ylim(bottom=0.58, top=0.63)
ax1.plot(pupil_0_ts, pupil_0_Y)
#ax1.set_ylim(bottom=0.44, top=0.46)
fig.suptitle(f"Pupil Centroids (x, y) During Central Fixations {subject}_{resolution}_{run} ({plugin})")
ax1.set_xlabel("Timestamp")
ax0.set_ylabel("Centroid Position (X)")
ax1.set_ylabel("Centroid Position (Y)")
plt.savefig(f'{cppp_dir}centroid_time_{subject}_{resolution}_{run}_eye{0}.png')
# ---------- PRECISION ----------
targetLoc_targNum_AzEl = sessionDict['processedSequence']['targetLocalSpherical'].drop_duplicates().values
calibrationPrecision = np.nanstd(sessionDict['processedSequence'][('gaze2Spherical', 'az')])
calibration_precision_errors = []
for tNum,(tX,tY) in enumerate(targetLoc_targNum_AzEl):
gbFixTrials = sessionDict['processedSequence'].groupby([('targetLocalSpherical','az'), ('targetLocalSpherical','el')])
trialsInGroup = gbFixTrials.get_group((tX,tY))
gbTrials = sessionDict['processedSequence'].groupby('trialNumber')
fixRowDataDf = gbTrials.get_group(trialsInGroup['trialNumber'].values[0])
for x in trialsInGroup['trialNumber'][1:]:
fixRowDataDf = pd.concat([fixRowDataDf,gbTrials.get_group(x)])
meanGazeAz = np.nanmean(fixRowDataDf['gaze2Spherical']['az']) # sigma_a
meanGazeEl = np.nanmean(fixRowDataDf['gaze2Spherical']['el']) # sigma_e
err_prec = np.mean(
np.sqrt(
np.square(fixRowDataDf['gaze2Spherical']['az'] - meanGazeAz) +\
np.square(fixRowDataDf['gaze2Spherical']['el'] - meanGazeEl)
)
)
calibration_precision_errors.append(err_prec)
fixDF = sessionDict['fixAssessmentData']
gb_h_w = fixDF.groupby([('gridSize', 'heightDegs'), ('gridSize', 'widthDegs')])
analysis_precision_errors = [] # wrong position (now right position?)
eccentricitiesPrecDict = {}
for (gHeight,gWidth) in list(gb_h_w.groups.keys()):
targetLoc_targNum_AzEl = gb_h_w.get_group((gHeight,gWidth))['fixTargetSpherical'].drop_duplicates().values
for tNum,(tX,tY) in enumerate(targetLoc_targNum_AzEl):
gbTargetType = sessionDict['trialInfo'].groupby(['targetType'])
fixTrialsDf = gbTargetType.get_group('fixation')
gbFixTrials = fixTrialsDf.groupby([('gridSize', 'heightDegs'), ('gridSize', 'widthDegs')])
fixTrialsDf = gbFixTrials.get_group((gHeight,gWidth))
gbFixTrials = fixTrialsDf.groupby([('fixTargetSpherical','az'),('fixTargetSpherical','el')])
trialsInGroup = gbFixTrials.get_group((tX,tY))
gbTrials = sessionDict['processedCalib'].groupby('trialNumber')
fixRowDataDFs = []
for x in trialsInGroup['trialNumber']:
grp = gbTrials.get_group(x)
fixRowDataDFs.append((x, grp, np.nanmean(grp['gaze2Spherical']['az']), np.nanmean(grp['gaze2Spherical']['el'])))
# NEW WAY: Pass raw gaze precisions to figure gen
for trialID, DFarr, avgAz, avgEl in fixRowDataDFs:
nparr = np.sqrt(
np.square(DFarr['gaze2Spherical']['az'].to_numpy() - avgAz) +\
np.square(DFarr['gaze2Spherical']['el'].to_numpy() - avgEl)
)
eccentricity = np.round(np.sqrt(tX**2 + tY**2))
if eccentricity in eccentricitiesPrecDict:
eccentricitiesPrecDict[eccentricity].append((trialID, nparr))#(nparr[np.logical_not(np.isnan(nparr))])
else:
eccentricitiesPrecDict[eccentricity] = [(trialID, nparr)]#[nparr[np.logical_not(np.isnan(nparr))]]
analysis_precision_errors.append(np.nanmean(nparr))
# ------------------------------
if subject not in results_by_subject:
results_by_subject[subject] = {sessionDict['plExportFolder']: {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array([]), 'analysis': np.array([])}}
elif sessionDict['plExportFolder'] not in results_by_subject[subject]:
results_by_subject[subject][sessionDict['plExportFolder']] = {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array([]), 'analysis': np.array([])}
else:
results_by_subject[subject][sessionDict['plExportFolder']]['calibration_precision'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['calibration_precision'], calibration_precision_errors)
results_by_subject[subject][sessionDict['plExportFolder']]['analysis_precision'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['analysis_precision'], analysis_precision_errors)
if subject not in results_by_subject: #^^^ WRONG? (Only using results by eccentricity anyways)
results_by_subject[subject] = {sessionDict['plExportFolder']: {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array(calibrationEuclideanFixErrors), 'analysis': np.array(analysisEuclideanFixErrors)}}
elif sessionDict['plExportFolder'] not in results_by_subject[subject]:
results_by_subject[subject][sessionDict['plExportFolder']] = {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array(calibrationEuclideanFixErrors), 'analysis': np.array(analysisEuclideanFixErrors)}
else:
results_by_subject[subject][sessionDict['plExportFolder']]['calibration_precision'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['calibration_precision'], calibration_precision_errors)
results_by_subject[subject][sessionDict['plExportFolder']]['analysis_precision'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['analysis_precision'], analysis_precision_errors)
results_by_subject[subject][sessionDict['plExportFolder']]['calibration'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['calibration'], calibrationEuclideanFixErrors)
results_by_subject[subject][sessionDict['plExportFolder']]['analysis'] = np.append(results_by_subject[subject][sessionDict['plExportFolder']]['analysis'], analysisEuclideanFixErrors)
if resolution not in results_by_resolution:
results_by_resolution[resolution] = {subject: {sessionDict['plExportFolder']: {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array(calibrationEuclideanFixErrors), 'analysis': np.array(analysisEuclideanFixErrors)}}}
elif subject not in results_by_resolution[resolution]:
results_by_resolution[resolution][subject] = {sessionDict['plExportFolder']: {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array(calibrationEuclideanFixErrors), 'analysis': np.array(analysisEuclideanFixErrors)}}
elif sessionDict['plExportFolder'] not in results_by_resolution[resolution][subject]:
results_by_resolution[resolution][subject][sessionDict['plExportFolder']] = {'calibration_precision': np.array(calibration_precision_errors), 'analysis_precision': np.array(analysis_precision_errors), 'calibration': np.array(calibrationEuclideanFixErrors), 'analysis': np.array(analysisEuclideanFixErrors)}
else:
results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['calibration_precision'] = np.append(results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['calibration_precision'], calibration_precision_errors)
results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['analysis_precision'] = np.append(results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['analysis_precision'], np.array(analysis_precision_errors))
results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['calibration'] = np.append(results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['calibration'], calibrationEuclideanFixErrors)
results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['analysis'] = np.append(results_by_resolution[resolution][subject][sessionDict['plExportFolder']]['analysis'], analysisEuclideanFixErrors)
def fix_np_len_bug(np_array):
return np.array([
np.append(np_array[j], [
np.nan for _ in range(
[
np.max([
len(np_array[g]) for g in range(len(np_array))
]) - len(np_array[q]) for q in range(len(np_array))
][j]
)
]) for j in range(len(np_array))
])
for eccentricity in eccentricities:
if eccentricity not in results_by_eccentricity:
results_by_eccentricity[eccentricity] = {resolution: {subject: {sessionDict['plExportFolder']: {'calibration_precision': None, 'analysis_precision': np.array([(i, d) for i, d in eccentricitiesPrecDict[eccentricity]], dtype=object), 'calibration': None, 'analysis': np.array([(i, d) for i, d in eccentricitiesAccDict[eccentricity]], dtype=object), 'eye0_rate': len(sessionDict['rawCalibGaze']['gaze_normal0_y']), 'eye1_rate': len(sessionDict['rawCalibGaze']['gaze_normal1_y'])}}}}
elif resolution not in results_by_eccentricity[eccentricity]:
results_by_eccentricity[eccentricity][resolution] = {subject: {sessionDict['plExportFolder']: {'calibration_precision': None, 'analysis_precision': np.array([(i, d) for i, d in eccentricitiesPrecDict[eccentricity]], dtype=object), 'calibration': None, 'analysis': np.array([(i, d) for i, d in eccentricitiesAccDict[eccentricity]], dtype=object), 'eye0_rate': len(sessionDict['rawCalibGaze']['gaze_normal0_y']), 'eye1_rate': len(sessionDict['rawCalibGaze']['gaze_normal1_y'])}}}
elif subject not in results_by_eccentricity[eccentricity][resolution]:
results_by_eccentricity[eccentricity][resolution][subject] = {sessionDict['plExportFolder']: {'calibration_precision': None, 'analysis_precision': np.array([(i, d) for i, d in eccentricitiesPrecDict[eccentricity]], dtype=object), 'calibration': None, 'analysis': np.array([(i, d) for i, d in eccentricitiesAccDict[eccentricity]], dtype=object), 'eye0_rate': len(sessionDict['rawCalibGaze']['gaze_normal0_y']), 'eye1_rate': len(sessionDict['rawCalibGaze']['gaze_normal1_y'])}}
elif sessionDict['plExportFolder'] not in results_by_eccentricity[eccentricity][resolution][subject]:
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']] = {'calibration_precision': None, 'analysis_precision': np.array([(i, d) for i, d in eccentricitiesPrecDict[eccentricity]], dtype=object), 'calibration': None, 'analysis': np.array([(i, d) for i, d in eccentricitiesAccDict[eccentricity]], dtype=object), 'eye0_rate': len(sessionDict['rawCalibGaze']['gaze_normal0_y']), 'eye1_rate': len(sessionDict['rawCalibGaze']['gaze_normal1_y'])}
else:
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['analysis'] = np.append(results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['analysis'], np.array([(i, d) for i, d in eccentricitiesAccDict[eccentricity]], dtype=object), axis=0)
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['calibration'] = None
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['analysis_precision'] = np.append(results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['analysis_precision'], np.array([(i, d) for i, d in eccentricitiesPrecDict[eccentricity]], dtype=object), axis=0)
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['calibration_precision'] = None
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['eye0_rate'] = len(sessionDict['rawCalibGaze']['gaze_normal0_y'])
results_by_eccentricity[eccentricity][resolution][subject][sessionDict['plExportFolder']]['eye1_rate'] = len(sessionDict['rawCalibGaze']['gaze_normal1_y'])
pd_acc_constructor = []
pd_prec_constructor = []
for eccentricity in results_by_eccentricity.keys():
for res in results_by_eccentricity[eccentricity]:
for sub in results_by_eccentricity[eccentricity][res]:
for plugin in results_by_eccentricity[eccentricity][res][sub]:
for idx, (trialID, datapoint) in enumerate(results_by_eccentricity[eccentricity][res][sub][plugin]['analysis']):
pd_acc_constructor.append({
"subject": sub,
"resolution": res,
"plugin": plugin,
"eccentricity": eccentricity,
"index": idx,
"trial-id": trialID,
"eye0-rate": results_by_eccentricity[eccentricity][res][sub][plugin]['eye0_rate'],
"eye1-rate": results_by_eccentricity[eccentricity][res][sub][plugin]['eye1_rate'],
"accuracy-error": datapoint
})
for idx, (trialID, datapoint) in enumerate(results_by_eccentricity[eccentricity][res][sub][plugin]['analysis_precision']):
pd_prec_constructor.append({
"subject": sub,
"resolution": res,
"plugin": plugin,
"eccentricity": eccentricity,
"index": idx,
"trial-id": trialID,
"eye0-rate": results_by_eccentricity[eccentricity][res][sub][plugin]['eye0_rate'],
"eye1-rate": results_by_eccentricity[eccentricity][res][sub][plugin]['eye1_rate'],
"precision-error": datapoint
})
pd_analysis_acc = pd.DataFrame.from_records(
pd_acc_constructor
)
pd_analysis_prec = pd.DataFrame.from_records(
pd_prec_constructor
)
np.set_printoptions(threshold=sys.maxsize)
pd_analysis_acc.to_csv(f'./{figout_loc}/analysis_accuracy_pd.csv')
pd_analysis_prec.to_csv(f'./{figout_loc}/analysis_precision_pd.csv')
else:
def converter(instr):
return np.fromstring(instr[1:-1], sep=' ').astype(np.float32)
pd_analysis_acc = pd.read_csv(f'./{figout_loc}/analysis_accuracy_pd.csv', converters={'accuracy-error': converter})
pd_analysis_prec = pd.read_csv(f'./{figout_loc}/analysis_precision_pd.csv', converters={'precision-error': converter})
ANOVA = False
if ANOVA:
import pingouin
pd_analysis_acc = pd_analysis_acc.rename(columns={"accuracy-error": "accuracyError"})
pd_analysis_prec = pd_analysis_prec.rename(columns={"precision-error": "precisionError"})
print("performing anova...")
print("---------------------ACCURACY---------------------")
#result = pingouin.anova(data=pd_analysis_acc, dv='accuracyError', between=['subject', 'resolution', 'eccentricity', 'plugin'])
result = pingouin.rm_anova(data=pd_analysis_acc, dv='accuracyError', within=['eccentricity', 'plugin'], subject='subject')
print(result)
print()
print("---------------------PRECISION---------------------")
#result = pingouin.anova(data=pd_analysis_prec, dv='precisionError', between=['subject', 'resolution', 'eccentricity', 'plugin'])
result = pingouin.rm_anova(data=pd_analysis_prec, dv='precisionError', within=['eccentricity', 'plugin'], subject='subject')
print(result)
exit()
COLORS = ['red', 'purple', 'pink', 'orange', 'gold', 'black']
nn_names = [
'Detector2DRITnetEllsegV2AllvonePlugin',
'Detector2DRITnetEllsegV2AllvoneEmbeddedPlugin',
'Detector2DRITnetEllsegV2AllvoneEmbeddedIrisPlugin',
'Detector2DESFnetPlugin', 'Detector2DESFnetEmbeddedPlugin',
'Detector2DRITnetPupilPlugin',
]
xlabel_dict = {
'vanilla': 'Native',
'Native': 'Native',
'Detector2DRITnetEllsegV2AllvonePlugin': 'EllSegGen',
'Detector2DRITnetEllsegV2AllvoneEmbeddedPlugin': 'EllSegGen\n(Direct Pupil)',
'Detector2DRITnetEllsegV2AllvoneEmbeddedIrisPlugin': 'EllSegGen\n(Direct Iris)',
'Detector2DESFnetPlugin': 'ESFnet',
'Detector2DESFnetEmbeddedPlugin': 'ESFnet\n(Direct Pupil)',
'Detector2DRITnetPupilPlugin': 'RITnet Pupil',
}
barlabel_dict = {
'vanilla': 'Native',
'Native': 'Native',
'Detector2DRITnetEllsegV2AllvonePlugin': 'EllSegGen',
'Detector2DRITnetEllsegV2AllvoneEmbeddedPlugin': 'EllSegGen (Direct Pupil)',
'Detector2DRITnetEllsegV2AllvoneEmbeddedIrisPlugin': 'EllSegGen (Direct Iris)',
'Detector2DESFnetPlugin': 'ESFnet',
'Detector2DESFnetEmbeddedPlugin': 'ESFnet (Direct Pupil)',
'Detector2DRITnetPupilPlugin': 'RITnet Pupil',
}
nn_names_ecc = nn_names
def flatten_np(nparray):
return np.array([item for sublist in nparray for item in sublist])
def mean_subarrays(nparray):
return np.array([np.nanmean(sublist) for sublist in nparray])
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data[~np.isnan(data)])
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m-h, m, m+h
if True:
DROPOUT = 10
ELIMINATE_DROPOUTS = True
MARKERSIZE = 2
colors = COLORS
SUBJECTS = (1,2,3,5,6,7,8,9,10,11)#(1,)
P = flatten_np(pd_analysis_acc['accuracy-error'].to_numpy())
gaussian_thresh = np.nanmean(P) + 2*np.nanstd(P)
print("Mean: {}, std: {}, 2*std: {}, mean+2*std: {}".format(
np.nanmean(P), np.nanstd(P), 2*np.nanstd(P), np.nanmean(P) + 2*np.nanstd(P)
))
plt.figure(figsize=(6.4, 2.8))
plt.plot(list(range(0, 50)), [100.0 - (100*np.count_nonzero(np.where(P >= i, 1, 0)) / len(P)) for i in range(0, 50)], '-o', mfc='none')
plt.title("Data Preserved Under Different Dropout Thresholds")
plt.xlabel("Dropout Threshold (Degrees)")
plt.ylabel("Percentage of Data Under Threshold")
plt.grid()
plt.savefig("plotted.png", bbox_inches='tight')
#exit()
print("Data dropped: {:.3f}% dropout, {:.3f} mean, {:.3f} std (data-driven)".format(
100*np.count_nonzero(np.where(P >= gaussian_thresh, 1, 0)) / len(P),
np.nanmean(P[P < gaussian_thresh]),
np.nanstd(P[P < gaussian_thresh])
))
print(" "*11+"vs {:.3f}% dropout, {:.3f} mean, {:.3f} std (hard thresh of {})".format(
100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P),
np.nanmean(P[P < DROPOUT]),
np.nanstd(P[P < DROPOUT]),
DROPOUT
))
for subj in SUBJECTS:
P = flatten_np(pd_analysis_acc.loc[pd_analysis_acc['subject'] == subj]['accuracy-error'])
print("(SUBJECT {})".format(subj))
print("Data dropped: {:.3f}% dropout, {:.3f} mean, {:.3f} std (data-driven)".format(
100*np.count_nonzero(np.where(P >= gaussian_thresh, 1, 0)) / len(P),
np.nanmean(P[P < gaussian_thresh]),
np.nanstd(P[P < gaussian_thresh])
))
print(" "*11+"vs {:.3f}% dropout, {:.3f} mean, {:.3f} std (hard thresh of {})".format(
100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P),
np.nanmean(P[P < DROPOUT]),
np.nanstd(P[P < DROPOUT]),
DROPOUT
))
print()
print()
grouped_dropouts = pd_analysis_acc.groupby(['resolution', 'eccentricity', 'plugin'])['accuracy-error'].aggregate(lambda d: [100*np.sum(s >= DROPOUT)/len(s) for s in d])
print(grouped_dropouts[192, 0.0, 'Detector2DESFnetPlugin'])
grouped_dropouts_by_subject = pd_analysis_acc.groupby(['resolution', 'subject', 'plugin'])['accuracy-error'].aggregate(lambda d: [100*np.sum(s >= DROPOUT)/len(s) for s in d])
print(grouped_dropouts_by_subject[192, 1, 'Detector2DESFnetPlugin'])
np_dropouts_plugins = {}
np_dropouts_resolution = {}
for plugin in ['vanilla'] + nn_names:
P = flatten_np(pd_analysis_acc.loc[pd_analysis_acc['plugin'] == plugin]['accuracy-error'])
print("(PLUGIN {})".format(plugin))
print(" "*11+"{:.3f}% dropout (hard thresh of {}deg)".format(
100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P),
DROPOUT
))
np_dropouts_plugins[plugin] = 100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P)
print()
print()
for resolution in (192, 400):
print("------(RESOLUTION {})------".format(resolution))
temp_top_dropouts = {}
for eccentricity in (0.0, 10.0, 15.0, 20.0):
print("------(ECCENTRICITY {})------".format(eccentricity))
temp_dropouts = {}
for plugin in ['vanilla'] + nn_names:
P = flatten_np(pd_analysis_acc.loc[(pd_analysis_acc['eccentricity'] == eccentricity) & (pd_analysis_acc['plugin'] == plugin) & (pd_analysis_acc['resolution'] == resolution)]['accuracy-error'])
print("(PLUGIN {})".format(plugin))
print(" "*11+"{:.3f}% dropout (hard thresh of {}deg)".format(
100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P),
DROPOUT
))
temp_dropouts[plugin] = 100*np.count_nonzero(np.where(P >= DROPOUT, 1, 0)) / len(P)
temp_top_dropouts[eccentricity] = temp_dropouts
print()
np_dropouts_resolution[resolution] = temp_top_dropouts
if ELIMINATE_DROPOUTS:
def tempfunc(row):
row['accuracy-error'] = row['accuracy-error'][row['accuracy-error'] < DROPOUT]
return row
def tempfunc2(row):
row['precision-error'] = row['precision-error'][row['accuracy-error'] < DROPOUT]
return row
pd_analysis_prec = pd_analysis_acc.join(pd_analysis_prec['precision-error'], how='left').apply(tempfunc2, axis=1)
pd_analysis_acc = pd_analysis_acc.apply(tempfunc, axis=1)
# ----- Plot All Points' Accuracy Error Over Native Accuracy Error -----
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla')
]['accuracy-error'].to_numpy())
#print(X)
#print(X.dtype)
#print(X.shape)
#print(X.reshape(-1))
plt.plot([0, np.max(np.nanmean(X))], [0, np.max(np.nanmean(X))], '-', label="Native Accuracy Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == method)
]['accuracy-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Accuracy Error vs Native Accuracy Error")
plt.xlabel("Native Accuracy Error")
plt.ylabel("NN-assisted Accuracy Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_ACCURACY_COMP.png', bbox_inches='tight')
plt.clf()
# Specify Resolution 192
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla') &\
(pd_analysis_acc['resolution'] == 192)
]['accuracy-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Accuracy Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == method) &\
(pd_analysis_acc['resolution'] == 192)
]['accuracy-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Accuracy Error vs Native Accuracy Error (192x192)")
plt.xlabel("Native Accuracy Error")
plt.ylabel("NN-assisted Accuracy Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_ACCURACY_192_COMP.png', bbox_inches='tight')
plt.clf()
# Specify Resolution 400
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla') &\
(pd_analysis_acc['resolution'] == 400)
]['accuracy-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Accuracy Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == method) &\
(pd_analysis_acc['resolution'] == 400)
]['accuracy-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Accuracy Error vs Native Accuracy Error (400x400)")
plt.xlabel("Native Accuracy Error")
plt.ylabel("NN-assisted Accuracy Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_ACCURACY_400_COMP.png', bbox_inches='tight')
plt.clf()
# ----- Plot All Points' Precision Error Over Native Precision Error -----
X = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == 'vanilla')
]['precision-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Precision Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == method)
]['precision-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Precision Error vs Native Precision Error")
plt.xlabel("Native Precision Error")
plt.ylabel("NN-assisted Precision Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_PRECISION_COMP.png', bbox_inches='tight')
plt.clf()
# Specify Resolution 192
X = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == 'vanilla') &\
(pd_analysis_prec['resolution'] == 192)
]['precision-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Precision Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == method) &\
(pd_analysis_prec['resolution'] == 192)
]['precision-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Precision Error vs Native Precision Error (192x192)")
plt.xlabel("Native Precision Error")
plt.ylabel("NN-assisted Precision Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_PRECISION_192_COMP.png', bbox_inches='tight')
plt.clf()
# Specify Resolution 400
X = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == 'vanilla') &\
(pd_analysis_prec['resolution'] == 400)
]['precision-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Precision Error", c='blue')
i = 0
for method in nn_names:
Y = mean_subarrays(pd_analysis_prec.loc[
(pd_analysis_prec['plugin'] == method) &\
(pd_analysis_prec['resolution'] == 400)
]['precision-error'].to_numpy())
plt.plot(X, Y, '+', label=method, c=colors[i], markersize=MARKERSIZE)
i += 1
plt.title("NN-assisted Precision Error vs Native Precision Error (400x400)")
plt.xlabel("Native Precision Error")
plt.ylabel("NN-assisted Precision Error")
plt.legend()
#plt.xlim(0, 6)
#plt.ylim(0, 6)
plt.savefig(f'{figout_loc}VANIL_PRECISION_400_COMP.png', bbox_inches='tight')
plt.clf()
# ----- Plot All Points' Binned&Averaged Accuracy Error Over Native Binned&Averaged Accuracy Error -----
from decimal import Decimal
for resolution in (None, 192, 400):
bins = {}
#expand_bin_size_at = 12.0
colors = COLORS
if resolution is None:
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla')
]['accuracy-error'].to_numpy())
else:
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla') &\
(pd_analysis_acc['resolution'] == resolution)
]['accuracy-error'].to_numpy())
plt.plot([0, np.max(X)], [0, np.max(X)], '-', label="Native Accuracy Error", c='blue')
i = 0
for method in nn_names:
bins[method] = []
if resolution is None:
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla')
]['accuracy-error'].to_numpy())
Y = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == method)
]['accuracy-error'].to_numpy())
else:
X = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == 'vanilla') &\
(pd_analysis_acc['resolution'] == resolution)
]['accuracy-error'].to_numpy())
Y = mean_subarrays(pd_analysis_acc.loc[
(pd_analysis_acc['plugin'] == method) &\
(pd_analysis_acc['resolution'] == resolution)
]['accuracy-error'].to_numpy())
vanillas = X
percentile50 = np.nanpercentile(vanillas, 50)
percentile90 = np.nanpercentile(vanillas, 90)
percentile95 = np.nanpercentile(vanillas, 95)
expand_bin_size_at = percentile90
max_vanillas = round(np.nanmax(vanillas), 1) # nearest tenth place
bin_group_1_size = 0.25
bin_group_3_size = 3.0
bg1s_decimal = Decimal(str(bin_group_1_size))
bg3s_decimal = Decimal(str(bin_group_3_size))
curr = 0.0
while curr <= max_vanillas:
bins[method].append([])
if curr < expand_bin_size_at:
curr += bin_group_1_size
else:
curr += bin_group_3_size
bins[method].append([])
for pt_idx in range(len(X)):
pt = X[pt_idx]
if pt < expand_bin_size_at + (bin_group_1_size / 2):
if (pt % bin_group_1_size) < (bin_group_1_size / 2):
modfix = float(Decimal(pt.item()) % bg1s_decimal)
idx = pt - modfix
else:
modfix = float(Decimal(pt.item()) % bg1s_decimal)
idx = pt + (bin_group_1_size - modfix)
idx = idx / bin_group_1_size
bins[method][int(round(idx))].append(Y[pt_idx])
else:
if (pt % bin_group_3_size) < (bin_group_3_size / 2):
modfix = float(Decimal(pt.item()) % bg3s_decimal)
idx = pt - modfix
else:
modfix = float(Decimal(pt.item()) % bg3s_decimal)
idx = pt + (bin_group_3_size - modfix)
#idx = round(idx)
idx = (expand_bin_size_at / bin_group_1_size) + ((idx - expand_bin_size_at) / bin_group_3_size)
if not np.isnan(idx):
bins[method][int(round(idx))].append(Y[pt_idx])
X = []
Y = []
for idx in range(len(bins[method])):
if len(bins[method][idx]):
if idx <= (expand_bin_size_at / bin_group_1_size):
bin = bin_group_1_size * idx
else:
bin = expand_bin_size_at + bin_group_3_size * (idx - (expand_bin_size_at / bin_group_1_size))
#X.append(bin)
#Y.append(np.mean(bins[method][idx]))
for currpt in bins[method][idx]:
X.append(bin)
Y.append(currpt)
#plt.plot(X, Y, '-o', markersize=5, label=method, c=colors[i])
sns.lineplot(x=X, y=Y, markers=True, label=method, color=colors[i], marker='o')
#plt.plot(X, Y, '-o', markersize=5, label=method, c=colors[i])
i += 1
plt.xlabel("Native Accuracy Error (degrees) (bin interval = {} -> {})".format(bin_group_1_size, bin_group_3_size))
plt.ylabel("NN-assisted Accuracy Error (degrees)")
#plt.xlim(0, 12)
#plt.ylim(0, 12)
plt.axvline(percentile50, linestyle=":", color="blue", label="50th percentile")
plt.axvline(percentile90, linestyle=":", color="green", label="90th percentile")
plt.axvline(percentile95, linestyle=":", color="red", label="95th percentile")
plt.legend()
#plt.xlim(0, percentile90)