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

features.html 51 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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
  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.features 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.features</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. from copy import deepcopy
  29. from os.path import join as oj
  30. import numpy as np
  31. import pandas as pd
  32. from sklearn.linear_model import LinearRegression, RidgeCV
  33. pd.options.mode.chained_assignment = None # default=&#39;warn&#39; - caution: this turns off setting with copy warning
  34. import pickle as pkl
  35. #from viz import *
  36. import config
  37. from scipy.interpolate import UnivariateSpline
  38. from sklearn.decomposition import DictionaryLearning, NMF
  39. from sklearn import decomposition
  40. import trend_filtering
  41. import data
  42. from scipy.stats import skew, pearsonr
  43. def add_pcs(df):
  44. &#39;&#39;&#39;adds 10 pcs based on feature names
  45. &#39;&#39;&#39;
  46. feat_names = data.get_feature_names(df)
  47. X = df[feat_names]
  48. X = (X - X.mean()) / X.std()
  49. pca = decomposition.PCA(whiten=True)
  50. pca.fit(X[df.valid])
  51. X_reduced = pca.transform(X)
  52. for i in range(10):
  53. df[&#39;pc_&#39; + str(i)] = X_reduced[:, i]
  54. return df
  55. def add_dict_features(df,
  56. sc_comps_file=oj(config.DIR_INTERIM, &#39;dictionaries/sc_12_alpha=1.pkl&#39;),
  57. nmf_comps_file=oj(config.DIR_INTERIM, &#39;dictionaries/nmf_12.pkl&#39;),
  58. use_processed=True):
  59. &#39;&#39;&#39;Add features from saved dictionary to df
  60. &#39;&#39;&#39;
  61. def sparse_code(X_mat, n_comps=12, alpha=1, out_dir=oj(config.DIR_INTERIM, &#39;dictionaries&#39;)):
  62. print(&#39;sparse coding...&#39;)
  63. d = DictionaryLearning(n_components=n_comps, alpha=alpha, random_state=42)
  64. d.fit(X_mat)
  65. pkl.dump(d, open(oj(out_dir, f&#39;sc_{n_comps}_alpha={alpha}.pkl&#39;), &#39;wb&#39;))
  66. def nmf(X_mat, n_comps=12, out_dir=oj(config.DIR_INTERIM, &#39;dictionaries&#39;)):
  67. print(&#39;running nmf...&#39;)
  68. d = NMF(n_components=n_comps, random_state=42)
  69. d.fit(X_mat)
  70. pkl.dump(d, open(oj(out_dir, f&#39;nmf_{n_comps}.pkl&#39;), &#39;wb&#39;))
  71. X_mat = extract_X_mat(df)
  72. X_mat -= np.min(X_mat)
  73. # if feats don&#39;t exist, compute them
  74. if not use_processed or not os.path.exists(sc_comps_file):
  75. os.makedirs(oj(config.DIR_INTERIM, &#39;dictionaries&#39;), exist_ok=True)
  76. sparse_code(X_mat)
  77. nmf(X_mat)
  78. try:
  79. # sc
  80. d_sc = pkl.load(open(sc_comps_file, &#39;rb&#39;))
  81. encoding = d_sc.transform(X_mat)
  82. for i in range(encoding.shape[1]):
  83. df[f&#39;sc_{i}&#39;] = encoding[:, i]
  84. # nmf
  85. d_nmf = pkl.load(open(nmf_comps_file, &#39;rb&#39;))
  86. encoding_nmf = d_nmf.transform(X_mat)
  87. for i in range(encoding_nmf.shape[1]):
  88. df[f&#39;nmf_{i}&#39;] = encoding_nmf[:, i]
  89. except:
  90. print(&#39;dict features not added!&#39;)
  91. return df
  92. def add_smoothed_splines(df,
  93. method=&#39;spline&#39;,
  94. s_spl=0.004):
  95. X_smooth_spl = []
  96. X_smooth_spl_dx = []
  97. X_smooth_spl_d2x = []
  98. def num_local_maxima(x):
  99. return (len([i for i in range(1, len(x) - 1) if x[i] &gt; x[i - 1] and x[i] &gt; x[i + 1]]))
  100. for x in df[&#39;X&#39;]:
  101. spl = UnivariateSpline(x=range(len(x)),
  102. y=x,
  103. w=[1.0 / len(x)] * len(x),
  104. s=np.var(x) * s_spl)
  105. spl_dx = spl.derivative()
  106. spl_d2x = spl_dx.derivative()
  107. X_smooth_spl.append(spl(range(len(x))))
  108. X_smooth_spl_dx.append(spl_dx(range(len(x))))
  109. X_smooth_spl_d2x.append(spl_d2x(range(len(x))))
  110. df[&#39;X_smooth_spl&#39;] = np.array(X_smooth_spl)
  111. df[&#39;X_smooth_spl_dx&#39;] = np.array(X_smooth_spl_dx)
  112. df[&#39;X_smooth_spl_d2x&#39;] = np.array(X_smooth_spl_d2x)
  113. df[&#39;X_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl])
  114. df[&#39;dx_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl_dx])
  115. df[&#39;d2x_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl_d2x])
  116. df[&#39;num_local_max_spl&#39;] = np.array([num_local_maxima(x) for x in X_smooth_spl])
  117. df[&#39;num_local_min_spl&#39;] = np.array([num_local_maxima(-1 * x) for x in X_smooth_spl])
  118. # linear fits
  119. x = np.arange(5).reshape(-1, 1)
  120. df[&#39;end_linear_fit&#39;] = [LinearRegression().fit(x, end).coef_[0] for end in df[&#39;X_ends&#39;]]
  121. df[&#39;start_linear_fit&#39;] = [LinearRegression().fit(x, start).coef_[0] for start in df[&#39;X_starts&#39;]]
  122. return df
  123. def add_trend_filtering(df):
  124. df_tf = deepcopy(df)
  125. for i in range(len(df)):
  126. df_tf[&#39;X&#39;].iloc[i] = trend_filtering.trend_filtering(y=df[&#39;X&#39;].iloc[i], vlambda=len(df[&#39;X&#39;].iloc[i]) * 5,
  127. order=1)
  128. df_tf = add_features(df_tf)
  129. feat_names = data.get_feature_names(df_tf)
  130. feat_names = [x for x in feat_names
  131. if not x.startswith(&#39;sc_&#39;)
  132. and not x.startswith(&#39;nmf_&#39;)
  133. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  134. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, &#39;X_max_diff_after_Y_peak&#39;,
  135. &#39;X_tf&#39;]
  136. and not x.startswith(&#39;pc_&#39;)
  137. # and not &#39;local&#39; in x
  138. # and not &#39;X_peak&#39; in x
  139. # and not &#39;slope&#39; in x
  140. # and not x in [&#39;fall_final&#39;, &#39;fall_slope&#39;, &#39;fall_imp&#39;, &#39;fall&#39;]
  141. ]
  142. for feat in feat_names:
  143. df[feat + &#39;_tf_smooth&#39;] = df_tf[feat]
  144. return df
  145. def add_basic_features(df):
  146. &#39;&#39;&#39;Add a bunch of extra features to the df based on df.X, df.X_extended, df.Y, df.lifetime
  147. &#39;&#39;&#39;
  148. df = df[df.lifetime &gt; 2]
  149. df[&#39;X_max&#39;] = np.array([max(x) for x in df.X.values])
  150. df[&#39;X_max_extended&#39;] = np.array([max(x) for x in df.X_extended.values])
  151. df[&#39;X_min&#39;] = np.array([min(x) for x in df.X.values])
  152. df[&#39;X_mean&#39;] = np.nan_to_num(np.array([np.nanmean(x) for x in df.X.values]))
  153. df[&#39;X_std&#39;] = np.nan_to_num(np.array([np.std(x) for x in df.X.values]))
  154. df[&#39;Y_max&#39;] = np.array([max(y) for y in df.Y.values])
  155. df[&#39;Y_mean&#39;] = np.nan_to_num(np.array([np.nanmean(y) for y in df.Y.values]))
  156. df[&#39;Y_std&#39;] = np.nan_to_num(np.array([np.std(y) for y in df.Y.values]))
  157. df[&#39;X_peak_idx&#39;] = np.nan_to_num(np.array([np.argmax(x) for x in df.X]))
  158. df[&#39;Y_peak_idx&#39;] = np.nan_to_num(np.array([np.argmax(y) for y in df.Y]))
  159. df[&#39;X_peak_time_frac&#39;] = df[&#39;X_peak_idx&#39;].values / df[&#39;lifetime&#39;].values
  160. # df[&#39;slope_end&#39;] = df.apply(lambda row: (row[&#39;X_max&#39;] - row[&#39;X&#39;][-1]) / (row[&#39;lifetime&#39;] - row[&#39;X_peak_idx&#39;]),
  161. # axis=1)
  162. df[&#39;X_peak_last_15&#39;] = df[&#39;X_peak_time_frac&#39;] &gt;= 0.85
  163. df[&#39;X_peak_last_5&#39;] = df[&#39;X_peak_time_frac&#39;] &gt;= 0.95
  164. # hand-engineeredd features
  165. def calc_rise(x):
  166. &#39;&#39;&#39;max change before peak
  167. &#39;&#39;&#39;
  168. idx_max = np.argmax(x)
  169. val_max = x[idx_max]
  170. return val_max - np.min(x[:idx_max + 1])
  171. def calc_fall(x):
  172. &#39;&#39;&#39;max change after peak
  173. &#39;&#39;&#39;
  174. idx_max = np.argmax(x)
  175. val_max = x[idx_max]
  176. return val_max - np.min(x[idx_max:])
  177. def calc_rise_slope(x):
  178. &#39;&#39;&#39;slope to max change before peak
  179. &#39;&#39;&#39;
  180. idx_max = np.argmax(x)
  181. val_max = x[idx_max]
  182. x_early = x[:idx_max + 1]
  183. idx_min = np.argmin(x_early)
  184. denom = (idx_max - idx_min)
  185. if denom == 0:
  186. return 0
  187. return (val_max - np.min(x_early)) / denom
  188. def calc_fall_slope(x):
  189. &#39;&#39;&#39;slope to max change after peak
  190. &#39;&#39;&#39;
  191. idx_max = np.argmax(x)
  192. val_max = x[idx_max]
  193. x_late = x[idx_max:]
  194. idx_min = np.argmin(x_late)
  195. denom = idx_min
  196. if denom == 0:
  197. return 0
  198. return (val_max - np.min(x_late)) / denom
  199. def max_diff(x):
  200. return np.max(np.diff(x))
  201. def min_diff(x):
  202. return np.min(np.diff(x))
  203. df[&#39;rise&#39;] = df.apply(lambda row: calc_rise(row[&#39;X&#39;]), axis=1)
  204. df[&#39;fall&#39;] = df.apply(lambda row: calc_fall(row[&#39;X&#39;]), axis=1)
  205. df[&#39;rise_extended&#39;] = df.apply(lambda row: calc_rise(row[&#39;X_extended&#39;]), axis=1)
  206. df[&#39;fall_extended&#39;] = df.apply(lambda row: calc_fall(row[&#39;X_extended&#39;]), axis=1)
  207. df[&#39;fall_late_extended&#39;] = df.apply(lambda row: row[&#39;fall_extended&#39;] if row[&#39;X_peak_last_15&#39;] else row[&#39;fall&#39;],
  208. axis=1)
  209. # df[&#39;fall_final&#39;] = df.apply(lambda row: row[&#39;X&#39;][-3] - row[&#39;X&#39;][-1], axis=1)
  210. df[&#39;rise_slope&#39;] = df.apply(lambda row: calc_rise_slope(row[&#39;X&#39;]), axis=1)
  211. df[&#39;fall_slope&#39;] = df.apply(lambda row: calc_fall_slope(row[&#39;X&#39;]), axis=1)
  212. num = 3
  213. df[&#39;rise_local_3&#39;] = df.apply(lambda row:
  214. calc_rise(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  215. row[&#39;X_peak_idx&#39;] + num + 1])),
  216. axis=1)
  217. df[&#39;fall_local_3&#39;] = df.apply(lambda row:
  218. calc_fall(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  219. row[&#39;X_peak_idx&#39;] + num + 1])),
  220. axis=1)
  221. num2 = 11
  222. df[&#39;rise_local_11&#39;] = df.apply(lambda row:
  223. calc_rise(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  224. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  225. axis=1)
  226. df[&#39;fall_local_11&#39;] = df.apply(lambda row:
  227. calc_fall(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  228. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  229. axis=1)
  230. df[&#39;max_diff&#39;] = df.apply(lambda row: max_diff(row[&#39;X&#39;]), axis=1)
  231. df[&#39;min_diff&#39;] = df.apply(lambda row: min_diff(row[&#39;X&#39;]), axis=1)
  232. # imputed feats
  233. d = df[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;, &#39;fall&#39;]]
  234. d = d[df[&#39;X_peak_time_frac&#39;] &lt;= 0.8]
  235. # m = RidgeCV().fit(d[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;]], d[&#39;fall&#39;])
  236. # fall_pred = m.predict(df[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;]])
  237. # fall_imp = df[&#39;fall&#39;]
  238. # fall_imp[df[&#39;X_peak_time_frac&#39;] &gt; 0.8] = fall_pred[df[&#39;X_peak_time_frac&#39;] &gt; 0.8]
  239. # df[&#39;fall_imp&#39;] = fall_imp
  240. return df
  241. def extract_X_mat(df):
  242. &#39;&#39;&#39;Extract matrix for X filled with zeros after sequences
  243. Width of matrix is length of longest lifetime
  244. &#39;&#39;&#39;
  245. p = df.lifetime.max()
  246. n = df.shape[0]
  247. X_mat = np.zeros((n, p)).astype(np.float32)
  248. X = df[&#39;X&#39;].values
  249. for i in range(n):
  250. x = X[i]
  251. num_timepoints = min(p, len(x))
  252. X_mat[i, :num_timepoints] = x[:num_timepoints]
  253. X_mat = np.nan_to_num(X_mat)
  254. X_mat -= np.min(X_mat)
  255. X_mat /= np.std(X_mat)
  256. return X_mat
  257. def add_binary_features(df, outcome_def):
  258. &#39;&#39;&#39;binarize features at the difference between the mean of each class
  259. &#39;&#39;&#39;
  260. feat_names = data.get_feature_names(df)
  261. threshes = (df[df[outcome_def] == 1].mean() + df[df[outcome_def] == 0].mean()) / 2
  262. for i, k in tqdm(enumerate(feat_names)):
  263. thresh = threshes.loc[k]
  264. df[k + &#39;_binary&#39;] = df[k] &gt;= thresh
  265. return df
  266. def add_dasc_features(df, bins=100, by_cell=True):
  267. &#34;&#34;&#34;
  268. add DASC features from Wang et al. 2020 paper
  269. Parameters:
  270. df: pd.DataFrame
  271. bins: int
  272. number of bins
  273. default value is 100: the intensity level of clathrin is assigned to 100 equal-length bins
  274. from vmin(min intensity across all tracks) to vmax(max intensity across all tracks)
  275. by_cell: Boolean
  276. whether to do binning within each cell
  277. &#34;&#34;&#34;
  278. x_dist = {}
  279. n = len(df)
  280. # gather min and max clathrin intensity within each cell
  281. if by_cell == True:
  282. for cell in set(df[&#39;cell_num&#39;]):
  283. x = []
  284. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  285. for i in cell_idx:
  286. x += df[&#39;X&#39;].values[i]
  287. x_dist[cell] = (min(x), max(x))
  288. else:
  289. x = []
  290. for i in range(n):
  291. x += df[&#39;X&#39;].values[i]
  292. for cell in set(df[&#39;cell_num&#39;]):
  293. x_dist[cell] = (min(x), max(x))
  294. # transform the clathrin intensity to a value between 0 to 100
  295. X_quantiles = []
  296. for i in range(n):
  297. r = df.iloc[i]
  298. cell = r[&#39;cell_num&#39;]
  299. X_quantiles.append([np.int(1.0*bins*(x - x_dist[cell][0])/(x_dist[cell][1] - x_dist[cell][0])) if not np.isnan(x) else 0 for x in r[&#39;X&#39;]])
  300. df[&#39;X_quantiles&#39;] = X_quantiles
  301. # compute transition probability between different intensities, for different frames
  302. trans_prob = {}
  303. tmax = max([len(df[&#39;X_quantiles&#39;].values[i]) for i in range(len(df))])
  304. for t in range(tmax - 1):
  305. int_pairs = []
  306. for i in range(n):
  307. if len(df[&#39;X_quantiles&#39;].values[i]) &gt; t + 1:
  308. int_pairs.append([df[&#39;X_quantiles&#39;].values[i][t], df[&#39;X_quantiles&#39;].values[i][t + 1]])
  309. int_pairs = np.array(int_pairs)
  310. trans_prob_t = {}
  311. for i in range(bins + 1):
  312. x1 = np.where(int_pairs[:,0]== i)[0]
  313. lower_states_num = np.zeros((i, 2))
  314. for j in range(len(int_pairs)):
  315. if int_pairs[j, 0] &lt; i:
  316. lower_states_num[int_pairs[j, 0], 0] += 1
  317. if int_pairs[j, 1] == i:
  318. lower_states_num[int_pairs[j, 0], 1] += 1
  319. lower_prob = [1.*lower_states_num[k, 1]/lower_states_num[k, 0] for k in range(i) if lower_states_num[k, 0] &gt; 0]
  320. trans_prob_t[i] = (np.nanmean(int_pairs[x1,1] &lt; i),
  321. #np.nanmean(int_pairs[x1,1] &gt; i)
  322. sum(lower_prob)
  323. )
  324. trans_prob[t] = trans_prob_t
  325. # compute D sequence
  326. X_d = [[] for i in range(len(df))]
  327. for i in range(len(df)):
  328. for j, q in enumerate(df[&#39;X_quantiles&#39;].values[i][:-1]):
  329. probs = trans_prob[j][q]
  330. if 0 &lt; probs[0] and 0 &lt; probs[1]:
  331. X_d[i].append(np.log(probs[0]/probs[1]))
  332. else:
  333. X_d[i].append(0)
  334. # compute features
  335. d1 = [np.mean(x) for x in X_d]
  336. d2 = [np.log(max((np.max(x) - np.min(x))/len(x), 1e-4)) for x in X_d]
  337. d3 = [skew(x) for x in X_d]
  338. df[&#39;X_d1&#39;] = d1
  339. df[&#39;X_d2&#39;] = d2
  340. df[&#39;X_d3&#39;] = d3
  341. return df
  342. def downsample(x, length, padding=&#39;end&#39;):
  343. &#34;&#34;&#34;
  344. downsample (clathrin) track
  345. Parameters:
  346. ==========================================================
  347. x: list
  348. original clathrin track (of different lengths)
  349. length: int
  350. length of track after downsampling
  351. Returns:
  352. ==========================================================
  353. x_ds: list
  354. downsampled track
  355. &#34;&#34;&#34;
  356. x = np.array(x)[np.where(np.isnan(x) == False)]
  357. n = len(x)
  358. if n &gt;= length:
  359. # if length of original track is greater than targeted length, downsample
  360. x_ds = [x[np.int(1.0 * (n-1) * i/(length - 1))] for i in range(length)]
  361. else:
  362. # if length of original track is smaller than targeted length, fill the track with 0s
  363. if padding == &#39;front&#39;:
  364. x_ds = [0]*(length - len(x)) + list(x)
  365. else:
  366. x_ds = list(x) + [0]*(length - len(x))
  367. return x_ds
  368. def downsample_video(x, length):
  369. &#34;&#34;&#34;
  370. downsample video feature in the same way
  371. &#34;&#34;&#34;
  372. n = len(x)
  373. if n &gt;= length:
  374. # if length of original track is greater than targeted length, downsample
  375. time_index = [np.int(1.0 * (n-1) * i/(length - 1)) for i in range(length)]
  376. x_ds = x[time_index, :, :]
  377. elif n &gt; 0:
  378. # if length of original track is smaller than targeted length, fill the track with 0s
  379. x_ds = np.vstack((x, np.zeros((length - n, 10, 10))))
  380. else:
  381. x_ds = np.zeros((40, 10, 10))
  382. return x_ds
  383. def normalize_track(df, track=&#39;X_same_length&#39;, by_time_point=True):
  384. &#34;&#34;&#34;
  385. normalize tracks
  386. &#34;&#34;&#34;
  387. df[f&#39;{track}_normalized&#39;] = df[track].values
  388. for cell in set(df[&#39;cell_num&#39;]):
  389. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  390. y = df[track].values[cell_idx]
  391. y = np.array(list(y))
  392. if by_time_point:
  393. df[f&#39;{track}_normalized&#39;].values[cell_idx] = list((y - np.mean(y, axis=0))/np.std(y, axis=0))
  394. else:
  395. df[f&#39;{track}_normalized&#39;].values[cell_idx] = list((y - np.mean(y))/np.std(y))
  396. return df
  397. def normalize_feature(df, feat):
  398. &#34;&#34;&#34;
  399. normalize scalar features
  400. &#34;&#34;&#34;
  401. df = df.astype({feat: &#39;float64&#39;})
  402. for cell in set(df[&#39;cell_num&#39;]):
  403. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  404. y = df[feat].values[cell_idx]
  405. #y = np.array(list(y))
  406. df[feat].values[cell_idx] = (y - np.nanmean(y))/np.nanstd(y)
  407. return df
  408. def normalize_video(df, video=&#39;X_video&#39;):
  409. &#34;&#34;&#34;
  410. normalize videos (different frames are normalized separately)
  411. e.g. to normalize the first frame, we take the first frame of all videos,
  412. flatten and concatenate them into one 1-d array,
  413. and extract the mean and std
  414. &#34;&#34;&#34;
  415. df[f&#39;{video}_normalized&#39;] = df[video].values
  416. for cell in set(df[&#39;cell_num&#39;]):
  417. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  418. y = df[video].values[cell_idx]
  419. video_shape = y[0].shape
  420. video_mean, video_std = np.zeros(video_shape), np.zeros(video_shape)
  421. for j in (range(video_shape[0])):
  422. all_frames_j = np.array([y[i][j].reshape(1, -1)[0] for i in range(len(y))]).reshape(1, -1)[0]
  423. video_mean[j] = np.mean(all_frames_j) * np.ones((video_shape[1], video_shape[2]))
  424. video_std[j] = np.std(all_frames_j) * np.ones((video_shape[1], video_shape[2]))
  425. df[f&#39;{video}_normalized&#39;].values[cell_idx] = list((list(y) - video_mean)/(video_std))
  426. return df
  427. </code></pre>
  428. </details>
  429. </section>
  430. <section>
  431. </section>
  432. <section>
  433. </section>
  434. <section>
  435. <h2 class="section-title" id="header-functions">Functions</h2>
  436. <dl>
  437. <dt id="src.features.add_basic_features"><code class="name flex">
  438. <span>def <span class="ident">add_basic_features</span></span>(<span>df)</span>
  439. </code></dt>
  440. <dd>
  441. <section class="desc"><p>Add a bunch of extra features to the df based on df.X, df.X_extended, df.Y, df.lifetime</p></section>
  442. <details class="source">
  443. <summary>
  444. <span>Expand source code</span>
  445. </summary>
  446. <pre><code class="python">def add_basic_features(df):
  447. &#39;&#39;&#39;Add a bunch of extra features to the df based on df.X, df.X_extended, df.Y, df.lifetime
  448. &#39;&#39;&#39;
  449. df = df[df.lifetime &gt; 2]
  450. df[&#39;X_max&#39;] = np.array([max(x) for x in df.X.values])
  451. df[&#39;X_max_extended&#39;] = np.array([max(x) for x in df.X_extended.values])
  452. df[&#39;X_min&#39;] = np.array([min(x) for x in df.X.values])
  453. df[&#39;X_mean&#39;] = np.nan_to_num(np.array([np.nanmean(x) for x in df.X.values]))
  454. df[&#39;X_std&#39;] = np.nan_to_num(np.array([np.std(x) for x in df.X.values]))
  455. df[&#39;Y_max&#39;] = np.array([max(y) for y in df.Y.values])
  456. df[&#39;Y_mean&#39;] = np.nan_to_num(np.array([np.nanmean(y) for y in df.Y.values]))
  457. df[&#39;Y_std&#39;] = np.nan_to_num(np.array([np.std(y) for y in df.Y.values]))
  458. df[&#39;X_peak_idx&#39;] = np.nan_to_num(np.array([np.argmax(x) for x in df.X]))
  459. df[&#39;Y_peak_idx&#39;] = np.nan_to_num(np.array([np.argmax(y) for y in df.Y]))
  460. df[&#39;X_peak_time_frac&#39;] = df[&#39;X_peak_idx&#39;].values / df[&#39;lifetime&#39;].values
  461. # df[&#39;slope_end&#39;] = df.apply(lambda row: (row[&#39;X_max&#39;] - row[&#39;X&#39;][-1]) / (row[&#39;lifetime&#39;] - row[&#39;X_peak_idx&#39;]),
  462. # axis=1)
  463. df[&#39;X_peak_last_15&#39;] = df[&#39;X_peak_time_frac&#39;] &gt;= 0.85
  464. df[&#39;X_peak_last_5&#39;] = df[&#39;X_peak_time_frac&#39;] &gt;= 0.95
  465. # hand-engineeredd features
  466. def calc_rise(x):
  467. &#39;&#39;&#39;max change before peak
  468. &#39;&#39;&#39;
  469. idx_max = np.argmax(x)
  470. val_max = x[idx_max]
  471. return val_max - np.min(x[:idx_max + 1])
  472. def calc_fall(x):
  473. &#39;&#39;&#39;max change after peak
  474. &#39;&#39;&#39;
  475. idx_max = np.argmax(x)
  476. val_max = x[idx_max]
  477. return val_max - np.min(x[idx_max:])
  478. def calc_rise_slope(x):
  479. &#39;&#39;&#39;slope to max change before peak
  480. &#39;&#39;&#39;
  481. idx_max = np.argmax(x)
  482. val_max = x[idx_max]
  483. x_early = x[:idx_max + 1]
  484. idx_min = np.argmin(x_early)
  485. denom = (idx_max - idx_min)
  486. if denom == 0:
  487. return 0
  488. return (val_max - np.min(x_early)) / denom
  489. def calc_fall_slope(x):
  490. &#39;&#39;&#39;slope to max change after peak
  491. &#39;&#39;&#39;
  492. idx_max = np.argmax(x)
  493. val_max = x[idx_max]
  494. x_late = x[idx_max:]
  495. idx_min = np.argmin(x_late)
  496. denom = idx_min
  497. if denom == 0:
  498. return 0
  499. return (val_max - np.min(x_late)) / denom
  500. def max_diff(x):
  501. return np.max(np.diff(x))
  502. def min_diff(x):
  503. return np.min(np.diff(x))
  504. df[&#39;rise&#39;] = df.apply(lambda row: calc_rise(row[&#39;X&#39;]), axis=1)
  505. df[&#39;fall&#39;] = df.apply(lambda row: calc_fall(row[&#39;X&#39;]), axis=1)
  506. df[&#39;rise_extended&#39;] = df.apply(lambda row: calc_rise(row[&#39;X_extended&#39;]), axis=1)
  507. df[&#39;fall_extended&#39;] = df.apply(lambda row: calc_fall(row[&#39;X_extended&#39;]), axis=1)
  508. df[&#39;fall_late_extended&#39;] = df.apply(lambda row: row[&#39;fall_extended&#39;] if row[&#39;X_peak_last_15&#39;] else row[&#39;fall&#39;],
  509. axis=1)
  510. # df[&#39;fall_final&#39;] = df.apply(lambda row: row[&#39;X&#39;][-3] - row[&#39;X&#39;][-1], axis=1)
  511. df[&#39;rise_slope&#39;] = df.apply(lambda row: calc_rise_slope(row[&#39;X&#39;]), axis=1)
  512. df[&#39;fall_slope&#39;] = df.apply(lambda row: calc_fall_slope(row[&#39;X&#39;]), axis=1)
  513. num = 3
  514. df[&#39;rise_local_3&#39;] = df.apply(lambda row:
  515. calc_rise(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  516. row[&#39;X_peak_idx&#39;] + num + 1])),
  517. axis=1)
  518. df[&#39;fall_local_3&#39;] = df.apply(lambda row:
  519. calc_fall(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num):
  520. row[&#39;X_peak_idx&#39;] + num + 1])),
  521. axis=1)
  522. num2 = 11
  523. df[&#39;rise_local_11&#39;] = df.apply(lambda row:
  524. calc_rise(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  525. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  526. axis=1)
  527. df[&#39;fall_local_11&#39;] = df.apply(lambda row:
  528. calc_fall(np.array(row[&#39;X&#39;][max(0, row[&#39;X_peak_idx&#39;] - num2):
  529. row[&#39;X_peak_idx&#39;] + num2 + 1])),
  530. axis=1)
  531. df[&#39;max_diff&#39;] = df.apply(lambda row: max_diff(row[&#39;X&#39;]), axis=1)
  532. df[&#39;min_diff&#39;] = df.apply(lambda row: min_diff(row[&#39;X&#39;]), axis=1)
  533. # imputed feats
  534. d = df[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;, &#39;fall&#39;]]
  535. d = d[df[&#39;X_peak_time_frac&#39;] &lt;= 0.8]
  536. # m = RidgeCV().fit(d[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;]], d[&#39;fall&#39;])
  537. # fall_pred = m.predict(df[[&#39;X_max&#39;, &#39;X_mean&#39;, &#39;lifetime&#39;, &#39;rise&#39;]])
  538. # fall_imp = df[&#39;fall&#39;]
  539. # fall_imp[df[&#39;X_peak_time_frac&#39;] &gt; 0.8] = fall_pred[df[&#39;X_peak_time_frac&#39;] &gt; 0.8]
  540. # df[&#39;fall_imp&#39;] = fall_imp
  541. return df</code></pre>
  542. </details>
  543. </dd>
  544. <dt id="src.features.add_binary_features"><code class="name flex">
  545. <span>def <span class="ident">add_binary_features</span></span>(<span>df, outcome_def)</span>
  546. </code></dt>
  547. <dd>
  548. <section class="desc"><p>binarize features at the difference between the mean of each class</p></section>
  549. <details class="source">
  550. <summary>
  551. <span>Expand source code</span>
  552. </summary>
  553. <pre><code class="python">def add_binary_features(df, outcome_def):
  554. &#39;&#39;&#39;binarize features at the difference between the mean of each class
  555. &#39;&#39;&#39;
  556. feat_names = data.get_feature_names(df)
  557. threshes = (df[df[outcome_def] == 1].mean() + df[df[outcome_def] == 0].mean()) / 2
  558. for i, k in tqdm(enumerate(feat_names)):
  559. thresh = threshes.loc[k]
  560. df[k + &#39;_binary&#39;] = df[k] &gt;= thresh
  561. return df</code></pre>
  562. </details>
  563. </dd>
  564. <dt id="src.features.add_dasc_features"><code class="name flex">
  565. <span>def <span class="ident">add_dasc_features</span></span>(<span>df, bins=100, by_cell=True)</span>
  566. </code></dt>
  567. <dd>
  568. <section class="desc"><p>add DASC features from Wang et al. 2020 paper</p>
  569. <h2 id="parameters">Parameters</h2>
  570. <dl>
  571. <dt><strong><code>df</code></strong></dt>
  572. <dd>pd.DataFrame</dd>
  573. <dt><strong><code>bins</code></strong></dt>
  574. <dd>int
  575. number of bins
  576. default value is 100: the intensity level of clathrin is assigned to 100 equal-length bins
  577. from vmin(min intensity across all tracks) to vmax(max intensity across all tracks)</dd>
  578. <dt><strong><code>by_cell</code></strong></dt>
  579. <dd>Boolean
  580. whether to do binning within each cell</dd>
  581. </dl></section>
  582. <details class="source">
  583. <summary>
  584. <span>Expand source code</span>
  585. </summary>
  586. <pre><code class="python">def add_dasc_features(df, bins=100, by_cell=True):
  587. &#34;&#34;&#34;
  588. add DASC features from Wang et al. 2020 paper
  589. Parameters:
  590. df: pd.DataFrame
  591. bins: int
  592. number of bins
  593. default value is 100: the intensity level of clathrin is assigned to 100 equal-length bins
  594. from vmin(min intensity across all tracks) to vmax(max intensity across all tracks)
  595. by_cell: Boolean
  596. whether to do binning within each cell
  597. &#34;&#34;&#34;
  598. x_dist = {}
  599. n = len(df)
  600. # gather min and max clathrin intensity within each cell
  601. if by_cell == True:
  602. for cell in set(df[&#39;cell_num&#39;]):
  603. x = []
  604. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  605. for i in cell_idx:
  606. x += df[&#39;X&#39;].values[i]
  607. x_dist[cell] = (min(x), max(x))
  608. else:
  609. x = []
  610. for i in range(n):
  611. x += df[&#39;X&#39;].values[i]
  612. for cell in set(df[&#39;cell_num&#39;]):
  613. x_dist[cell] = (min(x), max(x))
  614. # transform the clathrin intensity to a value between 0 to 100
  615. X_quantiles = []
  616. for i in range(n):
  617. r = df.iloc[i]
  618. cell = r[&#39;cell_num&#39;]
  619. X_quantiles.append([np.int(1.0*bins*(x - x_dist[cell][0])/(x_dist[cell][1] - x_dist[cell][0])) if not np.isnan(x) else 0 for x in r[&#39;X&#39;]])
  620. df[&#39;X_quantiles&#39;] = X_quantiles
  621. # compute transition probability between different intensities, for different frames
  622. trans_prob = {}
  623. tmax = max([len(df[&#39;X_quantiles&#39;].values[i]) for i in range(len(df))])
  624. for t in range(tmax - 1):
  625. int_pairs = []
  626. for i in range(n):
  627. if len(df[&#39;X_quantiles&#39;].values[i]) &gt; t + 1:
  628. int_pairs.append([df[&#39;X_quantiles&#39;].values[i][t], df[&#39;X_quantiles&#39;].values[i][t + 1]])
  629. int_pairs = np.array(int_pairs)
  630. trans_prob_t = {}
  631. for i in range(bins + 1):
  632. x1 = np.where(int_pairs[:,0]== i)[0]
  633. lower_states_num = np.zeros((i, 2))
  634. for j in range(len(int_pairs)):
  635. if int_pairs[j, 0] &lt; i:
  636. lower_states_num[int_pairs[j, 0], 0] += 1
  637. if int_pairs[j, 1] == i:
  638. lower_states_num[int_pairs[j, 0], 1] += 1
  639. lower_prob = [1.*lower_states_num[k, 1]/lower_states_num[k, 0] for k in range(i) if lower_states_num[k, 0] &gt; 0]
  640. trans_prob_t[i] = (np.nanmean(int_pairs[x1,1] &lt; i),
  641. #np.nanmean(int_pairs[x1,1] &gt; i)
  642. sum(lower_prob)
  643. )
  644. trans_prob[t] = trans_prob_t
  645. # compute D sequence
  646. X_d = [[] for i in range(len(df))]
  647. for i in range(len(df)):
  648. for j, q in enumerate(df[&#39;X_quantiles&#39;].values[i][:-1]):
  649. probs = trans_prob[j][q]
  650. if 0 &lt; probs[0] and 0 &lt; probs[1]:
  651. X_d[i].append(np.log(probs[0]/probs[1]))
  652. else:
  653. X_d[i].append(0)
  654. # compute features
  655. d1 = [np.mean(x) for x in X_d]
  656. d2 = [np.log(max((np.max(x) - np.min(x))/len(x), 1e-4)) for x in X_d]
  657. d3 = [skew(x) for x in X_d]
  658. df[&#39;X_d1&#39;] = d1
  659. df[&#39;X_d2&#39;] = d2
  660. df[&#39;X_d3&#39;] = d3
  661. return df</code></pre>
  662. </details>
  663. </dd>
  664. <dt id="src.features.add_dict_features"><code class="name flex">
  665. <span>def <span class="ident">add_dict_features</span></span>(<span>df, sc_comps_file='/accounts/projects/vision/chandan/auxilin-prediction/src/../data/interim/dictionaries/sc_12_alpha=1.pkl', nmf_comps_file='/accounts/projects/vision/chandan/auxilin-prediction/src/../data/interim/dictionaries/nmf_12.pkl', use_processed=True)</span>
  666. </code></dt>
  667. <dd>
  668. <section class="desc"><p>Add features from saved dictionary to df</p></section>
  669. <details class="source">
  670. <summary>
  671. <span>Expand source code</span>
  672. </summary>
  673. <pre><code class="python">def add_dict_features(df,
  674. sc_comps_file=oj(config.DIR_INTERIM, &#39;dictionaries/sc_12_alpha=1.pkl&#39;),
  675. nmf_comps_file=oj(config.DIR_INTERIM, &#39;dictionaries/nmf_12.pkl&#39;),
  676. use_processed=True):
  677. &#39;&#39;&#39;Add features from saved dictionary to df
  678. &#39;&#39;&#39;
  679. def sparse_code(X_mat, n_comps=12, alpha=1, out_dir=oj(config.DIR_INTERIM, &#39;dictionaries&#39;)):
  680. print(&#39;sparse coding...&#39;)
  681. d = DictionaryLearning(n_components=n_comps, alpha=alpha, random_state=42)
  682. d.fit(X_mat)
  683. pkl.dump(d, open(oj(out_dir, f&#39;sc_{n_comps}_alpha={alpha}.pkl&#39;), &#39;wb&#39;))
  684. def nmf(X_mat, n_comps=12, out_dir=oj(config.DIR_INTERIM, &#39;dictionaries&#39;)):
  685. print(&#39;running nmf...&#39;)
  686. d = NMF(n_components=n_comps, random_state=42)
  687. d.fit(X_mat)
  688. pkl.dump(d, open(oj(out_dir, f&#39;nmf_{n_comps}.pkl&#39;), &#39;wb&#39;))
  689. X_mat = extract_X_mat(df)
  690. X_mat -= np.min(X_mat)
  691. # if feats don&#39;t exist, compute them
  692. if not use_processed or not os.path.exists(sc_comps_file):
  693. os.makedirs(oj(config.DIR_INTERIM, &#39;dictionaries&#39;), exist_ok=True)
  694. sparse_code(X_mat)
  695. nmf(X_mat)
  696. try:
  697. # sc
  698. d_sc = pkl.load(open(sc_comps_file, &#39;rb&#39;))
  699. encoding = d_sc.transform(X_mat)
  700. for i in range(encoding.shape[1]):
  701. df[f&#39;sc_{i}&#39;] = encoding[:, i]
  702. # nmf
  703. d_nmf = pkl.load(open(nmf_comps_file, &#39;rb&#39;))
  704. encoding_nmf = d_nmf.transform(X_mat)
  705. for i in range(encoding_nmf.shape[1]):
  706. df[f&#39;nmf_{i}&#39;] = encoding_nmf[:, i]
  707. except:
  708. print(&#39;dict features not added!&#39;)
  709. return df</code></pre>
  710. </details>
  711. </dd>
  712. <dt id="src.features.add_pcs"><code class="name flex">
  713. <span>def <span class="ident">add_pcs</span></span>(<span>df)</span>
  714. </code></dt>
  715. <dd>
  716. <section class="desc"><p>adds 10 pcs based on feature names</p></section>
  717. <details class="source">
  718. <summary>
  719. <span>Expand source code</span>
  720. </summary>
  721. <pre><code class="python">def add_pcs(df):
  722. &#39;&#39;&#39;adds 10 pcs based on feature names
  723. &#39;&#39;&#39;
  724. feat_names = data.get_feature_names(df)
  725. X = df[feat_names]
  726. X = (X - X.mean()) / X.std()
  727. pca = decomposition.PCA(whiten=True)
  728. pca.fit(X[df.valid])
  729. X_reduced = pca.transform(X)
  730. for i in range(10):
  731. df[&#39;pc_&#39; + str(i)] = X_reduced[:, i]
  732. return df</code></pre>
  733. </details>
  734. </dd>
  735. <dt id="src.features.add_smoothed_splines"><code class="name flex">
  736. <span>def <span class="ident">add_smoothed_splines</span></span>(<span>df, method='spline', s_spl=0.004)</span>
  737. </code></dt>
  738. <dd>
  739. <section class="desc"></section>
  740. <details class="source">
  741. <summary>
  742. <span>Expand source code</span>
  743. </summary>
  744. <pre><code class="python">def add_smoothed_splines(df,
  745. method=&#39;spline&#39;,
  746. s_spl=0.004):
  747. X_smooth_spl = []
  748. X_smooth_spl_dx = []
  749. X_smooth_spl_d2x = []
  750. def num_local_maxima(x):
  751. return (len([i for i in range(1, len(x) - 1) if x[i] &gt; x[i - 1] and x[i] &gt; x[i + 1]]))
  752. for x in df[&#39;X&#39;]:
  753. spl = UnivariateSpline(x=range(len(x)),
  754. y=x,
  755. w=[1.0 / len(x)] * len(x),
  756. s=np.var(x) * s_spl)
  757. spl_dx = spl.derivative()
  758. spl_d2x = spl_dx.derivative()
  759. X_smooth_spl.append(spl(range(len(x))))
  760. X_smooth_spl_dx.append(spl_dx(range(len(x))))
  761. X_smooth_spl_d2x.append(spl_d2x(range(len(x))))
  762. df[&#39;X_smooth_spl&#39;] = np.array(X_smooth_spl)
  763. df[&#39;X_smooth_spl_dx&#39;] = np.array(X_smooth_spl_dx)
  764. df[&#39;X_smooth_spl_d2x&#39;] = np.array(X_smooth_spl_d2x)
  765. df[&#39;X_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl])
  766. df[&#39;dx_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl_dx])
  767. df[&#39;d2x_max_spl&#39;] = np.array([np.max(x) for x in X_smooth_spl_d2x])
  768. df[&#39;num_local_max_spl&#39;] = np.array([num_local_maxima(x) for x in X_smooth_spl])
  769. df[&#39;num_local_min_spl&#39;] = np.array([num_local_maxima(-1 * x) for x in X_smooth_spl])
  770. # linear fits
  771. x = np.arange(5).reshape(-1, 1)
  772. df[&#39;end_linear_fit&#39;] = [LinearRegression().fit(x, end).coef_[0] for end in df[&#39;X_ends&#39;]]
  773. df[&#39;start_linear_fit&#39;] = [LinearRegression().fit(x, start).coef_[0] for start in df[&#39;X_starts&#39;]]
  774. return df</code></pre>
  775. </details>
  776. </dd>
  777. <dt id="src.features.add_trend_filtering"><code class="name flex">
  778. <span>def <span class="ident">add_trend_filtering</span></span>(<span>df)</span>
  779. </code></dt>
  780. <dd>
  781. <section class="desc"></section>
  782. <details class="source">
  783. <summary>
  784. <span>Expand source code</span>
  785. </summary>
  786. <pre><code class="python">def add_trend_filtering(df):
  787. df_tf = deepcopy(df)
  788. for i in range(len(df)):
  789. df_tf[&#39;X&#39;].iloc[i] = trend_filtering.trend_filtering(y=df[&#39;X&#39;].iloc[i], vlambda=len(df[&#39;X&#39;].iloc[i]) * 5,
  790. order=1)
  791. df_tf = add_features(df_tf)
  792. feat_names = data.get_feature_names(df_tf)
  793. feat_names = [x for x in feat_names
  794. if not x.startswith(&#39;sc_&#39;)
  795. and not x.startswith(&#39;nmf_&#39;)
  796. and not x in [&#39;center_max&#39;, &#39;left_max&#39;, &#39;right_max&#39;, &#39;up_max&#39;, &#39;down_max&#39;,
  797. &#39;X_max_around_Y_peak&#39;, &#39;X_max_after_Y_peak&#39;, &#39;X_max_diff_after_Y_peak&#39;,
  798. &#39;X_tf&#39;]
  799. and not x.startswith(&#39;pc_&#39;)
  800. # and not &#39;local&#39; in x
  801. # and not &#39;X_peak&#39; in x
  802. # and not &#39;slope&#39; in x
  803. # and not x in [&#39;fall_final&#39;, &#39;fall_slope&#39;, &#39;fall_imp&#39;, &#39;fall&#39;]
  804. ]
  805. for feat in feat_names:
  806. df[feat + &#39;_tf_smooth&#39;] = df_tf[feat]
  807. return df</code></pre>
  808. </details>
  809. </dd>
  810. <dt id="src.features.downsample"><code class="name flex">
  811. <span>def <span class="ident">downsample</span></span>(<span>x, length, padding='end')</span>
  812. </code></dt>
  813. <dd>
  814. <section class="desc"><p>downsample (clathrin) track</p>
  815. <h1 id="parameters">Parameters:</h1>
  816. <pre><code>x: list
  817. original clathrin track (of different lengths)
  818. length: int
  819. length of track after downsampling
  820. </code></pre>
  821. <h1 id="returns">Returns:</h1>
  822. <pre><code>x_ds: list
  823. downsampled track
  824. </code></pre></section>
  825. <details class="source">
  826. <summary>
  827. <span>Expand source code</span>
  828. </summary>
  829. <pre><code class="python">def downsample(x, length, padding=&#39;end&#39;):
  830. &#34;&#34;&#34;
  831. downsample (clathrin) track
  832. Parameters:
  833. ==========================================================
  834. x: list
  835. original clathrin track (of different lengths)
  836. length: int
  837. length of track after downsampling
  838. Returns:
  839. ==========================================================
  840. x_ds: list
  841. downsampled track
  842. &#34;&#34;&#34;
  843. x = np.array(x)[np.where(np.isnan(x) == False)]
  844. n = len(x)
  845. if n &gt;= length:
  846. # if length of original track is greater than targeted length, downsample
  847. x_ds = [x[np.int(1.0 * (n-1) * i/(length - 1))] for i in range(length)]
  848. else:
  849. # if length of original track is smaller than targeted length, fill the track with 0s
  850. if padding == &#39;front&#39;:
  851. x_ds = [0]*(length - len(x)) + list(x)
  852. else:
  853. x_ds = list(x) + [0]*(length - len(x))
  854. return x_ds</code></pre>
  855. </details>
  856. </dd>
  857. <dt id="src.features.downsample_video"><code class="name flex">
  858. <span>def <span class="ident">downsample_video</span></span>(<span>x, length)</span>
  859. </code></dt>
  860. <dd>
  861. <section class="desc"><p>downsample video feature in the same way</p></section>
  862. <details class="source">
  863. <summary>
  864. <span>Expand source code</span>
  865. </summary>
  866. <pre><code class="python">def downsample_video(x, length):
  867. &#34;&#34;&#34;
  868. downsample video feature in the same way
  869. &#34;&#34;&#34;
  870. n = len(x)
  871. if n &gt;= length:
  872. # if length of original track is greater than targeted length, downsample
  873. time_index = [np.int(1.0 * (n-1) * i/(length - 1)) for i in range(length)]
  874. x_ds = x[time_index, :, :]
  875. elif n &gt; 0:
  876. # if length of original track is smaller than targeted length, fill the track with 0s
  877. x_ds = np.vstack((x, np.zeros((length - n, 10, 10))))
  878. else:
  879. x_ds = np.zeros((40, 10, 10))
  880. return x_ds</code></pre>
  881. </details>
  882. </dd>
  883. <dt id="src.features.extract_X_mat"><code class="name flex">
  884. <span>def <span class="ident">extract_X_mat</span></span>(<span>df)</span>
  885. </code></dt>
  886. <dd>
  887. <section class="desc"><p>Extract matrix for X filled with zeros after sequences
  888. Width of matrix is length of longest lifetime</p></section>
  889. <details class="source">
  890. <summary>
  891. <span>Expand source code</span>
  892. </summary>
  893. <pre><code class="python">def extract_X_mat(df):
  894. &#39;&#39;&#39;Extract matrix for X filled with zeros after sequences
  895. Width of matrix is length of longest lifetime
  896. &#39;&#39;&#39;
  897. p = df.lifetime.max()
  898. n = df.shape[0]
  899. X_mat = np.zeros((n, p)).astype(np.float32)
  900. X = df[&#39;X&#39;].values
  901. for i in range(n):
  902. x = X[i]
  903. num_timepoints = min(p, len(x))
  904. X_mat[i, :num_timepoints] = x[:num_timepoints]
  905. X_mat = np.nan_to_num(X_mat)
  906. X_mat -= np.min(X_mat)
  907. X_mat /= np.std(X_mat)
  908. return X_mat</code></pre>
  909. </details>
  910. </dd>
  911. <dt id="src.features.normalize_feature"><code class="name flex">
  912. <span>def <span class="ident">normalize_feature</span></span>(<span>df, feat)</span>
  913. </code></dt>
  914. <dd>
  915. <section class="desc"><p>normalize scalar features</p></section>
  916. <details class="source">
  917. <summary>
  918. <span>Expand source code</span>
  919. </summary>
  920. <pre><code class="python">def normalize_feature(df, feat):
  921. &#34;&#34;&#34;
  922. normalize scalar features
  923. &#34;&#34;&#34;
  924. df = df.astype({feat: &#39;float64&#39;})
  925. for cell in set(df[&#39;cell_num&#39;]):
  926. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  927. y = df[feat].values[cell_idx]
  928. #y = np.array(list(y))
  929. df[feat].values[cell_idx] = (y - np.nanmean(y))/np.nanstd(y)
  930. return df</code></pre>
  931. </details>
  932. </dd>
  933. <dt id="src.features.normalize_track"><code class="name flex">
  934. <span>def <span class="ident">normalize_track</span></span>(<span>df, track='X_same_length', by_time_point=True)</span>
  935. </code></dt>
  936. <dd>
  937. <section class="desc"><p>normalize tracks</p></section>
  938. <details class="source">
  939. <summary>
  940. <span>Expand source code</span>
  941. </summary>
  942. <pre><code class="python">def normalize_track(df, track=&#39;X_same_length&#39;, by_time_point=True):
  943. &#34;&#34;&#34;
  944. normalize tracks
  945. &#34;&#34;&#34;
  946. df[f&#39;{track}_normalized&#39;] = df[track].values
  947. for cell in set(df[&#39;cell_num&#39;]):
  948. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  949. y = df[track].values[cell_idx]
  950. y = np.array(list(y))
  951. if by_time_point:
  952. df[f&#39;{track}_normalized&#39;].values[cell_idx] = list((y - np.mean(y, axis=0))/np.std(y, axis=0))
  953. else:
  954. df[f&#39;{track}_normalized&#39;].values[cell_idx] = list((y - np.mean(y))/np.std(y))
  955. return df</code></pre>
  956. </details>
  957. </dd>
  958. <dt id="src.features.normalize_video"><code class="name flex">
  959. <span>def <span class="ident">normalize_video</span></span>(<span>df, video='X_video')</span>
  960. </code></dt>
  961. <dd>
  962. <section class="desc"><p>normalize videos (different frames are normalized separately)</p>
  963. <p>e.g. to normalize the first frame, we take the first frame of all videos,
  964. flatten and concatenate them into one 1-d array,
  965. and extract the mean and std</p></section>
  966. <details class="source">
  967. <summary>
  968. <span>Expand source code</span>
  969. </summary>
  970. <pre><code class="python">def normalize_video(df, video=&#39;X_video&#39;):
  971. &#34;&#34;&#34;
  972. normalize videos (different frames are normalized separately)
  973. e.g. to normalize the first frame, we take the first frame of all videos,
  974. flatten and concatenate them into one 1-d array,
  975. and extract the mean and std
  976. &#34;&#34;&#34;
  977. df[f&#39;{video}_normalized&#39;] = df[video].values
  978. for cell in set(df[&#39;cell_num&#39;]):
  979. cell_idx = np.where(df[&#39;cell_num&#39;].values == cell)[0]
  980. y = df[video].values[cell_idx]
  981. video_shape = y[0].shape
  982. video_mean, video_std = np.zeros(video_shape), np.zeros(video_shape)
  983. for j in (range(video_shape[0])):
  984. all_frames_j = np.array([y[i][j].reshape(1, -1)[0] for i in range(len(y))]).reshape(1, -1)[0]
  985. video_mean[j] = np.mean(all_frames_j) * np.ones((video_shape[1], video_shape[2]))
  986. video_std[j] = np.std(all_frames_j) * np.ones((video_shape[1], video_shape[2]))
  987. df[f&#39;{video}_normalized&#39;].values[cell_idx] = list((list(y) - video_mean)/(video_std))
  988. return df </code></pre>
  989. </details>
  990. </dd>
  991. </dl>
  992. </section>
  993. <section>
  994. </section>
  995. </article>
  996. <nav id="sidebar">
  997. <h1>Index</h1>
  998. <div class="toc">
  999. <ul></ul>
  1000. </div>
  1001. <ul id="index">
  1002. <li><h3>Super-module</h3>
  1003. <ul>
  1004. <li><code><a title="src" href="index.html">src</a></code></li>
  1005. </ul>
  1006. </li>
  1007. <li><h3><a href="#header-functions">Functions</a></h3>
  1008. <ul class="">
  1009. <li><code><a title="src.features.add_basic_features" href="#src.features.add_basic_features">add_basic_features</a></code></li>
  1010. <li><code><a title="src.features.add_binary_features" href="#src.features.add_binary_features">add_binary_features</a></code></li>
  1011. <li><code><a title="src.features.add_dasc_features" href="#src.features.add_dasc_features">add_dasc_features</a></code></li>
  1012. <li><code><a title="src.features.add_dict_features" href="#src.features.add_dict_features">add_dict_features</a></code></li>
  1013. <li><code><a title="src.features.add_pcs" href="#src.features.add_pcs">add_pcs</a></code></li>
  1014. <li><code><a title="src.features.add_smoothed_splines" href="#src.features.add_smoothed_splines">add_smoothed_splines</a></code></li>
  1015. <li><code><a title="src.features.add_trend_filtering" href="#src.features.add_trend_filtering">add_trend_filtering</a></code></li>
  1016. <li><code><a title="src.features.downsample" href="#src.features.downsample">downsample</a></code></li>
  1017. <li><code><a title="src.features.downsample_video" href="#src.features.downsample_video">downsample_video</a></code></li>
  1018. <li><code><a title="src.features.extract_X_mat" href="#src.features.extract_X_mat">extract_X_mat</a></code></li>
  1019. <li><code><a title="src.features.normalize_feature" href="#src.features.normalize_feature">normalize_feature</a></code></li>
  1020. <li><code><a title="src.features.normalize_track" href="#src.features.normalize_track">normalize_track</a></code></li>
  1021. <li><code><a title="src.features.normalize_video" href="#src.features.normalize_video">normalize_video</a></code></li>
  1022. </ul>
  1023. </li>
  1024. </ul>
  1025. </nav>
  1026. </main>
  1027. <footer id="footer">
  1028. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  1029. </footer>
  1030. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  1031. <script>hljs.initHighlightingOnLoad()</script>
  1032. </body>
  1033. </html>
Tip!

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

Comments

Loading...