-
Notifications
You must be signed in to change notification settings - Fork 2
/
LM_Imaging.py
2005 lines (1667 loc) · 79.7 KB
/
LM_Imaging.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
'''
'Mag' usually refers to the magnetic resin that contains magnetic and fluorescent particles of different wavelengths
'''
#########################################################
### Start of config example for NikonPeter microscope ###
#########################################################
mic = 'NikonPeter'
micromanagerFolder = r'C:\Micro-Manager-1.4.23N'
mmConfigFile = r'E:\UserData\Templier\MM\MMConfig_BCNikon2_Default_Sungsik.cfg'
folderSave = os.path.join(r'E:\UserData\Templier\WorkingFolder', '')
NikonColors = ['Blue', 'Cyan', 'Green', 'Red', 'Teal', 'Violet', 'White'] # the name of the colors of the Lumencor source - /!\ Warning: white has to be last
# size of field of view in micrometers for different magnifications
magnificationImageSizes = {
20: [20, 1328.6, 1020.6],
63: [63, 220, 220],
}
# properties to read the current objective
objectiveProperties = ['TINosePiece', 'Label']
# properties to set during initialization
initialProperties = []
initialProperties.append(['Core', 'Focus','TIZDrive']) # otherwise the z drive is not recognized
initialProperties.append(['TIFilterBlock1', 'Label', '2-Quad']) # or 3-FRAP
initialProperties.append(['TILightPath', 'Label', '2-Left100']) # or 3-Right100 probably for the other camera
initialProperties.append(['Core', 'TimeoutMs', '20000']) # to prevent timeout during long stage movements
for NikonColor in NikonColors:
initialProperties.append(['SpectraLED', NikonColor + '_Level', '100'])
# Change stage speed for accuracy: faster than 6 seemed to be inacurrate
initialProperties.append(['TIXYDrive', 'SpeedX', '6'])
initialProperties.append(['TIXYDrive', 'SpeedY', '6'])
initialProperties.append(['TIXYDrive', 'ToleranceX', '0'])
initialProperties.append(['TIXYDrive', 'ToleranceY', '0'])
acquisitionIntervalBF = 5 # in ms, acquisitionInterval during live brightfield imaging
acquisitionIntervalMag = 5 # in ms, acquisitionInterval during live fluo imaging
##############################
### All channel parameters ###
channelNames = {
'brightfield': ['White', '8-emty', ['SpectraLED', 'White_Level', '10']],
'dapi': ['Violet', '9-DAPI'],
488: ['Cyan', '0-FITC'],
546: ['Green', '5-mCherry'],
647: ['Red', '2-Cy5']}
objectives = [20, 63]
channelSpecs = ['exposure', 'offset']
channelContexts = ['imaging', 'focusing', 'live']
channelTargets = ['beads', 'tissue', 'general'] # 'general' used during live
# initialize the channels dictionnary: contains exposure times and z-offset of all channels
channels = {}
for channelName in channelNames:
channels[channelName] = {}
for objective in objectives:
channels[channelName][objective] = {}
for channelSpec in channelSpecs:
channels[channelName][objective][channelSpec] = {}
for channelContext in channelContexts:
channels[channelName][objective][channelSpec][channelContext] = {}
for channelContext in channelContexts:
channels[channelContext] = {}
objectiveBeads = 20
objectiveTissue = 63
### General exposure parameters independent of the imaging target (beads or tissue) for live imaging ###
channels['brightfield'][objectiveTissue]['exposure']['live']['general'] = 2
channels['dapi'][objectiveTissue]['exposure']['live']['general'] = 1
channels[488][objectiveTissue]['exposure']['live']['general'] = 1
channels[546][objectiveTissue]['exposure']['live']['general'] = 5
channels[647][objectiveTissue]['exposure']['live']['general'] = 5
channels['brightfield'][objectiveBeads]['exposure']['live']['general'] = 0.2
channels['dapi'][objectiveBeads]['exposure']['live']['general'] = 5
channels[488][objectiveBeads]['exposure']['live']['general'] = 5
channels[546][objectiveBeads]['exposure']['live']['general'] = 5
channels[647][objectiveBeads]['exposure']['live']['general'] = 5
### TISSUE-LIVE ### with objectiveTissue
channels['brightfield'][objectiveTissue]['exposure']['live']['tissue'] = 10
channels['dapi'][objectiveTissue]['exposure']['live']['tissue'] = 10
channels[488][objectiveTissue]['exposure']['live']['tissue'] = 10
channels[546][objectiveTissue]['exposure']['live']['tissue'] = 10
channels[647][objectiveTissue]['exposure']['live']['tissue'] = 10
### TISSUE-LIVE ### with objectiveBeads
channels['brightfield'][objectiveBeads]['exposure']['live']['tissue'] = 1
channels['dapi'][objectiveBeads]['exposure']['live']['tissue'] = 10
channels[488][objectiveBeads]['exposure']['live']['tissue'] = 10
channels[546][objectiveBeads]['exposure']['live']['tissue'] = 10
channels[647][objectiveBeads]['exposure']['live']['tissue'] = 10
### TISSUE-IMAGING ###
channels['brightfield'][objectiveTissue]['exposure']['imaging']['tissue'] = 1
channels['dapi'][objectiveTissue]['exposure']['imaging']['tissue'] = 500
channels[488][objectiveTissue]['exposure']['imaging']['tissue'] = 500
channels[546][objectiveTissue]['exposure']['imaging']['tissue'] = 500
channels[647][objectiveTissue]['exposure']['imaging']['tissue'] = 500
### BEADS-LIVE ###
channels['brightfield'][objectiveBeads]['exposure']['live']['beads'] = 0.2
channels['dapi'][objectiveBeads]['exposure']['live']['beads'] = 20
channels[488][objectiveBeads]['exposure']['live']['beads'] = 20
channels[546][objectiveBeads]['exposure']['live']['beads'] = 20
channels[647][objectiveBeads]['exposure']['live']['beads'] = 20
### BEADS-IMAGING ###
channels['brightfield'][objectiveBeads]['exposure']['imaging']['beads'] = 0.1
channels['dapi'][objectiveBeads]['exposure']['imaging']['beads'] = 100
channels[488][objectiveBeads]['exposure']['imaging']['beads'] = 100
channels[546][objectiveBeads]['exposure']['imaging']['beads'] = 100
channels[647][objectiveBeads]['exposure']['imaging']['beads'] = 100
### OFFSET-OBJECTIVEBEADS ###
channels['brightfield'][objectiveBeads]['offset']['imaging']['beads'] = 0
channels['dapi'][objectiveBeads]['offset']['imaging']['beads'] = 0
channels[488][objectiveBeads]['offset']['imaging']['beads'] = 0.925
channels[546][objectiveBeads]['offset']['imaging']['beads'] = 0 # reference
channels[647][objectiveBeads]['offset']['imaging']['beads'] = 0 # reference
### OFFSET-TISSUE ###
channels[546][objectiveTissue]['offset']['imaging']['tissue'] = 0 # reference
channels['brightfield'][objectiveTissue]['offset']['imaging']['tissue'] = 0.2 # well calibrated ...
channels[647][objectiveTissue]['offset']['imaging']['tissue'] = 0.2
channels[488][objectiveTissue]['offset']['imaging']['tissue'] = 0
##############################
#######################################################
### End of config example for NikonPeter microscope ###
#######################################################
############################
# Sample specific parameters
############################
waferName = 'C1_Wafer_500_Tissue'
# Mosaic Parameters for tissue
tileGrid = [2,2]
overlap = 20 # in percentage
# Mosaic Parameters for mag
tileGridMag = [1,1]
overlapMag = 20 # in percentage
# What channels should be used for bead imaging
channels['imaging']['beads'] = [488, 546, 'dapi', 'brightfield']
# What channels should be used for tissue imaging
channels['imaging']['tissue'] = [488, 546, 647, 'brightfield']
############################
###################
#### Constants ####
sleepSaver = 0.1 # the saver thread runs every sleepSaver second to check the savingQueue
liveGrabSleep = 0.1 # refresh cycle during the live visualization in s
# parameters of the cross displayed at the center of the field of view during live imaging
crossLength = 50
crossWidth = 5
stageInc = 1000 # displacement of the stage when the north/south/west/east buttons are pressed
#### End constants ####
#######################
import sys
sys.path.append(micromanagerFolder)
import MMCorePy
import os, time, datetime, shutil, pickle, argparse, tkFileDialog, subprocess, re, copy, random, json
from operator import itemgetter
import logging, colorlog # colorlog is not yet standard
#import logging
import threading
from threading import Thread
from Queue import Queue
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from mpl_toolkits.mplot3d import Axes3D
import winsound
import numpy as np
from numpy import sin, pi, cos, arctan, tan, sqrt
from Tkinter import Label, LabelFrame, Button, Frame, Tk, LEFT, Canvas, Toplevel
import ctypes
import copy
import PIL # xxx does this not need tifffile ?
from PIL import Image, ImageTk
from scipy import fftpack
from scipy.interpolate import Rbf, InterpolatedUnivariateSpline
from scipy.optimize import brent, minimize_scalar
#####################
### I/O Functions ###
def mkdir_p(path):
try:
os.mkdir(path)
logger.debug('Folder created: ' + path)
except Exception, e:
if e[0] == 20047 or e[0] == 183:
# IJ.log('Nothing done: folder already existing: ' + path)
pass
else:
logger.error('Exception during folder creation :', exc_info=True)
raise
return path
def getDirectory(text, startingFolder = None):
if startingFolder:
direc = os.path.join(tkFileDialog.askdirectory(title = text, initialdir = startingFolder), '')
else:
direc = os.path.join(tkFileDialog.askdirectory(title = text), '')
logger.debug('Directory chosen by user: ' + direc)
return direc
def getPath(text, startingFolder = None):
if startingFolder:
path = tkFileDialog.askopenfilename(title = text, initialdir = startingFolder)
else:
path = tkFileDialog.askopenfilename(title = text)
logger.debug('Path chosen by user: ' + path)
return path
def findFilesFromTags(folder,tags):
filePaths = []
for (dirpath, dirnames, filenames) in os.walk(folder):
for filename in filenames:
if (all(map(lambda x:x in filename,tags)) == True):
path = os.path.join(dirpath, filename)
filePaths.append(path)
filePaths = naturalSort(filePaths)
return filePaths
def readPoints(path):
x,y = [], []
with open(path, 'r') as f:
lines = f.readlines()
for point in lines:
x.append(float(point.split('\t')[0]))
try:
y.append(float(point.split('\t')[1]))
except Exception, e:
pass
logger.debug('Points read' + str([x,y]))
return np.array([x,y])
def writePoints(path, points):
with open(path, 'w') as f:
for point in points:
line = str(point[0]) + '\t' + str(point[1]) + '\n'
f.write(line)
logger.debug('The point coordinates have been written')
def readSectionCoordinates(path):
with open(path, 'r') as f:
lines = f.readlines()
sections = []
for line in lines:
points = line.split('\t')
points.pop()
section = [ [int(float(point.split(',')[0])), int(float(point.split(',')[1]))] for point in points ]
sections.append(section)
return sections
def naturalSort(l):
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
return sorted(l, key = alphanum_key)
def initLogger(path):
fileFormatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', datefmt = '%d-%m-%Y %H:%M:%S')
fileHandler = logging.FileHandler(path)
fileHandler.setFormatter(fileFormatter)
fileHandler.setLevel(logging.DEBUG) # should I also save an .INFO log ? no: if someone wants to check a log, he probably wants to see the .debug one ...
colorFormatter = colorlog.ColoredFormatter('%(log_color)s%(asctime)s %(levelname)s %(message)s', datefmt = '%d-%m-%Y %H:%M:%S')
streamHandler = colorlog.StreamHandler()
streamHandler.setFormatter(colorFormatter)
logger = logging.getLogger(__name__)
# clean the logger in case the script is run again in the same console
handlers = logger.handlers[:]
for handler in handlers:
handler.close()
logger.removeHandler(handler)
logger.setLevel(logging.DEBUG)
logger.propagate = False
logger.addHandler(fileHandler)
logger.addHandler(streamHandler)
return logger
def durationToPrint(d):
return str(round(d/60., 1)) + ' min = ' + str(round(d/3600., 1)) + ' hours = ' + str(round(d/(3600.*24), 1)) + ' days'
def saver(q):
while True:
if not q.empty():
logger.debug('Saving queue not empty')
toSave = q.get()
if toSave == 'finished':
logger.debug('Saver thread is going to terminate')
return
else:
sectionIndex, channel, tileId, folder, im, name = toSave
fileName = 'section_' + str(sectionIndex).zfill(4) + '_channel_' + str(channel) + '_tileId_' + str(tileId[0]).zfill(2) + '-' + str(tileId[1]).zfill(2) + (len(name)>0) * ('-' + str(name)) + '.tif'
path = os.path.join(folder, fileName)
logger.debug('Saving snapped image in ' + path)
# imsave(path, im) # with tifffile
# with PIL and saving as png
# im = np.array(im)
result = PIL.Image.fromarray((im).astype(np.uint16))
result.save(path)
time.sleep(sleepSaver)
###########################
### Geometric functions ###
def applyAffineT(points,coefs):
x,y = np.array(points)
x_out = coefs[1]*x - coefs[0]*y + coefs[2]
y_out = coefs[1]*y + coefs[0]*x + coefs[3]
return np.array([x_out,y_out])
def rotate(points, angle):
angleRadian = angle * pi / 180.
coefs = [sin(angleRadian), cos(angleRadian), 0, 0]
return applyAffineT(points,coefs)
def translate(points, v):
coefs = [0, 1, v[0], v[1]]
return applyAffineT(points,coefs)
def affineT(sourceLandmarks, targetLandmarks, sourcePoints):
# separating the x and y into separate variables
x_sourceLandmarks, y_sourceLandmarks = np.array(sourceLandmarks).T[:len(targetLandmarks.T)].T #sourceLandmarks trimmed to the number of existing targetlandmarks
x_targetLandmarks, y_targetLandmarks = targetLandmarks
x_sourcePoints, y_sourcePoints = sourcePoints
# Solving the affine transform
A_data = []
for i in range(len(x_sourceLandmarks)):
A_data.append( [-y_sourceLandmarks[i], x_sourceLandmarks[i], 1, 0])
A_data.append( [x_sourceLandmarks[i], y_sourceLandmarks[i], 0, 1])
b_data = []
for i in range(len(x_targetLandmarks)):
b_data.append(x_targetLandmarks[i])
b_data.append(y_targetLandmarks[i])
A = np.matrix( A_data )
b = np.matrix( b_data ).T
c = np.linalg.lstsq(A, b)[0].T #solving happens here
c = np.array(c)[0]
# print('Absolute errors in target coordinates : (xError, yError)')
# for i in range(len(x_sourceLandmarks)):
#print ("%f, %f" % (
# np.abs(c[1]*x_sourceLandmarks[i] - c[0]*y_sourceLandmarks[i] + c[2] - x_targetLandmarks[i]),
# np.abs(c[1]*y_sourceLandmarks[i] + c[0]*x_sourceLandmarks[i] + c[3] - y_targetLandmarks[i])))
#computing the accuracy
x_target_computed_landmarks, y_target_computed_landmarks = applyAffineT(sourceLandmarks, c)
accuracy = 0
for i in range(len(x_targetLandmarks)):
accuracy = accuracy + np.sqrt( np.square( x_targetLandmarks[i] - x_target_computed_landmarks[i] ) + np.square( y_targetLandmarks[i] - y_target_computed_landmarks[i] ) )
accuracy = accuracy/float(len(x_sourceLandmarks) + 1)
# print 'The mean accuracy in target coordinates is', accuracy
#computing the target points
x_target_points, y_target_points = applyAffineT(sourcePoints,c)
return np.array([x_target_points, y_target_points])
def getCenter(corners):
center = np.array(map(np.mean, corners))
return center
def getAngle(line):
line = np.array(line)
diff = line[0:2] - line[2:4]
theta = np.arctan2(diff[1], diff[0])
return theta
def getZInPlane(x,y,abc): #Fitted plane function
return float(abc[0]*x + abc[1]*y + abc[2])
def focusThePoints(focusedPoints, pointsToFocus):
x_pointsToFocus, y_pointsToFocus = pointsToFocus[0], pointsToFocus[1] # works even if pointsToFocus has no z coordinates
x_focusedPoints, y_focusedPoints, z_focusedPoints = focusedPoints # focusedPoints of course has 3 coordinates
# logger.debug('focusedPoints = ' + str(focusedPoints))
# logger.debug('pointsToFocus = ' + str(pointsToFocus))
# remove outliers
idInliers = getInlierIndices(z_focusedPoints)
# logger.debug('idInliers = ' + str(idInliers) )
# logger.debug('There are ' + str(idInliers.size) + ' inliers in ' + str(map(lambda x:round(x, 2), z_focusedPoints*1e6)) + ' um' )
if idInliers.size == 3:
logger.warning('One autofocus point has been removed for interpolative plane calculation')
x_focusedPoints, y_focusedPoints, z_focusedPoints = focusedPoints.T[idInliers].T
elif idInliers.size < 3:
logger.warning('There are only ' + str(idInliers.size) + ' inliers for the interpolative plane calculation. A strategy should be developed to address such an event.')
A = np.column_stack([x_focusedPoints, y_focusedPoints, np.ones_like(x_focusedPoints)])
abc,residuals,rank,s = np.linalg.lstsq(A, z_focusedPoints)
z_pointsToFocus = map(lambda a: getZInPlane (a[0],a[1],abc), np.array([x_pointsToFocus.transpose(), y_pointsToFocus.transpose()]).transpose())
# calculating the accuracy
z_check = np.array(map(lambda a: getZInPlane (a[0],a[1],abc), np.array([x_focusedPoints.transpose(), y_focusedPoints.transpose()]).transpose()))
diff = z_check - z_focusedPoints
meanDiff = np.mean(np.sqrt(diff * diff))
logger.debug('The plane difference is ' + str(diff*1e6) + ' um')
logger.info('The mean distance of focus points to the plane is ' + str(round(meanDiff*1e6, 3)) + ' um')
return np.array([x_pointsToFocus, y_pointsToFocus, z_pointsToFocus])
def transformCoordinates(coordinates, center, angle):
return (translate(rotate(coordinates.T, angle), center)).T
def getInlierIndices(data, m = 2.5):
d = np.abs(data - np.median(data))
# mdev = float(np.median(d))
mdev = float(np.mean(d))
s = d/mdev if mdev else np.array(len(data) * [0.])
# print 'mdev', mdev
# print 'd', d
# print 's', s
return np.where(s <= m)[0]
def getOutlierIndices(data, m = 2.5):
d = np.abs(data - np.median(data))
# mdev = float(np.median(d))
mdev = float(np.mean(d))
s = d/mdev if mdev else np.array(len(data) * [0.])
# print 'mdev', mdev
# print 'd', d
# print 's', s
return np.where(s > m)[0]
def bbox(points):
minx, miny = 1e9, 1e9
maxx, maxy = -1e9, -1e9
for point in points:
if point[0] > maxx:
maxx = point[0]
if point[0] < minx:
minx = point[0]
if point[1] > maxy:
maxy = point[1]
if point[1] < miny:
miny = point[1]
return minx, miny, maxx-minx, maxy-miny
def gridInBb(bb, gridLayout = None, gridSpacing = None):
if gridLayout is not None:
gridSpacing = np.array(bb[2:])/(np.array(gridLayout)-1)
else:
gridLayout = (np.array(bb[2:])/np.array(gridSpacing)).astype(int)
gridSpacing = np.array(bb[2:])/(np.array(gridLayout)-1)
topLeftCorner = bb[:2]
gridPoints = []
for x in range(gridLayout[0]):
for y in range(gridLayout[1]):
gridPoints.append( topLeftCorner + np.array([x,y]) * gridSpacing)
return np.array(gridPoints), gridLayout, gridSpacing
# # x = np.linspace(bb[0], bb[0] + bb[2], gridLayout[0])
# # y = np.linspace(bb[1], bb[1] + bb[3], gridLayout[1])
def bestNeighbors(gridPoints, targetPoints):
bestNeighbors = []
targetPoints = np.array(targetPoints).T[:2].T
for gridPoint in gridPoints:
distances = ((np.array(targetPoints) - gridPoint)**2).sum(axis=1)
sortedDistances = distances.argsort()
bestNeighbors.append(targetPoints[sortedDistances[0]])
return np.array(bestNeighbors)
def getNearestPoints(points, refPoint, nPoints = 1):
'''
Returns the nPoints indices of points indicating the closest points to the reference point refPoint
'''
# return (min((hypot(x2-refPoint[0],y2-refPoint[1]), x2, y2) for x2,y2 in points))[1:3]
sortedDistances = sorted( [[np.linalg.norm(np.array([point[0],point[1]]) - np.array(refPoint)), id] for id, point in enumerate(points)], key = lambda x: x[0], reverse = False)[:nPoints]
# print 'sortedDistances XXX UUU', sortedDistances
# return np.array([x[1:3] for x in sortedDistances]), np.array([x[0] for x in sortedDistances]) # centers, indices
return np.array([x[1] for x in sortedDistances]) # indices
def getPlaneMesh(array2D, array3D, grid):
'''
array2D gives the x,y boundaries for the mesh
array3D gives the interpolative plane
'''
# grid = 50
x = np.linspace(np.min(array2D[0]), np.max(array2D[0]), grid)
y = np.linspace(np.min(array2D[1]), np.max(array2D[1]), grid)
xv, yv = np.meshgrid(x, y)
xvFlat = [item for sublist in xv for item in sublist]
yvFlat = [item for sublist in yv for item in sublist]
planeMesh = focusThePoints( array3D, np.array([xvFlat, yvFlat]))
return planeMesh
def getRBFMesh(array2D, array3D, grid):
'''
array2D gives the x,y boundaries for the mesh
array3D gives the interpolative plane
'''
# grid = 50
x = np.linspace(np.min(array2D[0]), np.max(array2D[0]), grid)
y = np.linspace(np.min(array2D[1]), np.max(array2D[1]), grid)
xv, yv = np.meshgrid(x, y)
xvFlat = np.array([item for sublist in xv for item in sublist])
yvFlat = np.array([item for sublist in yv for item in sublist])
rbf = Rbf(np.array(array3D[0], array3D[1], array3D[2], epsilon = 2, function = 'thin_plate'))
autofocusedRBF = np.array([xvFlat, yvFlat, rbf(xvFlat, yvFlat)]).T
return autofocusedRBF
#####################
### GUI Functions ###
dirtyCounter = 0
class App:
global wafer
def __init__(self, master):
self.live = False
self.acquisitionInterval = acquisitionIntervalBF
self.frame = Frame(master)
self.frame.pack()
self.button1 = Button(self.frame, text='Acquire tissue *HAF*', command = self.tissueAcquireHAF)
self.button1.pack(side=LEFT)
self.button95 = Button(self.frame, text='Acq. manual mosaic *HAF*', command = self.tissueAcquireHAFFromManualSections)
self.button95.pack(side=LEFT)
self.button50 = Button(self.frame, text='Acquire tissue *manual*', command = self.tissueAcquireManual)
self.button50.pack(side=LEFT)
self.button2 = Button(self.frame, text='Add mosaic here', command = self.addMosaicHere)
self.button2.pack(side=LEFT)
self.button3 = Button(self.frame, text='Add lowres landmark', command = self.addLowResLandmark)
self.button3.pack(side=LEFT)
self.button22 = Button(self.frame, text='Add highres landmark', command = self.addHighResLandmark)
self.button22.pack(side=LEFT)
self.button4 = Button(self.frame, text='Load wafer', command = self.loadWafer)
self.button4.pack(side=LEFT)
self.button44 = Button(self.frame, text='ResetWaferKeepTargets', command = self.resetWaferKeepTargetCalibration)
self.button44.pack(side=LEFT)
self.button5 = Button(self.frame, text='Load sections and landmarks from pipeline', command = self.loadSectionsAndLandmarksFromPipeline)
self.button5.pack(side=LEFT)
self.button6 = Button(self.frame, text='Acquire mag *HAF*', command = self.magAcquireHAF)
self.button6.pack(side=LEFT)
self.button24 = Button(self.frame, text='Acquire mag *manual*', command = self.magAcquireManual)
self.button24.pack(side=LEFT)
self.button7 = Button(self.frame, text='Save Wafer', command = self.saveWafer)
self.button7.pack(side=LEFT)
self.button9 = Button(self.frame, text='Stop live', command = self.stopLive)
self.button9.pack(side=LEFT)
# # # self.buttonN = Button(self.frame, text='N', command = self.north)
# # # self.buttonN.pack(side=LEFT)
# # # self.buttonS = Button(self.frame, text='S', command = self.south)
# # # self.buttonS.pack(side=LEFT)
# # # self.buttonE = Button(self.frame, text='E', command = self.east)
# # # self.buttonE.pack(side=LEFT)
# # # self.buttonW = Button(self.frame, text='W', command = self.west)
# # # self.buttonW.pack(side=LEFT)
# self.button11 = Button(self.frame, text='GoToNextMag', command = self.goToNextMag)
# self.button11.pack(side=LEFT)
# self.button12 = Button(self.frame, text='resetGreenFocus', command = self.resetGreenFocus)
# self.button12.pack(side=LEFT)
# # self.button13 = Button(self.frame, text='rbf', command = self.rbf)
# # self.button13.pack(side=LEFT)
# # self.button14 = Button(self.frame, text='plane', command = self.plane)
# # self.button14.pack(side=LEFT)
# self.button15 = Button(self.frame, text='goToNextMagFocus', command = self.goToNextMagFocus)
# self.button15.pack(side=LEFT)
self.button66 = Button(self.frame, text='Live Dapi', command = self.liveDapi)
self.button66.pack(side=LEFT)
self.button16 = Button(self.frame, text='Live Green', command = self.liveGreen)
self.button16.pack(side=LEFT)
self.button30 = Button(self.frame, text='Live Red', command = self.liveRed)
self.button30.pack(side=LEFT)
self.button8 = Button(self.frame, text='Live BF', command = self.liveBF)
self.button8.pack(side=LEFT)
self.button87 = Button(self.frame, text='Live 647', command = self.live647)
self.button87.pack(side=LEFT)
# self.button17 = Button(self.frame, text='AF In Place', command = self.afInPlace)
# self.button17.pack(side=LEFT)
self.button18 = Button(self.frame, text='Snap', command = self.snap)
self.button18.pack(side=LEFT)
# self.button19 = Button(self.frame, text='ManualRetakesMag', command = self.manualRetakesMag)
# self.button19.pack(side=LEFT)
self.button20 = Button(self.frame, text='logHAF', command = self.logHAF)
self.button20.pack(side=LEFT)
self.button23 = Button(self.frame, text='HAF', command = self.logHAF)
self.button23.pack(side=LEFT)
self.button27 = Button(self.frame, text='ToggleNikonHAF', command = self.toggleNikonAutofocus)
self.button27.pack(side=LEFT)
self.button21 = Button(self.frame, text='ResetImagedSections', command = self.resetImagedSections)
self.button21.pack(side=LEFT)
self.button81 = Button(self.frame, text='getXYZ', command = self.logXYZ)
self.button81.pack(side=LEFT)
self.buttonQuit = Button(self.frame, text='Quit', command = root.destroy)
self.buttonQuit.pack(side=LEFT)
photo = ImageTk.PhotoImage(PIL.Image.fromarray(np.zeros((int(imageSize_px[0]), int(imageSize_px[1])))))
self.label = Label(master, image = photo)
self.label.image = photo # keep a reference?
self.label.pack()
# self.canvas = Canvas(master, width = imageSize_px[0], height = imageSize_px[1])
# self.imageCanvas = self.canvas.create_image(0, 0, image = photo)
# self.canvas.grid(row = 0, column = 0)
def snap(self):
if mmc.isSequenceRunning():
mmc.stopSequenceAcquisition()
takeImage(0, [0,0], folderSave, str(int(time.time())))
def north(self):
setXY(getXY()[0], getXY()[1] + stageInc)
def south(self):
setXY(getXY()[0], getXY()[1] - stageInc)
def east(self):
setXY(getXY()[0] - stageInc, getXY()[1])
def west(self):
setXY(getXY()[0] + stageInc, getXY()[1])
def acquireWaferButtonAction(self):
self.stopLive()
# # wafer.magSections = []
# # wafer.createMagSectionsFromPipeline()
# # self.frame.quit()
self.acquireWafer()
def resetGreenFocus(self):
wafer.targetMagFocus = []
def rbf(self):
rbf = Rbf(np.array(wafer.targetMagFocus).T[0], np.array(wafer.targetMagFocus).T[1], np.array(wafer.targetMagFocus).T[2], epsilon = 2, function = 'thin_plate')
wafer.targetMagCenters = np.array([np.array(wafer.targetMagCenters).T[0], np.array(wafer.targetMagCenters).T[1], rbf(np.array(wafer.targetMagCenters).T[0], np.array(wafer.targetMagCenters).T[1]) ]).T
logger.debug('rbf')
def plane(self):
wafer.targetMagCenters = focusThePoints(np.array(wafer.targetMagFocus).T, np.array(wafer.targetMagCenters).T).T
logger.debug('Plane')
def liveGrab(self):
logger.debug('Starting liveGrab ' + str(self.acquisitionInterval) )
if not mmc.isSequenceRunning():
mmc.startContinuousSequenceAcquisition(self.acquisitionInterval)
time.sleep(0.2)
currentChannel = getChannel()
logger.debug('** LIVEGRAB current channel ** ' + str(currentChannel))
try:
while self.live:
if (mmc.getRemainingImageCount() > 0):
lastImage = mmc.getLastImage()
if currentChannel == 'brightfield':
im = np.uint8(lastImage/256)
# im = mmc.getLastImage()
else:
# im = np.uint8(lastImage/256)
# im = np.uint8(lastImage/256 + 50)
im = lastImage
for x in range(crossLength):
for y in range(crossWidth):
im[imageSize_px[1]/2 - crossWidth/2 + y][imageSize_px[0]/2 - int(crossLength/2.) + x] = 0
for y in range(crossLength):
for x in range(crossWidth):
im[imageSize_px[1]/2 - int(crossLength/2.) + y ][imageSize_px[0]/2 - crossWidth/2 + x] = 0
else:
im = np.zeros((30, 30))
im = im[::2, ::2]
photo = ImageTk.PhotoImage(PIL.Image.fromarray(im))
self.label.configure(image=photo)
self.label.image = photo # keep a reference!
self.label.pack()
# self.canvas.itemconfig(self.imageCanvas, image = photo)
time.sleep(self.acquisitionInterval/50.)
except Exception, e:
logger.error('In liveGrab: ' + str(e))
logger.debug('liveGrab terminated')
def liveGreen(self):
# global live, liveThread
self.acquisitionInterval = acquisitionIntervalMag
self.live = True
self.liveThread = Thread(target = self.liveGrab)
##########################################
# # # Setting fluo conditions # # #
setChannel(488)
if mic == 'Z2':
setExposure(channels[488][5]['exposure']['live']['beads'])
elif mic == 'Leica' or mic == 'Nikon' or mic == 'NikonPeter':
setExposure(channels[488][currentObjectiveNumber]['exposure']['live']['general'])
mmc.setAutoShutter(False)
openShutter()
self.liveThread.start()
def liveRed(self):
# global live, liveThread
self.acquisitionInterval = acquisitionIntervalMag
self.live = True
self.liveThread = Thread(target = self.liveGrab)
##########################################
# # # Setting fluo conditions # # #
setChannel(546)
if mic == 'Z2':
setExposure(channels[546][5]['exposure']['live']['beads'])
elif mic == 'Leica' or mic == 'Nikon' or mic == 'NikonPeter':
setExposure(channels[546][currentObjectiveNumber]['exposure']['live']['general'])
mmc.setAutoShutter(False)
openShutter()
self.liveThread.start()
def live647(self):
# global live, liveThread
self.acquisitionInterval = acquisitionIntervalMag
self.live = True
self.liveThread = Thread(target = self.liveGrab)
##########################################
# # # Setting fluo conditions # # #
setChannel(647)
if mic == 'Z2':
setExposure(channels[546][5]['exposure']['live']['beads'])
elif mic == 'Leica' or mic == 'Nikon' or mic == 'NikonPeter':
setExposure(channels[546][currentObjectiveNumber]['exposure']['live']['general'])
mmc.setAutoShutter(False)
openShutter()
self.liveThread.start()
def liveDapi(self):
# global live, liveThread
self.acquisitionInterval = acquisitionIntervalMag
self.live = True
self.liveThread = Thread(target = self.liveGrab)
##########################################
# # # Setting fluo conditions # # #
setChannel('dapi')
if mic == 'Z2':
setExposure(channels['dapi'][5]['exposure']['live']['beads'])
elif mic == 'Leica' or mic == 'Nikon' or mic == 'NikonPeter':
setExposure(channels['dapi'][currentObjectiveNumber]['exposure']['live']['general'])
mmc.setAutoShutter(False)
openShutter()
self.liveThread.start()
def liveBF(self):
# global live, liveThread
self.acquisitionInterval = acquisitionIntervalMag
self.live = True
self.liveThread = Thread(target = self.liveGrab)
##########################################
# # # Setting fluo conditions # # #
setChannel('brightfield')
if mic == 'Z2':
setExposure(channels['brightfield'][5]['exposure']['live']['beads'])
elif mic == 'Leica' or mic == 'Nikon' or mic == 'NikonPeter':
setExposure(channels['brightfield'][currentObjectiveNumber]['exposure']['live']['general'])
mmc.setAutoShutter(False)
openShutter()
self.liveThread.start()
def stopLive(self):
self.live = False
time.sleep(0.2)
if mmc.isSequenceRunning():
mmc.stopSequenceAcquisition()
closeShutter()
# root.destroy() # no, it kills everything ...
def addLowResLandmark(self):
stageXY = getXY()
logger.info('wafer.targetLowResLandmarks --- before --- ' + str(wafer.targetLowResLandmarks))
wafer.targetLowResLandmarks.append([stageXY[0], stageXY[1], getZ()])
logger.info('wafer.targetLowResLandmarks --- after --- ' + str(wafer.targetLowResLandmarks))
nValidatedLandmarks = len(wafer.targetLowResLandmarks)
if nValidatedLandmarks == len(wafer.sourceLandmarks.T): # all target landmarks have been identified
logger.info('Good. All landmarks have been calibrated.')
wafer.save()
writePoints(os.path.join(wafer.pipelineFolder, 'target_lowres_landmarks.txt'), wafer.targetLowResLandmarks)
# # # # self.generateSections() # now done with the high res calibration
# # # # wafer.save()
elif nValidatedLandmarks > 1:
logger.info('There are still ' + str(len(wafer.sourceLandmarks[0]) - nValidatedLandmarks ) + ' landmarks to calibrate. The stage has been moved to the next landmark to be calibrated')
nextXY = affineT(wafer.sourceLandmarks, np.array(wafer.targetLowResLandmarks).T[:2], wafer.sourceLandmarks).T[nValidatedLandmarks]
logger.debug('Computing nextXY: wafer.sourceLandmarks - ' + str(wafer.sourceLandmarks) + ' np.array(wafer.targetLowResLandmarks).T[:2] - ' + str(np.array(wafer.targetLowResLandmarks).T[:2]) + ' nextXY = ' + str(nextXY))
setXY(*nextXY)
if nValidatedLandmarks > 3:
nextZ = focusThePoints(np.array(wafer.targetLowResLandmarks).T, np.array([[nextXY[0]], [nextXY[1]]]))[2][0] # the interpolative plane is calculated on the fly
print 'nextZ', nextZ
setZ(nextZ)
else:
logger.info('Please go manually to the second landmark.')
def addHighResLandmark(self):
nHighRes = len(wafer.targetHighResLandmarks)
if nHighRes == 0:
setXY(*wafer.targetLowResLandmarks[0][:2])
logger.info('Just moved to first landmark. Adjust this first landmark position with high resolution')
wafer.targetHighResLandmarks.append('dummy')
elif wafer.targetHighResLandmarks[0] == 'dummy':
wafer.targetHighResLandmarks.pop()
stageXY = getXY()
wafer.targetHighResLandmarks.append([stageXY[0], stageXY[1], getZ()])
setXY(*wafer.targetLowResLandmarks[1][:2])
logger.info('First high res landmark calibrated. Just moved to the second low res landmark: please adjust it.')
elif nHighRes == len(wafer.targetLowResLandmarks):
logger.info('HighRes target wafers had already been calibrated. Reinitializing calibration ...')
wafer.targetHighResLandmarks = []
setXY(*wafer.targetLowResLandmarks[0][:2])
logger.info('Just moved to first landmark. Adjust this first landmark position with high resolution')
wafer.targetHighResLandmarks.append('dummy')
else:
stageXY = getXY()
wafer.targetHighResLandmarks.append([stageXY[0], stageXY[1], getZ()])
if not (len(wafer.targetHighResLandmarks) == len(wafer.targetLowResLandmarks)):
nextXY = affineT(wafer.sourceLandmarks, np.array(wafer.targetHighResLandmarks).T[:2], wafer.sourceLandmarks).T[len(wafer.targetHighResLandmarks)]
setXY(*nextXY)
logger.info(str(len(wafer.targetHighResLandmarks)) + ' high res landmarks calibrated.')
else:
logger.info('All high res landmarks calibrated. Generating all sections.')
wafer.save()
writePoints(os.path.join(wafer.pipelineFolder, 'target_highres_landmarks.txt'), wafer.targetHighResLandmarks)
self.generateSections()
wafer.save()
def resetWaferKeepTargetCalibration(self): # no need to make wafer glogal as it was already global, right ?
newWafer = Wafer(waferName, ip)
newWafer.targetLowResLandmarks = copy.deepcopy(wafer.targetLowResLandmarks)
newWafer.targetHighResLandmarks = copy.deepcopy(wafer.targetHighResLandmarks)
newWafer.targetMagFocus = copy.deepcopy(wafer.targetMagFocus)
newWafer.sourceLandmarks = copy.deepcopy(wafer.sourceLandmarks)
newWafer.sourceMagDescription = copy.deepcopy(wafer.sourceMagDescription)
newWafer.sourceSectionsMagCoordinates = copy.deepcopy(wafer.sourceSectionsMagCoordinates)
newWafer.sourceSectionsTissueCoordinates = copy.deepcopy(wafer.sourceSectionsTissueCoordinates)
newWafer.sourceTissueDescription = copy.deepcopy(wafer.sourceTissueDescription)
self = newWafer # wtf is that ?
self.createSections()
def addMosaicHere(self):
wafer.addCurrentPosition()
def generateSections(self):
wafer.createSections()
def acquireWafer(self):
self.stopLive()
wafer.acquire()
def loadWafer(self):
global wafer
waferPath = getPath('Select the wafer pickle file', startingFolder = folderSave)
f = open(waferPath, 'r')
wafer = pickle.load(f)
f.close()
for magSection in wafer.magSections:
magSection.localized = False
def saveWafer(self):
wafer.save()
# def manualRetakesMag(self):
# wafer.manualRetakes(mag = True)
def loadSectionsAndLandmarksFromPipeline(self):
pipelineFolder = getDirectory('Select the folder containing the sections and landmarks from the pipeline', startingFolder = folderSave)
wafer.pipelineFolder = pipelineFolder # needed to write the target landmark coordinates for later proper orientation
sourceSectionsMagPath = os.path.join(pipelineFolder, 'source_sections_mag.txt.')
sourceSectionsTissuePath = os.path.join(pipelineFolder, 'source_sections_tissue.txt.')
wafer.sourceSectionsMagCoordinates = readSectionCoordinates(sourceSectionsMagPath) # list of lists
wafer.sourceSectionsTissueCoordinates = readSectionCoordinates(sourceSectionsTissuePath) # list of lists
# # wafer.sourceSectionCenters = np.array([getCenter(np.array(sourceSectionTissueCoordinates).T) for sourceSectionTissueCoordinates in wafer.sourceSectionsCoordinates])
sourceTissueMagDescriptionPath = os.path.join(pipelineFolder, 'source_tissue_mag_description.txt.') # 2 sections: template tissue and template mag
if os.path.isfile(sourceTissueMagDescriptionPath):
wafer.sourceTissueDescription, wafer.sourceMagDescription= readSectionCoordinates(sourceTissueMagDescriptionPath)
else:
logger.warning('There is no source_tissue_mag_description')
sourceLandmarksPath = os.path.join(pipelineFolder, 'source_landmarks.txt.')
wafer.sourceLandmarks = readPoints(sourceLandmarksPath)
sourceROIDescriptionPath = os.path.join(pipelineFolder, 'source_ROI_description.txt')
if os.path.isfile(sourceROIDescriptionPath):
wafer.sourceROIDescription = readSectionCoordinates(sourceROIDescriptionPath)
else:
logger.warning('There is no source_ROI_description. The center of the section will be used.')
def magAcquireHAF(self):
self.stopLive()
wafer.magSections = []
wafer.createMagSectionsFromPipeline()
wafer.magAcquire()
def magAcquireManual(self):
self.stopLive()
if wafer.magSections == []:
wafer.magSections = []
wafer.createMagSectionsFromPipeline()
wafer.magAcquire(manualFocus = True)
self.liveGreen()
time.sleep(0.2)
self.liveGreen()
winsound.Beep(440,100)
def tissueAcquireHAF(self):
self.stopLive()
wafer.sections = []
wafer.createSectionsFromPipeline()
wafer.acquire()
def tissueAcquireHAFFromManualSections(self):
self.stopLive()
wafer.acquire(manualFocus = False)