-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_plots.py
More file actions
1302 lines (1150 loc) · 71 KB
/
make_plots.py
File metadata and controls
1302 lines (1150 loc) · 71 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 numpy as np
import csv
import seaborn as sns
#from matplotlib.pyplot import savefig, violinplot, boxplot, figure, subplot, close, plot, legend, tight_layout, scatter, yscale, xscale, text
import matplotlib.pyplot as plt
import matplotlib
import argparse
import os
import warnings
import pydicom
import scipy.stats
import loader
x_cache = {}
def get_t(path, name):
if name in x_cache:
return x_cache[name]
path = os.path.join(os.path.normpath(path), name)
dceFiles = []
for dirpath, _, filenames in os.walk(path):
for fileName in filenames:
if fileName.endswith('.dcm'):
if dirpath.split('\\')[-1].startswith("t2"):
pass
else:
dceFiles.append(os.path.join(dirpath, fileName))
time = []
currentTimeSeries = -1
for fileName in dceFiles:
ds = pydicom.read_file(fileName)
if(currentTimeSeries != ds[0x20,0x12].value):
currentTimeSeries = ds[0x20,0x12].value
h = float(ds[0x08,0x32].value[0:2])
m = float(ds[0x08,0x32].value[2:4])
s = float(ds[0x08,0x32].value[4:6])
time.append(h*60*60 + m*60 + s)
t0 = False
times = []
for t in sorted(time):
if not t0:
t0 = t
times.append((t-t0) / 60)
x_cache[name] = np.array(times)
return np.array(times)
def readCSV(file_path, fieldnames = None):
data = {}
if not os.path.exists(file_path):
return data
with open(file_path, newline='', encoding='utf8') as csvfile:
csv_reader = csv.DictReader(csvfile, delimiter=',')
skip = False
for row in csv_reader:
if skip:
skip = False
continue
if len(data) > 0 and any([k not in row.keys() for k in data]): continue
for k in row.keys():
if k==None or (fieldnames and k not in fieldnames):
continue
if k not in data:
data[k] = []
if k == "modelName" or k == "fileName":
data[k].append(row[k])
else:
try:
if row[k] != None and row[k] != "" and row[k][0] != '[':
value = float(row[k])
if value > 1e8:
value = 1e8
data[k].append(value)
else:
pass
#data[k].append(np.nan)
except Exception as e:
print(k, row[k], e, file_path)
raise
for k in data.keys():
data[k] = np.array(data[k])
return data
def transform_curves(data):
output = {}
for k in data.keys():
algorithm, filename = k.rsplit(' ', maxsplit=1)
if filename not in output:
output[filename] = {}
if "-" in algorithm and "-1" not in algorithm:
netname, fold, loss_function, params = algorithm.split('-')
if loss_function in y_labels:
loss_function = y_labels[loss_function]
else:
#print(loss_function)
pass
if netname in y_labels:
netname = y_labels[netname]
else:
#print(netname)
pass
algorithm = netname + "-" + fold + "-" + loss_function + "-" + params
else:
if algorithm in y_labels:
algorithm = y_labels[algorithm]
#else:
# print(algorithm)
output[filename][algorithm] = np.array(data[k])
output[filename]["x"] = get_t(os.path.join(dataDir, "input_"), filename)[:-1]
return output
def get_datafilter(data, key, ignore, key2):
output = []
names = []
if key not in data:
return np.array(output), np.array(names)
for k in sorted(list(set(data[key]))):
if k in ignore or (type(k) == str and k.rsplit(" ",1)[-1] in ("Left", "Right") and k.rsplit(" ",1)[0] in ignore):
continue
datafilter = data[key]==k
if key2:
for k2 in sorted(list(set(data[key2][datafilter]))):
if k2 in ignore or (type(k2) == str and k2.rsplit(" ", 1)[-1] in ("Left", "Right") and k2.rsplit(" ", 1)[0] in ignore):
continue
datafilter2 = np.bitwise_and(data[key2]==k2, datafilter)
output.append(datafilter2)
if k in y_labels:
names.append(y_labels[k] + " " + str(k2))
else:
names.append(str(k) + " " + str(k2))
else:
output.append(datafilter)
if k in y_labels:
names.append(y_labels[k])
else:
if '.' in k:
a, n = k.split('.')
if a in y_labels:
names.append(y_labels[a] + "." + n)
else:
names.append(a)
else:
names.append(str(k))
return np.array(output), np.array(names)
x_labels = { "time": "t [s]", "acc": "accuracy", "label_acc": "accuracy", "dice": "Dice-Sørensen-Coefficient", "delta_t_peak": "Δt/min", "delta_peak": "ΔS(t)",
"delta_auc": "", "ratio_t_peak": "", "ratio_peak": "%", "ratio_auc": "", "aif_mse": "Mean Square Error Sum", "overlap_dice": "Dice Coefficient",
"overlap_false_negative": "False Negative", "overlap_false_positive": "False Positive", "mean_surface_distance": "Mean Surface Distance",
"median_surface_distance": "Median Surface Distance", "recall": "Recall", "precision": "Precision",
"Fp": "Fp [ml/min/100ml]", "vp": "vp [ml/100ml]", "PS": "PS [ml/min/100ml]", "ve": "ve [ml/100ml]", "MTT": "MTT [min]",
"Ktrans": "Ktrans [1/min]", "E": "extraction fraction [%]", "χ": "",
"%Fp": "% Fp", "%vp": "%vp", "%PS": "% PS", "%ve": "% ve", "%MTT": "% MTT",
"%Ktrans": "% Ktrans", "%E": "% extraction fraction", "%χ": "" , "aif_sse": "Squared Error Sum", "aif_normalized_cross_correlation": "Normalized Cross Correlation",
"aif_normalized_mutual_information": "Normalized Mutual Information", "std_surface_distance": "Std Surface Distance", "max_surface_distance": "Maximal Surface Distance",
"overlap_volume_similarity": "Overlap Volume Similarity"}
y_labels = {"time": "Time", "acc": "Accuracy", "label_acc": "Label Accuracy", "dice": "Dice", "delta_t_peak": "Δt_peak", "delta_peak": "ΔS(t_peak)",
"delta_auc": "Δ∫S(t)", "ratio_t_peak": "t_peak/t_peak_target", "ratio_peak": "S(t_peak)/(t_peak_target)", "ratio_auc": "∫S(t)dt / ∫S_target(t)dt",
"aif_mse": "Mean Square Error", "overlap_dice": "Dice", "overlap_false_negative": "False Negative", "overlap_false_positive": "False Positive",
"Fp": "Fp", "vp": "vp", "PS": "PS", "ve": "ve", "MTT": "MTT", "Ktrans": "Ktrans", "E": "E", "χ": "χ",
"%Fp": "Fp", "%vp": "vp", "%PS": "PS", "%ve": "ve", "%MTT": "MTT", "%Ktrans": "Ktrans", "%E": "E", "%χ": "χ",
"mean_surface_distance": "Mean Surface Distance [mm]", "median_surface_distance": "Median Surface Distance [mm]", "recall": "Recall", "precision": "Precision",
"dante": "Dante", "DisLAIF": "Dis LAIF", "DisLAIF_opening": "DisLAIF Opening",
"target": "Target", "target_eroded": "Eroded", "target_middle": "Middle Slice", "target_upper": "Upper Slice", "target_lower": "Lower Slice",
"target_leftSide": "Left Artery", "target_rightSide": "Right Artery", "middle_back": "Middle Back Shift", "middle_fore": "Middle Fore Shift",
"target_back": "Back Shift", "target_fore": "Fore Shift",
"middle_left": "Middle Left Shift", "middle_right": "Middle Right Shift", "middle_up": "Middle Up Shift", "middle_down": "Middle Down Shift",
"middle_leftSide": "Middle Left Side", "middle_rightSide": "Middle Right Side", "middle_eroded": "Middle Eroded", "middle_dilated": "Middle Dilated",
"target_middlem": "Middle Slice -3", "target_middlep": "Middle Slice +3", "target_right": "Right Shift", "target_left": "Left Shift", "target_up": "Up Shift", "target_down": "Down Shift",
"target_dilated": "Dilated", "chen2008": "Chen 2008", "shi2013": "Shi 2013", "parker2003": "Parker 2003", "max05": "Max 0.5%", "gamma_variate": "GVF Fit",
"max05total": "max05total", "noop": "No Operation", "DisLAIF_sato": "DisLAIF Sato", "DisLAIF_frangi": "DisLAIF_frangi", "DisLAIF_hession": "DisLAIF Hessian",
"PTU": "PTU", "CTU": "CTU", "AATH": "AATH", "2CXM": "2CXM", "DP": "DP", "Tofts": "Tofts",
"TNC": "Truncated Newton", "least_squares": "least squares", "trust_constr": "trust constr", 0.0: "0", 1.0: "1", 2.0: "2"}
colors = {"lines": "#ffffff", "time": "#ff0000", "acc": "#00ff00", "label_acc": "#00ff00", "dice": "#0000ff", "delta_t_peak": "#00ffff", "delta_peak": "#ff00ff", "delta_auc": "#ffff00", "ratio_t_peak": "#00ffff", "ratio_peak": "#ff00ff", "ratio_auc": "#ffff00", "aif_mse": "#0000ff", "overlap_dice": "#00ff00", "overlap_false_negative": "#ff0000", "overlap_false_positive": "#00ff00", "Fp": "#ff0000", "vp": "#00ffff", "PS": "#ff00ff", "ve": "#ffff00", "MTT": "#0000ff", "Ktrans": "#00ffff", "E": "#00ff00", "χ": "#aaaaaa",
"dante": "#006600", "dante_lower": "#009900", "dante_upper": "#00AA00", "dante_middle": "#00CC00", "dante_middlem": "#00EE00", "dante_middlep": "#00FF00",
"DisLAIF": "#00ff00", "DisLAIF_lower": "#00ff00", "DisLAIF_upper": "#00ff00", "DisLAIF_middle": "#00ff00", "DisLAIF_middlep": "#00ff00", "DisLAIF_middlem": "#00ff00",
"DisLAIF_opening": "#000000", "DisLAIF_1": "#000000", "DisLAIF_2": "#000000", "DisLAIF_3": "#000000", "DisLAIF_4": "#000000", "DisLAIF_5": "#000000", "target": "#000000", "TumorTarget": "#000000",
"DisLAIF_4_6" : "#000000", "DisLAIF_4_6_8": "#000000", "DisLAIF_4_8": "#000000", "DisLAIF_4_3_8": "#000000", "DisLAIF_3_9": "#aaffaa", "DisLAIF_3_8_9": "#000000", "DisLAIF_gvt_pixel": "#000000", "DisLAIF_2_9": "#000000",
"DisLAIF_sato": "#00aa00", "DisLAIF_frangi": "#00aa00", "DisLAIF_hessian": "#00aa00", "target_sato": "#000000", "target_frangi": "#000000", "target_hessian": "#000000",
"target_middle": "#FF0000", "target_middlep": "#FF00AA", "target_middlem": "#FFAA00", "target_upper": "#0000FF", "target_lower": "#000099", "target_eroded": "#FF0000", "target_dilated": "#990000",
"target_right": "#000000", "target_left": "#000000", "target_up": "#000000", "target_down": "#000000", "target_fore":"#000000", "target_back":"#000000", "target_rightSide": "#000000", "target_leftSide": "#000000", "rightSide": "#000000", "leftSide": "#000000",
"chen2008": "#ff0000", "shi2013": "#0000ff", "max05": "#ff00ff", "parker2003": "#ff00ff", "gamma_variate": "#00ffff", "max05total": "#0000ff",
"noop": "#aaaaaa", "null": "#aaaaaa", "OldDisLAIF": "#aaaaaa", "DisLAIF_size": "#aaaaaa", "DisLAIF_grow" : "#aaaaaa", "DisLAIF_dilated": "#aaaaaa", "DisLAIF_eroded": "#aaaaaa",
"target_test": "#000000", "DisLAIF_meijering": "#00aa00", "DisLAIF_frangi2": "#00aa00", "DisLAIF_sato2": "#00aa00", "DisLAIF4": "#00aa00",
"middle_left": "#FF0000", "middle_right": "#FF0000", "middle_up": "#FF0000", "middle_down": "#00FF00", "middle_fore": "#ff0000", "middle_back": "#ff0000",
"middle_leftSide": "#FF0000", "middle_rightSide": "#FF0000", "middle_eroded": "#FF5500", "middle_dilated": "#995500",
"PTU": "#ff0000", "CTU": "#ffff00", "AATH": "#ff00ff", "2CXM": "#00ff00", "DP": "#0000ff", "Tofts": "#00ffff",
"dice_loss": "#ff0000", "logits_loss": "#00ff00", "tversky_loss": "#0000ff",
"4f1e": "#000000", "4f10000e": "#660000", "4f10e": "#006600", "4f100e": "#000066", "4f500e": "#660066", "4f1000e": "#666666", "4f3000e": "#666600", "4f5000e": "#006666",
"8f1e": "#000000", "8f10000e": "#990000", "8f10e": "#009900", "8f100e": "#000099", "8f500e": "#990099", "8f1000e": "#999999", "8f2000e": "#009900", "8f3000e": "#999900", "8f5000e": "#009999",
"16f1e": "#000000", "16f10000e": "#cc0000", "16f10e": "#00cc00", "16f100e": "#0000cc", "16f500e": "#cc00cc", "16f1000e": "#cccccc", "16f2000e": "#00cc00", "16f3000e": "#cccc00", "16f5000e": "#00cccc",
"32f1e": "#000000", "32f10000e": "#ff0000", "32f10e": "#00ff00", "32f100e": "#0000ff", "32f500e": "#ff00ff", "32f1000e": "#ffffff", "32f2000e": "#00ff00", "32f3000e": "#ffff00", "32f5000e": "#00ffff",
"TNC": "#ff0000", "least_squares": "#00ff00", "trust_constr": "#0000ff",
"UNet-": "#ff0000", "U": "#ff0000", "UHU": "#00ff00", "Deeper": "#00ff00", "UHUNet_deeper": "#009900", "MCUNet": "#ff0000", "UNet": "#ff0000", "VoxResNet": "#ff00ff", "ResNet": "#ff00ff", "MCVoxResNet": "#ff00ff", "SegNet": "#00ffff", "*SegNet": "#559999", "MCUNet3D": "#0000ff", "UNet3D": "#0000ff", "*3D-UNet": "#555599",
"DeepVesselNet": "#0000ff", "V-Net": "#ffff00" }
#colors_dark = {"time": "#aa0000", "acc": "#00aa00", "label_acc": "#00aa00", "dice": "#0000aa", "delta_t_peak": "#00aaaa", "delta_peak": "#aa00aa", "delta_auc": "#aaaa00", "ratio_t_peak": "#00aaaa", "ratio_peak": "#aa00aa", "ratio_auc": "#aaaa00", "aif_mse": "#0000aa", "overlap_dice": "#00aa00", "overlap_false_negative": "#aa0000", "overlap_false_positive": "#00aa00", "Fp": "#aa0000", "vp": "#00aaaa", "PS": "#aa00aa", "ve": "#aaaa00", "MTT": "#0000aa", "Ktrans": "#00aaaa", "E": "#00aa00", "χ": "#000000",
#"dante": "#00aa00", "target": "#0000aa", "target_eroded": "#aa0000", "target_dilated": "#aaaa00", "chen2008": "#00aaaa", "shi2013": "#aa00aa", "max05": "#aa0000", "gamma_variate": "#aaaa00", "max05total": "#0000aa", "noop": "#aaaaaa"}
titles = {"dice": "Dice", "tversky": "Tversky", "logits": "Cross Entropy", "crossentropy": "Cross Entropy", "tanimoto": "Tanimoto",
"dice_loss": "", "tversky_loss": "Tversky Loss", "logits_loss": "Cross Entropy", "crossentropy_loss": "Cross Entropy Loss",
"UNet-": "UNet", "UHU": "UHUNet", "UHUNet_deeper": "Deeper UHUNet", "MCUNet": "Multi-Channel UNet", "tanimoto_loss": "Tanimoto Loss",
"UNet": "UNet", "UHUNet": "UHUNet", "null": "Null", "MCSegNet": "Multi-Channel SegNet", "MCUNet3D": "Multi-Channel 3D-UNet",
"VoxResNet": "ResNet", "SegNet": "SegNet", "UNet3D": "3D-UNet", "MCVoxResNet": "Multi-Channel ResNet",
"4": "#Filter: 4", "8": "#Filter: 8", "16": "#Filter: 16", "32": "#Filter: 32",
"TNC": "Truncated newton", "least_squares": "least squares", "trust_constr": "trust constr",
"2CXM": "2CXM", "DP": "DP", "PTU": "PTU", "CTU": "CTU", "AATH": "AATH", "Tofts": "Tofts",
"delta_auc": "|ΔAUC|", "delta_t_peak": "|Δt_peak|", "delta_peak": "|Δc(t_peak)|", "aif_mse": "Mean squared error", "ratio_peak": "Δc(t_peak) in %",
"ratio_t_peak": "Δt_peak", "recall": "Recall", "precision": "Precision",
"mean_surface_distance": "Mean Surface Distance", "median_surface_distance": "Median Surface Distance",
"DUHUNet2D": "Deeper UHUNet", "UHUNet2D": "UHUNet", "UNet2D": "U-Net", "FCN2D": "DeepVesselNet", "VNet2D": "V-Net", "ResNet2D": "ResNet",
"DUHUNet3D": "Deeper UHUNet 3D", "UHUNet3D": "UHUNet 3D", "UNet3D": "U-Net 3D", "FCN3D": "DeepVesselNet 3D", "VNet3D": "V-Net 3D", "ResNet3D": "ResNet 3D",
"0": "Trans", "1": "Cor", "2": "Sag", "both": "Both", "dce": "DCE", "t2": "T2"}
for k in colors.keys():
colors[k] = colors[k].replace("#ffffff", "#000000")
for k in list(colors.keys()):
if k in y_labels:
colors[y_labels[k]] = colors[k]
for k in list(colors.keys()):
if k in titles:
colors[titles[k]] = colors[k]
for k in list(colors.keys()):
if ' ' in k:
colors[k.split(' ')[-1]] = colors[k]
colors_dark = {}
for k in list(colors.keys()):
colors_dark[k] = colors[k].replace('ff', 'aa')
for p in test:
x_labels[p] = p
y_labels[p] = p
titles[p] = p
for i, p in enumerate(pats):
x_labels[p] = "Pat-" + str(i)
y_labels[p] = "Pat-" + str(i)
titles[p] = "Pat-" + str(i)
pats = pats + [titles[p] for p in pats]
def get_color(label):
try:
if label in colors:
return colors[label]
if " - " in label:
if label.split(' - ')[0] in colors:
return colors[label.split(" - ")[0]]
else:
return colors[label.split(" - ")[1]]
if ":" in label:
return colors[label.split(":")[0]]
if '-' in label and '.' in label and ' ' in label:
return colors[label.split('-')[2].split('.')[0].split(' ')[0]]
if '-' in label:
return get_color(label.split('-')[0])
if '.' in label:
return colors[label.split('.')[0]]
if ' ' in label:
if label.endswith(" Slice") or label.endswith(" Right") or label.endswith(" Left"):
return colors[label.split(' ')[-2]]
if label.endswith('T2') or label.endswith('DCE') or label.endswith('Both') or ' + ' in label:
return colors[label.split(' ')[0]]
return colors[label.split(' ')[-1]]
except Exception as e:
#print(e)
pass
return "k"
def get_dark_color(label):
try:
if label in colors_dark:
return colors_dark[label]
if " - " in label:
if label.split(' - ')[0] in colors_dark:
return colors_dark[label.split(" - ")[0]]
else:
return colors_dark[label.split(" - ")[1]]
if ":" in label:
return colors_dark[label.split(":")[0]]
if '-' in label and '.' in label and ' ' in label:
return colors_dark[label.split('-')[2].split('.')[0].split(' ')[0]]
if '-' in label:
return get_dark_color(label.split('-')[0])
if '.' in label:
return colors_dark[label.split('.')[0]]
if ' ' in label:
if label.endswith(" Slice") or label.endswith(" Right") or label.endswith(" Left"):
return colors_dark[label.split(' ')[-2]]
if label.endswith('T2') or label.endswith('DCE') or label.endswith('Both'):
return colors_dark[label.split(' ')[0]]
return colors_dark[label.split(' ')[-1]]
except Exception as e:
#print(e)
pass
return "k"
matplotlib.pyplot.rcParams.update(
{"ytick.color" : get_color("lines"),
"xtick.color" : get_color("lines"),
"grid.color": get_color("lines"),
"text.color": get_color("lines"),
"axes.labelcolor" : get_color("lines"),
"axes.edgecolor" : get_color("lines"),
"legend.edgecolor" : get_color("lines"),
"legend.framealpha": 0}
)
def save_plot(data, data_type, title, y_label, file_path, stats = False, stretch_target=True, showmeans=True, showfliers=False, annotated_median=True, log_scale=False, show_box=True, significance_thresh=0):
f = plt.figure(figsize=(30,1*len(data)+5))
try:
ax = plt.subplot(111)
[i.set_linewidth(5) for i in ax.spines.values()]
prefix = ""
if data_type[0] == "Δ":
prefix = "Δ"
data_type = data_type[1:]
if title in titles:
ax.set_title(titles[title], pad=20)
else:
ax.set_title(title, pad=20)
if log_scale:
#index = np.argsort([np.quantile(data,0.95) for data in data])[-3:]
if type(log_scale) == int:
index = np.argsort([np.median(data) for data in data])[-log_scale:]
else:
index = np.argsort([np.median(data) for data in data])[-2:]
imax = np.max([np.max(data) for data in data])
#print(imax)
sdata = []
slabels = []
for i,d in enumerate(data):
if i in index:
continue
sdata.append(d)
slabels.append(y_label[i])
if len(sdata) > 0:
p = plt.boxplot(sdata, notch=False, whis=[0,100], showmeans=showmeans, showbox=True, meanline=True, showfliers=showfliers, vert=False, widths=0.9, labels=slabels)
else:
p = plt.boxplot(data, notch=False, whis=[0,100], showmeans=showmeans, showbox=True, meanline=True, showfliers=showfliers, vert=False, widths=0.9, labels=y_label)
with plt.warnings.catch_warnings():
#warnings.simplefilter("error")
try:
plt.tight_layout()
except Exception as e:
print(e, prefix, data_type, title, y_label, file_path)
xlim = ax.get_xlim()
plt.close()
f = plt.figure(figsize=(30,1*len(data)+5))
ax = plt.subplot(111)
[i.set_linewidth(5) for i in ax.spines.values()]
#prefix = ""
#if data_type[0] == "Δ":
# prefix = "Δ"
# data_type = data_type[1:]
if title in titles:
ax.set_title(titles[title], pad=20)
else:
ax.set_title(title, pad=20)
if show_box:
p = plt.boxplot(data, notch=False, whis=[0,100], showmeans=showmeans, meanline=True, showfliers=showfliers, vert=False, widths=0.9, labels=y_label)
else:
p = {}
with plt.warnings.catch_warnings():
#warnings.simplefilter("error")
try:
plt.tight_layout()
except Exception as e:
print(e, prefix, data_type, title, y_label, file_path)
if not log_scale:
xlim = ax.get_xlim()
#[t.label1.set_color(get_color(label)) for label, t in zip(y_label,ax.yaxis.get_major_ticks())]
y_label2 = [label for label in y_label for _ in range(2)]
if stretch_target:
if "Target" in y_label:
target_i = y_label.index("Target")
elif "TumorTarget" in y_label:
target_i = y_label.index("TumorTarget")
elif "Pat-0 Target-TumorTarget" in y_label:
target_i = y_label.index("Pat-0 Target-TumorTarget")
elif "Pat-0 Target-TumorTarget - TumorTarget" in y_label:
target_i = y_label.index("Pat-0 Target-TumorTarget - TumorTarget")
else:
#print(y_label)
target_i = -1
if "boxes" in p:
[box.set_color(get_color(label)) for label, box in zip(y_label,p["boxes"])]
[box.set_linewidth(5) for box in p["boxes"]]
pvalues = {l:0 for l in y_label}
if "whiskers" in p:
[whisker.set_color(get_dark_color(label)) for label, whisker in zip( y_label2,p["whiskers"])]
[whisker.set_linewidth(5) for whisker in p["whiskers"]]
sig = []
for i, x in enumerate(data):
for j, y in enumerate(data[i+1:], start=i+1):
if False and (y_label[i] == "Target" or y_label[j] == "Target"):
pass
elif y_label[j] == "Dis LAIF" or y_label[i] == "Dis LAIF":
pass
elif len(y_label[j].split()) > 1 and len(y_label[i].split()) > 1 and y_label[j].split()[-2] == y_label[i].split()[-2]:
pass
#elif abs(i-j) == 1:
# pass
else:
continue
try:
#_, pvalue = scipy.stats.mannwhitneyu(x, y, alternative='two-sided')
#_, pvalue3 = scipy.stats.ranksums(x, y)
#_, pvalue4 = scipy.stats.wilcoxon(x,y)
#_, pvalue5 = scipy.stats.kruskal(x, y)
_, pvalue = scipy.stats.ttest_rel(x, y)
#print(pvalue1, pvalue3, pvalue4, pvalue5)
#pvalue = np.median((pvalue1, pvalue3, pvalue4, pvalue5))
if y_label[j] == "Dis LAIF" or y_label[i] == "Dis LAIF":
pvalues[y_label[i]] = pvalue
if pvalue < significance_thresh:
sig.append((j-i, i, j, pvalue))
except Exception as e:
pvalues[y_label[i]] = -1
#if not str(e).startswith("All "):
# print(e, i, j, y_label[i], y_label[j])
#raise
if significance_thresh > 0 and len(sig) > 0:
minx = np.array([[True for _ in range(len(data)-1) ] for _ in range(len(sig))], dtype=bool)
for d, i, j, pvalue in sorted(sig, key=lambda i: (i[0], i[2])):
lx = max(np.max(p["whiskers"][i*2].get_xdata()), np.max(p["whiskers"][i*2+1].get_xdata()))
ly = max(np.median(p["whiskers"][i*2].get_ydata()), np.median(p["whiskers"][i*2+1].get_ydata()))
rx = max(np.max(p["whiskers"][j*2].get_xdata()), np.max(p["whiskers"][j*2+1].get_xdata()))
ry = max(np.median(p["whiskers"][j*2].get_ydata()), np.median(p["whiskers"][j*2+1].get_ydata()))
#dy = ry-ly
dy = j-i - 1.5# (len(data))//2
#bx = np.max([np.max(w.get_xdata()) for i, w in enumerate(p["whiskers"]) if y_label[i//2] != "Target"])
bx = xlim[1]
#bx = np.max([np.max(w.get_xdata()) for i, w in enumerate(p["whiskers"])])
ly = ly - 0.1*dy
ry = ry + 0.1*dy
rx = bx + 0.02*bx
lx = bx + 0.02*bx
for k in range(minx.shape[0]):
if minx[k,i:j].all():
bx = bx + (k+2)*0.02*bx
minx[k,i:j] = False
break
#bx = bx + 0.05*bx*(j-i)
#if (j-i) > 1:
# bx = bx + 0.01*bx*(i-1)
#rx = rx + (bx-rx)/2
#lx = lx + (bx-lx)/2
#print(i, j, ly, ry, bx)
plt.plot([lx, bx], [ly, ly], c=p["whiskers"][i*2].get_color(), clip_on=False)
plt.plot([bx,bx], [ly, ry], c='black', clip_on=False)
plt.plot([rx, bx], [ry, ry], c=p["whiskers"][j*2].get_color(), clip_on=False)
#plt.text(bx, (ly+ry)/2, "{:.4f}".format(pvalue) )
#if log_scale:
# for k in reversed(range(minx.shape[0])):
# if minx[k].any():
# #xlim = (xlim[0], xlim[1] + (k+3)*0.02*xlim[1])
# break
if "medians" in p:
if stretch_target and target_i >= 0:
p["medians"][target_i].set_ydata([ np.min([y for median in p["medians"] for y in median.get_ydata()]), np.max([y for median in p["medians"] for y in median.get_ydata()]) ])
#p["medians"][target_i].set_xdata([ np.min([y for median in p["medians"] for y in median.get_xdata()]), np.max([y for median in p["medians"] for y in median.get_xdata()]) ])
#if annotated_median:
# ydata = [ np.min([y for median in p["medians"] for y in median.get_ydata()]), np.max([y for median in p["medians"] for y in median.get_ydata()]) ]
# [median.set_ydata(ydata) for median in p["medians"]]
[median.set_color(get_dark_color(label)) for label, median in zip(y_label,p["medians"])]
[median.set_linewidth(5) for median in p["medians"]]
if "means" in p:
[mean.set_color(get_dark_color(label)) for label, mean in zip(y_label,p["means"])]
[mean.set_linewidth(5) for mean in p["means"]]
if "caps" in p:
[cap.set_color(get_dark_color(label)) for label, cap in zip(y_label2,p["caps"])]
[cap.set_linewidth(5) for cap in p["caps"]]
if "fliers" in p:
[flier.set_color(get_dark_color(label)) for label, flier in zip(y_label,p["fliers"])]
[flier.set_markerfacecolor(get_dark_color(label)) for label, flier in zip(y_label,p["fliers"])]
[flier.set_fillstyle("full") for label, flier in zip(y_label,p["fliers"])]
#pos = range(0, len(data))
#ax.set_yticks(pos)
#ax.set_yticklabels(y_label)
#max_length = str(max(len(title), np.max([len(l) for l in y_label])) + 2)
if stats:
#tabular = "\\begin{table}\n\\centering\n\\resizebox{\\linewidth}{!}{\n\\begin{tabular}{| c | c | c | c | c | c | c | c |} \n \\hline \n"
#tabular = "\\begin{longtable}{| c | c | c | c | c | c | c | c |}\n\hline\n"
tabular = "\\begin{longtable}{| c | c | c | c | c | c |}\n\hline\n"
#tabular += prefix + y_labels[data_type] + " & Median & Average & Std & P \\\\ \\hline \n"
#tabular += "Architecture & Loss & Filter & Epochs & Orientation & Median & Average & Std \\\\ \\hline \n \hline \n"
tabular += "Architecture & Loss & Filter & Epochs & Slice & Average \\\\ \\hline \n \hline \n"
#print(("{:" + max_length + "} {:>15} {:>15} {:>15} {:>15} {:>15} {:>15}").format(title, "min", "q25", "median", "q75", "max", "avg"))
for i, (d, l) in enumerate(zip(data, y_label)):
if(len(d) == 0): continue
if not show_box:
plt.scatter(d, [i+1]*len(d), color=get_color(l), linewidths="9")
means = plt.scatter(np.mean(d), [i+1,], color=get_dark_color(l), linewidths="120", marker="|")
for m in means.get_paths():
m.vertices = [[m.vertices[0][0], m.vertices[0][1]-3], [m.vertices[1][0], m.vertices[1][1]+3]]
avg = np.mean(d)
q0 = np.quantile(d, 0)
q25 = np.quantile(d, 0.25)
q5 = np.median(d)
q75 = np.quantile(d, 0.75)
q1 = np.quantile(d, 1)
std = np.std(d)
if annotated_median:
ax.annotate("median: {:.2f} average: {:.2f}".format(q5,avg), xy=(1, (i+0.5) / len(data)), xycoords='axes fraction', xytext=(5,0), textcoords='offset pixels', horizontalalignment='left', verticalalignment='center')
if stats:
#tabular += ("{} & {:.4f} & {:.4f} & {:.4f} & {:.4f} & {:.4f} & {:.4f} & {:.4f} \\\\ \\hline \n").format(l.split(' - ')[-1], q0, q25, q5, q75, q1, avg, std).replace('_', ' ')
if ': ' in l:
name, l1 = l.split(' - ')[-1].replace('_',' ').split(': ', maxsplit=1)
#if len(l1.split(' ')) < 7:
# print(l1)
loss = l1.split(' ')[0]
filters = l1.split(' ')[2]
epochs = l1.split(' ')[3]
orientation = l1.split(' ')[5]
else:
name = l
loss = ""
filters = ""
epochs = ""
orientation = ""
if loss in titles:
#tabular += ("{} & {} & {} & {} & {} & {:.2f} & {:.2f} & {:.2f} \\\\ \\hline \n").format(name.replace("Multi-Channel", "MC"), titles[loss], filters, epochs, orientation, q5, avg, std).replace('_', ' ')
tabular += ("{} & {} & {} & {} & {} & ${:.5f} \\pm {:.5f}$ \\\\ \\hline \n").format(name.replace("Multi-Channel", "MC"), titles[loss], filters, epochs, orientation, avg, std).replace('_', ' ')
else:
#tabular += ("{} & {} & {} & {} & {} & {:.2f} & {:.2f} & {:.2f} \\\\ \\hline \n").format(name.replace("Multi-Channel", "MC"), loss, filters, epochs, orientation, q5, avg, std).replace('_', ' ')
tabular += ("{} & {} & {} & {} & {} & ${:.5f} \\pm {:.5f}$ \\\\ \\hline \n").format(name.replace("Multi-Channel", "MC"), loss, filters, epochs, orientation, avg, std).replace('_', ' ')
#print(("{:" + max_length + "} {:15.4f} {:15.4f} {:15.4f} {:15.4f} {:15.4f} {:15.4f}").format(l, q0, q25, q5, q75, q1, avg))
#if np.isfinite(q5) and annotated_median:
#ax.annotate("median = {:.2f}".format(q5), xy=(q5, i+1), xycoords='data', xytext=(10, 27),
# textcoords='offset pixels', arrowprops=None, horizontalalignment='left',
# verticalalignment='center')
#ax.annotate("median = {:.2f}".format(q5), xy=(q5, i+1), xycoords='data', xytext=(1.01, 0),
# textcoords=('axes fraction', 'offset pixels'), arrowprops=None, horizontalalignment='left',
# verticalalignment='center')
ax.set_xlabel(prefix + x_labels[data_type])
if not show_box:
ts = [t for t in ax.get_yticklabels()]
for i,label in enumerate(y_label):
if len(ts) == i+1:
break
ts[i+1].set_text(label)
ts[i+1].set_color(get_color(label))
ax.set_yticklabels(ts)
if log_scale:
#ax.set_xscale('symlog', linthershx=0.001)
#ax.set_xscale('log')
#ax.set_xscale('logit')
ax.set_xscale('linear')
ax.set_xlim(xlim)
else:
ax.set_xscale('linear')
ax.set_xlim(xlim)
#ax.set_yticklabels(ts)
#[t.label1.set_color(get_color(label)) for label, t in zip(y_label,ax.yaxis.get_major_ticks())]
#ax.set_yticklabels(y_label)
#[t.label1.set_text(label) for label, t in zip(y_label,ax.yaxis.get_major_ticks())]
with plt.warnings.catch_warnings():
#warnings.simplefilter("error")
try:
plt.tight_layout()
except Exception as e:
print(e, prefix, data_type, title, len(y_label), file_path)
if stats:
tabular += "\\caption{}\n"
tabular += "\\label{tab:" + file_path.split('\\')[-1] + "} \n\end{longtable}\n"
with open(file_path + ".tex", "w", encoding="utf8") as f:
f.write(tabular)
#savefig(file_path + ".svg", transparent=True)
plt.savefig(file_path + ".png", transparent=True)
except Exception as e:
raise e
finally:
plt.close()
def save_plot_clean(data, title, y_label, file_path, stretch_target=True, showmeans=True, showfliers=False, significance_thresh=0):
f = plt.figure(figsize=(30,1*len(data)+5))
ax = plt.subplot(111)
[i.set_linewidth(5) for i in ax.spines.values()]
ax.set_title(title, pad=20)
p = plt.boxplot(data, notch=False, whis=[5,95], showmeans=showmeans, meanline=True, showfliers=showfliers, vert=False, widths=0.9, labels=y_label)
if stretch_target:
if "Target" in y_label:
target_i = y_label.index("Target")
elif "TumorTarget" in y_label:
target_i = y_label.index("TumorTarget")
elif "Pat-0 Target-TumorTarget" in y_label:
target_i = y_label.index("Pat-0 Target-TumorTarget")
elif "Pat-0 Target-TumorTarget - TumorTarget" in y_label:
target_i = y_label.index("Pat-0 Target-TumorTarget - TumorTarget")
else:
target_i = -1
y_label2 = [label for label in y_label for _ in range(2)]
if "boxes" in p:
[box.set_color(get_color(label)) for label, box in zip(y_label,p["boxes"])]
[box.set_linewidth(5) for box in p["boxes"]]
if "medians" in p:
if stretch_target and target_i >= 0:
p["medians"][target_i].set_ydata([ np.min([y for median in p["medians"] for y in median.get_ydata()]), np.max([y for median in p["medians"] for y in median.get_ydata()]) ])
[median.set_color(get_dark_color(label)) for label, median in zip(y_label,p["medians"])]
[median.set_linewidth(5) for median in p["medians"]]
if "means" in p:
[mean.set_color(get_dark_color(label)) for label, mean in zip(y_label,p["means"])]
[mean.set_linewidth(5) for mean in p["means"]]
if "caps" in p:
[cap.set_color(get_dark_color(label)) for label, cap in zip(y_label2,p["caps"])]
[cap.set_linewidth(5) for cap in p["caps"]]
if "fliers" in p:
[flier.set_color(get_dark_color(label)) for label, flier in zip(y_label,p["fliers"])]
[flier.set_markerfacecolor(get_dark_color(label)) for label, flier in zip(y_label,p["fliers"])]
[flier.set_fillstyle("full") for label, flier in zip(y_label,p["fliers"])]
if "whiskers" in p:
[whisker.set_color(get_dark_color(label)) for label, whisker in zip( y_label2,p["whiskers"])]
[whisker.set_linewidth(5) for whisker in p["whiskers"]]
if significance_thresh > 0:
xlim = ax.get_xlim()
sig = []
for i, x in enumerate(data):
for j, y in enumerate(data[i+1:], start=i+1):
if y_label[i] == "Target" or y_label[j] == "Target":
pass
if y_label[j] != "Dis LAIF" and y_label[i] != "Dis LAIF":
pass
try:
_, pvalue = scipy.stats.mannwhitneyu(x, y, alternative='two-sided')
if pvalue < significance_thresh:
sig.append((j-i, i, j, pvalue))
except Exception as e:
print(e, i, j, y_label[i], y_label[j])
if len(sig) > 0:
minx = np.array([[True for _ in range(len(data)-1) ] for _ in range(len(sig))], dtype=bool)
for d, i, j, pvalue in sorted(sig, key=lambda i: (i[0], i[2])):
lx = max(np.max(p["whiskers"][i*2].get_xdata()), np.max(p["whiskers"][i*2+1].get_xdata()))
ly = max(np.median(p["whiskers"][i*2].get_ydata()), np.median(p["whiskers"][i*2+1].get_ydata()))
rx = max(np.max(p["whiskers"][j*2].get_xdata()), np.max(p["whiskers"][j*2+1].get_xdata()))
ry = max(np.median(p["whiskers"][j*2].get_ydata()), np.median(p["whiskers"][j*2+1].get_ydata()))
dy = j-i - (len(data))//2
bx = xlim[1]
ly = ly - 0.1*dy
ry = ry + 0.1*dy
rx = bx + 0.02*bx
lx = bx + 0.02*bx
for k in range(minx.shape[0]):
if minx[k,i:j].all():
bx = bx + (k+2)*0.02*bx
minx[k,i:j] = False
break
plt.plot([lx, bx], [ly, ly], c=p["whiskers"][i*2].get_color(), clip_on=False)
plt.plot([bx,bx], [ly, ry], c='black', clip_on=False)
plt.plot([rx, bx], [ry, ry], c=p["whiskers"][j*2].get_color(), clip_on=False)
ax.set_xlim(xlim)
with plt.warnings.catch_warnings():
try:
plt.tight_layout()
except Exception as e:
print(e, title, y_label, file_path)
plt.savefig(file_path + ".png", transparent=True)
plt.close()
if __name__ == "__main__":
export_aif_stats = False
export_aif_curves = False
export_aif_eval = False
dataDir = "./"
if not os.path.exists(os.path.join(dataDir, "graphs")):
os.makedirs(os.path.join(dataDir, "graphs"))
if not os.path.exists(os.path.join(dataDir, "perf")):
os.makedirs(os.path.join(dataDir, "perf"))
if not os.path.exists(os.path.join(dataDir, "aifs")):
os.makedirs(os.path.join(dataDir, "aifs"))
if not os.path.exists(os.path.join(dataDir, "tumors")):
os.makedirs(os.path.join(dataDir, "tumors"))
matplotlib.rc("font", size=40)
matplotlib.rc("lines", linewidth=3)
if export_aif_stats:
aif_csv = readCSV(os.path.join(dataDir, "aif.csv"))
tabular = "\\begin{tabular}{|c||c|c|c||c|c|c|}\n\hline\n& \\multicolumn{3}{c||}{Mean Error compared to Manual Annotation} & \\multicolumn{3}{c|}{Median Error}\\\\ \n \\hline \n"
tabular += "AIF Algorithm & $\\Delta t_{peak}$ & $\\Delta \\hat{S}(t_{peak})$ & $\\Delta AUC$ & $\\Delta t_{peak}$ & $\\Delta \\hat{S}(t_{peak})$ & $\\Delta AUC$ \\\\ \\hhline{|=||===||===|}\n"
stats = {}
aifs = {}
for filename in aif_csv.keys():
algorithm, _ = filename.rsplit(' ', maxsplit=1)
if algorithm not in ["target", "DisLAIF", "chen2008", "shi2013", "gamma_variate", "parker2003"]:
continue
if algorithm not in aifs:
aifs[algorithm] = []
aifs[algorithm].append(aif_csv[filename])
stats["target"] = {'peak': [], 'peak_t': [], 'auc': [], 'n_auc': [], 'n_peak': [], 'n_peak_t': []}
for aif in aifs["target"]:
stats["target"]["peak"].append(np.max(aif))
stats["target"]["peak_t"].append(np.argmax(aif))
stats["target"]["auc"].append(np.sum(aif))
stats["target"]["n_peak"].append(np.max((aif-aif[0])))
stats["target"]["n_auc"].append(np.sum((aif-aif[0]) / stats["target"]["n_peak"][-1] ))
stats["target"]["n_peak_t"].append(np.argmax(aif-aif[0]))
for algorithm in aifs:
if algorithm not in stats:
stats[algorithm] = {'peak': [], 'peak_t': [], 'auc': [], 'n_auc': [], 'n_peak': [], 'n_peak_t': []}
else:
continue
for i, aif in enumerate(aifs[algorithm]):
stats[algorithm]['peak'].append(np.max(aif))
stats[algorithm]['peak_t'].append(np.argmax(aif))
stats[algorithm]['auc'].append(np.sum(aif))
stats[algorithm]['n_peak'].append(np.abs(1-np.max((aif-aif[0])/stats["target"]["n_peak"][i])))
stats[algorithm]['n_auc'].append( np.sum(np.abs((aifs["target"][i]-aifs["target"][0])/stats["target"]["n_peak"][i] - (aif-aif[0])/stats["target"]["n_peak"][i])))
stats[algorithm]['n_peak_t'].append( np.abs(np.argmax(aif)-stats["target"]["peak_t"][i]) )
for algorithm, values in stats.items():
tabular += ("{} & ${:.3f} \\pm {:.3f}$ & ${:.3f} \\pm {:.3f}$ & ${:.3f} \\pm {:.3f}$ & ${:.3f}$ & ${:.3f}$ & ${:.3f}$ \\\\ \\hline \n").format(algorithm,
np.mean(values['n_peak_t']), np.std(values['n_peak_t']), np.mean(values['n_peak']), np.std(values['n_peak']),
np.mean(values['n_auc']), np.std(values['n_auc']), np.median(values['n_peak_t']), np.median(values['n_peak']), np.median(values['n_auc']) )
tabular += "\n\end{tabular}\n"
with open(os.path.join(dataDir, 'aifs/', "aif_stats.tex"), "w", encoding="utf8") as f:
f.write(tabular)
if export_aif_curves:
aif_csv = readCSV(os.path.join(dataDir, "aif.csv"))
aif = transform_curves(aif_csv)
#print(aif.keys())
for filename in aif.keys():
break
plt.figure(figsize=(30,15))
x = aif[filename]["x"]*60
if len(x) != len(aif[filename]["Target"]):
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"])
ax = plt.subplot(111)
#if filename in titles:
# ax.set_title(titles[filename])
#else:
# ax.set_title(filename)
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("t / s", fontsize=40)
ax.set_ylabel("avg [$\hat{S}(t)$]", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm not in [y_labels[l] for l in ("target", "target_eroded", "target_dilated", "target_right", "target_left", "target_up", "target_down")]:
continue
plt.plot(x, aif[filename][algorithm]/target_peak, label=algorithm, linewidth=5, color=get_color(algorithm))
xv = x[np.argmax(aif[filename][algorithm])]
yv = np.max(aif[filename][algorithm])
if algorithm == "Target":
ax.annotate("max S(t) = {:.0f}".format(yv), xy=(xv,yv), xycoords='data', xytext=(0.3, 0.6),
textcoords='axes fraction', arrowprops={'facecolor':get_color("lines"), 'shrink':0.05}, horizontalalignment='left',
verticalalignment='center')
else:
ax.annotate("max S(t) = {:.0f} ≙ {:2.0f}%".format(yv, 100*yv/target_peak), xy=(xv,yv), xycoords='data', xytext=(0.3, 0.7 if algorithm=="Eroded" else 0.5),
textcoords='axes fraction', arrowprops={'facecolor':get_color("lines"), 'shrink':0.05}, horizontalalignment='left',
verticalalignment='center')
plt.legend(loc="upper right", fontsize=40)
plt.savefig(os.path.join(dataDir, 'aifs/', "aif_diff-" + filename + ".png"), transparent=True)
plt.close()
for filename in aif.keys():
break
plt.figure(figsize=(30,15))
x = aif[filename]["x"]*60
if len(x) != len(aif[filename]["Target"]):
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"])
ax = plt.subplot(111)
if filename in titles:
ax.set_title(titles[filename])
else:
ax.set_title(filename)
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("t / s", fontsize=40)
ax.set_ylabel("avg S(t)", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm not in [y_labels[l] for l in ("target", "target_middle", "target_upper", "target_lower", "target_middlep", "target_middlem")]:
continue
plt.plot(x, aif[filename][algorithm]/target_peak, label=algorithm, linewidth=5, color=get_color(algorithm))
xv = x[np.argmax(aif[filename][algorithm])]
yv = np.max(aif[filename][algorithm])
if algorithm == "Target":
ax.annotate("max S(t) = {:.0f}".format(yv), xy=(xv,yv), xycoords='data', xytext=(0.3, 0.6),
textcoords='axes fraction', arrowprops={'facecolor':get_color("lines"), 'shrink':0.05}, horizontalalignment='left',
verticalalignment='center')
else:
ax.annotate("max S(t) = {:.0f} ≙ {:2.0f}%".format(yv, 100*yv/target_peak), xy=(xv,yv), xycoords='data', xytext=(0.3, 0.7 if algorithm=="Eroded" else 0.5),
textcoords='axes fraction', arrowprops={'facecolor':get_color("lines"), 'shrink':0.05}, horizontalalignment='left',
verticalalignment='center')
plt.legend(loc="upper right", fontsize=40)
plt.savefig(os.path.join(dataDir, '/aifs/', "aif_2d-" + filename + ".png"), transparent=True)
plt.close()
for i, filename in enumerate(aif.keys()):
break
#data = []
#for algorithm in aif[filename]:
# data.append(aif[filename][algorithm])
plt.figure(figsize=(30,15))
x = aif[filename]["x"]*60
if len(x) != len(aif[filename]["Target"]):
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"])
ax = plt.subplot(111)
#if filename in titles:
# ax.set_title(titles[filename])
#else:
# ax.set_title(filename)
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("t / s", fontsize=40)
ax.set_ylabel("avg S(t)", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm in ("x", "max05", "max05total", "No Operation", "Chen 2008", "Shi 2013", "GVF Fit"):
continue
if not (algorithm.startswith("dante") or algorithm in ("Target", "Middle")):
continue
plt.plot(x, aif[filename][algorithm]/target_peak, label=algorithm, linewidth=5, color=get_color(algorithm))
plt.legend(loc="upper right", fontsize=30)
plt.savefig(os.path.join(dataDir, '/aifs/', "aif-dante-" + str(i) + ".png"), transparent=True)
plt.close()
f = open("aif.csv", "w")
for i,filename in enumerate(aif.keys()):
plt.figure(figsize=(30,15))
x = aif[filename]["x"]*60
if len(x) != len(aif[filename]["Target"]):
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"])
ax = plt.subplot(111)
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("t / s", fontsize=40)
ax.set_ylabel("avg $S(t)$", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm not in ("Dis LAIF", "Target", "Parker 2003", "Shi 2013", "Chen 2008", "GVF Fit"):
continue
plt.plot(x, aif[filename][algorithm], label=algorithm, linewidth=5, color=get_color(algorithm))
plt.legend(loc="upper right", fontsize=30)
d = aif[filename]["Dis LAIF"]
t = aif[filename]["Target"]
f.write(str(i) + "," + str(np.abs(np.max(d)-np.max(t))) + "," + str(np.abs(np.argmax(d)-np.argmax(t))) + "," + str(np.abs(np.sum(d)-np.sum(t))) + "\n")
plt.savefig(os.path.join(dataDir, '/aifs/', "aif-" + str(i) + ".png"), transparent=True)
plt.close()
f.close()
for i,filename in enumerate(aif.keys()):
plt.figure(figsize=(30,15))
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"])
ax = plt.subplot(111)
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("timestep", fontsize=40)
ax.set_ylabel("avg $S(t)$", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm not in ("Dis LAIF", "Target", "Parker 2003", "Shi 2013", "Chen 2008", "GVF Fit"):
continue
plt.plot(x, aif[filename][algorithm], label=algorithm, linewidth=5, color=get_color(algorithm))
plt.legend(loc="upper right", fontsize=30)
plt.savefig(os.path.join(dataDir, '/aifs/', "aif-no_time-" + str(i) + ".png"), transparent=True)
plt.close()
f = open("aif_norm.csv", "w")
for i,filename in enumerate(aif.keys()):
#data = []
#for algorithm in aif[filename]:
# data.append(aif[filename][algorithm])
plt.figure(figsize=(30,15))
x = aif[filename]["x"]*60
if len(x) != len(aif[filename]["Target"]):
x = np.arange(0,len(aif[filename]["Target"]))
target_peak = np.max(aif[filename]["Target"]-aif[filename]["Target"][0])
ax = plt.subplot(111)
#if i in titles:
# ax.set_title(titles[i])
#else:
# ax.set_title("Patient " + str(i))
ax.set_facecolor(get_color("lines"))
ax.set_xlabel("t / s", fontsize=40)
ax.set_ylabel("avg $\hat{S}(t)$", fontsize=40)
for algorithm in sorted(aif[filename].keys()):
if algorithm in ("x", "max05", "max05total", "No Operation", "Dante"):
continue
if algorithm not in ("Dis LAIF", "Target", "Parker 2003", "Shi 2013", "Chen 2008", "GVF Fit"):
continue
plt.plot(x, (aif[filename][algorithm]-aif[filename][algorithm][0])/target_peak, label=algorithm, linewidth=5, color=get_color(algorithm))
plt.legend(loc="upper right", fontsize=30)
d = aif[filename]["Dis LAIF"]
t = aif[filename]["Target"]
t = t-t[0]
d = (d-d[0]) / np.max(t)
t = t / np.max(t)
f.write(str(i) + "," + str(np.abs(np.max(d)-np.max(t))) + "," + str(np.abs(np.argmax(d)-np.argmax(t))) + "," + str(np.abs(np.sum(d)-np.sum(t))) + "\n")
plt.savefig(os.path.join(dataDir, 'aifs/', "aif-norm-" + str(i) + ".png"), transparent=True)
plt.close()
if export_aif_eval: