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

data.html 38 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
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  6. <meta name="generator" content="pdoc 0.7.2" />
  7. <title>src.data API documentation</title>
  8. <meta name="description" content="" />
  9. <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
  10. <link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
  11. <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
  12. <style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
  13. <style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
  14. <style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
  15. </head>
  16. <body>
  17. <main>
  18. <article id="content">
  19. <header>
  20. <h1 class="title">Module <code>src.data</code></h1>
  21. </header>
  22. <section id="section-intro">
  23. <details class="source">
  24. <summary>
  25. <span>Expand source code</span>
  26. </summary>
  27. <pre><code class="python">import os
  28. import sys
  29. from copy import deepcopy
  30. from os.path import join as oj
  31. import mat4py
  32. import numpy as np
  33. import pandas as pd
  34. from matplotlib import pyplot as plt
  35. try:
  36. from skimage.external.tifffile import imread
  37. except:
  38. from skimage.io import imread
  39. pd.options.mode.chained_assignment = None # default=&#39;warn&#39; - caution: this turns off setting with copy warning
  40. import pickle as pkl
  41. from viz import *
  42. import math
  43. import config
  44. import features
  45. import outcomes
  46. import load_tracking
  47. from tqdm import tqdm
  48. import train_reg
  49. def load_dfs_for_lstm(dsets=[&#39;clath_aux+gak_new&#39;],
  50. splits=[&#39;test&#39;],
  51. meta=None,
  52. length=40,
  53. normalize=True,
  54. lifetime_threshold=15,
  55. filter_short=True,
  56. padding=&#39;end&#39;):
  57. &#39;&#39;&#39;Loads dataframes preprocessed ready for LSTM
  58. &#39;&#39;&#39;
  59. dfs = {}
  60. for dset in tqdm(dsets):
  61. for split in splits:
  62. df = get_data(dset=dset)
  63. df = df[~df.hotspots]
  64. if filter_short and lifetime_threshold == 15:
  65. # df = df[~(df.short | df.long)]
  66. # df = df[df.valid]
  67. df = df[df.lifetime &gt; 15] # only keep hard tracks
  68. elif not lifetime_threshold == 15:
  69. df = df[df.lifetime &gt; lifetime_threshold] # only keep hard tracks
  70. else:
  71. df = df[~df.hotspots]
  72. df = df[df.cell_num.isin(config.DSETS[dset][split])] # select train/test etc.
  73. feat_names = [&#39;X_same_length_normalized&#39;] + select_final_feats(get_feature_names(df))
  74. # downsample tracks
  75. df[&#39;X_same_length&#39;] = [features.downsample(df.iloc[i][&#39;X&#39;],length, padding=padding)
  76. for i in range(len(df))] # downsampling
  77. df[&#39;X_same_length_extended&#39;] = [features.downsample(df.iloc[i][&#39;X_extended&#39;], length, padding=padding)
  78. for i in range(len(df))] # downsampling
  79. # normalize tracks
  80. df = features.normalize_track(df, track=&#39;X_same_length&#39;, by_time_point=False)
  81. df = features.normalize_track(df, track=&#39;X_same_length_extended&#39;, by_time_point=False)
  82. # regression response
  83. df = outcomes.add_sig_mean(df, resp_tracks=[&#39;Y&#39;])
  84. df = outcomes.add_aux_dyn_outcome(df)
  85. df[&#39;X_max_orig&#39;] = deepcopy(df[&#39;X_max&#39;].values)
  86. # remove extraneous feats
  87. # df = df[feat_names + meta]
  88. # df = df.dropna()
  89. # normalize features
  90. if normalize:
  91. for feat in feat_names:
  92. if &#39;X_same_length&#39; not in feat:
  93. df = features.normalize_feature(df, feat)
  94. dfs[(dset, split)] = deepcopy(df)
  95. return dfs, feat_names
  96. def get_data(dset=&#39;clath_aux+gak_a7d2&#39;, use_processed=True, save_processed=True,
  97. processed_file=oj(config.DIR_PROCESSED, &#39;df.pkl&#39;),
  98. metadata_file=oj(config.DIR_PROCESSED, &#39;metadata.pkl&#39;),
  99. use_processed_dicts=True,
  100. compute_dictionary_learning=False,
  101. outcome_def=&#39;y_consec_thresh&#39;,
  102. pixel_data: bool=False,
  103. video_data: bool=False,
  104. acc_thresh=0.95,
  105. previous_meta_file: str=None):
  106. &#39;&#39;&#39;
  107. Params
  108. ------
  109. use_processed: bool, optional
  110. determines whether to load df from cached pkl
  111. save_processed: bool, optional
  112. if not using processed, determines whether to save the df
  113. use_processed_dicts: bool, optional
  114. if False, recalculate the dictionary features
  115. previous_meta_file: str, optional
  116. filename for metadata.pkl file saved by previous preprocessing
  117. the thresholds for lifetime are taken from this file
  118. &#39;&#39;&#39;
  119. # get things based onn dset
  120. DSET = config.DSETS[dset]
  121. LABELS = config.LABELS[dset]
  122. processed_file = processed_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  123. metadata_file = metadata_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  124. if use_processed and os.path.exists(processed_file):
  125. return pd.read_pickle(processed_file)
  126. else:
  127. print(&#39;loading + preprocessing data...&#39;)
  128. metadata = {}
  129. # load tracks
  130. print(&#39;\tloading tracks...&#39;)
  131. df = load_tracking.get_tracks(data_dir=DSET[&#39;data_dir&#39;],
  132. split=DSET,
  133. pixel_data=pixel_data,
  134. video_data=video_data,
  135. dset=dset) # note: different Xs can be different shapes
  136. # df = df.fillna(df.median()) # this only does anything for the dynamin tracks, where x_pos is sometimes NaN
  137. # print(&#39;num nans&#39;, df.isna().sum())
  138. df[&#39;pid&#39;] = np.arange(df.shape[0]) # assign each track a unique id
  139. df[&#39;valid&#39;] = True # all tracks start as valid
  140. # set testing tracks to not valid
  141. if DSET[&#39;test&#39;] is not None:
  142. df[&#39;valid&#39;][df.cell_num.isin(DSET[&#39;test&#39;])] = False
  143. metadata[&#39;num_tracks&#39;] = df.valid.sum()
  144. # print(&#39;training&#39;, df.valid.sum())
  145. # preprocess data
  146. print(&#39;\tpreprocessing data...&#39;)
  147. df = remove_invalid_tracks(df) # use catIdx
  148. # print(&#39;valid&#39;, df.valid.sum())
  149. df = features.add_basic_features(df)
  150. df = outcomes.add_outcomes(df, LABELS=LABELS)
  151. metadata[&#39;num_tracks_valid&#39;] = df.valid.sum()
  152. metadata[&#39;num_aux_pos_valid&#39;] = df[df.valid][outcome_def].sum()
  153. metadata[&#39;num_hotspots_valid&#39;] = df[df.valid][&#39;hotspots&#39;].sum()
  154. df[&#39;valid&#39;][df.hotspots] = False
  155. df, meta_lifetime = process_tracks_by_lifetime(df, outcome_def=outcome_def,
  156. plot=False, acc_thresh=acc_thresh,
  157. previous_meta_file=previous_meta_file)
  158. df[&#39;valid&#39;][df.short] = False
  159. df[&#39;valid&#39;][df.long] = False
  160. metadata.update(meta_lifetime)
  161. metadata[&#39;num_tracks_hard&#39;] = df[&#39;valid&#39;].sum()
  162. metadata[&#39;num_aux_pos_hard&#39;] = int(df[df.valid == 1][outcome_def].sum())
  163. # add features
  164. print(&#39;\tadding features...&#39;)
  165. df = features.add_dasc_features(df)
  166. if compute_dictionary_learning:
  167. df = features.add_dict_features(df, use_processed=use_processed_dicts)
  168. # df = features.add_smoothed_tracks(df)
  169. # df = features.add_pcs(df)
  170. # df = features.add_trend_filtering(df)
  171. # df = features.add_binary_features(df, outcome_def=outcome_def)
  172. if save_processed:
  173. print(&#39;\tsaving...&#39;)
  174. pkl.dump(metadata, open(metadata_file, &#39;wb&#39;))
  175. df.to_pickle(processed_file)
  176. return df
  177. def remove_invalid_tracks(df, keep=[1, 2]):
  178. &#39;&#39;&#39;Remove certain types of tracks based on cat_idx.
  179. Only keep cat_idx = 1 and 2
  180. 1-4 (non-complex trajectory - no merges and splits)
  181. 1 - valid
  182. 2 - signal occasionally drops out
  183. 3 - cut - starts / ends
  184. 4 - multiple - at the same place (continues throughout)
  185. 5-8 (there is merging or splitting)
  186. &#39;&#39;&#39;
  187. return df[df.catIdx.isin(keep)]
  188. def process_tracks_by_lifetime(df: pd.DataFrame, outcome_def: str,
  189. plot=False, acc_thresh=0.95, previous_meta_file=None):
  190. &#39;&#39;&#39;Calculate accuracy you can get by just predicting max class
  191. as a func of lifetime and return points within proper lifetime (only looks at training cells)
  192. &#39;&#39;&#39;
  193. vals = df[df.valid == 1][[&#39;lifetime&#39;, outcome_def]]
  194. R, C = 1, 3
  195. lifetimes = np.unique(vals[&#39;lifetime&#39;])
  196. # cumulative accuracy for different thresholds
  197. accs_cum_lower = np.array([1 - np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &lt;= l]) for l in lifetimes])
  198. accs_cum_higher = np.array([np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &gt;= l]) for l in lifetimes]).flatten()
  199. if previous_meta_file is None:
  200. try:
  201. idx_thresh = np.nonzero(accs_cum_lower &gt;= acc_thresh)[0][-1] # last nonzero index
  202. thresh_lower = lifetimes[idx_thresh]
  203. except:
  204. idx_thresh = 0
  205. thresh_lower = lifetimes[idx_thresh] - 1
  206. try:
  207. idx_thresh_2 = np.nonzero(accs_cum_higher &gt;= acc_thresh)[0][0]
  208. thresh_higher = lifetimes[idx_thresh_2]
  209. except:
  210. idx_thresh_2 = lifetimes.size - 1
  211. thresh_higher = lifetimes[idx_thresh_2] + 1
  212. else:
  213. previous_meta = pkl.load(open(previous_meta_file, &#39;rb&#39;))
  214. thresh_lower = previous_meta[&#39;thresh_short&#39;]
  215. thresh_higher = previous_meta[&#39;thresh_long&#39;]
  216. # only df with lifetimes in proper range
  217. df[&#39;short&#39;] = df[&#39;lifetime&#39;] &lt;= thresh_lower
  218. df[&#39;long&#39;] = df[&#39;lifetime&#39;] &gt;= thresh_higher
  219. n = vals.shape[0]
  220. n_short = np.sum(df[&#39;short&#39;])
  221. n_long = np.sum(df[&#39;long&#39;])
  222. acc_short = 1 - np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &lt;= thresh_lower])
  223. acc_long = np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &gt;= thresh_higher])
  224. metadata = {&#39;num_short&#39;: n_short, &#39;num_long&#39;: n_long, &#39;acc_short&#39;: acc_short,
  225. &#39;acc_long&#39;: acc_long, &#39;thresh_short&#39;: thresh_lower, &#39;thresh_long&#39;: thresh_higher}
  226. if plot:
  227. plt.figure(figsize=(12, 4), dpi=200)
  228. plt.subplot(R, C, 1)
  229. outcome = df[outcome_def]
  230. plt.hist(df[&#39;lifetime&#39;][outcome == 1], label=&#39;aux+&#39;, alpha=1, color=cb, bins=25)
  231. plt.hist(df[&#39;lifetime&#39;][outcome == 0], label=&#39;aux-&#39;, alpha=0.7, color=cr, bins=25)
  232. plt.xlabel(&#39;lifetime&#39;)
  233. plt.ylabel(&#39;count&#39;)
  234. plt.legend()
  235. plt.subplot(R, C, 2)
  236. plt.plot(lifetimes, accs_cum_lower, color=cr)
  237. # plt.axvline(thresh_lower)
  238. plt.axvspan(0, thresh_lower, alpha=0.2, color=cr)
  239. plt.ylabel(&#39;fraction of negative events&#39;)
  240. plt.xlabel(f&#39;lifetime &lt;= value\nshaded includes {n_short / n * 100:0.0f}% of pts&#39;)
  241. plt.subplot(R, C, 3)
  242. plt.plot(lifetimes, accs_cum_higher, cb)
  243. plt.axvspan(thresh_higher, max(lifetimes), alpha=0.2, color=cb)
  244. plt.ylabel(&#39;fraction of positive events&#39;)
  245. plt.xlabel(f&#39;lifetime &gt;= value\nshaded includes {n_long / n * 100:0.0f}% of pts&#39;)
  246. plt.tight_layout()
  247. return df, metadata
  248. def get_feature_names(df):
  249. &#39;&#39;&#39;Returns features (all of which are scalar)
  250. Removes metadata + time-series columns + outcomes
  251. &#39;&#39;&#39;
  252. ks = list(df.keys())
  253. feat_names = [
  254. k for k in ks
  255. if not k.startswith(&#39;y&#39;)
  256. and not k.startswith(&#39;Y&#39;)
  257. and not k.startswith(&#39;Z&#39;)
  258. and not k.startswith(&#39;pixel&#39;)
  259. # and not k.startswith(&#39;pc_&#39;)
  260. and not k in [&#39;catIdx&#39;, &#39;cell_num&#39;, &#39;pid&#39;, &#39;valid&#39;, # metadata
  261. &#39;X&#39;, &#39;X_pvals&#39;, &#39;x_pos&#39;, &#39;X_starts&#39;, &#39;X_ends&#39;, &#39;X_extended&#39;, # curves
  262. &#39;short&#39;, &#39;long&#39;, &#39;hotspots&#39;, &#39;sig_idxs&#39;, # should be weeded out
  263. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, # redudant with X_max / fall
  264. &#39;X_max_diff&#39;, &#39;X_peak_idx&#39;, # unlikely to be useful
  265. &#39;t&#39;, &#39;x_pos_seq&#39;, &#39;y_pos_seq&#39;, # curves
  266. &#39;X_smooth_spl&#39;, &#39;X_smooth_spl_dx&#39;, &#39;X_smooth_spl_d2x&#39;, # curves
  267. &#39;X_quantiles&#39;,
  268. ]
  269. ]
  270. return feat_names
  271. def select_final_feats(feat_names, binarize=False):
  272. feat_names = [x for x in feat_names
  273. if not x.startswith(&#39;sc_&#39;) # sparse coding
  274. and not x.startswith(&#39;nmf_&#39;) # nmf
  275. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  276. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, &#39;X_max_diff_after_Y_peak&#39;]
  277. and not x.startswith(&#39;pc_&#39;)
  278. and not &#39;extended&#39; in x
  279. and not x == &#39;slope_end&#39;
  280. and not &#39;_tf_smooth&#39; in x
  281. and not &#39;local&#39; in x
  282. and not &#39;last&#39; in x
  283. and not &#39;video&#39; in x
  284. and not x == &#39;X_quantiles&#39;
  285. # and not &#39;X_peak&#39; in x
  286. # and not &#39;slope&#39; in x
  287. # and not x in [&#39;fall_final&#39;, &#39;fall_slope&#39;, &#39;fall_imp&#39;, &#39;fall&#39;]
  288. ]
  289. if binarize:
  290. feat_names = [x for x in feat_names if &#39;binary&#39; in x]
  291. else:
  292. feat_names = [x for x in feat_names if not &#39;binary&#39; in x]
  293. return feat_names
  294. if __name__ == &#39;__main__&#39;:
  295. # process original data (and save out lifetime thresholds)
  296. dset_orig = &#39;clath_aux+gak_a7d2&#39;
  297. df = get_data(dset=dset_orig) # save out orig
  298. # process new data (using lifetime thresholds from original data)
  299. outcome_def = &#39;y_consec_sig&#39;
  300. # for dset in [&#39;clath_aux_dynamin&#39;]:
  301. for dset in config.DSETS.keys():
  302. df = get_data(dset=dset, previous_meta_file=None)
  303. # df = get_data(dset=dset, previous_meta_file=f&#39;{config.DIR_PROCESSED}/metadata_{dset_orig}.pkl&#39;)
  304. print(dset, &#39;num cells&#39;, len(df[&#39;cell_num&#39;].unique()), &#39;num tracks&#39;, df.shape[0], &#39;num aux+&#39;,
  305. df[outcome_def].sum(), &#39;aux+ fraction&#39;, (df[outcome_def].sum() / df.shape[0]).round(3),
  306. &#39;valid&#39;, df.valid.sum(), &#39;valid aux+&#39;, df[df.valid][outcome_def].sum(), &#39;valid aux+ fraction&#39;,
  307. (df[df.valid][outcome_def].sum() / df.valid.sum()).round(3))</code></pre>
  308. </details>
  309. </section>
  310. <section>
  311. </section>
  312. <section>
  313. </section>
  314. <section>
  315. <h2 class="section-title" id="header-functions">Functions</h2>
  316. <dl>
  317. <dt id="src.data.get_data"><code class="name flex">
  318. <span>def <span class="ident">get_data</span></span>(<span>dset='clath_aux+gak_a7d2', use_processed=True, save_processed=True, processed_file='/accounts/projects/vision/chandan/auxilin-prediction/src/../data/processed/df.pkl', metadata_file='/accounts/projects/vision/chandan/auxilin-prediction/src/../data/processed/metadata.pkl', use_processed_dicts=True, compute_dictionary_learning=False, outcome_def='y_consec_thresh', pixel_data=False, video_data=False, acc_thresh=0.95, previous_meta_file=None)</span>
  319. </code></dt>
  320. <dd>
  321. <section class="desc"><h2 id="params">Params</h2>
  322. <dl>
  323. <dt><strong><code>use_processed</code></strong> :&ensp;<code>bool</code>, optional</dt>
  324. <dd>determines whether to load df from cached pkl</dd>
  325. <dt><strong><code>save_processed</code></strong> :&ensp;<code>bool</code>, optional</dt>
  326. <dd>if not using processed, determines whether to save the df</dd>
  327. <dt><strong><code>use_processed_dicts</code></strong> :&ensp;<code>bool</code>, optional</dt>
  328. <dd>if False, recalculate the dictionary features</dd>
  329. <dt><strong><code>previous_meta_file</code></strong> :&ensp;<code>str</code>, optional</dt>
  330. <dd>filename for metadata.pkl file saved by previous preprocessing
  331. the thresholds for lifetime are taken from this file</dd>
  332. </dl></section>
  333. <details class="source">
  334. <summary>
  335. <span>Expand source code</span>
  336. </summary>
  337. <pre><code class="python">def get_data(dset=&#39;clath_aux+gak_a7d2&#39;, use_processed=True, save_processed=True,
  338. processed_file=oj(config.DIR_PROCESSED, &#39;df.pkl&#39;),
  339. metadata_file=oj(config.DIR_PROCESSED, &#39;metadata.pkl&#39;),
  340. use_processed_dicts=True,
  341. compute_dictionary_learning=False,
  342. outcome_def=&#39;y_consec_thresh&#39;,
  343. pixel_data: bool=False,
  344. video_data: bool=False,
  345. acc_thresh=0.95,
  346. previous_meta_file: str=None):
  347. &#39;&#39;&#39;
  348. Params
  349. ------
  350. use_processed: bool, optional
  351. determines whether to load df from cached pkl
  352. save_processed: bool, optional
  353. if not using processed, determines whether to save the df
  354. use_processed_dicts: bool, optional
  355. if False, recalculate the dictionary features
  356. previous_meta_file: str, optional
  357. filename for metadata.pkl file saved by previous preprocessing
  358. the thresholds for lifetime are taken from this file
  359. &#39;&#39;&#39;
  360. # get things based onn dset
  361. DSET = config.DSETS[dset]
  362. LABELS = config.LABELS[dset]
  363. processed_file = processed_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  364. metadata_file = metadata_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  365. if use_processed and os.path.exists(processed_file):
  366. return pd.read_pickle(processed_file)
  367. else:
  368. print(&#39;loading + preprocessing data...&#39;)
  369. metadata = {}
  370. # load tracks
  371. print(&#39;\tloading tracks...&#39;)
  372. df = load_tracking.get_tracks(data_dir=DSET[&#39;data_dir&#39;],
  373. split=DSET,
  374. pixel_data=pixel_data,
  375. video_data=video_data,
  376. dset=dset) # note: different Xs can be different shapes
  377. # df = df.fillna(df.median()) # this only does anything for the dynamin tracks, where x_pos is sometimes NaN
  378. # print(&#39;num nans&#39;, df.isna().sum())
  379. df[&#39;pid&#39;] = np.arange(df.shape[0]) # assign each track a unique id
  380. df[&#39;valid&#39;] = True # all tracks start as valid
  381. # set testing tracks to not valid
  382. if DSET[&#39;test&#39;] is not None:
  383. df[&#39;valid&#39;][df.cell_num.isin(DSET[&#39;test&#39;])] = False
  384. metadata[&#39;num_tracks&#39;] = df.valid.sum()
  385. # print(&#39;training&#39;, df.valid.sum())
  386. # preprocess data
  387. print(&#39;\tpreprocessing data...&#39;)
  388. df = remove_invalid_tracks(df) # use catIdx
  389. # print(&#39;valid&#39;, df.valid.sum())
  390. df = features.add_basic_features(df)
  391. df = outcomes.add_outcomes(df, LABELS=LABELS)
  392. metadata[&#39;num_tracks_valid&#39;] = df.valid.sum()
  393. metadata[&#39;num_aux_pos_valid&#39;] = df[df.valid][outcome_def].sum()
  394. metadata[&#39;num_hotspots_valid&#39;] = df[df.valid][&#39;hotspots&#39;].sum()
  395. df[&#39;valid&#39;][df.hotspots] = False
  396. df, meta_lifetime = process_tracks_by_lifetime(df, outcome_def=outcome_def,
  397. plot=False, acc_thresh=acc_thresh,
  398. previous_meta_file=previous_meta_file)
  399. df[&#39;valid&#39;][df.short] = False
  400. df[&#39;valid&#39;][df.long] = False
  401. metadata.update(meta_lifetime)
  402. metadata[&#39;num_tracks_hard&#39;] = df[&#39;valid&#39;].sum()
  403. metadata[&#39;num_aux_pos_hard&#39;] = int(df[df.valid == 1][outcome_def].sum())
  404. # add features
  405. print(&#39;\tadding features...&#39;)
  406. df = features.add_dasc_features(df)
  407. if compute_dictionary_learning:
  408. df = features.add_dict_features(df, use_processed=use_processed_dicts)
  409. # df = features.add_smoothed_tracks(df)
  410. # df = features.add_pcs(df)
  411. # df = features.add_trend_filtering(df)
  412. # df = features.add_binary_features(df, outcome_def=outcome_def)
  413. if save_processed:
  414. print(&#39;\tsaving...&#39;)
  415. pkl.dump(metadata, open(metadata_file, &#39;wb&#39;))
  416. df.to_pickle(processed_file)
  417. return df</code></pre>
  418. </details>
  419. </dd>
  420. <dt id="src.data.get_feature_names"><code class="name flex">
  421. <span>def <span class="ident">get_feature_names</span></span>(<span>df)</span>
  422. </code></dt>
  423. <dd>
  424. <section class="desc"><p>Returns features (all of which are scalar)
  425. Removes metadata + time-series columns + outcomes</p></section>
  426. <details class="source">
  427. <summary>
  428. <span>Expand source code</span>
  429. </summary>
  430. <pre><code class="python">def get_feature_names(df):
  431. &#39;&#39;&#39;Returns features (all of which are scalar)
  432. Removes metadata + time-series columns + outcomes
  433. &#39;&#39;&#39;
  434. ks = list(df.keys())
  435. feat_names = [
  436. k for k in ks
  437. if not k.startswith(&#39;y&#39;)
  438. and not k.startswith(&#39;Y&#39;)
  439. and not k.startswith(&#39;Z&#39;)
  440. and not k.startswith(&#39;pixel&#39;)
  441. # and not k.startswith(&#39;pc_&#39;)
  442. and not k in [&#39;catIdx&#39;, &#39;cell_num&#39;, &#39;pid&#39;, &#39;valid&#39;, # metadata
  443. &#39;X&#39;, &#39;X_pvals&#39;, &#39;x_pos&#39;, &#39;X_starts&#39;, &#39;X_ends&#39;, &#39;X_extended&#39;, # curves
  444. &#39;short&#39;, &#39;long&#39;, &#39;hotspots&#39;, &#39;sig_idxs&#39;, # should be weeded out
  445. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, # redudant with X_max / fall
  446. &#39;X_max_diff&#39;, &#39;X_peak_idx&#39;, # unlikely to be useful
  447. &#39;t&#39;, &#39;x_pos_seq&#39;, &#39;y_pos_seq&#39;, # curves
  448. &#39;X_smooth_spl&#39;, &#39;X_smooth_spl_dx&#39;, &#39;X_smooth_spl_d2x&#39;, # curves
  449. &#39;X_quantiles&#39;,
  450. ]
  451. ]
  452. return feat_names</code></pre>
  453. </details>
  454. </dd>
  455. <dt id="src.data.load_dfs_for_lstm"><code class="name flex">
  456. <span>def <span class="ident">load_dfs_for_lstm</span></span>(<span>dsets=['clath_aux+gak_new'], splits=['test'], meta=None, length=40, normalize=True, lifetime_threshold=15, filter_short=True, padding='end')</span>
  457. </code></dt>
  458. <dd>
  459. <section class="desc"><p>Loads dataframes preprocessed ready for LSTM</p></section>
  460. <details class="source">
  461. <summary>
  462. <span>Expand source code</span>
  463. </summary>
  464. <pre><code class="python">def load_dfs_for_lstm(dsets=[&#39;clath_aux+gak_new&#39;],
  465. splits=[&#39;test&#39;],
  466. meta=None,
  467. length=40,
  468. normalize=True,
  469. lifetime_threshold=15,
  470. filter_short=True,
  471. padding=&#39;end&#39;):
  472. &#39;&#39;&#39;Loads dataframes preprocessed ready for LSTM
  473. &#39;&#39;&#39;
  474. dfs = {}
  475. for dset in tqdm(dsets):
  476. for split in splits:
  477. df = get_data(dset=dset)
  478. df = df[~df.hotspots]
  479. if filter_short and lifetime_threshold == 15:
  480. # df = df[~(df.short | df.long)]
  481. # df = df[df.valid]
  482. df = df[df.lifetime &gt; 15] # only keep hard tracks
  483. elif not lifetime_threshold == 15:
  484. df = df[df.lifetime &gt; lifetime_threshold] # only keep hard tracks
  485. else:
  486. df = df[~df.hotspots]
  487. df = df[df.cell_num.isin(config.DSETS[dset][split])] # select train/test etc.
  488. feat_names = [&#39;X_same_length_normalized&#39;] + select_final_feats(get_feature_names(df))
  489. # downsample tracks
  490. df[&#39;X_same_length&#39;] = [features.downsample(df.iloc[i][&#39;X&#39;],length, padding=padding)
  491. for i in range(len(df))] # downsampling
  492. df[&#39;X_same_length_extended&#39;] = [features.downsample(df.iloc[i][&#39;X_extended&#39;], length, padding=padding)
  493. for i in range(len(df))] # downsampling
  494. # normalize tracks
  495. df = features.normalize_track(df, track=&#39;X_same_length&#39;, by_time_point=False)
  496. df = features.normalize_track(df, track=&#39;X_same_length_extended&#39;, by_time_point=False)
  497. # regression response
  498. df = outcomes.add_sig_mean(df, resp_tracks=[&#39;Y&#39;])
  499. df = outcomes.add_aux_dyn_outcome(df)
  500. df[&#39;X_max_orig&#39;] = deepcopy(df[&#39;X_max&#39;].values)
  501. # remove extraneous feats
  502. # df = df[feat_names + meta]
  503. # df = df.dropna()
  504. # normalize features
  505. if normalize:
  506. for feat in feat_names:
  507. if &#39;X_same_length&#39; not in feat:
  508. df = features.normalize_feature(df, feat)
  509. dfs[(dset, split)] = deepcopy(df)
  510. return dfs, feat_names</code></pre>
  511. </details>
  512. </dd>
  513. <dt id="src.data.process_tracks_by_lifetime"><code class="name flex">
  514. <span>def <span class="ident">process_tracks_by_lifetime</span></span>(<span>df, outcome_def, plot=False, acc_thresh=0.95, previous_meta_file=None)</span>
  515. </code></dt>
  516. <dd>
  517. <section class="desc"><p>Calculate accuracy you can get by just predicting max class
  518. as a func of lifetime and return points within proper lifetime (only looks at training cells)</p></section>
  519. <details class="source">
  520. <summary>
  521. <span>Expand source code</span>
  522. </summary>
  523. <pre><code class="python">def process_tracks_by_lifetime(df: pd.DataFrame, outcome_def: str,
  524. plot=False, acc_thresh=0.95, previous_meta_file=None):
  525. &#39;&#39;&#39;Calculate accuracy you can get by just predicting max class
  526. as a func of lifetime and return points within proper lifetime (only looks at training cells)
  527. &#39;&#39;&#39;
  528. vals = df[df.valid == 1][[&#39;lifetime&#39;, outcome_def]]
  529. R, C = 1, 3
  530. lifetimes = np.unique(vals[&#39;lifetime&#39;])
  531. # cumulative accuracy for different thresholds
  532. accs_cum_lower = np.array([1 - np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &lt;= l]) for l in lifetimes])
  533. accs_cum_higher = np.array([np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &gt;= l]) for l in lifetimes]).flatten()
  534. if previous_meta_file is None:
  535. try:
  536. idx_thresh = np.nonzero(accs_cum_lower &gt;= acc_thresh)[0][-1] # last nonzero index
  537. thresh_lower = lifetimes[idx_thresh]
  538. except:
  539. idx_thresh = 0
  540. thresh_lower = lifetimes[idx_thresh] - 1
  541. try:
  542. idx_thresh_2 = np.nonzero(accs_cum_higher &gt;= acc_thresh)[0][0]
  543. thresh_higher = lifetimes[idx_thresh_2]
  544. except:
  545. idx_thresh_2 = lifetimes.size - 1
  546. thresh_higher = lifetimes[idx_thresh_2] + 1
  547. else:
  548. previous_meta = pkl.load(open(previous_meta_file, &#39;rb&#39;))
  549. thresh_lower = previous_meta[&#39;thresh_short&#39;]
  550. thresh_higher = previous_meta[&#39;thresh_long&#39;]
  551. # only df with lifetimes in proper range
  552. df[&#39;short&#39;] = df[&#39;lifetime&#39;] &lt;= thresh_lower
  553. df[&#39;long&#39;] = df[&#39;lifetime&#39;] &gt;= thresh_higher
  554. n = vals.shape[0]
  555. n_short = np.sum(df[&#39;short&#39;])
  556. n_long = np.sum(df[&#39;long&#39;])
  557. acc_short = 1 - np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &lt;= thresh_lower])
  558. acc_long = np.mean(vals[outcome_def][vals[&#39;lifetime&#39;] &gt;= thresh_higher])
  559. metadata = {&#39;num_short&#39;: n_short, &#39;num_long&#39;: n_long, &#39;acc_short&#39;: acc_short,
  560. &#39;acc_long&#39;: acc_long, &#39;thresh_short&#39;: thresh_lower, &#39;thresh_long&#39;: thresh_higher}
  561. if plot:
  562. plt.figure(figsize=(12, 4), dpi=200)
  563. plt.subplot(R, C, 1)
  564. outcome = df[outcome_def]
  565. plt.hist(df[&#39;lifetime&#39;][outcome == 1], label=&#39;aux+&#39;, alpha=1, color=cb, bins=25)
  566. plt.hist(df[&#39;lifetime&#39;][outcome == 0], label=&#39;aux-&#39;, alpha=0.7, color=cr, bins=25)
  567. plt.xlabel(&#39;lifetime&#39;)
  568. plt.ylabel(&#39;count&#39;)
  569. plt.legend()
  570. plt.subplot(R, C, 2)
  571. plt.plot(lifetimes, accs_cum_lower, color=cr)
  572. # plt.axvline(thresh_lower)
  573. plt.axvspan(0, thresh_lower, alpha=0.2, color=cr)
  574. plt.ylabel(&#39;fraction of negative events&#39;)
  575. plt.xlabel(f&#39;lifetime &lt;= value\nshaded includes {n_short / n * 100:0.0f}% of pts&#39;)
  576. plt.subplot(R, C, 3)
  577. plt.plot(lifetimes, accs_cum_higher, cb)
  578. plt.axvspan(thresh_higher, max(lifetimes), alpha=0.2, color=cb)
  579. plt.ylabel(&#39;fraction of positive events&#39;)
  580. plt.xlabel(f&#39;lifetime &gt;= value\nshaded includes {n_long / n * 100:0.0f}% of pts&#39;)
  581. plt.tight_layout()
  582. return df, metadata</code></pre>
  583. </details>
  584. </dd>
  585. <dt id="src.data.remove_invalid_tracks"><code class="name flex">
  586. <span>def <span class="ident">remove_invalid_tracks</span></span>(<span>df, keep=[1, 2])</span>
  587. </code></dt>
  588. <dd>
  589. <section class="desc"><p>Remove certain types of tracks based on cat_idx.
  590. Only keep cat_idx
  591. = 1 and 2
  592. 1-4 (non-complex trajectory - no merges and splits)
  593. 1 - valid
  594. 2 - signal occasionally drops out
  595. 3 - cut
  596. - starts / ends
  597. 4 - multiple - at the same place (continues throughout)
  598. 5-8 (there is merging or splitting)</p></section>
  599. <details class="source">
  600. <summary>
  601. <span>Expand source code</span>
  602. </summary>
  603. <pre><code class="python">def remove_invalid_tracks(df, keep=[1, 2]):
  604. &#39;&#39;&#39;Remove certain types of tracks based on cat_idx.
  605. Only keep cat_idx = 1 and 2
  606. 1-4 (non-complex trajectory - no merges and splits)
  607. 1 - valid
  608. 2 - signal occasionally drops out
  609. 3 - cut - starts / ends
  610. 4 - multiple - at the same place (continues throughout)
  611. 5-8 (there is merging or splitting)
  612. &#39;&#39;&#39;
  613. return df[df.catIdx.isin(keep)]</code></pre>
  614. </details>
  615. </dd>
  616. <dt id="src.data.select_final_feats"><code class="name flex">
  617. <span>def <span class="ident">select_final_feats</span></span>(<span>feat_names, binarize=False)</span>
  618. </code></dt>
  619. <dd>
  620. <section class="desc"></section>
  621. <details class="source">
  622. <summary>
  623. <span>Expand source code</span>
  624. </summary>
  625. <pre><code class="python">def select_final_feats(feat_names, binarize=False):
  626. feat_names = [x for x in feat_names
  627. if not x.startswith(&#39;sc_&#39;) # sparse coding
  628. and not x.startswith(&#39;nmf_&#39;) # nmf
  629. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  630. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, &#39;X_max_diff_after_Y_peak&#39;]
  631. and not x.startswith(&#39;pc_&#39;)
  632. and not &#39;extended&#39; in x
  633. and not x == &#39;slope_end&#39;
  634. and not &#39;_tf_smooth&#39; in x
  635. and not &#39;local&#39; in x
  636. and not &#39;last&#39; in x
  637. and not &#39;video&#39; in x
  638. and not x == &#39;X_quantiles&#39;
  639. # and not &#39;X_peak&#39; in x
  640. # and not &#39;slope&#39; in x
  641. # and not x in [&#39;fall_final&#39;, &#39;fall_slope&#39;, &#39;fall_imp&#39;, &#39;fall&#39;]
  642. ]
  643. if binarize:
  644. feat_names = [x for x in feat_names if &#39;binary&#39; in x]
  645. else:
  646. feat_names = [x for x in feat_names if not &#39;binary&#39; in x]
  647. return feat_names</code></pre>
  648. </details>
  649. </dd>
  650. </dl>
  651. </section>
  652. <section>
  653. </section>
  654. </article>
  655. <nav id="sidebar">
  656. <h1>Index</h1>
  657. <div class="toc">
  658. <ul></ul>
  659. </div>
  660. <ul id="index">
  661. <li><h3>Super-module</h3>
  662. <ul>
  663. <li><code><a title="src" href="index.html">src</a></code></li>
  664. </ul>
  665. </li>
  666. <li><h3><a href="#header-functions">Functions</a></h3>
  667. <ul class="">
  668. <li><code><a title="src.data.get_data" href="#src.data.get_data">get_data</a></code></li>
  669. <li><code><a title="src.data.get_feature_names" href="#src.data.get_feature_names">get_feature_names</a></code></li>
  670. <li><code><a title="src.data.load_dfs_for_lstm" href="#src.data.load_dfs_for_lstm">load_dfs_for_lstm</a></code></li>
  671. <li><code><a title="src.data.process_tracks_by_lifetime" href="#src.data.process_tracks_by_lifetime">process_tracks_by_lifetime</a></code></li>
  672. <li><code><a title="src.data.remove_invalid_tracks" href="#src.data.remove_invalid_tracks">remove_invalid_tracks</a></code></li>
  673. <li><code><a title="src.data.select_final_feats" href="#src.data.select_final_feats">select_final_feats</a></code></li>
  674. </ul>
  675. </li>
  676. </ul>
  677. </nav>
  678. </main>
  679. <footer id="footer">
  680. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  681. </footer>
  682. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  683. <script>hljs.initHighlightingOnLoad()</script>
  684. </body>
  685. </html>
Tip!

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

Comments

Loading...