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.py 15 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
  1. import os
  2. import sys
  3. from copy import deepcopy
  4. from os.path import join as oj
  5. import mat4py
  6. import numpy as np
  7. import pandas as pd
  8. from matplotlib import pyplot as plt
  9. try:
  10. from skimage.external.tifffile import imread
  11. except:
  12. from skimage.io import imread
  13. from sklearn.model_selection import train_test_split
  14. pd.options.mode.chained_assignment = None # default='warn' - caution: this turns off setting with copy warning
  15. import pickle as pkl
  16. from viz import *
  17. import math
  18. import config
  19. import features
  20. import outcomes
  21. import load_tracking
  22. from tqdm import tqdm
  23. import train_reg
  24. def load_dfs_for_lstm(dsets=['clath_aux+gak_new'],
  25. splits=['test'],
  26. meta=None,
  27. length=40,
  28. normalize=True,
  29. lifetime_threshold=15,
  30. hotspots_threshold=25,
  31. filter_hotspots=True,
  32. filter_short=True,
  33. padding='end'):
  34. '''Loads dataframes preprocessed ready for LSTM
  35. '''
  36. dfs = {}
  37. for dset in tqdm(dsets):
  38. for split in splits:
  39. df = get_data(dset=dset)
  40. if filter_short:
  41. df = df[df.lifetime > lifetime_threshold] # only keep hard tracks
  42. if filter_hotspots:
  43. if hotspots_threshold is None:
  44. df = df[~df.hotspots]
  45. else:
  46. df = df[df.lifetime <= hotspots_threshold]
  47. df = df[df.cell_num.isin(config.DSETS[dset][split])] # select train/test etc.
  48. feat_names = ['X_same_length_normalized'] + select_final_feats(get_feature_names(df))
  49. # print('mid shape', df.shape)
  50. # downsample tracks
  51. df['X_same_length'] = [features.downsample(df.iloc[i]['X'],
  52. length, padding=padding)
  53. for i in range(len(df))] # downsampling
  54. df['X_same_length_extended'] = [features.downsample(df.iloc[i]['X_extended'],
  55. length, padding=padding)
  56. for i in range(len(df))] # downsampling
  57. # normalize tracks
  58. df = features.normalize_track(df, track='X_same_length', by_time_point=False)
  59. df = features.normalize_track(df, track='X_same_length_extended', by_time_point=False)
  60. # regression response
  61. df = outcomes.add_sig_mean(df, resp_tracks=['Y'])
  62. df = outcomes.add_aux_dyn_outcome(df)
  63. df['X_max_orig'] = deepcopy(df['X_max'].values)
  64. # remove extraneous feats
  65. # df = df[feat_names + meta]
  66. # df = df.dropna()
  67. # normalize features
  68. if normalize:
  69. for feat in feat_names:
  70. if 'X_same_length' not in feat:
  71. df = features.normalize_feature(df, feat)
  72. dfs[(dset, split)] = deepcopy(df)
  73. return dfs, feat_names
  74. def get_data(dset='clath_aux+gak_a7d2', use_processed=True, save_processed=True,
  75. processed_file=oj(config.DIR_PROCESSED, 'df.pkl'),
  76. metadata_file=oj(config.DIR_PROCESSED, 'metadata.pkl'),
  77. use_processed_dicts=True,
  78. compute_dictionary_learning=False,
  79. outcome_def='y_consec_thresh',
  80. pixel_data: bool=False,
  81. video_data: bool=False,
  82. acc_thresh=0.95,
  83. previous_meta_file: str=None):
  84. '''
  85. Params
  86. ------
  87. use_processed: bool, optional
  88. determines whether to load df from cached pkl
  89. save_processed: bool, optional
  90. if not using processed, determines whether to save the df
  91. use_processed_dicts: bool, optional
  92. if False, recalculate the dictionary features
  93. previous_meta_file: str, optional
  94. filename for metadata.pkl file saved by previous preprocessing
  95. the thresholds for lifetime are taken from this file
  96. '''
  97. # get things based onn dset
  98. DSET = config.DSETS[dset]
  99. LABELS = config.LABELS[dset]
  100. processed_file = processed_file[:-4] + '_' + dset + '.pkl'
  101. metadata_file = metadata_file[:-4] + '_' + dset + '.pkl'
  102. if use_processed and os.path.exists(processed_file):
  103. return pd.read_pickle(processed_file)
  104. else:
  105. print('loading + preprocessing data...')
  106. metadata = {}
  107. # load tracks
  108. print('\tloading tracks...')
  109. df = load_tracking.get_tracks(data_dir=DSET['data_dir'],
  110. split=DSET,
  111. pixel_data=pixel_data,
  112. video_data=video_data,
  113. dset=dset) # note: different Xs can be different shapes
  114. # df = df.fillna(df.median()) # this only does anything for the dynamin tracks, where x_pos is sometimes NaN
  115. # print('num nans', df.isna().sum())
  116. df['pid'] = np.arange(df.shape[0]) # assign each track a unique id
  117. df['valid'] = True # all tracks start as valid
  118. # set testing tracks to not valid
  119. if DSET['test'] is not None:
  120. df['valid'][df.cell_num.isin(DSET['test'])] = False
  121. metadata['num_tracks'] = df.valid.sum()
  122. # print('training', df.valid.sum())
  123. # preprocess data
  124. print('\tpreprocessing data...')
  125. df = remove_invalid_tracks(df) # use catIdx
  126. # print('valid', df.valid.sum())
  127. df = features.add_basic_features(df)
  128. df = outcomes.add_outcomes(df,
  129. LABELS=LABELS,
  130. vps_data='vps' in dset)
  131. metadata['num_tracks_valid'] = df.valid.sum()
  132. metadata['num_aux_pos_valid'] = df[df.valid][outcome_def].sum()
  133. metadata['num_hotspots_valid'] = df[df.valid]['hotspots'].sum()
  134. df['valid'][df.hotspots] = False
  135. df, meta_lifetime = process_tracks_by_lifetime(df, outcome_def=outcome_def,
  136. plot=False, acc_thresh=acc_thresh,
  137. previous_meta_file=previous_meta_file)
  138. df['valid'][df.short] = False
  139. df['valid'][df.long] = False
  140. metadata.update(meta_lifetime)
  141. metadata['num_tracks_hard'] = df['valid'].sum()
  142. metadata['num_aux_pos_hard'] = int(df[df.valid == 1][outcome_def].sum())
  143. # add features
  144. print('\tadding features...')
  145. df = features.add_dasc_features(df)
  146. if compute_dictionary_learning:
  147. df = features.add_dict_features(df, use_processed=use_processed_dicts)
  148. # df = features.add_smoothed_tracks(df)
  149. # df = features.add_pcs(df)
  150. # df = features.add_trend_filtering(df)
  151. # df = features.add_binary_features(df, outcome_def=outcome_def)
  152. if save_processed:
  153. print('\tsaving...')
  154. pkl.dump(metadata, open(metadata_file, 'wb'))
  155. df.to_pickle(processed_file)
  156. return df
  157. def get_snf_mt_vs_wt():
  158. """Need to merge the train and test data and split
  159. This is because they were split discretely in a way that using X_normalized gives an unfair hint to the algorithm
  160. Set outcome mt to whether or not the
  161. """
  162. df_fulls = []
  163. for i, dsets in enumerate([['vps4_snf7'], ['vps4_snf7___key=mt']]):
  164. dfs, feat_names = data.load_dfs_for_lstm(dsets=dsets,
  165. splits=['train', 'test'],
  166. filter_hotspots=True,
  167. filter_short=False,
  168. lifetime_threshold=None,
  169. hotspots_threshold=25,
  170. meta=['cell_num', 'Y_sig_mean', 'Y_sig_mean_normalized'],
  171. normalize=False)
  172. print('feat_names', feat_names)
  173. df_full = pd.concat(list(dfs.values()))
  174. df_full['mt'] = i
  175. df_fulls.append(df_full)
  176. df_full = pd.concat(df_fulls)
  177. df_train, df_test = train_test_split(df_full, random_state=13, test_size=0.33)
  178. return df_train, df_test, feat_names
  179. def remove_invalid_tracks(df, keep=[1, 2]):
  180. '''Remove certain types of tracks based on cat_idx.
  181. Only keep cat_idx = 1 and 2
  182. 1-4 (non-complex trajectory - no merges and splits)
  183. 1 - valid
  184. 2 - signal occasionally drops out
  185. 3 - cut - starts / ends
  186. 4 - multiple - at the same place (continues throughout)
  187. 5-8 (there is merging or splitting)
  188. '''
  189. return df[df.catIdx.isin(keep)]
  190. def process_tracks_by_lifetime(df: pd.DataFrame, outcome_def: str,
  191. plot=False, acc_thresh=0.95, previous_meta_file=None):
  192. '''Calculate accuracy you can get by just predicting max class
  193. as a func of lifetime and return points within proper lifetime (only looks at training cells)
  194. '''
  195. vals = df[df.valid == 1][['lifetime', outcome_def]]
  196. R, C = 1, 3
  197. lifetimes = np.unique(vals['lifetime'])
  198. # cumulative accuracy for different thresholds
  199. accs_cum_lower = np.array([1 - np.mean(vals[outcome_def][vals['lifetime'] <= l]) for l in lifetimes])
  200. accs_cum_higher = np.array([np.mean(vals[outcome_def][vals['lifetime'] >= l]) for l in lifetimes]).flatten()
  201. if previous_meta_file is None:
  202. try:
  203. idx_thresh = np.nonzero(accs_cum_lower >= acc_thresh)[0][-1] # last nonzero index
  204. thresh_lower = lifetimes[idx_thresh]
  205. except:
  206. idx_thresh = 0
  207. thresh_lower = lifetimes[idx_thresh] - 1
  208. try:
  209. idx_thresh_2 = np.nonzero(accs_cum_higher >= acc_thresh)[0][0]
  210. thresh_higher = lifetimes[idx_thresh_2]
  211. except:
  212. idx_thresh_2 = lifetimes.size - 1
  213. thresh_higher = lifetimes[idx_thresh_2] + 1
  214. else:
  215. previous_meta = pkl.load(open(previous_meta_file, 'rb'))
  216. thresh_lower = previous_meta['thresh_short']
  217. thresh_higher = previous_meta['thresh_long']
  218. # only df with lifetimes in proper range
  219. df['short'] = df['lifetime'] <= thresh_lower
  220. df['long'] = df['lifetime'] >= thresh_higher
  221. n = vals.shape[0]
  222. n_short = np.sum(df['short'])
  223. n_long = np.sum(df['long'])
  224. acc_short = 1 - np.mean(vals[outcome_def][vals['lifetime'] <= thresh_lower])
  225. acc_long = np.mean(vals[outcome_def][vals['lifetime'] >= thresh_higher])
  226. metadata = {'num_short': n_short, 'num_long': n_long, 'acc_short': acc_short,
  227. 'acc_long': acc_long, 'thresh_short': thresh_lower, 'thresh_long': thresh_higher}
  228. if plot:
  229. plt.figure(figsize=(12, 4), dpi=200)
  230. plt.subplot(R, C, 1)
  231. outcome = df[outcome_def]
  232. plt.hist(df['lifetime'][outcome == 1], label='aux+', alpha=1, color=cb, bins=25)
  233. plt.hist(df['lifetime'][outcome == 0], label='aux-', alpha=0.7, color=cr, bins=25)
  234. plt.xlabel('lifetime')
  235. plt.ylabel('count')
  236. plt.legend()
  237. plt.subplot(R, C, 2)
  238. plt.plot(lifetimes, accs_cum_lower, color=cr)
  239. # plt.axvline(thresh_lower)
  240. plt.axvspan(0, thresh_lower, alpha=0.2, color=cr)
  241. plt.ylabel('fraction of negative events')
  242. plt.xlabel(f'lifetime <= value\nshaded includes {n_short / n * 100:0.0f}% of pts')
  243. plt.subplot(R, C, 3)
  244. plt.plot(lifetimes, accs_cum_higher, cb)
  245. plt.axvspan(thresh_higher, max(lifetimes), alpha=0.2, color=cb)
  246. plt.ylabel('fraction of positive events')
  247. plt.xlabel(f'lifetime >= value\nshaded includes {n_long / n * 100:0.0f}% of pts')
  248. plt.tight_layout()
  249. return df, metadata
  250. def get_feature_names(df):
  251. '''Returns features (all of which are scalar)
  252. Removes metadata + time-series columns + outcomes
  253. '''
  254. ks = list(df.keys())
  255. feat_names = [
  256. k for k in ks
  257. if not k.startswith('y')
  258. and not k.startswith('Y')
  259. and not k.startswith('Z')
  260. and not k.startswith('pixel')
  261. # and not k.startswith('pc_')
  262. and not k in ['catIdx', 'cell_num', 'pid', 'valid', # metadata
  263. 'X', 'X_pvals', 'X_starts', 'X_ends', 'X_extended', # curves
  264. 'short', 'long', 'hotspots', 'sig_idxs', # should be weeded out
  265. 'X_max_around_Y_peak', 'X_max_after_Y_peak', # redudant with X_max / fall
  266. 'X_max_diff', 'X_peak_idx', # unlikely to be useful
  267. 'x_pos', 'z_pos', # curves
  268. 't', 'x_pos_seq', 'y_pos_seq', 'z_pos_seq', # curves
  269. 'X_smooth_spl', 'X_smooth_spl_dx', 'X_smooth_spl_d2x', # curves
  270. 'X_quantiles',
  271. ]
  272. ]
  273. return feat_names
  274. def select_final_feats(feat_names, binarize=False):
  275. feat_names = [x for x in feat_names
  276. if not x.startswith('sc_') # sparse coding
  277. and not x.startswith('nmf_') # nmf
  278. and not x in ['center_max', 'left_max', 'right_max', 'up_max', 'down_max',
  279. 'X_max_around_Y_peak', 'X_max_after_Y_peak', 'X_max_diff_after_Y_peak']
  280. and not x.startswith('pc_')
  281. and not 'extended' in x
  282. and not x == 'slope_end'
  283. and not '_tf_smooth' in x
  284. and not 'local' in x
  285. and not 'last' in x
  286. and not 'video' in x
  287. and not x == 'X_quantiles'
  288. # and not 'X_peak' in x
  289. # and not 'slope' in x
  290. # and not x in ['fall_final', 'fall_slope', 'fall_imp', 'fall']
  291. ]
  292. if binarize:
  293. feat_names = [x for x in feat_names if 'binary' in x]
  294. else:
  295. feat_names = [x for x in feat_names if not 'binary' in x]
  296. return feat_names
  297. if __name__ == '__main__':
  298. # process original data (and save out lifetime thresholds)
  299. # dset_orig = 'clath_aux+gak_a7d2'
  300. # df = get_data(dset=dset_orig) # save out orig
  301. # process new data (using lifetime thresholds from original data)
  302. outcome_def = 'y_consec_sig'
  303. for dset in ['vps4_snf7___key=mt', 'vps4_snf7']: # two keys from the same file
  304. # for dset in config.DSETS.keys():
  305. df = get_data(dset=dset, previous_meta_file=None, save_processed=True)
  306. # df = get_data(dset=dset, previous_meta_file=f'{config.DIR_PROCESSED}/metadata_{dset_orig}.pkl')
  307. print(dset, 'num cells', len(df['cell_num'].unique()), 'num tracks', df.shape[0], 'num aux+',
  308. df[outcome_def].sum(), 'aux+ fraction', (df[outcome_def].sum() / df.shape[0]).round(3),
  309. 'valid', df.valid.sum(), 'valid aux+', df[df.valid][outcome_def].sum(), 'valid aux+ fraction',
  310. (df[df.valid][outcome_def].sum() / df.valid.sum()).round(3))
Tip!

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

Comments

Loading...