forked from junlabucsd/mm3
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmm3_FocusTrackGUI.py
executable file
·1959 lines (1587 loc) · 91 KB
/
mm3_FocusTrackGUI.py
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
#! /usr/bin/env python3
from __future__ import print_function, division
from PyQt5.QtWidgets import (QApplication, QMainWindow, QGraphicsScene, QGraphicsView,
QRadioButton, QButtonGroup, QVBoxLayout, QHBoxLayout,
QWidget, QLabel, QAction, QDockWidget, QPushButton, QGraphicsItem,
QGridLayout, QGraphicsLineItem, QGraphicsPathItem, QGraphicsPixmapItem,
QGraphicsEllipseItem, QGraphicsTextItem, QInputDialog)
from PyQt5.QtGui import (QIcon, QImage, QPainter, QPen, QPixmap, qGray, QColor, QPainterPath, QBrush,
QTransform, QPolygonF, QFont, QPaintDevice)
from PyQt5.QtCore import Qt, QPoint, QRectF, QLineF
from skimage import io, img_as_ubyte, color, draw, measure, morphology, feature
import numpy as np
from matplotlib import pyplot as plt
import argparse
import glob
from pprint import pprint # for human readable file output
import pickle as pickle
import sys
import re
import os
import random
import yaml
import multiprocessing
import pandas as pd
sys.path.insert(0,os.path.dirname(os.path.realpath(__file__)))
import mm3_helpers as mm3
import mm3_plots
class Window(QMainWindow):
def __init__(self, channel=1, parent=None):
super(Window, self).__init__(parent)
top = 400
left = 400
width = 800
height = 600
self.setWindowTitle("Update your tracking results and save for deep learning.")
self.setGeometry(top,left,width,height)
# load specs file
with open(os.path.join(params['ana_dir'], 'specs.yaml'), 'r') as specs_file:
specs = yaml.safe_load(specs_file)
self.frames = FrameImgWidget(specs=specs, channel=channel)
# make scene the central widget
self.setCentralWidget(self.frames)
eventButtonGroup = QButtonGroup()
migrateButton = QRadioButton("Migration")
migrateButton.setShortcut("Ctrl+V")
migrateButton.setToolTip("(Ctrl+V) Draw white migration lines\nbetween foci in adjacent frames or\nin frames separated by one timepoint.")
migrateButton.clicked.connect(self.frames.scene.set_migration)
migrateButton.click()
eventButtonGroup.addButton(migrateButton)
childrenButton = QRadioButton("Children")
childrenButton.setShortcut("Ctrl+C")
childrenButton.setToolTip("(Ctrl+C) Draw green split lines\nbetween a parent focus and any number of children.")
childrenButton.clicked.connect(self.frames.scene.set_children)
eventButtonGroup.addButton(childrenButton)
joinButton = QRadioButton("Join")
joinButton.setShortcut("Ctrl+J")
joinButton.setToolTip("(Ctrl+J) Draw red join lines.")
joinButton.clicked.connect(self.frames.scene.set_join)
eventButtonGroup.addButton(joinButton)
appearButton = QRadioButton("Appear")
appearButton.setShortcut("Ctrl+A")
appearButton.setToolTip("(Ctrl+A) Denotes a focus appeared,\nor entered the field of view at this frame.")
appearButton.clicked.connect(self.frames.scene.set_appear)
eventButtonGroup.addButton(appearButton)
disappearButton = QRadioButton("Disappear")
disappearButton.setShortcut("Ctrl+D")
disappearButton.setToolTip("(Ctrl+D) Indicate a focus disappears or leaves\nthe field of view after this frame.")
disappearButton.clicked.connect(self.frames.scene.set_disappear)
eventButtonGroup.addButton(disappearButton)
removeEventsButton = QRadioButton("Remove events")
removeEventsButton.setShortcut("Ctrl+R")
removeEventsButton.setToolTip("(Ctrl+R) Eliminate events belonging entirely to this\nfocus, and emantating from this focus.")
removeEventsButton.clicked.connect(self.frames.scene.remove_all_focus_events)
eventButtonGroup.addButton(removeEventsButton)
eventButtonLayout = QVBoxLayout()
eventButtonLayout.addWidget(migrateButton)
eventButtonLayout.addWidget(childrenButton)
eventButtonLayout.addWidget(joinButton)
eventButtonLayout.addWidget(appearButton)
eventButtonLayout.addWidget(disappearButton)
eventButtonLayout.addWidget(removeEventsButton)
eventButtonGroupWidget = QWidget()
eventButtonGroupWidget.setLayout(eventButtonLayout)
eventButtonDockWidget = QDockWidget()
eventButtonDockWidget.setWidget(eventButtonGroupWidget)
self.addDockWidget(Qt.LeftDockWidgetArea, eventButtonDockWidget)
goToPeakButton = QPushButton('Go to fov/peak')
goToPeakButton.clicked.connect(self.frames.get_fov_peak_dialog)
advancePeakButton = QPushButton("Next peak")
advancePeakButton.clicked.connect(self.frames.scene.next_peak)
priorPeakButton = QPushButton("Prior peak")
priorPeakButton.clicked.connect(self.frames.scene.prior_peak)
advanceFOVButton = QPushButton("Next FOV")
advanceFOVButton.clicked.connect(self.frames.scene.next_fov)
priorFOVButton = QPushButton("Prior FOV")
priorFOVButton.clicked.connect(self.frames.scene.prior_fov)
saveUpdatedTracksButton = QPushButton("Save updated tracking info\nfor neural net training data")
saveUpdatedTracksButton.setShortcut("Ctrl+S")
saveUpdatedTracksButton.clicked.connect(self.frames.scene.save_updates)
fileAdvanceLayout = QVBoxLayout()
fileAdvanceLayout.addWidget(goToPeakButton)
fileAdvanceLayout.addWidget(advancePeakButton)
fileAdvanceLayout.addWidget(priorPeakButton)
fileAdvanceLayout.addWidget(advanceFOVButton)
fileAdvanceLayout.addWidget(priorFOVButton)
fileAdvanceLayout.addWidget(saveUpdatedTracksButton)
fileAdvanceGroupWidget = QWidget()
fileAdvanceGroupWidget.setLayout(fileAdvanceLayout)
fileAdvanceDockWidget = QDockWidget()
fileAdvanceDockWidget.setWidget(fileAdvanceGroupWidget)
self.addDockWidget(Qt.RightDockWidgetArea, fileAdvanceDockWidget)
class FrameImgWidget(QWidget):
# class for setting three frames side-by-side as a central widget in a QMainWindow object
def __init__(self, specs, channel):
super(FrameImgWidget, self).__init__()
print("Starting in track edit mode.")
# add images and focus regions as ellipses to each frame in a QGraphicsScene object
self.specs = specs
self.channel = channel
self.scene = TrackItem(specs, channel)
self.view = View(self)
self.view.setScene(self.scene)
def get_fov_peak_dialog(self):
fov_id, pressed = QInputDialog.getInt(self,
"Type your desired FOV",
"fov_id (should be an integer):")
if pressed:
fov_id = fov_id
peak_id, pressed = QInputDialog.getInt(self,
"Go to peak",
"peak_id (should be an integer):")
if pressed:
peak_id = peak_id
self.scene.go_to_fov_and_peak_id(fov_id,peak_id)
# def enter_mask_edit_mode(self):
# print("Entering mask edit mode.")
# ###### NOTE: consider prompting to save track edits prior to switching modes
# self.scene.clear()
# self.scene = MaskItem(self.specs)
# self.view = View(self)
# self.view.setScene(self.scene)
#
# def enter_track_edit_mode(self):
# print("Entering track edit mode.")
# ###### NOTE: consider prompting to save new masks prior to switching modes
# self.scene.clear()
# self.scene = TrackItem(self.specs)
# self.view = View(self)
# self.view.setScene(self.scene)
class View(QGraphicsView):
'''
Re-implementation of QGraphicsView to accept mouse+Ctrl event
as a zoom transformation
'''
def __init__(self, parent):
super(View, self).__init__(parent)
# set upper and lower bounds on zooming
self.setTransformationAnchor(QGraphicsView.AnchorViewCenter)
self.maxScale = 2.5
self.minScale = 0.3
def wheelEvent(self, event):
if event.modifiers() == Qt.ControlModifier:
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
m11 = self.transform().m11() # horizontal scale factor
m12 = self.transform().m12()
m13 = self.transform().m13()
m21 = self.transform().m21()
m22 = self.transform().m22() # vertizal scale factor
m23 = self.transform().m23()
m31 = self.transform().m31()
m32 = self.transform().m32()
m33 = self.transform().m33()
adjust = event.angleDelta().y()/120 * 0.1
if (m11 >= self.maxScale) and (adjust > 0):
m11 = m11
m22 = m22
elif (m11 <= self.minScale) and (adjust < 0):
m11 = m11
m22 = m22
else:
m11 += adjust
m22 += adjust
self.setTransform(QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33))
elif event.modifiers() == Qt.AltModifier:
self.setTransformationAnchor(QGraphicsView.NoAnchor)
adjust = event.angleDelta().x()/120 * 50
self.translate(adjust,0)
else:
QGraphicsView.wheelEvent(self, event)
class TrackItem(QGraphicsScene):
# add more functionality for setting event type, i.e., parent-child, migrate, death, leave frame, etc..
def __init__(self, specs, channel):
super(TrackItem, self).__init__()
self.specs = specs
self.channel = channel
# add QImages to scene
self.fov_id_list = [fov_id for fov_id in self.specs.keys()]
self.fovIndex = 0
self.fov_id = self.fov_id_list[self.fovIndex]
self.peak_id_list_in_fov = [peak_id for peak_id in self.specs[self.fov_id].keys() if self.specs[self.fov_id][peak_id] == 1]
self.peakIndex = 0
self.peak_id = self.peak_id_list_in_fov[self.peakIndex]
# print(self.peak_id)
# print(self.fov_id)
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
# read in cell tracking info
cell_filename_all = os.path.join(params['cell_dir'], 'all_cells.pkl')
with open(cell_filename_all, 'rb') as cell_file:
self.All_Cells = pickle.load(cell_file)
self.fov_Cells = mm3.filter_cells(self.All_Cells, attr="fov", val=self.fov_id)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# read in focus tracking info
focus_filename_all = os.path.join(params['foci_track_dir'], 'all_foci.pkl')
with open(focus_filename_all, 'rb') as focus_file:
self.All_Foci = pickle.load(focus_file)
self.fov_Foci = mm3.filter_cells(self.All_Foci, attr="fov", val=self.fov_id)
self.these_Foci = mm3.filter_cells(self.fov_Foci, attr="fov", val=self.peak_id)
plot_dir = os.path.join(params['foci_track_dir'], 'plots')
if not os.path.exists(plot_dir):
os.makedirs(plot_dir)
lin_dir = os.path.join(plot_dir, 'lineage_plots_full')
if not os.path.exists(lin_dir):
os.makedirs(lin_dir)
# look for previously edited info and load it if it is found
self.get_track_pickle()
# self.no_track_pickle_lookup()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.drawing = False
self.remove_events = False
self.brushSize = 2
self.brushColor = QColor('black')
self.lastPoint = QPoint()
self.pen = QPen()
# class options
self.event_types_list = ["ChildLine",
"MigrationLine",
"AppearSymbol",
"DisappearSymbol",
"JoinLine"]
self.line_events_list = ["ChildLine","MigrationLine","JoinLine"]
self.end_check_events_list = ["AppearSymbol","ZeroFocusSymbol"]
# the below lookup table may need reworked to handle migration and child lines to/from a focus
# or the handling may be better done in the update_focus_info function
self.event_type_index_lookup = {"MigrationLine":0,
"ChildLine":1,
"AppearSymbol":2,
"DisappearSymbol":3,
"JoinLine":4,
"NoData":5
}
# given an event type for a focus, what are the event types that are incompatible within that same focus?
self.forbidden_events_lookup = {"MigrationStart":["ChildStart","DisappearSymbol","DieSymbol","MigrationStart","JoinStart","ZeroFocusSymbol"],
"MigrationEnd":["ChildEnd","AppearSymbol","BornSymbol","MigrationEnd","JoinEnd","ZeroFocusSymbol"],
"ChildStart":["MigrationStart","DisappearSymbol","DieSymbol","JoinStart","ZeroFocusSymbol"],
"ChildEnd":["MigrationEnd","AppearSymbol","ChildEnd","JoinEnd","ZeroFocusSymbol"],
"BornSymbol":["MigrationEnd","AppearSymbol","BornSymbol","JoinEnd","ZeroFocusSymbol"],
"AppearSymbol":["MigrationEnd","ChildEnd","BornSymbol","AppearSymbol","JoinEnd","ZeroFocusSymbol"],
"DisappearSymbol":["MigrationStart","ChildStart","DieSymbol","DisappearSymbol","JoinStart","ZeroFocusSymbol"],
"DieSymbol":["MigrationStart","ChildStart","DisappearSymbol","DieSymbol","JoinStart","ZeroFocusSymbol"],
"JoinStart":["MigrationStart","ChildStart","DisappearSymbol","DieSymbol","JoinStart","ZeroFocusSymbol"],
"JoinEnd":["ChildEnd","AppearSymbol","BornSymbol","MigrationEnd","ZeroFocusSymbol"],
"ZeroFocusSymbol":["OneFocusSymbol","TwoFocusSymbol","ThreeFocusSymbol","MigrationStart",
"MigrationEnd","ChildStart","ChildEnd","BornSymbol",
"AppearSymbol","DisappearSymbol","DieSymbol","JoinStart","JoinEnd"],
"OneFocusSymbol":["ZeroFocusSymbol","TwoFocusSymbol","ThreeFocusSymbol"],
"TwoFocusSymbol":["ZeroFocusSymbol","OneFocusSymbol","ThreeFocusSymbol"],
"ThreeFocusSymbol":["ZeroFocusSymbol","OneFocusSymbol","TwoFocusSymbol"]}
self.migration = False
self.children = False
self.appear = False
self.disappear = False
self.join = False
# apply focus events to the scene
self.draw_focus_events()
def save_updates(self):
track_info = self.track_info
for t, time_info in track_info.items():
# all_t_cells = time_info['cells']
# for cell_id, cell_info in all_t_cells.items():
for region_label, region in time_info['regions'].items():
if 'region_graphic' in region:
if 'pen' in region['region_graphic']:
region['region_graphic'].pop('pen')
if 'brush' in region['region_graphic']:
region['region_graphic'].pop('brush')
with open(self.pickle_file_name, 'wb') as track_file:
try:
pickle.dump(track_info, track_file)
track_file.close()
print("Saved updated tracking information to {}.".format(self.pickle_file_name))
except Exception as e:
track_file.close()
print(str(e))
df_file_name = os.path.dirname(os.path.realpath(__file__))+r'\focus_track_training_file_paths.csv'
# df_file_name = '/Users/jt/code/mm3/focus_track_training_file_paths.csv'
if os.path.isfile(df_file_name):
track_file_name_df = pd.read_csv(df_file_name)
# if the current training data isn't yet in the dataframe, add it and save the updated dataframe
if not self.pickle_file_name in track_file_name_df.file_path.values:
print("Appending file name {} as new row in {}.".format(self.pickle_file_name, df_file_name))
track_file_name_df = track_file_name_df.append({'file_path':self.pickle_file_name, 'include':1}, ignore_index=True)
track_file_name_df.to_csv(df_file_name,index=False)
else:
track_file_name_df = pd.DataFrame(data={
'file_path':[self.pickle_file_name],
'include':[1]
})
track_file_name_df.to_csv(df_file_name,index=False)
def no_track_pickle_lookup(self):
self.track_info = self.create_tracking_information(self.fov_id, self.peak_id, self.labelStack, self.phaseStack)
def get_track_pickle(self):
self.pickle_file_name = os.path.join(params['foci_track_dir'], '{}_xy{:0=3}_p{:0=4}_updated_tracks.pkl'.format(params['experiment_name'], self.fov_id, self.peak_id))
# look for previously updated tracking information and load that if it is found.
if not os.path.isfile(self.pickle_file_name):
# get tracking information in a format usable and updatable by qgraphicsscene
self.track_info = self.create_tracking_information(self.fov_id, self.peak_id, self.labelStack, self.phaseStack)
else:
with open(self.pickle_file_name, 'rb') as pickle_file:
try:
print("Found updated track information in {}. Uploading and plotting it.".format(self.pickle_file_name))
self.track_info = pickle.load(pickle_file)
except Exception as e:
print("Could not load pickle file specified.")
print(e)
def go_to_fov_and_peak_id(self, fov_id, peak_id):
# start by removing all current graphics items from the scene, the scene here being 'self'
self.clear()
self.fov_id = fov_id
self.fovIndex = self.fov_id_list.index(self.fov_id)
self.peak_id_list_in_fov = [peak_id for peak_id in self.specs[self.fov_id].keys() if self.specs[self.fov_id][peak_id] == 1]
self.peak_id = peak_id
print(self.peak_id)
# Now we'll look up the peakIndex
self.peakIndex = self.peak_id_list_in_fov.index(self.peak_id)
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
self.fov_Cells = mm3.filter_cells(self.All_Cells, attr="fov", val=self.fov_id)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# look for previously edited info and load it if it is found
self.get_track_pickle()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.draw_focus_events()
def next_peak(self):
# start by removing all current graphics items from the scene, the scene here being 'self'
self.clear()
# self.center_frame_index = 1
self.peakIndex += 1
self.peak_id = self.peak_id_list_in_fov[self.peakIndex]
# print(self.peak_id)
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# look for previously edited info and load it if it is found
self.get_track_pickle()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.draw_focus_events()
def prior_peak(self):
# start by removing all current graphics items from the scene, the scene here being 'self'
self.clear()
# self.center_frame_index = 1
self.peakIndex -= 1
self.peak_id = self.peak_id_list_in_fov[self.peakIndex]
# print(self.peak_id)
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# look for previously edited info and load it if it is found
self.get_track_pickle()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.draw_focus_events()
def next_fov(self):
# start by removing all current graphics items from the scene, the scene here being 'self'
self.clear()
# self.center_frame_index = 1
self.fovIndex += 1
self.fov_id = self.fov_id_list[self.fovIndex]
self.peak_id_list_in_fov = [peak_id for peak_id in self.specs[self.fov_id].keys() if self.specs[self.fov_id][peak_id] == 1]
self.peakIndex = 0
self.peak_id = self.peak_id_list_in_fov[self.peakIndex]
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
self.fov_Cells = mm3.filter_cells(self.All_Cells, attr="fov", val=self.fov_id)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# look for previously edited info and load it if it is found
self.get_track_pickle()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.draw_focus_events()
def prior_fov(self):
# start by removing all current graphics items from the scene, the scene here being 'self'
self.clear()
# self.center_frame_index = 1
self.fovIndex -= 1
self.fov_id = self.fov_id_list[self.fovIndex]
self.peak_id_list_in_fov = [peak_id for peak_id in self.specs[self.fov_id].keys() if self.specs[self.fov_id][peak_id] == 1]
self.peakIndex = 0
self.peak_id = self.peak_id_list_in_fov[self.peakIndex]
# construct image stack file names from params
self.phaseImgPath = os.path.join(params['chnl_dir'], "{}_xy{:0=3}_p{:0=4}_c{}.tif".format(params['experiment_name'], self.fov_id, self.peak_id, self.channel))
self.labelImgPath = os.path.join(params['foci_seg_dir'], "{}_xy{:0=3}_p{:0=4}_foci_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.cellLabelImgPath = os.path.join(params['seg_dir'], "{}_xy{:0=3}_p{:0=4}_seg_unet.tif".format(params['experiment_name'], self.fov_id, self.peak_id))
self.labelStack = io.imread(self.labelImgPath)
self.phaseStack = io.imread(self.phaseImgPath)
self.cellLabelStack = io.imread(self.cellLabelImgPath)
self.fov_Cells = mm3.filter_cells(self.All_Cells, attr="fov", val=self.fov_id)
self.these_Cells = mm3.filter_cells(self.fov_Cells, attr="peak", val=self.peak_id)
# look for previously edited info and load it if it is found
self.get_track_pickle()
self.all_frames_by_time_dict = self.all_phase_img_and_regions()
self.draw_focus_events()
def all_phase_img_and_regions(self):
frame_dict_by_time = {}
xPos = 0
for time,t_info in self.track_info.items():
frame_index = time-1
frame,t_info = self.phase_img_and_regions(frame_index)
frame_dict_by_time[time] = self.addPixmap(frame)
frame_dict_by_time[time].time = time
self.add_regions_to_frame(t_info, frame_dict_by_time[time])
frame_dict_by_time[time].setPos(xPos, 0)
xPos += frame_dict_by_time[time].pixmap().width()
return(frame_dict_by_time)
def phase_img_and_regions(self, frame_index, watershed=False):
time = frame_index+1
phaseImg = self.phaseStack[frame_index,:,:]
maskImg = self.labelStack[frame_index,:,:]
originalImgMax = np.max(phaseImg)
phaseImg = phaseImg/originalImgMax
phaseImg = color.gray2rgb(phaseImg)
RGBImg = (phaseImg*255).astype('uint8')
originalHeight, originalWidth, originalChannelNumber = RGBImg.shape
phaseQimage = QImage(RGBImg, originalWidth, originalHeight,
RGBImg.strides[0], QImage.Format_RGB888)#.scaled(512, 512, aspectRatioMode=Qt.KeepAspectRatio)
phaseQpixmap = QPixmap(phaseQimage)
phaseQpixmap.time = time
# create transparent rbg overlay to grab colors from for drawing focus regions as QGraphicsPathItems
RGBLabelImg = color.label2rgb(maskImg, bg_label=0)
RGBLabelImg = (RGBLabelImg*255).astype('uint8')
originalHeight, originalWidth, RGBLabelChannelNumber = RGBLabelImg.shape
RGBLabelImg = QImage(RGBLabelImg, originalWidth, originalHeight, RGBLabelImg.strides[0], QImage.Format_RGB888)#.scaled(512, 512, aspectRatioMode=Qt.KeepAspectRatio)
time_info = self.track_info[time]
time_info['time'] = time
# for cell_data in time_info['cells'].values():
regions = time_info['regions']
for region in regions.values():
brush = QBrush()
brush.setStyle(Qt.SolidPattern)
pen = QPen()
pen.setStyle(Qt.SolidLine)
props = region['props']
coords = props.coords
min_row, min_col, max_row, max_col = props.bbox
label = props.label
centroidY,centroidX = props.centroid
brushColor = RGBLabelImg.pixelColor(centroidX,centroidY)
brushColor.setAlphaF(0.15)
brush.setColor(brushColor)
pen.setColor(brushColor)
region['region_graphic'] = {'top_y':min_row, 'bottom_y':max_row,
'left_x':min_col, 'right_x':max_col,
'coords':coords,
'pen':pen, 'brush':brush}
return(phaseQpixmap, time_info)
# def get_foci_regions_by_time(self, focus_label_stack):
# '''This function provides support to detect to which cell each focus belongs, and to
# add additional information to each focus' regionprops based on that focus' position
# within its cell.
# '''
# t_adj = 1
# foci_by_time = {frame+t_adj: {} for frame in range(focus_label_stack.shape[0])}
# cell_id_list = [k for k in self.these_Cells.keys()]
# # get to first timepoint containing cells
# for t in foci_by_time.keys():
# t_foci = mm3.filter_cells_containing_val_in_attr(self.these_Cells, attr='times', val=t)
# if t_cells:
# break
# skipped_cells = []
# # loop over cells, begining with cells at current time
# for cell_id,cell in t_cells.items():
# foci_in_cell = cell.foci
# for t in cell.times:
# cell_idx = cell.times.index(t)
# foci_in_cell = cell.foci
# these_foci = {focus_id:focus for focus_id,focus in foci_in_cell.items() if t in focus.times}
# t_foci = mm3.filter_cells_containing_val_in_attr(self.these_Foci, attr='times', val=t)
# if len(t_foci) > 0:
# for focus_id,focus in t_foci.items():
# focus_idx = focus.times.index(t)
# # loop over cells to which this focus belongs
# for cell in focus.cells:
# cell_times = cell.times
# # if the current time is in this cell grab the index
# # for this cell and its id
# if t in cell_times:
# cell_idx = cell.times.index(t)
# cell_id = cell.id
# break
# cell_y,cell_x = cell.centroids[cell_idx]
# focus_y,focus_x = focus.regions[focus_idx].centroid
# focus.regions[focus_idx].cell_y_pos = cell_y-focus_y
# focus.regions[focus_idx].cell_x_pos = cell_x-focus_x
# focus.daughter_cell_ids = []
# if cell.daughters:
# for daughter_cell in cell.daughters:
# focus.daughter_cell_ids.append(daughter_cell.id)
# cell_data[t].append(focus)
# return(foci_by_cell_and_time)
def create_tracking_information(self, fov_id, peak_id, label_stack, img_stack):
t_adj = 1
regions_by_time = {frame+t_adj: measure.regionprops(label_stack[frame,:,:], img_stack[frame,:,:]) for frame in range(label_stack.shape[0])}
regions_and_events_by_time = {frame+t_adj: {'regions' : {}, 'matrix' : None} for frame in range(label_stack.shape[0])}
# iterate through all times, collecting focus information and adding
# cell-centric tracking info to the dictionary as we go
for t,regions in regions_by_time.items():
for region in regions:
default_events = np.zeros(6, dtype=np.int)
default_events[5] = 1 # set N to 1
# add information at 'focus_cell_label'
regions_and_events_by_time[t]['regions'][region.label] = {
'props' : region,
'events' : default_events,
}
for t, t_data in regions_and_events_by_time.items():
n_regions_in_t = len(regions_by_time[t])
if t+1 in regions_by_time:
n_regions_in_t_plus_1 = len(regions_by_time[t+1])
else:
n_regions_in_t_plus_1 = 0
t_data['matrix'] = np.zeros((n_regions_in_t+1, n_regions_in_t_plus_1+1), dtype=np.int)
# Loop over foci and edit event information
# We will use the dictionary All_Foci.
# Each Focus object has a number of attributes that are useful to us.
# We will go through each focus by its time points and edit the events associated with that region.
# We will also edit the matrix when appropriate.
# pull out only the foci in of this FOV
foci_tmp = mm3_plots.find_cells_of_fov_and_peak(self.All_Foci, fov_id, peak_id)
print('There are {} foci for this trap'.format(len(foci_tmp)))
for focus_id,focus_tmp in foci_tmp.items():
# Check for when focus has less time points than it should
if (focus_tmp.times[-1] - focus_tmp.times[0])+1 > len(focus_tmp.times):
print('Focus {} has less time points than it should, skipping.'.format(focus_id))
continue
for i,t in enumerate(focus_tmp.times):
t_info = regions_and_events_by_time[t]
label_tmp = focus_tmp.labels[i]
# M migration, event 0
# If the focus has another time point after this one then it must have migrated
max_focus_time = np.max(focus_tmp.times)
# print('focus {} has max time {}.'.format(focus_id,max_focus_time))
if t < max_focus_time:
t_info['regions'][label_tmp]['events'][0] = 1
# update matrix using this region label and the next one
# print(focus_cell_label, focus_cell_labels[focus_idx+1], cell_info['matrix'])
t_info['matrix'][label_tmp, focus_tmp.labels[i+1]] = 1
# S division, 1
if focus_tmp.daughters and t == max_focus_time:
t_info['regions'][label_tmp]['events'][1] = 1
# daughter 1 and 2 label
d1_label = self.All_Foci[focus.daughters[0]].labels[0]
try:
d2_label = self.All_Foci[focus.daughters[1]].labels[0]
t_info['matrix'][label_tmp, d1_label] = 1
t_info['matrix'][label_tmp, d2_label] = 1
except IndexError as e:
print("At timepoint {} there was an index error in assigning daughters: {}".format(t,e))
# I appears, 2
if not t == 1:
if not focus_tmp.parent and i == 0:
t_info['regions'][label_tmp]['events'][2] = 1
# O disappears, 3
if not focus_tmp.daughters and t == max_focus_time:
t_info['regions'][label_tmp]['events'][3] = 1
t_info['matrix'][label_tmp, 0] = 1
# N no data, 4 - Set this to zero as this region as been checked.
t_info['regions'][label_tmp]['events'][5] = 0
# If any focus has still not been visited,
# make their appropriate matrix value 1, which should be in the first column.
for t,t_data in regions_and_events_by_time.items():
for region,region_data in t_data['regions'].items():
if region_data['events'][5] == 1:
t_data['matrix'][region, 0] = 1
return(regions_and_events_by_time)
# pprint(regions_and_events_by_time)
# if not cell_id in regions_and_events_by_cell_and_time:
# regions_and_events_by_cell_and_time[cell_id] = {}
# cell_data = regions_and_events_by_cell_and_time[cell_id]
# for t,t_region_list in this_cell_time_info.items():
# if not t in cell_data:
# cell_data[t] = {'regions' : {}, 'matrix' : None}
# for i,region in enumerate(t_region_list):
# default_events = np.zeros(6, dtype=np.int)
# default_events[5] = 1 # set N to 1
# cell_data[t]['regions'][i+1] = {
# 'props' : region,
# 'events' : default_events,
# }
# create default interaction matrix
# Now that we know how many regions there are per time point, we will create a default matrix which indicates how regions are connected to each between this time point, t, and the next one, t+1. The row index will be the region label of the region in t, and the column index will be the region label of the region in t+1.
# If a region migrates from t to t+1, its row should have a sum of 1 corresponding from which region (row) to which region (column) it moved. If the region divided, then both of the daughter columns will get value 1.
# Note that the regions are labeled from 1, but Numpy arrays and indexed from zero. We can use this to store some additional informaiton. If a region disappears, it will receive a 1 in the column with index 0.
# In the last time point all regions will be connected to the disappear column
# for cell_id, this_cell_time_info in regions_and_events_by_cell_and_time.items():
# for t,t_data in this_cell_time_info.items():
# n_regions_in_t = len(t_data['regions'])
# if t+1 in this_cell_time_info:
# n_regions_in_t_plus_1 = len(this_cell_time_info[t+1]['regions'])
# else:
# n_regions_in_t_plus_1 = 0
# t_data['matrix'] = np.zeros((n_regions_in_t+1, n_regions_in_t_plus_1+1), dtype=np.int)
# regions_and_events_by_time = {frame+t_adj : {'regions' : {}, 'matrix' : None} for frame in range(label_stack.shape[0])}
# # loop through regions and add them to the main dictionary.
# for t, regions in regions_by_time.items():
# # this is a list, while we want it to be a dictionary with the region label as the key
# for region in regions:
# default_events = np.zeros(6, dtype=np.int)
# default_events[5] = 1 # set N to 1
# regions_and_events_by_time[t]['regions'][region.label] = {'props' : region,
# 'events' : default_events}
# create default interaction matrix
# Now that we know how many regions there are per time point, we will create a default matrix which indicates how regions are connected to each between this time point, t, and the next one, t+1. The row index will be the region label of the region in t, and the column index will be the region label of the region in t+1.
# If a region migrates from t to t+1, its row should have a sum of 1 corresponding from which region (row) to which region (column) it moved. If the region divided, then both of the daughter columns will get value 1.
# Note that the regions are labeled from 1, but Numpy arrays and indexed from zero. We can use this to store some additional informaiton. If a region disappears, it will receive a 1 in the column with index 0.
# In the last time point all regions will be connected to the disappear column
# for t, t_data in regions_and_events_by_time.items():
# n_regions_in_t = len(regions_by_time[t])
# if t+1 in regions_by_time:
# n_regions_in_t_plus_1 = len(regions_by_time[t+1])
# else:
# n_regions_in_t_plus_1 = 0
# t_data['matrix'] = np.zeros((n_regions_in_t+1, n_regions_in_t_plus_1+1), dtype=np.int)
# Loop over foci and edit event information
# We will use the focus dictionary All_Foci.
# Each focus object has a number of attributes that are useful to us.
# We will go through each focus by its time points and edit the events associated with that region.
# We will also edit the matrix when appropriate.
# pull out only the foci in of this FOV
# for focus_id,focus_tmp in foci_tmp.items():
# cell_id = focus_id_cell_id_lut[focus_id]
# cell_data = regions_and_events_by_cell_and_time[cell_id]
# # Check for when focus has less time points than it should
# # if (focus_tmp.times[-1] - focus_tmp.times[0])+1 > len(focus_tmp.times):
# # print('Focus {} has less time points than it should, skipping.'.format(focus_id))
# # continue
# unique_times = list(np.unique(focus_tmp.times))
# focus_tmp_labels = [focus_tmp.cell_labels[focus_tmp.times.index(t)] for t in unique_times]
# # Go over the time points of this focus and edit appropriate information main dictionary
# for i, t in enumerate(unique_times):
# # get the region label
# label_tmp = focus_tmp_labels[i]
# # M migration, event 0
# # If the focus has another time point after this one then it must have migrated
# if i != len(unique_times)-1:
# cell_data[t]['regions'][label_tmp]['events'][0] = 1
# # regions_and_events_by_time[t]['regions'][label_tmp]['events'][0] = 1
# # update matrix using this region label and the next one
# # print(label_tmp, focus_tmp_labels[i+1], regions_and_events_by_time[t]['matrix'])
# cell_data[t]['matrix'][label_tmp, focus_tmp_labels[i+1]] = 1
# # regions_and_events_by_time[t]['matrix'][label_tmp, focus_tmp_labels[i+1]] = 1
# # S division, 1
# if focus_tmp.daughters and i == len(unique_times)-1:
# cell_data[t]['regions'][label_tmp]['events'][1] = 1
# # regions_and_events_by_time[t]['regions'][label_tmp]['events'][1] = 1
# # daughter 1 and 2 label
# # d1_label = self.All_Foci[focus_tmp.daughters[0].id].labels[0]
# d1_label = self.All_Foci[focus_tmp.daughters[0]].labels[0]
# try:
# # d2_label = self.All_Foci[focus_tmp.daughters[1].id].labels[0]
# d2_label = self.All_Foci[focus_tmp.daughters[1]].labels[0]
# cell_data[t]['matrix'][label_tmp, d1_label] = 1
# cell_data[t]['matrix'][label_tmp, d2_label] = 1
# # regions_and_events_by_time[t]['matrix'][label_tmp, d1_label] = 1
# # regions_and_events_by_time[t]['matrix'][label_tmp, d2_label] = 1
# except IndexError as e:
# print("At timepoint {} there was an index error in assigning daughters: {}".format(t,e))
# # I appears, 2
# if not t == 1:
# if not focus_tmp.parent and i == 0:
# cell_data[t]['regions'][label_tmp]['events'][2] = 1
# # regions_and_events_by_time[t]['regions'][label_tmp]['events'][2] = 1
# # O disappears, 3
# if not focus_tmp.daughters and i == len(unique_times)-1:
# cell_data[t]['regions'][label_tmp]['events'][3] = 1
# cell_data[t]['matrix'][label_tmp, 0] = 1
# # regions_and_events_by_time[t]['regions'][label_tmp]['events'][3] = 1
# # regions_and_events_by_time[t]['matrix'][label_tmp, 0] = 1
# # N no data, 4 - Set this to zero as this region as been checked.
# cell_data[t]['regions'][label_tmp]['events'][5] = 0
# # regions_and_events_by_time[t]['regions'][label_tmp]['events'][5] = 0
# # Set remaining regions to event space [0 0 0 0 1 1]
# # Also make their appropriate matrix value 1, which should be in the first column.
# for cell_id,cell_data in regions_and_events_by_cell_and_time.items():
# for t, t_data in cell_data.items():
# for region, region_data in t_data['regions'].items():
# if region_data['events'][5] == 1:
# t_data['matrix'][region, 0] = 1
# for t, t_data in regions_and_events_by_time.items():
# for region, region_data in t_data['regions'].items():
# if region_data['events'][5] == 1:
# t_data['matrix'][region, 0] = 1
# return(regions_and_events_by_time)
def add_regions_to_frame(self, t_info, frame):
# loop through foci within this frame and add their ellipses as children of their corresponding qpixmap object
# all_t_cells = t_info['cells']
# print(regions_and_events)
frame_time = t_info['time']
# for cell_id,cell_info in all_t_cells.items():
regions = t_info['regions']
for region in regions.values():
# construct the ellipse
graphic = region['region_graphic']
top_left = QPoint(graphic['left_x'],graphic['top_y'])
bottom_right = QPoint(graphic['right_x'],graphic['bottom_y'])
rect = QRectF(top_left,bottom_right)
# painter_path = graphic['path']
pen = graphic['pen']
brush = graphic['brush']
# focus = FocusItem(region, parent=frame)
# instantiate a QGraphicsEllipseItem
ellipse = QGraphicsEllipseItem(rect, frame)
# add focus information to the QGraphicsEllipseItem
ellipse.focusMatrix = t_info['matrix']
ellipse.focusEvents = region['events']
ellipse.focusProps = region['props']
#################### 2020-10-31 #####################
# ellipse.cell_id = cell_id
# ellipse.cell_daughters = t_info['daughters']
#####################################################
# print(dir(region['props']))
ellipse.time = frame_time
ellipse.setBrush(brush)
ellipse.setPen(pen)
# # add focus information to the QGraphicsPathItem
# path = QGraphicsPathItem(painter_path, frame)
# path.focusMatrix = regions_and_events['matrix']
# path.focusEvents = regions_and_events['regions'][region_id]['events']
# path.focusProps = regions_and_events['regions'][region_id]['props']
# path.time = frame_time
# path.setBrush(brush)
# path.setPen(pen)
# set up QPainter object to actually paint the QGraphicsPathItem
# painter = QPainter()
# paint_device = QPaintDevice()
# painter.begin(paint_device)
# painter.setPen(pen)
# painter.setBrush(brush)
# painter.drawPath(painter_path)
# painter.end()
# path.paint()
#
def draw_focus_events(self, start_time=1, end_time=None, update=False, original_event_type=None):
# Here is where we will draw the intial lines and symbols representing
# focus events and linkages between foci.
# Set up a list of time points at which we will re-draw events