Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

viz.py 39 KB

You have to be logged in to leave a comment. Sign In
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
1001
  1. import pickle as pkl
  2. import sys
  3. sys.path.append('..')
  4. import config
  5. import data
  6. from os.path import join as oj
  7. import matplotlib.gridspec as grd
  8. import numpy as np
  9. import pandas as pd
  10. import seaborn as sns
  11. from matplotlib import pyplot as plt
  12. from matplotlib_venn import venn2
  13. from sklearn import decomposition
  14. from sklearn import metrics
  15. from sklearn.covariance import EllipticEnvelope
  16. from sklearn.ensemble import IsolationForest
  17. from sklearn.neighbors import LocalOutlierFactor
  18. from sklearn.svm import OneClassSVM
  19. from sklearn.utils.multiclass import unique_labels
  20. import os
  21. import matplotlib.ticker as mtick
  22. from config import DIR_FIGS
  23. from matplotlib.colors import LinearSegmentedColormap
  24. from matplotlib import cm
  25. from matplotlib.colors import ListedColormap
  26. import dvu
  27. # DIR_FILE = os.path.dirname(os.path.realpath(__file__)) # directory of this file
  28. # DIR_FIGS = oj(DIR_FILE, '../reports/figs')
  29. try:
  30. from skimage.external.tifffile import imread
  31. except:
  32. from skimage.io import imread
  33. cb2 = '#66ccff'
  34. cb = '#1f77b4'
  35. co = '#ff7f0e'
  36. cr = '#cc0000'
  37. cp = '#cc3399'
  38. cy = '#d8b365'
  39. cg = '#5ab4ac'
  40. cmap = LinearSegmentedColormap.from_list(
  41. name='orange-blue',
  42. colors=[(205/255, 85/255, 51/255),
  43. 'lightgray',
  44. (50/255, 129/255, 168/255)]
  45. )
  46. def savefig(s: str, png=False):
  47. # plt.tight_layout()
  48. plt.savefig(oj(DIR_FIGS, 'fig_' + s + '.pdf'), bbox_inches='tight')
  49. if png:
  50. plt.savefig(oj(DIR_FIGS, 'fig_' + s + '.png'), dpi=300, bbox_inches='tight')
  51. def fix_feat_name(s):
  52. return s.replace('_', ' ').replace('X', 'Clath').capitalize()
  53. def plot_confusion_matrix(y_true, y_pred, classes,
  54. normalize=False,
  55. title=None,
  56. cmap=plt.cm.Blues):
  57. """
  58. This function prints and plots the confusion matrix.
  59. Normalization can be applied by setting `normalize=True`.
  60. Params
  61. ------
  62. classes: np.ndarray(Str)
  63. classes=np.array(['aux-', 'aux+'])
  64. """
  65. plt.figure(dpi=300)
  66. if not title:
  67. if normalize:
  68. title = 'Normalized confusion matrix'
  69. else:
  70. title = 'Confusion matrix, without normalization'
  71. # Compute confusion matrix
  72. cm = metrics.confusion_matrix(y_true, y_pred)
  73. # Only use the labels that appear in the data
  74. classes = classes[unique_labels(y_true.astype(np.int), y_pred.astype(np.int))]
  75. if normalize:
  76. cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
  77. # fig, ax = plt.subplots()
  78. im = plt.imshow(cm, interpolation='nearest', cmap=cmap)
  79. ax = plt.gca()
  80. # ax.figure.colorbar(im, ax=ax)
  81. # We want to show all ticks...
  82. ax.set(xticks=np.arange(cm.shape[1]),
  83. yticks=np.arange(cm.shape[0]),
  84. # ... and label them with the respective list entries
  85. xticklabels=classes, yticklabels=classes,
  86. # title=title,
  87. ylabel='True label',
  88. xlabel='Predicted label')
  89. # Rotate the tick labels and set their alignment.
  90. plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
  91. rotation_mode="anchor")
  92. # Loop over data dimensions and create text annotations.
  93. fmt = '.2f' if normalize else 'd'
  94. thresh = cm.max() / 2.
  95. for i in range(cm.shape[0]):
  96. for j in range(cm.shape[1]):
  97. ax.text(j, i, format(cm[i, j], fmt),
  98. ha="center", va="center",
  99. color="white" if cm[i, j] > thresh else "black")
  100. return ax
  101. def highlight_max(data, color='#0e5c99'):
  102. '''
  103. highlight the maximum in a Series or DataFrame
  104. '''
  105. attr = 'background-color: {}'.format(color)
  106. if data.ndim == 1: # Series from .apply(axis=0) or axis=1
  107. is_max = data == data.max()
  108. return [attr if v else '' for v in is_max]
  109. else: # from .apply(axis=None)
  110. is_max = data == data.max().max()
  111. return pd.DataFrame(np.where(is_max, attr, ''),
  112. index=data.index, columns=data.columns)
  113. # visualize biggest errs
  114. def viz_biggest_errs(df, idxs_cv, idxs, Y_test, preds, preds_proba,
  115. num_to_plot=20,
  116. aux_thresh=642,
  117. show_track_num=True,
  118. show_track_pid=False,
  119. sort_by_residuals=True,
  120. width_mult=3,
  121. plot_x=True,
  122. plot_y=True,
  123. plot_z=False,
  124. plot_axhline=True,
  125. xlim_constant=True,
  126. ylim: tuple=None,
  127. yticks=None,
  128. yticklabels=None,
  129. lifetime_max=None,
  130. text_labels=False,
  131. text_label_size=25):
  132. '''Visualize X and Y where the top examples are the most wrong / least confident
  133. Params
  134. ------
  135. idxs_cv: integer ndarray
  136. which idxs are not part of the test set (usually just 0, 1, 2, ...)
  137. idxs: boolean ndarray
  138. subset of points to plot
  139. '''
  140. DIFF = 0 # use this to ensure values are all positive
  141. # deal with idxs
  142. if idxs is not None:
  143. Y_test = Y_test[idxs]
  144. preds = preds[idxs]
  145. preds_proba = preds_proba[idxs]
  146. if idxs_cv is None:
  147. idxs_cv = np.arange(df.shape[0])
  148. df = df.iloc[idxs_cv][idxs]
  149. # get args to sort by
  150. if sort_by_residuals:
  151. residuals = np.abs(Y_test - preds_proba)
  152. args = np.argsort(residuals)[::-1]
  153. dft = df.iloc[args]
  154. else:
  155. dft = df
  156. if lifetime_max is None:
  157. lifetime_max = np.max(dft.lifetime.values)
  158. if num_to_plot is None:
  159. num_to_plot = dft.shape[0]
  160. R = int(np.sqrt(num_to_plot))
  161. C = num_to_plot // R # + 1
  162. plt.figure(figsize=(C * width_mult, R * 2.5), dpi=200)
  163. i = 0
  164. for r in range(R):
  165. for c in range(C):
  166. if i < dft.shape[0]:
  167. row = dft.iloc[i]
  168. ax = plt.subplot(R, C, i + 1)
  169. # show nums on tracks
  170. if show_track_num:
  171. ax.text(.5, .9, f'{i}', # row.pid
  172. horizontalalignment='right',
  173. transform=ax.transAxes)
  174. elif show_track_pid:
  175. ax.text(.5, .9, f'{row.pid}', # row.pid
  176. horizontalalignment='right',
  177. transform=ax.transAxes)
  178. # plt.axis('off')
  179. if '1.5s' in row['cell_num']:
  180. interval = 1.5
  181. else:
  182. interval = 1
  183. if plot_x:
  184. plt.plot(interval * np.arange(len(row["X"])), np.array(row["X"]) + DIFF, color=cr, label='clath', lw=2) # could do X_extended
  185. if plot_y:
  186. plt.plot(interval * np.arange(len(row["Y"])), np.array(row["Y"]) + DIFF, color=cg, label='aux', lw=2)
  187. if plot_z:
  188. plt.plot(interval * np.arange(len(row["Z"])), np.array(row["Z"]) + DIFF, color='gray', label='dyn')
  189. if xlim_constant:
  190. plt.xlim([-1, lifetime_max])
  191. if plot_axhline:
  192. plt.axhline(aux_thresh, color='gray', alpha=0.5, lw=2)
  193. #plt.yscale('log')
  194. if ylim is not None:
  195. plt.ylim((ylim[0] + DIFF, ylim[1] + DIFF))
  196. if not r == R - 1:
  197. plt.xticks([])
  198. if not c == 0:
  199. plt.yticks([])
  200. elif yticks is not None:
  201. plt.yticks(yticks, labels=yticklabels)
  202. i += 1
  203. if text_labels:
  204. plt.text(len(row["X"]), row["X"][-1] + DIFF, 'Clathrin', color=cr,
  205. fontsize=text_label_size, fontweight='bold')
  206. plt.text(len(row["Y"]), row["Y"][-1] + DIFF, 'Auxilin', color=cg,
  207. fontsize=text_label_size, fontweight='bold')
  208. if plot_z:
  209. plt.text(len(row["Z"]), row["Z"][-1] + DIFF, 'Dynamin',
  210. fontsize=text_label_size, color='gray', fontweight='bold')
  211. plt.tight_layout()
  212. return dft
  213. def viz_errs_2d(df, idxs_test, preds, Y_test, key1='x_pos', key2='y_pos', X=None, plot_correct=True):
  214. '''visualize distribution of errs wrt to 2 dimensions
  215. '''
  216. x_pos = df[key1].iloc[idxs_test]
  217. y_pos = df[key2].iloc[idxs_test]
  218. plt.figure(dpi=200)
  219. ms = 4
  220. me = 1
  221. if plot_correct:
  222. plt.plot(x_pos[(preds == Y_test) & (preds == 1)], y_pos[(preds == Y_test) & (preds == 1)], 'o',
  223. color=cb, alpha=0.4, label='true pos', ms=ms, markeredgewidth=0)
  224. plt.plot(x_pos[(preds == Y_test) & (preds == 0)], y_pos[(preds == Y_test) & (preds == 0)], 'o',
  225. color=cr, alpha=0.4, label='true neg', ms=ms, markeredgewidth=0)
  226. plt.plot(x_pos[preds > Y_test], y_pos[preds > Y_test], 'x', color=cb,
  227. alpha=0.4, label='false pos', ms=ms, markeredgewidth=1)
  228. plt.plot(x_pos[preds < Y_test], y_pos[preds < Y_test], 'x', color=cr,
  229. alpha=0.4, label='false neg', ms=ms, markeredgewidth=1)
  230. plt.legend()
  231. # plt.scatter(x_pos, y_pos, c=preds==Y_test, alpha=0.5)
  232. plt.xlabel(key1)
  233. plt.ylabel(key2)
  234. plt.tight_layout()
  235. def viz_errs_1d(X_test, preds, preds_proba, Y_test, norms, key='lifetime'):
  236. '''visualize errs based on lifetime
  237. '''
  238. plt.figure(dpi=200)
  239. correct_idxs = preds == Y_test
  240. lifetime = X_test[key] * norms[key]['std'] + norms[key]['mu']
  241. plt.plot(lifetime[(preds == Y_test) & (preds == 1)], preds_proba[(preds == Y_test) & (preds == 1)], 'o',
  242. color=cb, alpha=0.5, label='true pos')
  243. plt.plot(lifetime[(preds == Y_test) & (preds == 0)], preds_proba[(preds == Y_test) & (preds == 0)], 'x',
  244. color=cb, alpha=0.5, label='true neg')
  245. plt.plot(lifetime[preds > Y_test], preds_proba[preds > Y_test], 'o', color=cr, alpha=0.5, label='false pos')
  246. plt.plot(lifetime[preds < Y_test], preds_proba[preds < Y_test], 'x', color=cr, alpha=0.5, label='false neg')
  247. plt.xlabel(key)
  248. plt.ylabel('predicted probability')
  249. plt.legend()
  250. plt.show()
  251. def plot_above_threshold(x1, y1, b1, x2, y2, b2, ax, color, lsty):
  252. sl1 = (y2 - y1)/(x2 - x1)
  253. sl2 = (b2 - b1)/(x2 - x1)
  254. if y1 >= b1 and y2 >= b2:
  255. ax.plot([x1, x2], [y1, y2], linestyle=lsty, color=color, alpha=1)
  256. elif y1 < b1 and y2 < b2:
  257. ax.plot([x1, x2], [y1, y2], linestyle=lsty, color=color, alpha=.1)
  258. elif y1 >= b1 and y2 < b2:
  259. crosspoint_x, crosspoint_y = x1 + (y1 - b1)/(sl2 - sl1), y1 + sl1 * (y1 - b1)/(sl2 - sl1)
  260. ax.plot([x1, crosspoint_x], [y1, crosspoint_y], linestyle=lsty, color=color, alpha=1)
  261. ax.plot([crosspoint_x, x2], [crosspoint_y, y2], linestyle=lsty, color=color, alpha=.1)
  262. elif y1 < b1 and y2 >= b2:
  263. crosspoint_x, crosspoint_y = x1 + (y1 - b1)/(sl2 - sl1), y1 + sl1 * (y1 - b1)/(sl2 - sl1)
  264. ax.plot([x1, crosspoint_x], [y1, crosspoint_y], linestyle=lsty, color=color, alpha=.1)
  265. ax.plot([crosspoint_x, x2], [crosspoint_y, y2], linestyle=lsty, color=color, alpha=1)
  266. def plot_background(interval, bg, trace, color, ax):
  267. ax.fill_between(interval * np.arange(len(bg)),
  268. [0] * len(bg),
  269. 2 * np.array(bg),
  270. alpha=.1,
  271. color=color)
  272. x, y, lt = np.arange(len(trace)), np.array(trace), len(trace)
  273. #ax.plot(interval * x, y, linestyle='--', color=cr, alpha=.2)
  274. bg = 2 * np.array(bg)
  275. for f in range(lt - 1):
  276. lsty = '--' if f < 5 or f >= lt - 5 else '-'
  277. plot_above_threshold(x1=interval*x[f],
  278. y1=y[f],
  279. b1=bg[f],
  280. x2=interval*x[f+1],
  281. y2=y[f+1],
  282. b2=bg[f+1],
  283. ax=ax,
  284. color=color,
  285. lsty=lsty)
  286. def plot_curves(df, extra_key=None, extra_key_label=None,
  287. hline=True, R=5, C=8,
  288. xlim=None,
  289. fig=None, ylim_constant=False, background=False, ylim_cla=None,
  290. ylim_aux=None, ylim_dyn=None,
  291. xlim_constant=True, legend=True, plot_x=True,
  292. yticks=None, yticklabels=None, num_axes=3, show_track_pid=False,
  293. axes_invisible=False,
  294. clath_lab='CLTA-TagRFP',
  295. aux_lab='EGFP-Aux1-GAK-F6'):
  296. '''Plot time-series curves from df
  297. '''
  298. DIFF = 0
  299. if fig is None:
  300. plt.figure(figsize=(16, 10), dpi=200, facecolor='white')
  301. lifetime_max = np.max(df.lifetime.values[:R * C])
  302. df = df.iloc[:R * C]
  303. for i in range(R * C):
  304. if i < df.shape[0]:
  305. ax = plt.subplot(R, C, i + 1)
  306. row = df.iloc[i]
  307. if '1.5s' in row['cell_num']:
  308. interval = 1.5
  309. else:
  310. interval = 1
  311. if num_axes == 1:
  312. if plot_x:
  313. plt.plot(interval * np.arange(len(row.X_extended)), np.array(row.X_extended) + DIFF, linestyle='--', color=cr)
  314. plt.plot(interval * np.arange(len(row.Y_extended)), np.array(row.Y_extended) + DIFF, linestyle='--', color=cg)
  315. plt.plot(interval * np.arange(5, len(row.X_extended)-5), np.array(row.X_extended)[5:(-5)] + DIFF, color=cr, label='Clathrin')
  316. plt.plot(interval * np.arange(5, len(row.Y_extended)-5), np.array(row.Y_extended)[5:(-5)] + DIFF, color=cg, label='Auxilin')
  317. #plt.plot(interval * np.arange(5), np.array(row.X_extended)[-5:] + DIFF, linestyle='--', color=cr, label='Clathrin')
  318. #plt.plot(interval * np.arange(5), np.array(row.Y_extended)[-5:] + DIFF, linestyle='--', color=cg, label='Auxilin')
  319. if background:
  320. ax.plot(interval * np.arange(len(row.X_extended)), np.array(row.X_c_extended),
  321. color=cr, linewidth=.8)
  322. ax.fill_between(interval * np.arange(len(row.X_extended)),
  323. np.array(row.X_extended) - np.array(row.X_std_extended),
  324. np.array(row.X_extended) + np.array(row.X_std_extended),
  325. alpha=.2,
  326. color=cr
  327. )
  328. if hline:
  329. plt.axhline(642.3754691658837, color='gray', alpha=0.5)
  330. if extra_key is not None:
  331. if extra_key_label is None:
  332. if extra_key == 'Z':
  333. extra_key_label = 'Dynamin'
  334. else:
  335. extra_key_label = extra_key
  336. plt.plot(interval * np.arange(len(row[extra_key])), np.array(row[extra_key]) + DIFF, linestyle='--', color='gray')
  337. plt.plot(interval * np.arange(5, len(row[extra_key])-5), np.array(row[extra_key])[5:(-5)] + DIFF, color='gray', label=extra_key_label)
  338. if xlim_constant:
  339. if xlim is None:
  340. plt.xlim([-1, lifetime_max + 1])
  341. else:
  342. print(xlim)
  343. plt.xlim(xlim)
  344. if ylim_constant:
  345. if ylim is None:
  346. plt.ylim([-10, max(max(df.X_max), max(df.Y_max)) + 1])
  347. else:
  348. plt.ylim(ylim[0] + DIFF, ylim[1] + DIFF)
  349. if yticks is not None:
  350. plt.yticks(yticks, labels=yticklabels)
  351. else:
  352. ax.spines['right'].set_visible(True)
  353. twin1 = ax.twinx()
  354. if num_axes == 3:
  355. twin2 = ax.twinx()
  356. twin2.spines['right'].set_visible(True)
  357. twin2.spines['right'].set_position(("axes", 1.2))
  358. else:
  359. twin2 = twin1
  360. if show_track_pid:
  361. ax.text(.5, .9, f'{row.pid}', # row.pid
  362. horizontalalignment='right',
  363. transform=ax.transAxes)
  364. if plot_x:
  365. p1, = ax.plot(interval * np.arange(len(row.X_extended)), np.array(row.X_extended) + DIFF, linestyle='--', color=cr, alpha=.1)
  366. if i == 0:
  367. ax.text(x=interval * len(row.X_extended),
  368. y=np.array(row.X_extended)[-1],
  369. s=clath_lab,
  370. color=cr,
  371. size=8)
  372. if background:
  373. plot_background(interval, row.X_sigma_extended, row.X_extended, color=cr, ax=ax)
  374. else:
  375. ax.plot(interval * np.arange(5, len(row.X_extended)-5), np.array(row.X_extended)[5:(-5)] + DIFF, color=cr)
  376. if i == 0 and legend:
  377. dvu.line_legend()
  378. ax.fill_between(interval * np.arange(len(row.X_extended)),
  379. np.array(row.X_extended) - np.array(row.X_std_extended),
  380. np.array(row.X_extended) + np.array(row.X_std_extended),
  381. alpha=.2,
  382. color=cr
  383. )
  384. p2, = twin1.plot(interval * np.arange(len(row.Y_extended)), np.array(row.Y_extended) + DIFF, linestyle='--', color=cg, alpha=.1)
  385. if background:
  386. plot_background(interval, row.Y_sigma_extended, row.Y_extended, color=cg, ax=twin1
  387. )
  388. else:
  389. twin1.plot(interval * np.arange(5, len(row.Y_extended)-5), np.array(row.Y_extended)[5:(-5)] + DIFF, color=cg, label=aux_lab)
  390. if i == 0 and legend:
  391. dvu.line_legend()
  392. twin1.fill_between(interval * np.arange(len(row.Y_extended)),
  393. np.array(row.Y_extended) - np.array(row.Y_std_extended),
  394. np.array(row.Y_extended) + np.array(row.Y_std_extended),
  395. alpha=.2,
  396. color=cg
  397. )
  398. if i == 0:
  399. twin1.text(x=interval * len(row.Y_extended),
  400. y=np.array(row.Y_extended)[-1],
  401. s=aux_lab,
  402. color=cg,
  403. size=8)
  404. #plt.plot(interval * np.arange(5), np.array(row.X_extended)[-5:] + DIFF, linestyle='--', color=cr, label='Clathrin')
  405. #plt.plot(interval * np.arange(5), np.array(row.Y_extended)[-5:] + DIFF, linestyle='--', color=cg, label='Auxilin')
  406. if hline:
  407. ax.axhline(642.3754691658837, color='gray', alpha=0.5)
  408. if extra_key is not None:
  409. if extra_key_label is None:
  410. if extra_key == 'Z':
  411. extra_key_label = 'Dynamin'
  412. else:
  413. extra_key_label = extra_key
  414. p3, = twin2.plot(interval * np.arange(len(row.Z_extended)), np.array(row.Z_extended) + DIFF, linestyle='--', color='gray', alpha=.1)
  415. if background:
  416. plot_background(interval, row.Z_sigma_extended, row.Z_extended, color='gray', ax=twin2)
  417. else:
  418. twin2.plot(interval * np.arange(5, len(row.Z_extended)-5), np.array(row.Z_extended)[5:(-5)] + DIFF, color='gray')
  419. twin2.fill_between(interval * np.arange(len(row.Z_extended)),
  420. np.array(row.Z_extended) - np.array(row.Z_std_extended),
  421. np.array(row.Z_extended) + np.array(row.Z_std_extended),
  422. alpha=.1,
  423. color='gray'
  424. )
  425. if i == 0:
  426. twin2.text(x=interval * len(row.Z_extended),
  427. y=np.array(row.Z_extended)[-1]-500,
  428. s='Dyn2-Halo-E1-JF646',
  429. color='gray',
  430. size=8)
  431. #if i == 0 and legend:
  432. # dvu.line_legend()
  433. tkw = dict(size=4, width=1.5)
  434. ax.spines['right'].set_color(cg)
  435. ax.tick_params(axis='y', colors=cr, labelsize=6, **tkw)
  436. twin1.spines['left'].set_color(cr)
  437. ax.spines['left'].set_color(cr)
  438. #twin1.spines['left'].set_color(cg)
  439. if num_axes == 3:
  440. twin2.spines['left'].set_color(cr)
  441. twin2.spines['right'].set_color(p3.get_color())
  442. twin2.tick_params(axis='y', colors=p3.get_color(), labelsize=6, **tkw)
  443. if ylim_constant:
  444. ax.set_ylim(ylim_cla)
  445. twin1.set_ylim(ylim_aux)
  446. twin2.set_ylim(ylim_dyn)
  447. else:
  448. #p1_ylim = ax.get_ylim()
  449. p2_ylim = twin1.get_ylim()
  450. p3_ylim = twin2.get_ylim()
  451. ylim_min = min(p2_ylim[0], p3_ylim[0])
  452. twin1.set_ylim((ylim_min, 2*p2_ylim[1]))
  453. twin2.set_ylim((ylim_min, 3*p3_ylim[1]))
  454. p1_ylim = ax.get_ylim()
  455. ax.set_ylim((- 2 * p1_ylim[1], p1_ylim[1]))
  456. p2_ylim = twin1.get_ylim()
  457. twin1.set_ylim((- 0.5 * p2_ylim[1], p2_ylim[1]))
  458. #p3_ylim = twin2.get_ylim()
  459. #twin1.set_ylim((- 0.5 * p3_ylim[1], p3_ylim[1]))
  460. twin1.tick_params(axis='y', colors=cg, labelsize=6, **tkw)
  461. ax.tick_params(axis='x', **tkw)
  462. yticks = ax.get_yticks()
  463. #if len(yticks) > 5:
  464. ax.set_yticks([yt for yt in yticks if yt >= 0])
  465. yticks = twin1.get_yticks()
  466. #if len(yticks) > 5:
  467. twin1.set_yticks(yticks[np.arange(1, len(yticks), 2)])
  468. if num_axes == 3:
  469. yticks = twin2.get_yticks()
  470. if len(yticks) > 5:
  471. twin2.set_yticks(yticks[np.arange(1, len(yticks), 2)])
  472. if xlim_constant:
  473. if xlim is None:
  474. plt.xlim([-1, lifetime_max + 16])
  475. else:
  476. print(xlim)
  477. plt.xlim(xlim)
  478. if axes_invisible:
  479. ax.yaxis.set_visible(False)
  480. ax.xaxis.set_visible(False)
  481. twin1.yaxis.set_visible(False)
  482. twin1.spines['left'].set_color('w')
  483. twin2.spines['left'].set_color('w')
  484. twin2.yaxis.set_visible(False)
  485. twin1.spines['right'].set_color('w')
  486. twin2.spines['right'].set_color('w')
  487. #plt.yscale('log')
  488. # plt.axi('off')
  489. # plt.legend()
  490. plt.tight_layout()
  491. if fig is None:
  492. plt.show()
  493. def viz_errs_outliers_venn(X_test, preds, Y_test, num_feats_reduced=5):
  494. '''Compare outliers to errors in venn-diagram
  495. '''
  496. feat_names = data.get_feature_names(X_test)
  497. X_feat = X_test[feat_names]
  498. if num_feats_reduced is not None:
  499. pca = decomposition.PCA(n_components=num_feats_reduced)
  500. X_reduced = pca.fit_transform(X_feat)
  501. else:
  502. X_reduced = X_feat
  503. R, C = 2, 2
  504. titles = ['isolation forest', 'local outlier factor', 'elliptic envelop', 'one-class svm']
  505. plt.figure(figsize=(6, 5), dpi=200)
  506. for i in range(4):
  507. plt.subplot(R, C, i + 1)
  508. plt.title(titles[i])
  509. if i == 0:
  510. clf = IsolationForest(n_estimators=10, warm_start=True)
  511. elif i == 1:
  512. clf = LocalOutlierFactor(novelty=True)
  513. elif i == 2:
  514. clf = EllipticEnvelope()
  515. elif i == 3:
  516. clf = OneClassSVM()
  517. clf.fit(X_reduced) # fit 10 trees
  518. is_outlier = clf.predict(X_reduced) == -1
  519. is_err = preds != Y_test
  520. idxs = np.arange(is_outlier.size)
  521. venn2([set(idxs[is_outlier]), set(idxs[is_err])], set_labels=['outliers', 'errors'])
  522. def plot_pcs(pca, X):
  523. '''Pretty plot of pcs with explained var bars
  524. Params
  525. ------
  526. pca: sklearn PCA class after being fitted
  527. '''
  528. plt.figure(figsize=(6, 9), dpi=200)
  529. # extract out relevant pars
  530. comps = pca.components_.transpose()
  531. var_norm = pca.explained_variance_ / np.sum(pca.explained_variance_) * 100
  532. # create a 2 X 2 grid
  533. gs = grd.GridSpec(2, 2, height_ratios=[2, 10],
  534. width_ratios=[12, 1], wspace=0.1, hspace=0)
  535. # plot explained variance
  536. ax2 = plt.subplot(gs[0])
  537. ax2.bar(np.arange(0, comps.shape[1]), var_norm,
  538. color='gray', width=0.8)
  539. plt.title('Explained variance (%)')
  540. ax2.spines['right'].set_visible(False)
  541. ax2.spines['top'].set_visible(False)
  542. ax2.yaxis.set_ticks_position('left')
  543. ax2.set_yticks([0, max(var_norm)])
  544. plt.xlim((-0.5, comps.shape[1] - 0.5))
  545. # plot pcs
  546. ax = plt.subplot(gs[2])
  547. vmaxabs = np.max(np.abs(comps))
  548. p = ax.imshow(comps, interpolation='None', aspect='auto',
  549. cmap=sns.diverging_palette(10, 240, as_cmap=True, center='light'),
  550. vmin=-vmaxabs, vmax=vmaxabs) # center at 0
  551. plt.xlabel('PCA component number')
  552. ax.set_yticklabels(list(X))
  553. ax.set_yticks(range(len(list(X))))
  554. # make colorbar
  555. colorAx = plt.subplot(gs[3])
  556. cb = plt.colorbar(p, cax=colorAx)
  557. plt.show()
  558. def print_metadata(acc=None, metadata_file=oj(config.DIR_PROCESSED, 'metadata_clath_aux+gak_a7d2.pkl')):
  559. m = pkl.load(open(metadata_file, 'rb'))
  560. print(
  561. f'valid:\t\t{m["num_aux_pos_valid"]:>4.0f} aux+ / {m["num_tracks_valid"]:>4.0f} ({m["num_aux_pos_valid"] / m["num_tracks_valid"]:.3f})')
  562. print('----------------------------------------')
  563. print(f'hotspots:\t{m["num_hotspots_valid"]:>4.0f} aux+ / {m["num_hotspots_valid"]:>4.0f}')
  564. print(
  565. f'short:\t\t{m["num_short"] - m["num_short"] * m["acc_short"]:>4.0f} aux+ / {m["num_short"]:>4.0f} ({m["acc_short"]:.3f})')
  566. print(f'long:\t\t{m["num_long"] * m["acc_long"]:>4.0f} aux+ / {m["num_long"]:>4.0f} ({m["acc_long"]:.3f})')
  567. print(
  568. f'hard:\t\t{m["num_aux_pos_hard"]:>4.0f} aux+ / {m["num_tracks_hard"]:>4.0f} ({m["num_aux_pos_hard"] / m["num_tracks_hard"]:.3f})')
  569. if acc is not None:
  570. print('----------------------------------------')
  571. print(f'hard acc:\t\t\t {acc:.3f}')
  572. num_eval = m["num_tracks_valid"] - m["num_hotspots_valid"]
  573. # print(
  574. # f'total acc (no hotspots):\t {(m["num_short"] * m["acc_short"] + m["num_long"] * m["acc_long"] + acc * m["num_tracks_hard"]) / num_eval:.3f}')
  575. print('\nlifetime threshes', m['thresh_short'], m['thresh_long'])
  576. def jointplot_grouped(col_x: str, col_y: str, col_k: str, df,
  577. k_is_color=False, scatter_alpha=.5, add_global_hists: bool = False, ms=None):
  578. '''Jointplot of hists + densities
  579. Params
  580. ------
  581. col_x
  582. name of X var
  583. col_y
  584. name of Y var
  585. col_k
  586. name of variable to group/color by
  587. add_global_hists
  588. whether to plot the global hist as well
  589. '''
  590. def colored_scatter(x, y, c=None):
  591. def scatter(*args, **kwargs):
  592. args = (x, y)
  593. if c is not None:
  594. kwargs['c'] = c
  595. kwargs['marker'] = '.'
  596. kwargs['alpha'] = scatter_alpha
  597. plt.scatter(*args, **kwargs)
  598. return scatter
  599. g = sns.JointGrid(
  600. x=col_x,
  601. y=col_y,
  602. data=df
  603. )
  604. color = None
  605. legends = []
  606. for name, df_group in df.groupby(col_k):
  607. legends.append(name)
  608. if k_is_color:
  609. color = name
  610. g.plot_joint(
  611. colored_scatter(df_group[col_x], df_group[col_y], color),
  612. )
  613. sns.distplot(
  614. df_group[col_x].values,
  615. ax=g.ax_marg_x,
  616. color=color,
  617. )
  618. sns.distplot(
  619. df_group[col_y].values,
  620. ax=g.ax_marg_y,
  621. color=color,
  622. vertical=True
  623. )
  624. if add_global_hists:
  625. sns.distplot(
  626. df[col_x].values,
  627. ax=g.ax_marg_x,
  628. color='grey'
  629. )
  630. sns.distplot(
  631. df[col_y].values.ravel(),
  632. ax=g.ax_marg_y,
  633. color='grey',
  634. vertical=True
  635. )
  636. plt.legend(legends)
  637. # 2d decision boundary
  638. def plot_decision_boundary(X_col, Y_col, m, df, norms, num_pts=100):
  639. '''still not finished...
  640. '''
  641. x = df[X_col]
  642. y = df[Y_col]
  643. x = np.linspace(x.min(), x.max(), num_pts)
  644. y = np.linspace(y.min(), y.max(), num_pts)
  645. # normalize
  646. xv, yv = np.meshgrid(x, y, indexing='ij')
  647. x = xv.flatten()
  648. y = yv.flatten()
  649. x = (x - norms[X_col]['mu']) / (norms[X_col]['std'])
  650. y = (y - norms[Y_col]['mu']) / (norms[Y_col]['std'])
  651. X = np.hstack((x, y)).reshape(-1, 2)
  652. print(X.shape)
  653. X = df[results_individual['feat_names_selected']]
  654. preds = m.predict(X)
  655. def cumulative_acc_plot_hard(preds_proba, preds, y_full_cv):
  656. args = np.argsort(np.abs(preds_proba - 0.5))[::-1]
  657. accs = (preds == y_full_cv)[args]
  658. n = accs.size
  659. accs = np.cumsum(accs) / np.arange(1, n + 1)
  660. plt.figure(dpi=500)
  661. plt.plot(preds_proba[args], '.', ms=0.5, label='predicted prob', color=cb)
  662. plt.plot(accs, label='cumulative acc', color=cr)
  663. plt.yticks(np.arange(-0.05, 1.05, 0.1))
  664. plt.xlabel('num pts included')
  665. plt.grid(alpha=0.2)
  666. plt.legend()
  667. plt.show()
  668. def cumulative_acc_plot_all(df, pred_proba_key='preds_proba', pred_key='preds',
  669. outcome_def='y_consec_thresh',
  670. plot_vert_line_for_high_lifetimes=False, show=True):
  671. plt.figure(dpi=500)
  672. ax = plt.subplot(111)
  673. # full (no model)
  674. argsf = np.argsort(df.lifetime.values)
  675. accsf = (1 - df[outcome_def]).values[argsf]
  676. n = df.shape[0]
  677. plt.plot(np.cumsum(accsf) / np.arange(1, accsf.size + 1), label='Predicting all abortive', color='gray')
  678. print('accsf', np.sum(accsf))
  679. # short
  680. ds = df[df.short]
  681. argss = np.argsort(ds.lifetime.values)
  682. accss = (1 - ds[outcome_def]).values[argss]
  683. ns = ds.shape[0]
  684. # hard
  685. dh = df[~df.short]
  686. argsh = np.argsort(np.abs(dh[pred_key])) #[::-1]
  687. accsh = ((dh[pred_key].values > 0) == dh[outcome_def].values)[argsh]
  688. # put things together
  689. accs = np.hstack((accss, accsh))
  690. print(accsf.shape, accss.shape, accsh.shape, accs.shape)
  691. plt.plot(np.cumsum(accs) / np.arange(1, accs.size + 1), label='LSTM', color=cb)
  692. print(accs)
  693. plt.axvline(ns, lw=2.5, color='black')
  694. # dvu.line_legend()
  695. plt.xlabel('Percentage of tracks included (sorted by uncertainty)')
  696. plt.ylabel('Accuracy')
  697. ax.xaxis.set_ticks([int(x) for x in np.arange(0, n + 1, n//5)])
  698. ax.xaxis.set_ticklabels([str(int(x)) + '%' for x in np.arange(0, 101, 100/5)])
  699. plt.legend(fontsize='x-large', frameon=False, labelcolor='linecolor')
  700. plt.grid(alpha=0.2)
  701. plt.tight_layout()
  702. def plot_example(ex):
  703. '''ex - row of the dataframe
  704. '''
  705. plt.figure(dpi=200)
  706. plt.plot(ex['X'], color='red', label='clathrin')
  707. plt.plot(ex['Y'], color='green', label='auxilin')
  708. plt.xlabel('Time')
  709. plt.ylabel('Amplitude')
  710. plt.legend()
  711. def get_videos(cell_dir: str):
  712. '''Loads in X and Y for one cell
  713. Params
  714. ------
  715. cell_dir
  716. Path to directory for one cell
  717. Returns
  718. -------
  719. videos
  720. '''
  721. fname = {'cla': 'TagRFP', 'aux': 'EGFP', 'dyn': 'JF646'}
  722. videos = {}
  723. for m in fname:
  724. for name in os.listdir(oj(cell_dir, fname[m])):
  725. #print(f"filename: {name}")
  726. if 'tif' in name:
  727. videos[m] = imread(oj(cell_dir, fname[m], name))
  728. return videos
  729. def get_all_dynamin_videos(cells):
  730. all_videos = {}
  731. upper_dir = oj('/scratch/users/vision/data/abc_data/dynamin_data_with_ims/',
  732. 'CLTA-TagRFP EGFP-Aux1-GAK-F6 Dyn2-Halo-E1-JF646')
  733. for cell_num in cells:
  734. cell_dir = cell_num[:-6] + 'Cell1_1.5s'
  735. full_dir = oj(upper_dir, cell_dir)
  736. all_videos[cell_num] = get_videos(full_dir)
  737. return all_videos
  738. def get_dynamin_data_videos(df, pids, add_px=2, apply_norm=True):
  739. """
  740. extract videos of dynamin traces
  741. Params:
  742. ------
  743. df: pd.DataFrame
  744. dataframe
  745. pids: list
  746. list of pids to plot
  747. add_px: int
  748. number of additional pixels in each direction
  749. add_px=1 means 3*3 pixels around the center, add_px=2 means 5*5, etc.
  750. Returns:
  751. ------
  752. videos
  753. """
  754. indices = np.array([np.where(df.pid.values == pid)[0][0] for pid in pids])
  755. df = df.iloc[indices]
  756. cells = set(df.cell_num.values)
  757. raw_videos = get_all_dynamin_videos(cells)
  758. videos = {}
  759. for i in range(len(df)):
  760. cell_num = df.cell_num.iloc[i]
  761. fr, h, w = raw_videos[cell_num]['cla'].shape
  762. pid = df.pid.iloc[i]
  763. videos[pid] = {}
  764. x_pos, y_pos = df.x_pos_seq.iloc[i], df.y_pos_seq.iloc[i]
  765. x_pos = [x_pos[0]]*5 + x_pos + [x_pos[-1]]*5
  766. y_pos = [y_pos[0]]*5 + y_pos + [y_pos[-1]]*5
  767. t, lt = df.t.iloc[i] - 5*1.5, min(len(x_pos), len(y_pos))
  768. for m in ['cla', 'aux', 'dyn']:
  769. videos[pid][m] = []
  770. for j in range(lt):
  771. for m in ['cla', 'aux', 'dyn']:
  772. crop_y_pos = np.maximum(0, np.minimum(h - 1, np.arange(int(y_pos[j]) - add_px, int(y_pos[j]) + add_px + 1)))
  773. crop_x_pos = np.maximum(0, np.minimum(h - 1, np.arange(int(x_pos[j]) - add_px, int(x_pos[j]) + add_px + 1)))
  774. videos[pid][m].append(raw_videos[cell_num][m][int(t/1.5) + j,:,:] \
  775. [crop_y_pos, :] \
  776. [:, crop_x_pos])
  777. # normalize by the min/max intensities
  778. #vmin, vmax = raw_videos[cell_num][m][int(t/1.5) + j,:,:].mean(), raw_videos[cell_num][m][int(t/1.5) + j,:,:].max()
  779. #videos[pid][m][-1] = (videos[pid][m][-1] - vmin)/(vmax - vmin)
  780. # normalization
  781. norm = {}
  782. for m in ['cla', 'aux', 'dyn']:
  783. norm[m] = [1e9, -1e9] # min, max
  784. for pid in videos:
  785. for j in range(len(videos[pid][m])):
  786. norm[m][0] = min(norm[m][0], videos[pid][m][j].min())
  787. norm[m][1] = max(norm[m][1], videos[pid][m][j].max())
  788. if apply_norm:
  789. for pid in videos:
  790. for m in ['cla', 'aux', 'dyn']:
  791. for j in range(len(videos[pid][m])):
  792. videos[pid][m][j] = (videos[pid][m][j] - norm[m][0])/(norm[m][1] - norm[m][0])
  793. return videos, norm
  794. def plot_kymographs(df, pids, add_px=2):
  795. """
  796. plot kymographs of dynamin traces
  797. Params:
  798. ------
  799. df: pd.DataFrame
  800. dataframe
  801. pids: list
  802. list of pids to plot
  803. add_px: int
  804. number of additional pixels in each direction
  805. add_px=1 means 3*3 pixels around the center, add_px=2 means 5*5, etc.
  806. Returns:
  807. ------
  808. cla_traces: np.array
  809. clathrin traces from raw images
  810. aux_traces: np.array
  811. auxilin traces from raw images
  812. rgb_image: 3d np.array
  813. 3d array (RGB values) of kymographs
  814. """
  815. indices = np.array([np.where(df.pid.values == pid)[0][0] for pid in pids])
  816. df = df.iloc[indices]
  817. cells = set(df.cell_num.values)
  818. raw_videos = get_all_dynamin_videos(cells)
  819. viridis = cm.get_cmap('viridis', 12)
  820. reds = cm.get_cmap('Reds', 12) # red palette for clathrin
  821. greens = cm.get_cmap('Greens', 12) # green palette for auxilin
  822. lmax = max([len(df.x_pos_seq.iloc[i]) for i in range(len(df))]) + 2
  823. width = 2 * add_px + 1
  824. cla_traces, aux_traces = {}, {}
  825. for i in range(len(df)):
  826. cla_traces[i], aux_traces[i] = np.zeros((lmax, width)), np.zeros((lmax, width))
  827. #xmean = X[df.cell_num.iloc[i]].mean()
  828. cell_num = df.cell_num.iloc[i]
  829. x_pos, y_pos = df.x_pos_seq.iloc[i], df.y_pos_seq.iloc[i]
  830. t, lt = df.t.iloc[i], min(len(x_pos), len(y_pos))
  831. for k in range(-add_px, add_px + 1):
  832. for j in range(lt):
  833. video = raw_videos[cell_num]['cla']
  834. cla_traces[i][j, k + add_px] = max(video[int(t/1.5) + j, \
  835. range(int(y_pos[j]) - 0, int(y_pos[j]) + 0 + 1), \
  836. int(x_pos[j] + k)])
  837. vmin, vmax = video[int(t/1.5) + j,:,:].min(), video[int(t/1.5) + j,:,:].max()
  838. cla_traces[i][j, k + add_px] = (cla_traces[i][j, k + add_px] - vmin)/(vmax - vmin)
  839. video = raw_videos[cell_num]['aux']
  840. aux_traces[i][j, k + add_px] = max(video[int(t/1.5) + j, \
  841. range(int(y_pos[j]) - 0, int(y_pos[j]) + 0 + 1), \
  842. int(x_pos[j] + k)])
  843. vmin, vmax = video[int(t/1.5) + j,:,:].min(), video[int(t/1.5) + j,:,:].max()
  844. aux_traces[i][j, k + add_px] = (aux_traces[i][j, k + add_px] - vmin)/(vmax - vmin)
  845. ncol = 3 * width * len(df)
  846. cla_sparse = np.zeros((lmax, ncol))
  847. aux_sparse = np.zeros((lmax, ncol))
  848. for i in range(len(df)):
  849. start_index = 3 * width * i
  850. cla_sparse[:, (start_index):(start_index + width)] = cla_traces[i]
  851. aux_sparse[:, (start_index + width):(start_index + 2 * width)] = aux_traces[i]
  852. rgb_image = np.array([[list(reds(cla_sparse[i][j])[:3])
  853. #[1, 1 - cla_sparse[i][j], 1 - cla_sparse[i][j]] \
  854. if 0 < cla_sparse[i][j] < 1 \
  855. else \
  856. list(greens(aux_sparse[i][j])[:3]) \
  857. #[1 - aux_sparse[i][j], 1, 1 - aux_sparse[i][j]] \
  858. if 0 < aux_sparse[i][j] < 1 \
  859. #else list(viridis(np.random.choice(background, 1)[0])[:3])\
  860. else (1, 1, 1)
  861. for i in range(lmax)] \
  862. for j in range(ncol)])
  863. #cla_sparse = np.transpose(cla_sparse)
  864. #aux_sparse = np.transpose(aux_sparse)
  865. return cla_traces, aux_traces, rgb_image
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...