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.html 34 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
  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.load_tracking 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.load_tracking</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. sys.path.append(&#39;..&#39;)
  32. import mat4py
  33. import numpy as np
  34. import pandas as pd
  35. from matplotlib import pyplot as plt
  36. try:
  37. from skimage.external.tifffile import imread
  38. except:
  39. from skimage.io import imread
  40. pd.options.mode.chained_assignment = None # default=&#39;warn&#39; - caution: this turns off setting with copy warning
  41. import pickle as pkl
  42. from viz import *
  43. import math
  44. import config
  45. from tqdm import tqdm
  46. def get_tracks(data_dir, split=None, pixel_data=False, video_data=False,
  47. processed_tracks_file=oj(config.DIR_TRACKS, &#39;tracks.pkl&#39;),
  48. dset=&#39;orig&#39;):
  49. &#39;&#39;&#39;Read and save tracks tracks from folders within data_dir into a dataframe
  50. Assumes (matlab) tracking has been run
  51. &#39;&#39;&#39;
  52. processed_tracks_file = processed_tracks_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  53. print(&#39;\t&#39;, processed_tracks_file, data_dir)
  54. if os.path.exists(processed_tracks_file):
  55. print(&#39;\tusing cached tracks!&#39;)
  56. return pd.read_pickle(processed_tracks_file)
  57. dfs = []
  58. if split[&#39;feature_selection&#39;] is None:
  59. split = None
  60. if split is not None:
  61. flatten = lambda l: [item for sublist in l for item in sublist]
  62. split = flatten(split.values())
  63. # 2 directories of naming
  64. for upper_dir in sorted(os.listdir(data_dir)):
  65. print(&#39;dirs&#39;, upper_dir)
  66. if upper_dir.startswith(&#39;.&#39;) or &#39;Icon&#39; in upper_dir:
  67. continue
  68. for cell_dir in sorted(os.listdir(oj(data_dir, upper_dir))):
  69. print(&#39;\t&#39;, cell_dir)
  70. if not &#39;Cell&#39; in cell_dir:
  71. continue
  72. cell_num = oj(upper_dir, cell_dir.replace(&#39;Cell&#39;, &#39;&#39;).replace(&#39;_1s&#39;, &#39;&#39;))
  73. if split is not None:
  74. if not cell_num in split:
  75. continue
  76. full_dir = f&#39;{data_dir}/{upper_dir}/{cell_dir}&#39;
  77. fname = full_dir + &#39;/TagRFP/Tracking/ProcessedTracks.mat&#39;
  78. print(&#39;\t&#39;, cell_num)
  79. # fname_image = oj(data_dir, upper_dir, cell_dir)
  80. mat = mat4py.loadmat(fname)
  81. tracks = mat[&#39;tracks&#39;]
  82. n = len(tracks[&#39;t&#39;])
  83. # basic features
  84. t = np.array([tracks[&#39;t&#39;][i] for i in range(n)])
  85. data = {
  86. &#39;lifetime&#39;: tracks[&#39;lifetime_s&#39;],
  87. &#39;cell_num&#39;: [cell_num] * n,
  88. &#39;catIdx&#39;: tracks[&#39;catIdx&#39;],
  89. &#39;t&#39;: [t[i][0] for i in range(n)],
  90. }
  91. # displacement features
  92. totalDisplacement = []
  93. msd = [] # mean squared displacement
  94. for i in range(n):
  95. try:
  96. totalDisplacement.append(tracks[&#39;MotionAnalysis&#39;][i][&#39;totalDisplacement&#39;])
  97. except:
  98. totalDisplacement.append(0)
  99. try:
  100. msd.append(np.nanmax(tracks[&#39;MotionAnalysis&#39;][i][&#39;MSD&#39;]))
  101. except:
  102. msd.append(0)
  103. data[&#39;mean_total_displacement&#39;] = [totalDisplacement[i] / tracks[&#39;lifetime_s&#39;][i] for i in range(n)]
  104. data[&#39;mean_square_displacement&#39;] = msd
  105. # position features
  106. x_pos_seq = np.array(
  107. [tracks[&#39;x&#39;][i][0] for i in range(n)]) # x-position for clathrin (auxilin is very similar)
  108. y_pos_seq = np.array(
  109. [tracks[&#39;y&#39;][i][0] for i in range(n)]) # y-position for clathrin (auxilin is very similar)
  110. data[&#39;x_pos_seq&#39;] = x_pos_seq
  111. data[&#39;y_pos_seq&#39;] = y_pos_seq
  112. data[&#39;x_pos&#39;] = [sum(x) / len(x) for x in x_pos_seq] # mean position in the image
  113. data[&#39;y_pos&#39;] = [sum(y) / len(y) for y in y_pos_seq]
  114. # track features
  115. num_channels = len(tracks[&#39;A&#39;][0])
  116. for idx_channel, prefix in zip(range(num_channels),
  117. [&#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;][:num_channels]):
  118. # print(tracks.keys())
  119. track = np.array([tracks[&#39;A&#39;][i][idx_channel] for i in range(n)])
  120. cs = np.array([tracks[&#39;c&#39;][i][idx_channel] for i in range(n)])
  121. # print(&#39;track keys&#39;, tracks.keys())
  122. pvals = np.array([tracks[&#39;pval_Ar&#39;][i][idx_channel] for i in range(n)])
  123. stds = np.array([tracks[&#39;A_pstd&#39;][i][idx_channel] for i in range(n)])
  124. sigmas = np.array([tracks[&#39;sigma_r&#39;][i][idx_channel] for i in range(n)])
  125. data[prefix + &#39;_pvals&#39;] = pvals
  126. starts = []
  127. starts_p = []
  128. starts_c = []
  129. starts_s = []
  130. starts_sig = []
  131. for d in tracks[&#39;startBuffer&#39;]:
  132. if len(d) == 0:
  133. starts.append([])
  134. starts_p.append([])
  135. starts_c.append([])
  136. starts_s.append([])
  137. starts_sig.append([])
  138. else:
  139. # print(&#39;buffkeys&#39;, d.keys())
  140. starts.append(d[&#39;A&#39;][idx_channel])
  141. starts_p.append(d[&#39;pval_Ar&#39;][idx_channel])
  142. starts_c.append(d[&#39;c&#39;][idx_channel])
  143. starts_s.append(d[&#39;A_pstd&#39;][idx_channel])
  144. starts_sig.append(d[&#39;sigma_r&#39;][idx_channel])
  145. ends = []
  146. ends_p = []
  147. ends_c = []
  148. ends_s = []
  149. ends_sig = []
  150. for d in tracks[&#39;endBuffer&#39;]:
  151. if len(d) == 0:
  152. ends.append([])
  153. ends_p.append([])
  154. ends_c.append([])
  155. ends_s.append([])
  156. ends_sig.append([])
  157. else:
  158. ends.append(d[&#39;A&#39;][idx_channel])
  159. ends_p.append(d[&#39;pval_Ar&#39;][idx_channel])
  160. ends_c.append(d[&#39;c&#39;][idx_channel])
  161. ends_s.append(d[&#39;A_pstd&#39;][idx_channel])
  162. ends_sig.append(d[&#39;sigma_r&#39;][idx_channel])
  163. # if prefix == &#39;X&#39;:
  164. data[prefix + &#39;_extended&#39;] = [starts[i] + track[i] + ends[i] for i in range(n)]
  165. data[prefix + &#39;_pvals_extended&#39;] = [starts_p[i] + pvals[i] + ends_p[i] for i in range(n)]
  166. data[prefix] = track
  167. data[prefix + &#39;_c_extended&#39;] = [starts_c[i] + cs[i] + ends_c[i] for i in range(n)]
  168. data[prefix + &#39;_std_extended&#39;] = [starts_s[i] + stds[i] + ends_s[i] for i in range(n)]
  169. data[prefix + &#39;_sigma_extended&#39;] = [starts_sig[i] + sigmas[i] + ends_sig[i] for i in range(n)]
  170. data[prefix + &#39;_starts&#39;] = starts
  171. data[prefix + &#39;_ends&#39;] = ends
  172. data[&#39;lifetime_extended&#39;] = [len(x) for x in data[&#39;X_extended&#39;]]
  173. # pixel features
  174. if pixel_data:
  175. cla, aux = get_images(full_dir)
  176. pixel = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), int(x_pos_seq[i][j])]
  177. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  178. for i in range(n)])
  179. pixel_up = np.array(
  180. [[cla[int(t[i][j]), min(int(y_pos_seq[i][j] + 1), cla.shape[1] - 1), int(x_pos_seq[i][j])]
  181. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  182. for i in range(n)])
  183. pixel_down = np.array([[cla[int(t[i][j]), max(int(y_pos_seq[i][j] - 1), 0), int(x_pos_seq[i][j])]
  184. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  185. for i in range(n)])
  186. pixel_left = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), max(int(x_pos_seq[i][j] - 1), 0)]
  187. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  188. for i in range(n)])
  189. pixel_right = np.array(
  190. [[cla[int(t[i][j]), int(y_pos_seq[i][j]), min(int(x_pos_seq[i][j] + 1), cla.shape[2] - 1)]
  191. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  192. for i in range(n)])
  193. data[&#39;pixel&#39;] = pixel
  194. data[&#39;pixel_left&#39;] = pixel_left
  195. data[&#39;pixel_right&#39;] = pixel_right
  196. data[&#39;pixel_up&#39;] = pixel_up
  197. data[&#39;pixel_down&#39;] = pixel_down
  198. data[&#39;center_max&#39;] = [max(pixel[i]) for i in range(n)]
  199. data[&#39;left_max&#39;] = [max(pixel_left[i]) for i in range(n)]
  200. data[&#39;right_max&#39;] = [max(pixel_right[i]) for i in range(n)]
  201. data[&#39;up_max&#39;] = [max(pixel_up[i]) for i in range(n)]
  202. data[&#39;down_max&#39;] = [max(pixel_down[i]) for i in range(n)]
  203. if video_data:
  204. # load video data
  205. X_video = []
  206. square_size = 10
  207. cla, aux = get_images(full_dir)
  208. for i in (range(n)):
  209. # only extract videos if lifetime &gt; 15
  210. if data[&#39;lifetime&#39;][i] &gt;= 15:
  211. # range of positions of track
  212. x_pos_max, x_pos_min = int(max(data[&#39;x_pos_seq&#39;][i])), int(min(data[&#39;x_pos_seq&#39;][i]))
  213. y_pos_max, y_pos_min = int(max(data[&#39;y_pos_seq&#39;][i])), int(min(data[&#39;y_pos_seq&#39;][i]))
  214. # crop videos to 10X10 square
  215. # e.g. if x_pos_max = 52, x_pos_min = 48, then take x_left = 45, x_right = 54, etc.
  216. if x_pos_max - x_pos_min &lt; square_size:
  217. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  218. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  219. if x_left &lt; 0:
  220. x_left, x_right = 0, square_size - 1
  221. if x_right &gt; cla.shape[2] - 1:
  222. x_left, x_right = cla.shape[2] - square_size, cla.shape[2] - 1
  223. else:
  224. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  225. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  226. if y_pos_max - y_pos_min &lt; square_size:
  227. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  228. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  229. if y_left &lt; 0:
  230. y_left, y_right = 0, square_size - 1
  231. if y_right &gt; cla.shape[1] - 1:
  232. y_left, y_right = cla.shape[1] - square_size, cla.shape[1] - 1
  233. else:
  234. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  235. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  236. video = cla[int(np.nanmin(t[i])):int(np.nanmax(t[i]) + 1), :, :][:, y_left:(y_right + 1), :][:, :, x_left:(x_right + 1)]
  237. X_video.append(video)
  238. else:
  239. X_video.append(np.zeros(0))
  240. data[&#39;X_video&#39;] = X_video
  241. df = pd.DataFrame.from_dict(data)
  242. dfs.append(deepcopy(df))
  243. df = pd.concat(dfs)
  244. os.makedirs(os.path.dirname(processed_tracks_file), exist_ok=True)
  245. df.to_pickle(processed_tracks_file)
  246. return df
  247. def get_images(cell_dir: str):
  248. &#39;&#39;&#39;Loads in X and Y for one cell
  249. Params
  250. ------
  251. cell_dir
  252. Path to directory for one cell
  253. Returns
  254. -------
  255. X : np.ndarray
  256. has shape (W, H, num_images)
  257. Y : np.ndarray
  258. has shape (W, H, num_images)
  259. &#39;&#39;&#39;
  260. for name in os.listdir(oj(cell_dir, &#39;TagRFP&#39;)):
  261. if &#39;tif&#39; in name:
  262. fname1 = name
  263. for name in os.listdir(oj(cell_dir, &#39;EGFP&#39;)):
  264. if &#39;tif&#39; in name:
  265. fname2 = name
  266. print(cell_dir)
  267. X = imread(oj(cell_dir, &#39;TagRFP&#39;, fname1)) # .astype(np.float32) # X = RFP(clathrin) (num_images x H x W)
  268. Y = imread(oj(cell_dir, &#39;EGFP&#39;, fname2)) # .astype(np.float32) # Y = EGFP (auxilin) (num_image x H x W)
  269. return X, Y</code></pre>
  270. </details>
  271. </section>
  272. <section>
  273. </section>
  274. <section>
  275. </section>
  276. <section>
  277. <h2 class="section-title" id="header-functions">Functions</h2>
  278. <dl>
  279. <dt id="src.load_tracking.get_images"><code class="name flex">
  280. <span>def <span class="ident">get_images</span></span>(<span>cell_dir)</span>
  281. </code></dt>
  282. <dd>
  283. <section class="desc"><p>Loads in X and Y for one cell</p>
  284. <h2 id="params">Params</h2>
  285. <dl>
  286. <dt><strong><code>cell_dir</code></strong></dt>
  287. <dd>Path to directory for one cell</dd>
  288. </dl>
  289. <h2 id="returns">Returns</h2>
  290. <dl>
  291. <dt><strong><code>X</code></strong> :&ensp;<code>np.ndarray</code></dt>
  292. <dd>has shape (W, H, num_images)</dd>
  293. <dt><strong><code>Y</code></strong> :&ensp;<code>np.ndarray</code></dt>
  294. <dd>has shape (W, H, num_images)</dd>
  295. </dl></section>
  296. <details class="source">
  297. <summary>
  298. <span>Expand source code</span>
  299. </summary>
  300. <pre><code class="python">def get_images(cell_dir: str):
  301. &#39;&#39;&#39;Loads in X and Y for one cell
  302. Params
  303. ------
  304. cell_dir
  305. Path to directory for one cell
  306. Returns
  307. -------
  308. X : np.ndarray
  309. has shape (W, H, num_images)
  310. Y : np.ndarray
  311. has shape (W, H, num_images)
  312. &#39;&#39;&#39;
  313. for name in os.listdir(oj(cell_dir, &#39;TagRFP&#39;)):
  314. if &#39;tif&#39; in name:
  315. fname1 = name
  316. for name in os.listdir(oj(cell_dir, &#39;EGFP&#39;)):
  317. if &#39;tif&#39; in name:
  318. fname2 = name
  319. print(cell_dir)
  320. X = imread(oj(cell_dir, &#39;TagRFP&#39;, fname1)) # .astype(np.float32) # X = RFP(clathrin) (num_images x H x W)
  321. Y = imread(oj(cell_dir, &#39;EGFP&#39;, fname2)) # .astype(np.float32) # Y = EGFP (auxilin) (num_image x H x W)
  322. return X, Y</code></pre>
  323. </details>
  324. </dd>
  325. <dt id="src.load_tracking.get_tracks"><code class="name flex">
  326. <span>def <span class="ident">get_tracks</span></span>(<span>data_dir, split=None, pixel_data=False, video_data=False, processed_tracks_file='/accounts/projects/vision/chandan/auxilin-prediction/src/../data/tracks/tracks.pkl', dset='orig')</span>
  327. </code></dt>
  328. <dd>
  329. <section class="desc"><p>Read and save tracks tracks from folders within data_dir into a dataframe
  330. Assumes (matlab) tracking has been run</p></section>
  331. <details class="source">
  332. <summary>
  333. <span>Expand source code</span>
  334. </summary>
  335. <pre><code class="python">def get_tracks(data_dir, split=None, pixel_data=False, video_data=False,
  336. processed_tracks_file=oj(config.DIR_TRACKS, &#39;tracks.pkl&#39;),
  337. dset=&#39;orig&#39;):
  338. &#39;&#39;&#39;Read and save tracks tracks from folders within data_dir into a dataframe
  339. Assumes (matlab) tracking has been run
  340. &#39;&#39;&#39;
  341. processed_tracks_file = processed_tracks_file[:-4] + &#39;_&#39; + dset + &#39;.pkl&#39;
  342. print(&#39;\t&#39;, processed_tracks_file, data_dir)
  343. if os.path.exists(processed_tracks_file):
  344. print(&#39;\tusing cached tracks!&#39;)
  345. return pd.read_pickle(processed_tracks_file)
  346. dfs = []
  347. if split[&#39;feature_selection&#39;] is None:
  348. split = None
  349. if split is not None:
  350. flatten = lambda l: [item for sublist in l for item in sublist]
  351. split = flatten(split.values())
  352. # 2 directories of naming
  353. for upper_dir in sorted(os.listdir(data_dir)):
  354. print(&#39;dirs&#39;, upper_dir)
  355. if upper_dir.startswith(&#39;.&#39;) or &#39;Icon&#39; in upper_dir:
  356. continue
  357. for cell_dir in sorted(os.listdir(oj(data_dir, upper_dir))):
  358. print(&#39;\t&#39;, cell_dir)
  359. if not &#39;Cell&#39; in cell_dir:
  360. continue
  361. cell_num = oj(upper_dir, cell_dir.replace(&#39;Cell&#39;, &#39;&#39;).replace(&#39;_1s&#39;, &#39;&#39;))
  362. if split is not None:
  363. if not cell_num in split:
  364. continue
  365. full_dir = f&#39;{data_dir}/{upper_dir}/{cell_dir}&#39;
  366. fname = full_dir + &#39;/TagRFP/Tracking/ProcessedTracks.mat&#39;
  367. print(&#39;\t&#39;, cell_num)
  368. # fname_image = oj(data_dir, upper_dir, cell_dir)
  369. mat = mat4py.loadmat(fname)
  370. tracks = mat[&#39;tracks&#39;]
  371. n = len(tracks[&#39;t&#39;])
  372. # basic features
  373. t = np.array([tracks[&#39;t&#39;][i] for i in range(n)])
  374. data = {
  375. &#39;lifetime&#39;: tracks[&#39;lifetime_s&#39;],
  376. &#39;cell_num&#39;: [cell_num] * n,
  377. &#39;catIdx&#39;: tracks[&#39;catIdx&#39;],
  378. &#39;t&#39;: [t[i][0] for i in range(n)],
  379. }
  380. # displacement features
  381. totalDisplacement = []
  382. msd = [] # mean squared displacement
  383. for i in range(n):
  384. try:
  385. totalDisplacement.append(tracks[&#39;MotionAnalysis&#39;][i][&#39;totalDisplacement&#39;])
  386. except:
  387. totalDisplacement.append(0)
  388. try:
  389. msd.append(np.nanmax(tracks[&#39;MotionAnalysis&#39;][i][&#39;MSD&#39;]))
  390. except:
  391. msd.append(0)
  392. data[&#39;mean_total_displacement&#39;] = [totalDisplacement[i] / tracks[&#39;lifetime_s&#39;][i] for i in range(n)]
  393. data[&#39;mean_square_displacement&#39;] = msd
  394. # position features
  395. x_pos_seq = np.array(
  396. [tracks[&#39;x&#39;][i][0] for i in range(n)]) # x-position for clathrin (auxilin is very similar)
  397. y_pos_seq = np.array(
  398. [tracks[&#39;y&#39;][i][0] for i in range(n)]) # y-position for clathrin (auxilin is very similar)
  399. data[&#39;x_pos_seq&#39;] = x_pos_seq
  400. data[&#39;y_pos_seq&#39;] = y_pos_seq
  401. data[&#39;x_pos&#39;] = [sum(x) / len(x) for x in x_pos_seq] # mean position in the image
  402. data[&#39;y_pos&#39;] = [sum(y) / len(y) for y in y_pos_seq]
  403. # track features
  404. num_channels = len(tracks[&#39;A&#39;][0])
  405. for idx_channel, prefix in zip(range(num_channels),
  406. [&#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;][:num_channels]):
  407. # print(tracks.keys())
  408. track = np.array([tracks[&#39;A&#39;][i][idx_channel] for i in range(n)])
  409. cs = np.array([tracks[&#39;c&#39;][i][idx_channel] for i in range(n)])
  410. # print(&#39;track keys&#39;, tracks.keys())
  411. pvals = np.array([tracks[&#39;pval_Ar&#39;][i][idx_channel] for i in range(n)])
  412. stds = np.array([tracks[&#39;A_pstd&#39;][i][idx_channel] for i in range(n)])
  413. sigmas = np.array([tracks[&#39;sigma_r&#39;][i][idx_channel] for i in range(n)])
  414. data[prefix + &#39;_pvals&#39;] = pvals
  415. starts = []
  416. starts_p = []
  417. starts_c = []
  418. starts_s = []
  419. starts_sig = []
  420. for d in tracks[&#39;startBuffer&#39;]:
  421. if len(d) == 0:
  422. starts.append([])
  423. starts_p.append([])
  424. starts_c.append([])
  425. starts_s.append([])
  426. starts_sig.append([])
  427. else:
  428. # print(&#39;buffkeys&#39;, d.keys())
  429. starts.append(d[&#39;A&#39;][idx_channel])
  430. starts_p.append(d[&#39;pval_Ar&#39;][idx_channel])
  431. starts_c.append(d[&#39;c&#39;][idx_channel])
  432. starts_s.append(d[&#39;A_pstd&#39;][idx_channel])
  433. starts_sig.append(d[&#39;sigma_r&#39;][idx_channel])
  434. ends = []
  435. ends_p = []
  436. ends_c = []
  437. ends_s = []
  438. ends_sig = []
  439. for d in tracks[&#39;endBuffer&#39;]:
  440. if len(d) == 0:
  441. ends.append([])
  442. ends_p.append([])
  443. ends_c.append([])
  444. ends_s.append([])
  445. ends_sig.append([])
  446. else:
  447. ends.append(d[&#39;A&#39;][idx_channel])
  448. ends_p.append(d[&#39;pval_Ar&#39;][idx_channel])
  449. ends_c.append(d[&#39;c&#39;][idx_channel])
  450. ends_s.append(d[&#39;A_pstd&#39;][idx_channel])
  451. ends_sig.append(d[&#39;sigma_r&#39;][idx_channel])
  452. # if prefix == &#39;X&#39;:
  453. data[prefix + &#39;_extended&#39;] = [starts[i] + track[i] + ends[i] for i in range(n)]
  454. data[prefix + &#39;_pvals_extended&#39;] = [starts_p[i] + pvals[i] + ends_p[i] for i in range(n)]
  455. data[prefix] = track
  456. data[prefix + &#39;_c_extended&#39;] = [starts_c[i] + cs[i] + ends_c[i] for i in range(n)]
  457. data[prefix + &#39;_std_extended&#39;] = [starts_s[i] + stds[i] + ends_s[i] for i in range(n)]
  458. data[prefix + &#39;_sigma_extended&#39;] = [starts_sig[i] + sigmas[i] + ends_sig[i] for i in range(n)]
  459. data[prefix + &#39;_starts&#39;] = starts
  460. data[prefix + &#39;_ends&#39;] = ends
  461. data[&#39;lifetime_extended&#39;] = [len(x) for x in data[&#39;X_extended&#39;]]
  462. # pixel features
  463. if pixel_data:
  464. cla, aux = get_images(full_dir)
  465. pixel = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), int(x_pos_seq[i][j])]
  466. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  467. for i in range(n)])
  468. pixel_up = np.array(
  469. [[cla[int(t[i][j]), min(int(y_pos_seq[i][j] + 1), cla.shape[1] - 1), int(x_pos_seq[i][j])]
  470. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  471. for i in range(n)])
  472. pixel_down = np.array([[cla[int(t[i][j]), max(int(y_pos_seq[i][j] - 1), 0), int(x_pos_seq[i][j])]
  473. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  474. for i in range(n)])
  475. pixel_left = np.array([[cla[int(t[i][j]), int(y_pos_seq[i][j]), max(int(x_pos_seq[i][j] - 1), 0)]
  476. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  477. for i in range(n)])
  478. pixel_right = np.array(
  479. [[cla[int(t[i][j]), int(y_pos_seq[i][j]), min(int(x_pos_seq[i][j] + 1), cla.shape[2] - 1)]
  480. if not math.isnan(t[i][j]) else 0 for j in range(len(tracks[&#39;t&#39;][i]))]
  481. for i in range(n)])
  482. data[&#39;pixel&#39;] = pixel
  483. data[&#39;pixel_left&#39;] = pixel_left
  484. data[&#39;pixel_right&#39;] = pixel_right
  485. data[&#39;pixel_up&#39;] = pixel_up
  486. data[&#39;pixel_down&#39;] = pixel_down
  487. data[&#39;center_max&#39;] = [max(pixel[i]) for i in range(n)]
  488. data[&#39;left_max&#39;] = [max(pixel_left[i]) for i in range(n)]
  489. data[&#39;right_max&#39;] = [max(pixel_right[i]) for i in range(n)]
  490. data[&#39;up_max&#39;] = [max(pixel_up[i]) for i in range(n)]
  491. data[&#39;down_max&#39;] = [max(pixel_down[i]) for i in range(n)]
  492. if video_data:
  493. # load video data
  494. X_video = []
  495. square_size = 10
  496. cla, aux = get_images(full_dir)
  497. for i in (range(n)):
  498. # only extract videos if lifetime &gt; 15
  499. if data[&#39;lifetime&#39;][i] &gt;= 15:
  500. # range of positions of track
  501. x_pos_max, x_pos_min = int(max(data[&#39;x_pos_seq&#39;][i])), int(min(data[&#39;x_pos_seq&#39;][i]))
  502. y_pos_max, y_pos_min = int(max(data[&#39;y_pos_seq&#39;][i])), int(min(data[&#39;y_pos_seq&#39;][i]))
  503. # crop videos to 10X10 square
  504. # e.g. if x_pos_max = 52, x_pos_min = 48, then take x_left = 45, x_right = 54, etc.
  505. if x_pos_max - x_pos_min &lt; square_size:
  506. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  507. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  508. if x_left &lt; 0:
  509. x_left, x_right = 0, square_size - 1
  510. if x_right &gt; cla.shape[2] - 1:
  511. x_left, x_right = cla.shape[2] - square_size, cla.shape[2] - 1
  512. else:
  513. x_left, x_right = int((x_pos_max + x_pos_min - square_size + 1) / 2), \
  514. int((x_pos_max + x_pos_min + square_size - 1) / 2)
  515. if y_pos_max - y_pos_min &lt; square_size:
  516. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  517. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  518. if y_left &lt; 0:
  519. y_left, y_right = 0, square_size - 1
  520. if y_right &gt; cla.shape[1] - 1:
  521. y_left, y_right = cla.shape[1] - square_size, cla.shape[1] - 1
  522. else:
  523. y_left, y_right = int((y_pos_max + y_pos_min - square_size + 1) / 2), \
  524. int((y_pos_max + y_pos_min + square_size - 1) / 2)
  525. video = cla[int(np.nanmin(t[i])):int(np.nanmax(t[i]) + 1), :, :][:, y_left:(y_right + 1), :][:, :, x_left:(x_right + 1)]
  526. X_video.append(video)
  527. else:
  528. X_video.append(np.zeros(0))
  529. data[&#39;X_video&#39;] = X_video
  530. df = pd.DataFrame.from_dict(data)
  531. dfs.append(deepcopy(df))
  532. df = pd.concat(dfs)
  533. os.makedirs(os.path.dirname(processed_tracks_file), exist_ok=True)
  534. df.to_pickle(processed_tracks_file)
  535. return df</code></pre>
  536. </details>
  537. </dd>
  538. </dl>
  539. </section>
  540. <section>
  541. </section>
  542. </article>
  543. <nav id="sidebar">
  544. <h1>Index</h1>
  545. <div class="toc">
  546. <ul></ul>
  547. </div>
  548. <ul id="index">
  549. <li><h3>Super-module</h3>
  550. <ul>
  551. <li><code><a title="src" href="index.html">src</a></code></li>
  552. </ul>
  553. </li>
  554. <li><h3><a href="#header-functions">Functions</a></h3>
  555. <ul class="">
  556. <li><code><a title="src.load_tracking.get_images" href="#src.load_tracking.get_images">get_images</a></code></li>
  557. <li><code><a title="src.load_tracking.get_tracks" href="#src.load_tracking.get_tracks">get_tracks</a></code></li>
  558. </ul>
  559. </li>
  560. </ul>
  561. </nav>
  562. </main>
  563. <footer id="footer">
  564. <p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.7.2</a>.</p>
  565. </footer>
  566. <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
  567. <script>hljs.initHighlightingOnLoad()</script>
  568. </body>
  569. </html>
Tip!

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

Comments

Loading...