forked from junlabucsd/mm3
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmm3_ChannelPicker.py
executable file
·1274 lines (1046 loc) · 52.6 KB
/
mm3_ChannelPicker.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
import six
# import modules
import sys
import os
import time
import inspect
import argparse
import yaml
import glob
from pprint import pprint # for human readable file output
try:
import cPickle as pickle
except:
import pickle
import numpy as np
import matplotlib as mpl
# mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# global settings mpl
plt.rcParams['axes.linewidth']=0.5
from skimage.exposure import rescale_intensity # for displaying in GUI
from skimage import io, morphology, segmentation, transform
# from scipy.misc import imresize # deprecated
# from skimage.external import tifffile as tiff
import multiprocessing
from multiprocessing import Pool
import warnings
import h5py
from tensorflow.keras import models
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# user modules
# realpath() will make your script run, even if you symlink it
cmd_folder = os.path.realpath(os.path.abspath(
os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# This makes python look for modules in ./external_lib
cmd_subfolder = os.path.realpath(os.path.abspath(
os.path.join(os.path.split(inspect.getfile(
inspect.currentframe()))[0], "external_lib")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# this is the mm3 module with all the useful functions and classes
import mm3_helpers as mm3
### functions
def fov_plot_channels(fov_id, crosscorrs, specs, outputdir='.', phase_plane='c1'):
'''
Creates a plot with the channels with guesses for empties and full channels.
The plot is saved in PDF format.
Parameters
fov_id : str
file name of the hdf5 file name in originals
crosscorrs : dictionary
dictionary for cross correlation values for all fovs.
specs: dictionary
dictionary for channal assignment (Analyze/Don't Analyze/Background).
'''
mm3.information("Plotting channels for FOV %d." % fov_id)
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
axw=1
axh=4*axw
nrows=3
ncols=int(n_peaks)
fig = plt.figure(num='none', facecolor='w',figsize=(ncols*axw,nrows*axh))
gs = gridspec.GridSpec(nrows,ncols,wspace=0.5,hspace=0.1,top=0.90)
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
for n, peak_id in enumerate(sorted_peaks):
if crosscorrs:
peak_xc = crosscorrs[fov_id][peak_id] # get cross corr data from dict
# load data for figure
image_data = mm3.load_stack(fov_id, peak_id, color=phase_plane)
io.imshow(image_data[0,...])
plt.show();
first_img = rescale_intensity(image_data[0,:,:]) # phase image at t=0
last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
# append an axis handle to ax list while adding a subplot to the figure which has a
axhi = fig.add_subplot(gs[0,n])
axmid = fig.add_subplot(gs[1,n])
axlo = fig.add_subplot(gs[2,n])
# plot the first image in each channel in top row
ax=axhi
ax.imshow(first_img, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title(str(peak_id), fontsize = 12)
if n == 0:
ax.set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax=axmid
ax.axis('off')
#ax.imshow(last_img,cmap=plt.cm.gray, interpolation='nearest')
#H,W = last_img.shape
#img = np.zeros((H,W,3))
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
#img[:,:,1]=last_img
cmap=plt.cm.Greens_r
elif specs[fov_id][peak_id] == 0: # 0 means reference, show blue
#img[:,:,2]=last_img
cmap=plt.cm.Blues_r
else: # otherwise show red, means don't analyze
#img[:,:,0]=last_img
cmap=plt.cm.Reds_r
ax.imshow(last_img,cmap=cmap, interpolation='nearest')
# format
if n == 0:
ax.set_ylabel("last time point")
# finally plot the cross correlations a cross time
ax=axlo
if crosscorrs: # don't try to plot if it's not there.
ccs = peak_xc['ccs'] # list of cc values
ax.plot(ccs,range(len(ccs)))
ax.set_title('avg=%1.2f' % peak_xc['cc_avg'], fontsize = 8)
else:
ax.plot(np.zeros(10), range(10))
ax.get_xaxis().set_ticks([0.8,0.9,1.0])
ax.set_xlim((0.8,1))
ax.tick_params('x',labelsize=8)
if not n == 0:
ax.set_yticks([])
else:
ax.set_ylabel("time index, CC on X")
fig.suptitle("FOV {:d}".format(fov_id),fontsize=14)
fileout=os.path.join(outputdir,'fov_xy{:03d}.pdf'.format(fov_id))
fig.savefig(fileout,bbox_inches='tight',pad_inches=0)
plt.close('all')
mm3.information("Written FOV {}'s channels in {}".format(fov_id,fileout))
return specs
def fov_CNN_plot_channels(fov_id, predictionDict, specs, outputdir='.', phase_plane='c1'):
'''
Creates a plot with the channels with guesses for empties and full channels.
The plot is saved in PDF format.
Parameters
fov_id : str
file name of the hdf5 file name in originals
predictionDict : dictionary
dictionary for cross correlation values for all fovs.
specs: dictionary
dictionary for channal assignment (Analyze/Don't Analyze/Background).
'''
mm3.information("Plotting channels for FOV %d." % fov_id)
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
axw=1
axh=4*axw
nrows=3
ncols=int(n_peaks)
fig = plt.figure(num='none', facecolor='w',figsize=(ncols*axw,nrows*axh))
gs = gridspec.GridSpec(nrows,ncols,wspace=0.5,hspace=0.1,top=0.90)
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
for n, peak_id in enumerate(sorted_peaks):
if predictionDict:
predictions = predictionDict[fov_id][peak_id] # get predictions array
# load data for figure
image_data = mm3.load_stack(fov_id, peak_id, color=phase_plane)
first_img = rescale_intensity(image_data[0,:,:]) # phase image at t=0
last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
# append an axis handle to ax list while adding a subplot to the figure which has a
axhi = fig.add_subplot(gs[0,n])
axmid = fig.add_subplot(gs[1,n])
axlo = fig.add_subplot(gs[2,n])
# plot the first image in each channel in top row
ax=axhi
ax.imshow(first_img,cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title(str(peak_id), fontsize = 12)
if n == 0:
ax.set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax=axmid
ax.axis('off')
#ax.imshow(last_img,cmap=plt.cm.gray, interpolation='nearest')
#H,W = last_img.shape
#img = np.zeros((H,W,3))
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
#img[:,:,1]=last_img
cmap=plt.cm.Greens_r
elif specs[fov_id][peak_id] == 0: # 0 means reference, show blue
#img[:,:,2]=last_img
cmap=plt.cm.Blues_r
else: # otherwise show red, means don't analyze
#img[:,:,0]=last_img
cmap=plt.cm.Reds_r
ax.imshow(last_img,cmap=cmap, interpolation='nearest')
# format
if n == 0:
ax.set_ylabel("last time point")
# finally plot the prediction values as horizontal bar chart
ax=axlo
if predictionDict:
ax.barh(range(len(predictions)), predictions)
#ax.vlines(x=p['channel_picker']['channel_picking_threshold'], ymin=-1, ymax=5, linestyles='dashed',colors='red')
ax.set_title('p', fontsize = 8)
else:
ax.plot(np.zeros(10), range(10))
ax.set_xlim((0,1)) # set limits to (0,1)
#ax.get_xaxis().set_ticks([])
if not n == 0:
ax.get_yaxis().set_ticks([])
else:
ax.set_yticklabels(labels=["","Good","Empty","Out-of-focus","Defective"])
ax.set_ylabel("CNN prediction category")
fig.suptitle("FOV {:d}".format(fov_id),fontsize=14)
fileout=os.path.join(outputdir,'fov_xy{:03d}.pdf'.format(fov_id))
fig.savefig(fileout,bbox_inches='tight',pad_inches=0)
plt.close('all')
mm3.information("Written FOV {}'s channels in {}".format(fov_id,fileout))
return specs
def fov_cell_segger_plot_channels(fov_id, predictionDict, specs, outputdir='.', phase_plane='c1'):
'''
Creates a plot with the channels with guesses for empties and full channels.
The plot is saved in PDF format.
Parameters
fov_id : str
file name of the hdf5 file name in originals
predictionDict : dictionary
dictionary for cross correlation values for all fovs.
specs: dictionary
dictionary for channal assignment (Analyze/Don't Analyze/Background).
'''
mm3.information("Plotting channels for FOV %d." % fov_id)
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
axw=1
axh=4*axw
nrows=3
ncols=int(n_peaks)
fig = plt.figure(num='none', facecolor='w',figsize=(ncols*axw,nrows*axh))
gs = gridspec.GridSpec(nrows,ncols,wspace=0.5,hspace=0.1,top=0.90)
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
for n, peak_id in enumerate(sorted_peaks):
if predictionDict:
predictions = predictionDict[fov_id][peak_id] # get predictions array
# load data for figure
image_data = mm3.load_stack(fov_id, peak_id, color=phase_plane)
img_idx = 0
first_img = image_data[img_idx,:,:] # phase image at t=0
print(np.mean(first_img))
while np.mean(first_img) < 200:
img_idx += 1
first_img = image_data[img_idx,:,:]
print(np.mean(first_img))
first_img = rescale_intensity(first_img) # phase image at t=0
last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
# append an axis handle to ax list while adding a subplot to the figure which has a
axhi = fig.add_subplot(gs[0,n])
axmid = fig.add_subplot(gs[1,n])
axlo = fig.add_subplot(gs[2,n])
# plot the first image in each channel in top row
ax=axhi
ax.imshow(first_img,cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
ax.set_title(str(peak_id), fontsize = 12)
if n == 0:
ax.set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax=axmid
ax.axis('off')
#ax.imshow(last_img,cmap=plt.cm.gray, interpolation='nearest')
#H,W = last_img.shape
#img = np.zeros((H,W,3))
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
#img[:,:,1]=last_img
cmap=plt.cm.Greens_r
elif specs[fov_id][peak_id] == 0: # 0 means reference, show blue
#img[:,:,2]=last_img
cmap=plt.cm.Blues_r
else: # otherwise show red, means don't analyze
#img[:,:,0]=last_img
cmap=plt.cm.Reds_r
ax.imshow(last_img,cmap=cmap, interpolation='nearest')
# format
if n == 0:
ax.set_ylabel("last time point")
# finally plot the prediction values as horizontal bar chart
ax=axlo
if predictionDict:
ax.barh([0], [predictions])
#ax.vlines(x=p['channel_picker']['channel_picking_threshold'], ymin=-1, ymax=5, linestyles='dashed',colors='red')
ax.set_title('cell count', fontsize = 8)
else:
ax.plot(np.zeros(10), range(10))
# ax.set_xlim((0,1)) # set limits to (0,1)
#ax.get_xaxis().set_ticks([])
if not n == 0:
ax.get_yaxis().set_ticks([])
else:
ax.set_yticklabels(labels=[""])
ax.set_ylabel("")
fig.suptitle("FOV {:d}".format(fov_id),fontsize=14)
fileout=os.path.join(outputdir,'fov_xy{:03d}.pdf'.format(fov_id))
fig.savefig(fileout,bbox_inches='tight',pad_inches=0)
plt.close('all')
mm3.information("Written FOV {}'s channels in {}".format(fov_id,fileout))
return specs
# funtion which makes the UI plot
def fov_choose_channels_UI(fov_id, crosscorrs, specs, UI_images):
'''Creates a plot with the channels with guesses for empties and full channels,
and requires the user to choose which channels to use for analysis and which to
average for empties and subtraction.
Parameters
fov_file : str
file name of the hdf5 file name in originals
fov_xcorrs : dictionary
dictionary for cross correlation values for all fovs.
Returns
bgdr_peaks : list
list of peak id's (int) of channels to be used for subtraction
spec_file_pkl : pickle file
saves the lists cell_peaks, bgrd_peaks, and drop_peaks to a pkl file
'''
mm3.information("Starting channel picking for FOV %d." % fov_id)
# define functions here so they have access to variables
# for UI. change specification of channel
def onclick_cells(event):
try:
peak_id = int(event.inaxes.get_title())
except AttributeError:
return
# reset image to be updated based on user clicks
ax_id = sorted_peaks.index(peak_id) * 3 + 1
new_img = last_imgs[sorted_peaks.index(peak_id)]
ax[ax_id].imshow(new_img, cmap=plt.cm.gray, interpolation='nearest')
# if it says analyze, change to empty
if specs[fov_id][peak_id] == 1:
specs[fov_id][peak_id] = 0
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array*0.1, ones_array)), alpha=0.25)
#mm3.information("peak %d now set to empty." % peak_id)
# if it says empty, change to don't analyze
elif specs[fov_id][peak_id] == 0:
specs[fov_id][peak_id] = -1
ax[ax_id].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to ignore." % peak_id)
# if it says don't analyze, change to analyze
elif specs[fov_id][peak_id] == -1:
specs[fov_id][peak_id] = 1
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to analyze." % peak_id)
plt.draw()
return
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
fig = plt.figure(figsize=(int(n_peaks/2), 12))
fig.set_size_inches(int(n_peaks/2),12)
ax = [] # for axis handles
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
last_imgs = [] # list that holds last images for updating figure
for n, peak_id in enumerate(sorted_peaks, start=1):
if crosscorrs:
peak_xc = crosscorrs[fov_id][peak_id] # get cross corr data from dict
# load data for figure
# image_data = mm3.load_stack(fov_id, peak_id, color='c1')
# first_img = rescale_intensity(image_data[0,:,:]) # phase image at t=0
# last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
last_imgs.append(UI_images[fov_id][peak_id]['last']) # append for updating later
# del image_data # clear memory (maybe)
# append an axis handle to ax list while adding a subplot to the figure which has a
# column for each peak and 3 rows
# plot the first image in each channel in top row
ax.append(fig.add_subplot(3, npeaks, n))
ax[-1].imshow(UI_images[fov_id][peak_id]['first'],
cmap=plt.cm.gray, interpolation='nearest')
ax = format_channel_plot(ax, peak_id) # format axis and title
if n == 1:
ax[-1].set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax.append(fig.add_subplot(3, npeaks, n + npeaks))
ax[-1].imshow(UI_images[fov_id][peak_id]['last'],
cmap=plt.cm.gray, interpolation='nearest')
# color image based on if it is thought empty or full
ones_array = np.ones_like(UI_images[fov_id][peak_id]['last'])
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
ax[-1].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
else: # otherwise show red, means don't analyze
ax[-1].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
# format
ax = format_channel_plot(ax, peak_id)
if n == 1:
ax[-1].set_ylabel("last time point")
# finally plot the cross correlations a cross time
ax.append(fig.add_subplot(3, npeaks, n + 2*npeaks))
if crosscorrs: # don't try to plot if it's not there.
ccs = peak_xc['ccs'] # list of cc values
ax[-1].plot(ccs, range(len(ccs)))
ax[-1].set_title('avg=%1.2f' % peak_xc['cc_avg'], fontsize = 8)
else:
pass
# ax[-1].plot(np.zeros(10), range(10))
ax[-1].set_xlim((0.8,1))
ax[-1].get_xaxis().set_ticks([])
if not n == 1:
ax[-1].get_yaxis().set_ticks([])
else:
ax[-1].set_ylabel("time index, CC on X")
# show the plot finally
fig.suptitle("FOV %d" % fov_id)
# enter user input
# ask the user to correct cell/nocell calls
cells_handler = fig.canvas.mpl_connect('button_press_event', onclick_cells)
# matplotlib has difefrent behavior for interactions in different versions.
if float(mpl.__version__[:3]) < 1.5: # check for verions less than 1.5
plt.show(block=False)
raw_input("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nPrees enter to go to the next FOV.")
else:
print("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nClose figure to go to the next FOV.")
plt.show(block=True)
fig.canvas.mpl_disconnect(cells_handler)
plt.close()
return specs
# function to plot CNN-derived trap classifications
def fov_CNN_choose_channels_UI(fov_id, predictionDict, specs, UI_images):
'''Creates a plot with the channels with guesses for empties and full channels,
and requires the user to choose which channels to use for analysis and which to
average for empties and subtraction.
Parameters
fov_file : str
file name of the hdf5 file name in originals
fov_xcorrs : dictionary
dictionary for cross correlation values for all fovs.
Returns
bgdr_peaks : list
list of peak id's (int) of channels to be used for subtraction
spec_file_pkl : pickle file
saves the lists cell_peaks, bgrd_peaks, and drop_peaks to a pkl file
'''
mm3.information("Starting channel picking for FOV %d." % fov_id)
# define functions here so they have access to variables
# for UI. change specification of channel
def onclick_cells(event):
try:
peak_id = int(event.inaxes.get_title())
except AttributeError:
return
# reset image to be updated based on user clicks
ax_id = sorted_peaks.index(peak_id) * 3 + 1
new_img = last_imgs[sorted_peaks.index(peak_id)]
ax[ax_id].imshow(new_img, cmap=plt.cm.gray, interpolation='nearest')
# if it says analyze, change to empty
if specs[fov_id][peak_id] == 1:
specs[fov_id][peak_id] = 0
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array*0.1, ones_array)), alpha=0.25)
#mm3.information("peak %d now set to empty." % peak_id)
# if it says empty, change to don't analyze
elif specs[fov_id][peak_id] == 0:
specs[fov_id][peak_id] = -1
ax[ax_id].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to ignore." % peak_id)
# if it says don't analyze, change to analyze
elif specs[fov_id][peak_id] == -1:
specs[fov_id][peak_id] = 1
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to analyze." % peak_id)
plt.draw()
return
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
fig = plt.figure(figsize=(int(n_peaks/2), 12))
fig.set_size_inches(int(n_peaks/2),12)
ax = [] # for axis handles
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
last_imgs = [] # list that holds last images for updating figure
for n, peak_id in enumerate(sorted_peaks, start=1):
if predictionDict:
predictions = predictionDict[fov_id][peak_id] # get predictions array
# load data for figure
# image_data = mm3.load_stack(fov_id, peak_id, color='c1')
# first_img = rescale_intensity(image_data[0,:,:]) # phase image at t=0
# last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
last_imgs.append(UI_images[fov_id][peak_id]['last']) # append for updating later
# del image_data # clear memory (maybe)
# append an axis handle to ax list while adding a subplot to the figure which has a
# column for each peak and 3 rows
# plot the first image in each channel in top row
ax.append(fig.add_subplot(3, npeaks, n))
ax[-1].imshow(UI_images[fov_id][peak_id]['first'],
cmap=plt.cm.gray, interpolation='nearest')
ax = format_channel_plot(ax, peak_id) # format axis and title
if n == 1:
ax[-1].set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax.append(fig.add_subplot(3, npeaks, n + npeaks))
ax[-1].imshow(UI_images[fov_id][peak_id]['last'],
cmap=plt.cm.gray, interpolation='nearest')
# color image based on if it is thought empty or full
ones_array = np.ones_like(UI_images[fov_id][peak_id]['last'])
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
ax[-1].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
else: # otherwise show red, means don't analyze
ax[-1].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
# format
ax = format_channel_plot(ax, peak_id)
if n == 1:
ax[-1].set_ylabel("last time point")
# finally plot the prediction values as horizontal bar chart
ax.append(fig.add_subplot(3, npeaks, n + 2*npeaks))
if predictionDict:
ax[-1].barh(range(len(predictions)), predictions)
#ax[-1].vlines(x=p['channel_picker']['channel_picking_threshold'], ymin=-1, ymax=5, linestyles='dashed',colors='red')
ax[-1].set_title('p', fontsize = 8)
else:
ax[-1].plot(np.zeros(10), range(10))
ax[-1].set_xlim((0,1)) # set limits to (0,1)
#ax[-1].get_xaxis().set_ticks([])
if not n == 1:
ax[-1].get_yaxis().set_ticks([])
else:
ax[-1].set_yticklabels(labels=["","Good","Empty","Out-of-focus","Defective"])
ax[-1].set_ylabel("CNN prediction category")
# show the plot finally
fig.suptitle("FOV %d" % fov_id)
# enter user input
# ask the user to correct cell/nocell calls
cells_handler = fig.canvas.mpl_connect('button_press_event', onclick_cells)
# matplotlib has difefrent behavior for interactions in different versions.
if float(mpl.__version__[:3]) < 1.5: # check for verions less than 1.5
plt.show(block=False)
raw_input("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nPrees enter to go to the next FOV.")
else:
print("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nClose figure to go to the next FOV.")
plt.show(block=True)
fig.canvas.mpl_disconnect(cells_handler)
plt.close()
return specs
# function to plot CNN-derived trap classifications
def fov_cell_segger_choose_channels_UI(fov_id, predictionDict, specs, UI_images):
'''Creates a plot with the channels with guesses for empties and full channels,
and requires the user to choose which channels to use for analysis and which to
average for empties and subtraction.
Parameters
fov_file : str
file name of the hdf5 file name in originals
fov_xcorrs : dictionary
dictionary for cross correlation values for all fovs.
Returns
bgdr_peaks : list
list of peak id's (int) of channels to be used for subtraction
spec_file_pkl : pickle file
saves the lists cell_peaks, bgrd_peaks, and drop_peaks to a pkl file
'''
mm3.information("Starting channel picking for FOV %d." % fov_id)
# define functions here so they have access to variables
# for UI. change specification of channel
def onclick_cells(event):
try:
peak_id = int(event.inaxes.get_title())
except AttributeError:
return
# reset image to be updated based on user clicks
ax_id = sorted_peaks.index(peak_id) * 3 + 1
new_img = last_imgs[sorted_peaks.index(peak_id)]
ax[ax_id].imshow(new_img, cmap=plt.cm.gray, interpolation='nearest')
# if it says analyze, change to empty
if specs[fov_id][peak_id] == 1:
specs[fov_id][peak_id] = 0
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array*0.1, ones_array)), alpha=0.25)
#mm3.information("peak %d now set to empty." % peak_id)
# if it says empty, change to don't analyze
elif specs[fov_id][peak_id] == 0:
specs[fov_id][peak_id] = -1
ax[ax_id].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to ignore." % peak_id)
# if it says don't analyze, change to analyze
elif specs[fov_id][peak_id] == -1:
specs[fov_id][peak_id] = 1
ax[ax_id].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
#mm3.information("peak %d now set to analyze." % peak_id)
plt.draw()
return
# set up figure for user assited choosing
n_peaks = len(specs[fov_id].keys())
fig = plt.figure(figsize=(int(n_peaks/2), 12))
fig.set_size_inches(int(n_peaks/2),12)
ax = [] # for axis handles
# plot the peaks peak by peak using sorted list
sorted_peaks = sorted([peak_id for peak_id in specs[fov_id].keys()])
npeaks = len(sorted_peaks)
last_imgs = [] # list that holds last images for updating figure
for n, peak_id in enumerate(sorted_peaks, start=1):
if predictionDict:
predictions = predictionDict[fov_id][peak_id] # get predictions array
# load data for figure
# image_data = mm3.load_stack(fov_id, peak_id, color='c1')
# first_img = rescale_intensity(image_data[0,:,:]) # phase image at t=0
# last_img = rescale_intensity(image_data[-1,:,:]) # phase image at end
last_imgs.append(UI_images[fov_id][peak_id]['last']) # append for updating later
# del image_data # clear memory (maybe)
# append an axis handle to ax list while adding a subplot to the figure which has a
# column for each peak and 3 rows
# plot the first image in each channel in top row
ax.append(fig.add_subplot(3, npeaks, n))
ax[-1].imshow(UI_images[fov_id][peak_id]['first'],
cmap=plt.cm.gray, interpolation='nearest')
ax = format_channel_plot(ax, peak_id) # format axis and title
if n == 1:
ax[-1].set_ylabel("first time point")
# plot middle row using last time point with highlighting for empty/full
ax.append(fig.add_subplot(3, npeaks, n + npeaks))
ax[-1].imshow(UI_images[fov_id][peak_id]['last'],
cmap=plt.cm.gray, interpolation='nearest')
# color image based on if it is thought empty or full
ones_array = np.ones_like(UI_images[fov_id][peak_id]['last'])
if specs[fov_id][peak_id] == 1: # 1 means analyze, show green
ax[-1].imshow(np.dstack((ones_array*0.1, ones_array, ones_array*0.1)), alpha=0.25)
else: # otherwise show red, means don't analyze
ax[-1].imshow(np.dstack((ones_array, ones_array*0.1, ones_array*0.1)), alpha=0.25)
# format
ax = format_channel_plot(ax, peak_id)
if n == 1:
ax[-1].set_ylabel("last time point")
# finally plot the prediction values as horizontal bar chart
ax.append(fig.add_subplot(3, npeaks, n + 2*npeaks))
if predictionDict:
# ax[-1].barh(range(len(predictions)), predictions)
ax[-1].barh([0], [predictions])
#ax[-1].vlines(x=p['channel_picker']['channel_picking_threshold'], ymin=-1, ymax=5, linestyles='dashed',colors='red')
ax[-1].set_title('cell count', fontsize = 8)
else:
ax[-1].plot(np.zeros(10), range(10))
# ax[-1].set_xlim((0,1)) # set limits to (0,1)
#ax[-1].get_xaxis().set_ticks([])
if not n == 1:
ax[-1].get_yaxis().set_ticks([])
else:
ax[-1].set_yticklabels(labels=["1"])
# ax[-1].set_yticklabels(labels=["",'1','2','3','4','5'])
ax[-1].set_ylabel("")
# show the plot finally
fig.suptitle("FOV %d" % fov_id)
# enter user input
# ask the user to correct cell/nocell calls
cells_handler = fig.canvas.mpl_connect('button_press_event', onclick_cells)
# matplotlib has difefrent behavior for interactions in different versions.
if float(mpl.__version__[:3]) < 1.5: # check for verions less than 1.5
plt.show(block=False)
raw_input("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nPrees enter to go to the next FOV.")
else:
print("Click colored channels to toggle between analyze (green), use for empty (blue), and ignore (red).\nClose figure to go to the next FOV.")
plt.show(block=True)
fig.canvas.mpl_disconnect(cells_handler)
plt.close()
return specs
# function for better formatting of channel plot
def format_channel_plot(ax, peak_id):
'''Removes axis and puts peak as title from plot for channels'''
ax[-1].get_xaxis().set_ticks([])
ax[-1].get_yaxis().set_ticks([])
ax[-1].set_title(str(peak_id), fontsize = 8)
return ax
# function to preload all images for all FOVs, hopefully saving time
def preload_images(specs, fov_id_list):
'''This dictionary holds the first and last image
for all channels in all FOVS. It is passed to the UI so that the
figures can be populated much faster
'''
global p
# Intialized the dicionary
UI_images = {}
for fov_id in fov_id_list:
mm3.information("Preloading images for FOV {}.".format(fov_id))
UI_images[fov_id] = {}
for peak_id in specs[fov_id].keys():
image_data = mm3.load_stack(fov_id, peak_id, color=p['phase_plane'])
UI_images[fov_id][peak_id] = {'first' : None, 'last' : None} # init dictionary
# phase image at t=0. Rescale intenstiy and also cut the size in half
first_image = p['channel_picker']['first_image']
UI_images[fov_id][peak_id]['first'] = transform.resize(image_data[first_image,:,:], (int(np.floor(image_data.shape[1]*0.5)),int(np.floor(image_data.shape[2]*0.5))))
last_image = p['channel_picker']['last_image']
# phase image at end
UI_images[fov_id][peak_id]['last'] = transform.resize(image_data[last_image,:,:], (int(np.floor(image_data.shape[1]*0.5)),int(np.floor(image_data.shape[2]*0.5))))
return UI_images
### For when this script is run from the terminal ##################################
if __name__ == "__main__":
'''mm3_ChannelPicker.py allows the user to identify full and empty channels.
'''
# set switches and parameters
parser = argparse.ArgumentParser(prog='python mm3_ChannelPicker.py',
description='Determines which channels should be analyzed, used as empties for subtraction, or ignored.')
parser.add_argument('-f', '--paramfile', type=str,
required=True, help='Yaml file containing parameters.')
parser.add_argument('-o', '--fov', type=str,
required=False, help='List of fields of view to analyze. Input "1", "1,2,3", or "1-10", etc.')
parser.add_argument('-j', '--nproc', type=int,
required=False, help='Number of processors to use.')
# parser.add_argument('-s', '--specfile', type=file,
# required=False, help='Filename of specs file.')
parser.add_argument('-i', '--noninteractive', action='store_true',
required=False, help='Do channel picking manually.')
parser.add_argument('-c', '--saved_cross_correlations', action='store_true',
required=False, help='Load cross correlation data instead of computing.')
parser.add_argument('-s', '--specfile', type=str,
required=False, help='Path to spec.yaml file.')
namespace = parser.parse_args()
# Load the project parameters file
mm3.information('Loading experiment parameters.')
if namespace.paramfile:
param_file_path = namespace.paramfile
else:
mm3.warning('No param file specified. Using 100X template.')
param_file_path = 'yaml_templates/params_SJ110_100X.yaml'
p = mm3.init_mm3_helpers(param_file_path) # initialized the helper library
if namespace.fov:
if '-' in namespace.fov:
user_spec_fovs = range(int(namespace.fov.split("-")[0]),
int(namespace.fov.split("-")[1])+1)
else:
user_spec_fovs = [int(val) for val in namespace.fov.split(",")]
else:
user_spec_fovs = []
# number of threads for multiprocessing
if namespace.nproc:
p['num_analyzers'] = namespace.nproc
else:
p['num_analyzers'] = 6
# use previous specfile
if namespace.specfile:
try:
specfile = os.path.relpath(namespace.specfile)
if not os.path.isfile(specfile):
raise ValueError
except ValueError:
mm3.warning("\"{}\" is not a regular file or does not exist".format(specfile))
else:
specfile = None
# set cross correlation calculation flag
if namespace.saved_cross_correlations:
do_crosscorrs = False
else:
do_crosscorrs = p['channel_picker']['do_crosscorrs']
do_CNN = p['channel_picker']['do_CNN']
do_seg = p['channel_picker']['do_seg']
# set interactive flag
if namespace.noninteractive:
interactive = False
else:
interactive = p['channel_picker']['interactive']
# assign shorthand directory names
ana_dir = os.path.join(p['experiment_directory'], p['analysis_directory'])
chnl_dir = os.path.join(p['experiment_directory'], p['analysis_directory'], 'channels')
hdf5_dir = os.path.join(p['experiment_directory'], p['analysis_directory'], 'hdf5')
# load channel masks
channel_masks = mm3.load_channel_masks()
# make list of FOVs to process (keys of channel_mask file), but only if there are channels
fov_id_list = sorted([fov_id for fov_id, peaks in six.iteritems(channel_masks) if peaks])
# remove fovs if the user specified so
if (len(user_spec_fovs) > 0):
fov_id_list = [int(fov) for fov in fov_id_list if fov in user_spec_fovs]
mm3.information("Found %d FOVs to process." % len(fov_id_list))
### Cross correlations ########################################################################
if do_CNN:
# a nested dict to hold predictions per channel per fov.
crosscorrs = None
predictionDict = {}
mm3.information('Loading model ....')
# read in model for inference of empty vs good traps
model_file_path = p['channel_picker']['channel_picker_model_file']
model = models.load_model(model_file_path)
mm3.information("Model loaded.")
for fov_id in fov_id_list:
predictionDict[fov_id] = {}
mm3.information('Inferring good, empty, and defective traps on fov_id {} using CNN.'.format(fov_id))
# get list of tiff file names
tiff_file_names = glob.glob(os.path.join(chnl_dir, "*xy{:0=3}*_c1.tif".format(fov_id)))
tiff_file_names.sort()
#print(len(tiff_file_names)) # uncomment for debugging
# parameters to pass to custom image generator class, TrapKymographPredictionDataGenerator
cnn_params = {'dim': (210,256),
'batch_size': 40,
'n_classes': 4,
'n_channels': 1,
'shuffle': False}
# set up the image data generator
channel_image_generator = mm3.TrapKymographPredictionDataGenerator(tiff_file_names, **cnn_params)
# run the model
predictions = model.predict_generator(channel_image_generator)
#print(predictions.shape)
predictions = predictions[:len(tiff_file_names),:]
#print(predictions.shape)
# assign each prediction to the proper fov_id, peak_id in predictions dict
for i,peak_id in enumerate(sorted(channel_masks[fov_id].keys())):
# put prediction array into dictionary
#print(i, peak_id) # uncomment for debugging
predictionDict[fov_id][peak_id] = predictions[i,:]
# write predictions to pickle and text
mm3.information("Writing channel picking predictions file.")
with open(os.path.join(ana_dir,"channel_picker_CNN_results.pkl"), 'wb') as preds_file:
pickle.dump(predictionDict, preds_file, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(ana_dir,"channel_picker_CNN_results.txt"), 'w') as preds_file:
pprint(predictionDict, stream=preds_file)
mm3.information("Wrote channel picking predictions files.")
elif do_seg:
# a nested dict to hold predictions per channel per fov.
crosscorrs = None
predictionDict = {}
mm3.information('Loading model ....')
# read in model for inference of empty vs good traps
model_file_path = p['segment']['model_file']
model = models.load_model(model_file_path,
custom_objects={'bce_dice_loss': mm3.bce_dice_loss,
'dice_loss': mm3.dice_loss})
unet_shape = (p['segment']['trained_model_image_height'],
p['segment']['trained_model_image_width'])
batch_size = p['segment']['batch_size']
cellClassThreshold = p['segment']['cell_class_threshold']
if cellClassThreshold == 'None': # yaml imports None as a string
cellClassThreshold = False
min_object_size = p['segment']['min_object_size']
mm3.information("Model loaded.")
# arguments to data generator
data_gen_args = {'batch_size':p['segment']['batch_size'],
'n_channels':1,
'normalize_to_one':True,