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

load_tracking.py 14 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
  1. import os
  2. import sys
  3. from copy import deepcopy
  4. from os.path import join as oj
  5. sys.path.append('..')
  6. import mat4py
  7. import numpy as np
  8. import pandas as pd
  9. import scipy.io
  10. from matplotlib import pyplot as plt
  11. try:
  12. from skimage.external.tifffile import imread
  13. except:
  14. from skimage.io import imread
  15. pd.options.mode.chained_assignment = None # default='warn' - caution: this turns off setting with copy warning
  16. import pickle as pkl
  17. from viz import *
  18. import math
  19. import config
  20. from tqdm import tqdm
  21. def get_tracks(data_dir,
  22. split=None, pixel_data=False, video_data=False,
  23. processed_tracks_file=oj(config.DIR_TRACKS, 'tracks.pkl'),
  24. frac_cell_train_vps=0.75,
  25. dset='orig'):
  26. '''Read and save tracks tracks from folders within data_dir into a dataframe
  27. Assumes (matlab) tracking has been run
  28. Params
  29. ------
  30. data_dir: str
  31. 'data_dir' path inside of the config of the dataset
  32. alternatively, for new data, this is a path to a tracked .mat file
  33. split: dict
  34. entire dictionary of config for this dset
  35. split_cell_frac_vps: float
  36. for vps, only one cell is given.
  37. Assign frac_cell_train_vps of the tracks to training (cell_num=0)
  38. Assign remaining tracks to test (cell_num=-1)
  39. dset: str
  40. Key for the config in dataset
  41. '''
  42. # use cached tracks
  43. processed_tracks_file = processed_tracks_file[:-4] + '_' + dset + '.pkl'
  44. print('\t', processed_tracks_file, data_dir)
  45. if os.path.exists(processed_tracks_file):
  46. print('\tusing cached tracks!')
  47. return pd.read_pickle(processed_tracks_file)
  48. # new (vps_snf) data
  49. if data_dir.endswith('.mat'):
  50. mat = mat4py.loadmat(data_dir)['t']
  51. print('keys', mat.keys())
  52. if 'key=mt' in dset:
  53. track_key = 'allTracks_snf7_vps4mt' # for vps4_snf7
  54. else:
  55. track_key = 'allTracks_snf7_vps4wt' # for vps4_snf7
  56. print(f'\ttrack key: {track_key}')
  57. tracks = mat[track_key]
  58. print(f'\ttracks.keys() {tracks.keys()}')
  59. data = get_data_from_tracks(tracks, cell_num=None, use_vps_data_scheme=True,
  60. pixel_data=False, video_data=False)
  61. df = pd.DataFrame.from_dict(data)
  62. df['cell_num'] = 'test' # test
  63. df.loc[:int(df.shape[0] * frac_cell_train_vps), 'cell_num'] = 'train' # train
  64. os.makedirs(os.path.dirname(processed_tracks_file), exist_ok=True)
  65. df.to_pickle(processed_tracks_file)
  66. return df
  67. # deal with some folders to skip
  68. if split['feature_selection'] is None:
  69. split = None
  70. if split is not None:
  71. flatten = lambda l: [item for sublist in l for item in sublist]
  72. split = flatten(split.values()) # list of all folders
  73. # 2 directories of naming
  74. dfs = []
  75. for upper_dir in sorted(os.listdir(data_dir)):
  76. print('dirs', upper_dir)
  77. if upper_dir.startswith('.') or 'Icon' in upper_dir:
  78. continue
  79. for cell_dir in sorted(os.listdir(oj(data_dir, upper_dir))):
  80. print('\t', cell_dir)
  81. if not 'Cell' in cell_dir:
  82. continue
  83. cell_num = oj(upper_dir, cell_dir.replace('Cell', '').replace('_1s', ''))
  84. # skip folders that are not listed
  85. if split is not None:
  86. if not cell_num in split:
  87. continue
  88. full_dir = f'{data_dir}/{upper_dir}/{cell_dir}'
  89. fname = full_dir + '/TagRFP/Tracking/ProcessedTracks.mat'
  90. print('\t', cell_num)
  91. # fname_image = oj(data_dir, upper_dir, cell_dir)
  92. mat = mat4py.loadmat(fname)
  93. tracks = mat['tracks']
  94. data = get_data_from_tracks(tracks, cell_num, use_vps_data_scheme=False,
  95. pixel_data=pixel_data, video_data=video_data)
  96. df = pd.DataFrame.from_dict(data)
  97. dfs.append(deepcopy(df))
  98. df = pd.concat(dfs)
  99. # save and return
  100. os.makedirs(os.path.dirname(processed_tracks_file), exist_ok=True)
  101. df.to_pickle(processed_tracks_file)
  102. return df
  103. def get_data_from_tracks(tracks, cell_num=None, use_vps_data_scheme=False,
  104. pixel_data=False, video_data=False):
  105. """Unpack data from single tracking .mat file
  106. Params
  107. ------
  108. tracks: object from mat4py
  109. """
  110. n = len(tracks['t'])
  111. # basic features
  112. t = np.array([tracks['t'][i] for i in range(n)], dtype=object)
  113. data = {
  114. 'lifetime': tracks['lifetime_s'],
  115. 'cell_num': [cell_num] * n,
  116. 'catIdx': tracks['catIdx'],
  117. 't': [t[i][0] for i in range(n)],
  118. 'lifetime_s': tracks['lifetime_s'],
  119. }
  120. # displacement features
  121. totalDisplacement = []
  122. msd = [] # mean squared displacement
  123. for i in range(n):
  124. try:
  125. totalDisplacement.append(tracks['MotionAnalysis'][i]['totalDisplacement'])
  126. except:
  127. totalDisplacement.append(0)
  128. try:
  129. msd.append(np.nanmax(tracks['MotionAnalysis'][i]['MSD']))
  130. except:
  131. msd.append(0)
  132. data['mean_total_displacement'] = [totalDisplacement[i] / tracks['lifetime_s'][i] for i in range(n)]
  133. data['mean_square_displacement'] = msd
  134. # position features
  135. assert isinstance(tracks['A'][0][0], list), 'If this is not a list, then probably only recorded 1 channel'
  136. assert isinstance(tracks['x'][0][0], list), 'If this is not a list, then probably only recorded 1 channel'
  137. print('len', tracks['x'][0])
  138. x_pos_seq = np.array(
  139. [tracks['x'][i][0] for i in range(n)], dtype=object) # x-position for clathrin (auxilin is very similar)
  140. y_pos_seq = np.array(
  141. [tracks['y'][i][0] for i in range(n)], dtype=object) # y-position for clathrin (auxilin is very similar)
  142. data['x_pos_seq'] = x_pos_seq
  143. data['y_pos_seq'] = y_pos_seq
  144. data['x_pos'] = [sum(x) / len(x) for x in x_pos_seq] # mean position in the image
  145. data['y_pos'] = [sum(y) / len(y) for y in y_pos_seq]
  146. if 'z' in tracks.keys():
  147. z_pos_seq = np.array(
  148. [tracks['z'][i][0] for i in range(n)], dtype=object) # z-position for clathrin
  149. data['z_pos_seq'] = z_pos_seq
  150. data['z_pos'] = [sum(z) / len(z) for z in z_pos_seq]
  151. # track features
  152. num_channels = len(tracks['A'][0])
  153. for idx_channel, prefix in zip(range(num_channels),
  154. ['X', 'Y', 'Z'][:num_channels]):
  155. # print(tracks.keys())
  156. track = np.array([tracks['A'][i][idx_channel] for i in range(n)], dtype=object)
  157. cs = np.array([tracks['c'][i][idx_channel] for i in range(n)], dtype=object)
  158. # print('track keys', tracks.keys())
  159. pvals = np.array([tracks['pval_Ar'][i][idx_channel] for i in range(n)], dtype=object)
  160. stds = np.array([tracks['A_pstd'][i][idx_channel] for i in range(n)], dtype=object)
  161. sigmas = np.array([tracks['sigma_r'][i][idx_channel] for i in range(n)], dtype=object)
  162. data[prefix + '_pvals'] = pvals
  163. starts = []
  164. starts_p = []
  165. starts_c = []
  166. starts_s = []
  167. starts_sig = []
  168. for d in tracks['startBuffer']:
  169. if len(d) == 0:
  170. starts.append([])
  171. starts_p.append([])
  172. starts_c.append([])
  173. starts_s.append([])
  174. starts_sig.append([])
  175. else:
  176. # print('buffkeys', d.keys())
  177. starts.append(d['A'][idx_channel])
  178. starts_p.append(d['pval_Ar'][idx_channel])
  179. starts_c.append(d['c'][idx_channel])
  180. starts_s.append(d['A_pstd'][idx_channel])
  181. starts_sig.append(d['sigma_r'][idx_channel])
  182. ends = []
  183. ends_p = []
  184. ends_c = []
  185. ends_s = []
  186. ends_sig = []
  187. for d in tracks['endBuffer']:
  188. if len(d) == 0:
  189. ends.append([])
  190. ends_p.append([])
  191. ends_c.append([])
  192. ends_s.append([])
  193. ends_sig.append([])
  194. else:
  195. ends.append(d['A'][idx_channel])
  196. ends_p.append(d['pval_Ar'][idx_channel])
  197. ends_c.append(d['c'][idx_channel])
  198. ends_s.append(d['A_pstd'][idx_channel])
  199. ends_sig.append(d['sigma_r'][idx_channel])
  200. # if prefix == 'X':
  201. data[prefix + '_extended'] = [starts[i] + track[i] + ends[i] for i in range(n)]
  202. data[prefix + '_pvals_extended'] = [starts_p[i] + pvals[i] + ends_p[i] for i in range(n)]
  203. data[prefix] = track
  204. data[prefix + '_c_extended'] = [starts_c[i] + cs[i] + ends_c[i] for i in range(n)]
  205. data[prefix + '_std_extended'] = [starts_s[i] + stds[i] + ends_s[i] for i in range(n)]
  206. data[prefix + '_sigma_extended'] = [starts_sig[i] + sigmas[i] + ends_sig[i] for i in range(n)]
  207. data[prefix + '_starts'] = starts
  208. data[prefix + '_ends'] = ends
  209. data['lifetime_extended'] = [len(x) for x in data['X_extended']]
  210. # pixel features
  211. if pixel_data:
  212. cla, aux = get_images(full_dir)
  213. pixel = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), int(x_pos_seq[i][j])]
  214. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks['t'][i]))]
  215. for i in range(n)])
  216. pixel_up = np.array(
  217. [[cla[int(t[i][j]), min(int(y_pos_seq[i][j] + 1), cla.shape[1] - 1), int(x_pos_seq[i][j])]
  218. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks['t'][i]))]
  219. for i in range(n)])
  220. pixel_down = np.array([[cla[int(t[i][j]), max(int(y_pos_seq[i][j] - 1), 0), int(x_pos_seq[i][j])]
  221. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks['t'][i]))]
  222. for i in range(n)])
  223. pixel_left = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), max(int(x_pos_seq[i][j] - 1), 0)]
  224. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks['t'][i]))]
  225. for i in range(n)])
  226. pixel_right = np.array(
  227. [[cla[int(t[i][j]), int(y_pos_seq[i][j]), min(int(x_pos_seq[i][j] + 1), cla.shape[2] - 1)]
  228. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks['t'][i]))]
  229. for i in range(n)])
  230. data['pixel'] = pixel
  231. data['pixel_left'] = pixel_left
  232. data['pixel_right'] = pixel_right
  233. data['pixel_up'] = pixel_up
  234. data['pixel_down'] = pixel_down
  235. data['center_max'] = [max(pixel[i]) for i in range(n)]
  236. data['left_max'] = [max(pixel_left[i]) for i in range(n)]
  237. data['right_max'] = [max(pixel_right[i]) for i in range(n)]
  238. data['up_max'] = [max(pixel_up[i]) for i in range(n)]
  239. data['down_max'] = [max(pixel_down[i]) for i in range(n)]
  240. if video_data:
  241. # load video data
  242. X_video = []
  243. square_size = 10
  244. cla, aux = get_images(full_dir)
  245. for i in (range(n)):
  246. # only extract videos if lifetime > 15
  247. if data['lifetime'][i] >= 15:
  248. # range of positions of track
  249. x_pos_max, x_pos_min = int(max(data['x_pos_seq'][i])), int(min(data['x_pos_seq'][i]))
  250. y_pos_max, y_pos_min = int(max(data['y_pos_seq'][i])), int(min(data['y_pos_seq'][i]))
  251. # crop videos to 10X10 square
  252. # e.g. if x_pos_max = 52, x_pos_min = 48, then take x_left = 45, x_right = 54, etc.
  253. if x_pos_max - x_pos_min < square_size:
  254. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  255. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  256. if x_left < 0:
  257. x_left, x_right = 0, square_size - 1
  258. if x_right > cla.shape[2] - 1:
  259. x_left, x_right = cla.shape[2] - square_size, cla.shape[2] - 1
  260. else:
  261. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  262. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  263. if y_pos_max - y_pos_min < square_size:
  264. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  265. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  266. if y_left < 0:
  267. y_left, y_right = 0, square_size - 1
  268. if y_right > cla.shape[1] - 1:
  269. y_left, y_right = cla.shape[1] - square_size, cla.shape[1] - 1
  270. else:
  271. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  272. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  273. video = cla[int(np.nanmin(t[i])):int(np.nanmax(t[i]) + 1), :, :][:, y_left:(y_right + 1), :][:, :, x_left:(x_right + 1)]
  274. X_video.append(video)
  275. else:
  276. X_video.append(np.zeros(0))
  277. data['X_video'] = X_video
  278. return data
  279. def get_images(cell_dir: str):
  280. '''Loads in X and Y for one cell
  281. Params
  282. ------
  283. cell_dir
  284. Path to directory for one cell
  285. Returns
  286. -------
  287. X : np.ndarray
  288. has shape (W, H, num_images)
  289. Y : np.ndarray
  290. has shape (W, H, num_images)
  291. '''
  292. for name in os.listdir(oj(cell_dir, 'TagRFP')):
  293. if 'tif' in name:
  294. fname1 = name
  295. for name in os.listdir(oj(cell_dir, 'EGFP')):
  296. if 'tif' in name:
  297. fname2 = name
  298. print(cell_dir)
  299. X = imread(oj(cell_dir, 'TagRFP', fname1)) # .astype(np.float32) # X = RFP(clathrin) (num_images x H x W)
  300. Y = imread(oj(cell_dir, 'EGFP', fname2)) # .astype(np.float32) # Y = EGFP (auxilin) (num_image x H x W)
  301. return X, Y
Tip!

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

Comments

Loading...