-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMosaicPlanner.py
2422 lines (2065 loc) · 115 KB
/
MosaicPlanner.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
#===============================================================================
#
# License: GPL
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#===============================================================================
import os
import sys
import traceback
import time
import multiprocessing as mp
import pickle
import json
import wx
import numpy as np
import wx.lib.intctrl
import faulthandler
from pyqtgraph.Qt import QtCore, QtGui
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from zro import RemoteObject
import LiveMode
from PositionList import posList
from MyLasso import MyLasso
from MosaicImage import MosaicImage
from Transform import Transform,ChangeTransform
from imageSourceMM import imageSource
from MMPropertyBrowser import MMPropertyBrowser
from ASI_Control import ASI_AutoFocus
from FocusCorrectionPlaneWindow import FocusCorrectionPlaneWindow
from NavigationToolBarImproved import NavigationToolbar2Wx_improved as NavBarImproved
from Settings import (MosaicSettings, CameraSettings,SiftSettings,ChangeCameraSettings, ImageSettings,
ChangeImageMetadata, SmartSEMSettings, ChangeSEMSettings, ChannelSettings,
ChangeChannelSettings, ChangeSiftSettings, CorrSettings,ChangeCorrSettings,
ChangeZstackSettings, ZstackSettings, DirectorySettings, ChangeDirectorySettings)
from configobj import ConfigObj
from validate import Validator
import cv2 #MultiRibbons
from skimage.measure import block_reduce #MultiRibbons
from Snap import SnapView
from Retake import RetakeView
from LeicaAFCView import LeicaAFCView
from LeicaDMI import LeicaDMI
from SaveThread import file_save_process
import scipy.optimize as opt #softwarea-autofocus
from Tokens import STOP_TOKEN,BUBBLE_TOKEN
DEFAULT_SETTINGS_FILE = 'MosaicPlannerSettings.default.cfg'
SETTINGS_FILE = 'MosaicPlannerSettings.cfg'
SETTINGS_MODEL_FILE = 'MosaicPlannerSettingsModel.cfg'
import logging
logging.getLogger('MosaicPlanner').addHandler(logging.NullHandler())
class RemoteInterface(RemoteObject):
def __init__(self, rep_port, parent):
super(RemoteInterface, self).__init__(rep_port=rep_port)
print "Opening Remote Interface on port:{}".format(rep_port)
self.parent = parent
self.pause = False
def toggle_pause(self):
if self.pause is True:
self.pause = False
else:
self.pause = True
#import pdb; pdb.set_trace()
def _check_rep(self):
#import pdb; pdb.set_trace()
super(RemoteInterface, self)._check_rep()
def getStagePosition(self):
print "Getting stage position..."
#import pdb; pdb.set_trace()
stagePosition = self.parent.getStagePosition()
print "StagePosition:{}".format(stagePosition)
return stagePosition
def setStagePosition(self, incomingStagePosition):
print "setting new stage position to x:{}, y:{}".format(incomingStagePosition[0], incomingStagePosition[1])
self.parent.setStagePosition(incomingStagePosition[0], incomingStagePosition[1])
class MosaicToolbar(NavBarImproved):
"""A custom toolbar which adds buttons and to interact with a MosaicPanel
current installed buttons which, along with zoom/pan
are in "at most one of group can be selected mode":
selectnear: a cursor point
select: a lasso like icon
add: a cursor with a plus sign
selectone: a cursor with a number 1
selecttwo: a cursor with a number 2
installed Simple tool buttons:
deleteTool) calls self.canvas.OnDeleteSelected ID=ON_DELETE_SELECTED
corrTool: a button that calls self.canvas.on_corr_tool ID=ON_CORR
stepTool: a button that calls self.canvas.on_step_tool ID=ON_STEP
ffTool: a button that calls on_fastforward_tool ID=ON_FF
installed Toggle tool buttons:
gridTool: a toggled button that calls self.canvas.on_grid_tool with the ID=ON_GRID
rotateTool: a toggled button that calls self.canvas.on_rotate_tool with the ID=ON_ROTATE
THESE SHOULD PROBABLY BE CHANGED TO BE MORE MODULAR IN ITS EFFECT AND NOT ASSUME SOMETHING
ABOUT THE STRUCTURE OF self.canvas
a set of controls for setting the parameters of a mosaic (see class MosaicSettings)
the function getMosaicSettings will return an instance of MosaicSettings with the current settings from the controls
the function self.canvas.posList.set_mosaic_settings(self.getMosaicSettings) will be called when the mosaic settings are changed
the function self.canvas.posList.set_mosaic_visible(visible) will be called when the show? checkmark is click/unclick
THIS SHOULD BE CHANGED TO BE MORE MODULAR IN ITS EFFECT
note this will also call self.canvas.on_home_tool when the home button is pressed
"""
# Set up class attributes
ON_FIND = wx.NewId()
ON_SELECT = wx.NewId()
ON_NEWPOINT = wx.NewId()
ON_DELETE_SELECTED = wx.NewId()
#ON_CORR_LEFT = wx.NewId()
ON_STEP = wx.NewId()
ON_FF = wx.NewId()
ON_CORR = wx.NewId()
ON_FINETUNE = wx.NewId()
ON_GRID = wx.NewId()
ON_ROTATE = wx.NewId()
ON_REDRAW = wx.NewId()
ON_LIVE_MODE = wx.NewId()
MAGCHOICE = wx.NewId()
SHOWMAG = wx.NewId()
ON_ACQGRID = wx.NewId()
ON_RUN = wx.NewId()
ON_SNAP = wx.NewId()
ON_CROP = wx.NewId()
ON_RUN_MULTI = wx.NewId() #MultiRibbons
ON_SOFTWARE_AF = wx.NewId()
def __init__(self, plotCanvas):
"""
plotCanvas: an instance of MosaicPanel which has the correct features (see class doc)
"""
# call the init function of the class we inheriting from
NavBarImproved.__init__(self, plotCanvas)
wx.Log.SetLogLevel(0) # batman?
#import the icons
leftcorrBmp = wx.ArtProvider.GetBitmap(wx.ART_GO_BACK, wx.ART_TOOLBAR)
selectBmp = wx.Image('icons/lasso-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
addpointBmp = wx.Image('icons/add-icon.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
trashBmp = wx.Image('icons/delete-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
selectnearBmp = wx.Image('icons/cursor2-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
oneBmp = wx.Image('icons/one-icon.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
twoBmp = wx.Image('icons/two-icon.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
stepBmp = wx.Image('icons/step-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
corrBmp = wx.Image('icons/target-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
ffBmp = wx.Image('icons/ff-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
rotateBmp = wx.Image('icons/rotate-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
gridBmp = wx.Image('icons/grid-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
softwareAFbmp = wx.Image('icons/icons8-target-32.bmp', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
cameraBmp = wx.Image('icons/camera-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
mosaicBmp = wx.Image('icons/mosaic-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
carBmp = wx.Image('icons/car-icon.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
cropBmp = wx.Image('icons/new/crop.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
snapBmp = wx.Image('icons/new/snap.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
cameraBmp = wx.Image('icons/new/camera.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
liveBmp = wx.Image('icons/new/livemode.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
startBmp = wx.Image('icons/icons8-start-30.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
activateBmp = wx.Image('icons/activate-icon.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap()
#mosaicBmp = wx.Image('icons/new/mosaic_camera.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
# checkBmp = wx.Image('icons/new/1446777170_Check.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap() #MultiRibbons
self.DeleteTool(self.wx_ids['Subplots']) # batman - what is this? add comment above it?
#add the mutually exclusive/toggleable tools to the toolbar, see superclass for details on how function works
self.moveHereTool = self.add_user_tool('movehere',6,carBmp,True,'move scope here')
self.snapHereTool = self.add_user_tool('snaphere',7,cameraBmp,True,'move scope and snap image here')
self.snapPictureTool = self.add_user_tool('snappic',8,mosaicBmp,True,'take 3x3 mosaic on click')
self.selectNear = self.add_user_tool('selectnear',9,selectnearBmp,True,'Add Nearest Point to selection')
self.activateNear = self.add_user_tool('toggleactivate',10,activateBmp,True,'Toggle Activation of nearest point to selection, \n'
'Hold shift to activate/deactivate frame,\n'
'Hold T to activate/deactivate all frames,\n'
'Hold R to acttivate/deactivate same frame in all sections,\n'
'Hold F to toggle software autofocus on frame,\n'
'Hold C to toggle software autofocus on same frame in all sections,\n'
'Hold I to set inital frame in all sections,\n'
'Hold L to designate initial frame')
self.addTool = self.add_user_tool('add', 11, addpointBmp, True, 'Add a Point')
self.oneTool = self.add_user_tool('selectone', 12, oneBmp, True, 'Choose pointLine2D 1')
self.twoTool = self.add_user_tool('selecttwo', 13, twoBmp, True, 'Choose pointLine2D 2')
self.AddSeparator()
self.AddSeparator() # batman - why called twice, why called at all!, maybe add comment?
#add the simple button click tools
self.liveModeTool = self.AddSimpleTool(self.ON_LIVE_MODE,liveBmp,'Enter Live Mode','liveMode')
self.softwareAFTool = self.AddSimpleTool(self.ON_SOFTWARE_AF, softwareAFbmp, 'Execute Software AutoFocus','softwareAF')
self.deleteTool = self.AddSimpleTool(self.ON_DELETE_SELECTED,trashBmp,'Delete selected points','delete points')
self.corrTool = self.AddSimpleTool(self.ON_CORR,corrBmp,'Ajdust pointLine2D 2 with correlation','corrTool')
self.stepTool = self.AddSimpleTool(self.ON_STEP,stepBmp,'Take one step using points 1+2','stepTool')
self.ffTool = self.AddSimpleTool(self.ON_FF,ffBmp,'Auto-take steps till C<.3 or off image','fastforwardTool')
self.snapNowTool = self.AddSimpleTool(self.ON_SNAP,snapBmp,'Take a snap now','snapHereTool')
self.onCropTool = self.AddSimpleTool(self.ON_CROP,cropBmp,'Crop field of view','cropTool')
#add the toggleable tools
self.gridTool=self.AddCheckTool(self.ON_GRID,gridBmp,wx.NullBitmap,'toggle show frames')
self.rotateTool=self.AddCheckTool(self.ON_ROTATE,rotateBmp,wx.NullBitmap,'toggle rotate boxes')
self.runAcqTool=self.AddSimpleTool(self.ON_RUN,startBmp,'Acquire AT Data','run_tool')
# self.runMultiAcqTool=self.AddSimpleTool(self.ON_RUN_MULTI,checkBmp,'MultiRibbons','run_multi_tool') #MultiRibbons
#setup the controls for the mosaic
self.showMosaicCheck = wx.CheckBox(self)
self.showMosaicCheck.SetValue(True)
self.magChoiceCtrl = wx.lib.agw.floatspin.FloatSpin(self,
size=(65, -1 ),
value=self.canvas.posList.mosaic_settings.mag,
min_val=0,
increment=.1,
digits=2,
name='magnification')
self.mosaicXCtrl = wx.lib.intctrl.IntCtrl(self, value=1, size=(20, -1))
self.mosaicYCtrl = wx.lib.intctrl.IntCtrl(self, value=1, size=(20, -1))
self.overlapCtrl = wx.lib.intctrl.IntCtrl(self, value=20, size=(25, -1))
#setup the controls for the min/max slider
minstart=0
maxstart=500
self.slider = wx.Slider(self,value=250,minValue=minstart,maxValue=maxstart,size=( 180, -1),style = wx.SL_SELRANGE)
self.sliderMaxCtrl = wx.lib.intctrl.IntCtrl( self, value=maxstart,size=( 60, -1 ))
#add the control for the mosaic
self.AddControl(wx.StaticText(self,label="Show Mosaic"))
self.AddControl(self.showMosaicCheck)
self.AddControl(wx.StaticText(self,label="Mag"))
self.AddControl( self.magChoiceCtrl)
self.AddControl(wx.StaticText(self,label="MosaicX"))
self.AddControl(self.mosaicXCtrl)
self.AddControl(wx.StaticText(self,label="MosaicY"))
self.AddControl(self.mosaicYCtrl)
self.AddControl(wx.StaticText(self,label="%Overlap"))
self.AddControl(self.overlapCtrl)
self.AddSeparator()
self.AddControl(self.slider)
self.AddControl(self.sliderMaxCtrl)
#bind event handles for the various tools
#this one i think is inherited... the zoom_tool function (- batman, resolution to thinking?)
self.Bind(wx.EVT_TOOL, self.on_toggle_pan_zoom, self.zoom_tool)
self.Bind(wx.EVT_CHECKBOX,self.toggle_mosaic_visible,self.showMosaicCheck)
self.Bind( wx.lib.agw.floatspin.EVT_FLOATSPIN,self.update_mosaic_settings, self.magChoiceCtrl)
self.Bind(wx.lib.intctrl.EVT_INT,self.update_mosaic_settings, self.mosaicXCtrl)
self.Bind(wx.lib.intctrl.EVT_INT,self.update_mosaic_settings, self.mosaicYCtrl)
self.Bind(wx.lib.intctrl.EVT_INT,self.update_mosaic_settings, self.overlapCtrl)
#event binding for slider
self.Bind(wx.EVT_SCROLL_THUMBRELEASE,self.canvas.on_slider_change,self.slider)
self.Bind(wx.lib.intctrl.EVT_INT,self.updateSliderRange, self.sliderMaxCtrl)
wx.EVT_TOOL(self, self.ON_LIVE_MODE, self.canvas.on_live_mode)
wx.EVT_TOOL(self, self.ON_DELETE_SELECTED, self.canvas.on_delete_points)
wx.EVT_TOOL(self, self.ON_CORR, self.canvas.on_corr_tool)
wx.EVT_TOOL(self, self.ON_STEP, self.canvas.on_step_tool)
wx.EVT_TOOL(self, self.ON_RUN, self.canvas.on_run_acq)
wx.EVT_TOOL(self, self.ON_FF, self.canvas.on_fastforward_tool)
wx.EVT_TOOL(self, self.ON_GRID, self.canvas.on_grid_tool)
wx.EVT_TOOL(self, self.ON_ROTATE, self.canvas.on_rotate_tool)
wx.EVT_TOOL(self, self.ON_SNAP, self.canvas.on_snap_tool)
wx.EVT_TOOL(self, self.ON_CROP, self.canvas.on_crop_tool)
# wx.EVT_TOOL(self, self.ON_RUN_MULTI, self.canvas.on_run_multi_acq)
wx.EVT_TOOL(self, self.ON_SOFTWARE_AF, self.canvas.on_software_af_tool)
self.Realize()
def update_mosaic_settings(self, evt=""):
""""update the mosaic_settings variables of the canvas and the posList of the canvas and redraw
set_mosaic_settings should take care of what is necessary to replot the mosaic"""
self.canvas.posList.set_mosaic_settings(self.get_mosaic_parameters())
self.canvas.mosaic_settings = self.get_mosaic_parameters()
self.canvas.draw()
def updateSliderRange(self, evt=""):
#self.set_slider_min(self.sliderMinCtrl.GetValue())
self.set_slider_max(self.sliderMaxCtrl.GetValue())
def toggle_mosaic_visible(self, evt=""):
"""call the set_mosaic_visible function of self.canvas.posList to initiate what is necessary to hide the mosaic box"""
self.canvas.posList.set_mosaic_visible(self.showMosaicCheck.IsChecked())
self.canvas.draw()
def get_mosaic_parameters(self):
"""extract out an instance of MosaicSettings from the current controls with the proper values"""
return MosaicSettings(mag=self.magChoiceCtrl.GetValue(),
show_box=self.showMosaicCheck.IsChecked(),
mx=self.mosaicXCtrl.GetValue(),
my=self.mosaicYCtrl.GetValue(),
overlap=self.overlapCtrl.GetValue())
def set_mosaic_parameters(self,mosaic_settings):
self.magChoiceCtrl.SetValue(mosaic_settings.mag)
self.mosaicXCtrl.SetValue(mosaic_settings.mx)
self.mosaicYCtrl.SetValue(mosaic_settings.my)
self.overlapCtrl.SetValue(mosaic_settings.overlap)
self.showMosaicCheck.SetValue(mosaic_settings.show_box)
def cross_cursor(self, event):
self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
#overrides the default
def home(self, event):
"""calls self.canvas.on_home_tool(), should be triggered by the hometool press.. overrides default behavior"""
self.canvas.on_home_tool()
def set_slider_min(self, min=0):
self.slider.SetMin(min)
def set_slider_max(self, max=500):
self.slider.SetMax(max)
class MosaicPanel(FigureCanvas):
"""A panel that extends the matplotlib class FigureCanvas for plotting all the plots, and handling all the GUI interface events
"""
def __init__(self, parent, config, **kwargs):
"""keyword the same as standard init function for a FigureCanvas"""
self.figure = Figure(figsize=(5, 9))
FigureCanvas.__init__(self, parent, -1, self.figure, **kwargs)
self.canvas = self.figure.canvas
# set up the remote interface
self.interface = RemoteInterface(rep_port=7777, parent=self)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self._check_sock, self.timer)
self.timer.Start(200)
#format the appearance
self.figure.set_facecolor((1, 1, 1))
self.figure.set_edgecolor((1, 1, 1))
self.canvas.SetBackgroundColour('white')
#add subplots for various things
self.subplot = self.figure.add_axes([.05, .5, .92, .5])
self.posone_plot = self.figure.add_axes([.1, .025, .2, .4])
self.postwo_plot = self.figure.add_axes([.37, .025, .2, .4])
self.corrplot = self.figure.add_axes([.65, .025, .25, .4])
print 'pos2 plot position:', self.postwo_plot.get_position()
#initialize the camera settings and mosaic settings
self.cfg = config
self.camera_settings = CameraSettings()
self.camera_settings.load_settings(config)
mosaic_settings = MosaicSettings()
mosaic_settings.load_settings(config)
self.MM_config_file = self.cfg['MosaicPlanner']['MM_config_file']
print self.MM_config_file
#setup the image source
self.imgSrc=None
while self.imgSrc is None:
try:
if self.cfg['MosaicPlanner']['demoMode']:
from imageSourceDemo import imageSource
print 'demo'
else:
from imageSourceMM import imageSource
self.imgSrc=imageSource(self.MM_config_file,
MasterArduinoPort=self.cfg['MMArduino']['port'],
interframe_time=self.cfg['MMArduino']['interframe_time'],
filtswitch = self.cfg['MosaicPlanner']['filter_switch'])
except:
traceback.print_exc(file=sys.stdout)
dlg = wx.MessageBox("Error Loading Micromanager\n check scope and re-select config file","MM Error")
self.edit_MManager_config()
channels=self.imgSrc.get_channels()
self.channel_settings=ChannelSettings(self.imgSrc.get_channels())
self.channel_settings.load_settings(config)
self.imgSrc.set_channel(self.channel_settings.map_chan)
map_chan=self.channel_settings.map_chan
if map_chan not in channels: #if the saved settings don't match, call up dialog
self.edit_channels()
map_chan=self.channel_settings.map_chan
self.imgSrc.set_channel(map_chan)
self.imgSrc.set_exposure(self.channel_settings.exposure_times[map_chan])
#load the SIFT settings
self.SiftSettings = SiftSettings()
self.SiftSettings.load_settings(config)
self.CorrSettings = CorrSettings()
self.CorrSettings.load_settings(config)
# load directory settings
self.output_dir = self.startnewproject(config)
print self.output_dir
# self.cfg['MosaicPlanner']['default_outdir'] = self.output_dir
# self.outdirdict = {}
# self.multiribbon_boolean = self.askMultiribbons()
# if not self.multiribbon_boolean:
# self.Ribbon_Num = 1
# self.directory_settings = DirectorySettings()
# self.directory_settings.load_settings(config)
# self.edit_Directory_settings()
# dictvalue = self.get_output_dir(self.directory_settings)
# if dictvalue == None:
# print "line 382"
# goahead = False
# while goahead == False:
# self.edit_Directory_settings()
# print "line 385"
# dictvalue = self.get_output_dir(self.directory_settings)
# if dictvalue != None:
# goahead = True
#
# print 'Sample_ID:', self.directory_settings.Sample_ID
# print 'Ribbon_ID:', self.directory_settings.Ribbon_ID
# print 'Session_ID:', self.directory_settings.Session_ID
# print 'Map Number:', self.directory_settings.Map_num
# self.directory_settings.save_settings(config)
# self.outdirdict['Slot' + str(self.directory_settings.Slot_num)] = dictvalue
# self.directory_settings.create_directory(config,kind='map')
#
# else:
# self.Ribbon_Num = self.get_ribbon_number()
# self.directory_settings = DirectorySettings()
# self.directory_settings.load_settings(config)
# for i in range(self.Ribbon_Num):
# self.edit_Directory_settings()
# dictvalue = self.get_output_dir(self.directory_settings)
# if dictvalue == None:
# print "line 405"
# goahead = False
# while goahead == False:
# self.edit_Directory_settings()
# dictvalue = self.get_output_dir(self.directory_settings)
# if dictvalue != None:
# goahead = True
# self.outdirdict['Slot' + str(self.directory_settings.Slot_num)] = dictvalue
# self.directory_settings.save_settings(config)
# self.directory_settings.create_directory(config, kind= 'map')
#
# for key,value in self.outdirdict.iteritems():
# print "Output directory:",key,value
# print self.directory_settings
# load Zstack settings
self.zstack_settings = ZstackSettings()
self.zstack_settings.load_settings(config)
self.snapView = None
self.retakeView = None
#setup a blank position list
self.posList=posList(self.subplot,mosaic_settings,self.camera_settings)
#start with no MosaicImage
self.mosaicImage=None
#start with relative_motion on, so that keypress calls shift_selected_curved() of posList
self.relative_motion = True
self.focusCorrectionList = posList(self.subplot)
#read saved position list from configuration file
pos_list_string = self.cfg['MosaicPlanner']['focal_pos_list_pickle']
#if the saved list is not default blank.. add it to current list
print "pos_list",pos_list_string
if len(pos_list_string)>0:
print "loading saved position list"
pl = pickle.loads(pos_list_string)
self.focusCorrectionList.add_from_posList(pl)
x,y,z = self.focusCorrectionList.getXYZ()
if len(x)>2:
XYZ = np.column_stack((x,y,z))
self.imgSrc.define_focal_plane(np.transpose(XYZ))
#start with no toolbar and no lasso tool
self.navtoolbar = None
self.lasso = None
self.lassoLock=False
self.canvas.mpl_connect('button_press_event', self.on_press)
self.canvas.mpl_connect('button_release_event', self.on_release)
self.canvas.mpl_connect('key_press_event', self.on_key)
self.slacker = None
if len(self.cfg['LeicaDMI']['port']) > 0:
self.dmi = LeicaDMI(self.cfg['LeicaDMI']['port'])
else:
self.dmi = None
def _check_sock(self, event):
self.interface._check_rep()
def createnewproject(self, event = 'none'):
config = self.cfg
goahead = self.asknewproject()
if goahead:
self.posList.select_all()
self.posList.delete_selected()
self.subplot.cla()
self.corrplot.cla()
self.posone_plot.cla()
self.postwo_plot.cla()
self.output_dir = self.startnewproject(config)
def asknewproject(self):
dlg = wx.MessageDialog(self,message = "Are you sure you want to start a new project? Progress will not be saved.",style = wx.YES|wx.NO)
button_pressed = dlg.ShowModal()
if button_pressed == wx.ID_YES:
return True
else:
return False
def startnewproject(self,config):
self.directory_settings = DirectorySettings()
self.directory_settings.load_settings(config)
self.edit_Directory_settings()
outdir = self.get_output_dir(self.directory_settings)
if outdir == None:
print "line 382"
goahead = False
while goahead == False:
self.edit_Directory_settings()
print "line 385"
dictvalue = self.get_output_dir(self.directory_settings)
if dictvalue != None:
goahead = True
print 'Sample_ID:', self.directory_settings.Sample_ID
print 'Ribbon_ID:', self.directory_settings.Ribbon_ID
print 'Session_ID:', self.directory_settings.Session_ID
print 'Map Number:', self.directory_settings.Map_num
self.directory_settings.save_settings(config)
self.cfg['MosaicPlanner']['default_outdir'] = outdir
self.directory_settings.create_directory(config,kind='map')
return outdir
def edit_Directory_settings(self,event="none"):
dlg = ChangeDirectorySettings(None,-1,title = u"Enter Sample Information",style = wx.OK,settings=self.directory_settings)
ret = dlg.ShowModal()
if ret == wx.ID_OK:
self.directory_settings = dlg.get_settings()
self.directory_settings.save_settings(self.cfg)
if ret == wx.ID_CANCEL:
self.edit_Directory_settings()
dlg.Destroy()
def askMultiribbons(self):
dlg = wx.MessageDialog(self,message = "Are you imaging multiple ribbons?",style = wx.YES|wx.NO)
button_pressed = dlg.ShowModal()
if button_pressed == wx.ID_YES:
return True
else:
return False
def get_ribbon_number(self):
dlg = RibbonNumberDialog(None,-1,style = wx.ID_OK)
dlg.ShowModal()
Ribbon_Num = dlg.GetValue()
dlg.Destroy()
return Ribbon_Num
def handle_close(self,evt=None):
print "handling close"
#if not self.mosaicImage == None:
# self.mosaicImage.cursor_timer.cancel()
self.imgSrc.stopSequenceAcquisition()
self.imgSrc.shutdown()
def on_load(self,rootPath):
self.rootPath = rootPath
os.path.join(rootPath)
print "transpose toggle state",self.imgSrc.transpose_xy
self.mosaicImage=MosaicImage(self.subplot,self.posone_plot,self.postwo_plot,self.corrplot,self.imgSrc,rootPath,figure=self.figure)
self.on_crop_tool()
self.draw()
def write_slice_metadata(self,filename,ch,xpos,ypos,zpos):
f = open(filename, 'w')
channelname=self.channel_settings.prot_names[ch]
(height,width)=self.imgSrc.get_sensor_size()
ScaleFactorX=self.imgSrc.get_pixel_size()
ScaleFactorY=self.imgSrc.get_pixel_size()
exp_time=self.channel_settings.exposure_times[ch]
f.write("Channel\tWidth\tHeight\tMosaicX\tMosaicY\tScaleX\tScaleY\tExposureTime\n")
f.write("%s\t%d\t%d\t%d\t%d\t%f\t%f\t%f\n" % \
(channelname, width, height, 1, 1, ScaleFactorX, ScaleFactorY, exp_time))
f.write("XPositions\tYPositions\tFocusPositions\n")
f.write("%s\t%s\t%s\n" %(xpos, ypos, zpos))
def write_session_metadata(self,outdir):
filename=os.path.join(outdir,'session_metadata.txt')
f = open(filename, 'w')
(height,width)=self.imgSrc.get_sensor_size()
Nch=0
for k,ch in enumerate(self.channel_settings.channels):
if self.channel_settings.usechannels[ch]:
Nch+=1
f.write("Width\tHeight\t#chan\tMosaicX\tMosaicY\tScaleX\tScaleY\n")
f.write("%d\t%d\t%d\t%d\t%d\t%f\t%f\n" % (width,height, Nch,self.posList.mosaic_settings.mx, self.posList.mosaic_settings.my, self.imgSrc.get_pixel_size(), self.imgSrc.get_pixel_size()))
f.write("Channel\tExposure Times (msec)\tRLPosition\n")
for k,ch in enumerate(self.channel_settings.channels):
if self.channel_settings.usechannels[ch]:
f.write(self.channel_settings.prot_names[ch] + "\t" + "%f\t%s\n" % (self.channel_settings.exposure_times[ch],ch))
f.write("Imaged on:" + "\t" + self.cfg['MosaicPlanner']['microscope_name'])
def write_session_metadata_json(self,outdir):
height, width = self.imgSrc.get_sensor_size()
length = len(self.posList.slicePositions)
numchan = 0
channel_list = []
for k,ch in enumerate(self.channel_settings.channels):
if self.channel_settings.usechannels[ch]:
numchan += 1
channel_dict = {'RLPosition': ch,
'exposture_times' : self.channel_settings.exposure_times[ch],
'channel' : self.channel_settings.prot_names[ch]}
channel_list.append(channel_dict)
scalex = self.imgSrc.get_pixel_size()
scaley = self.imgSrc.get_pixel_size()
mosaicX = self.posList.mosaic_settings.mx
mosaicY = self.posList.mosaic_settings.my
scope_name = self.cfg['MosaicPlanner']['microscope_name']
session_num = self.cfg['Directories']['Session_ID']
owner = self.cfg['Directories']['meta_experiment_name'] #will change meta_experiment_name to owner
project = self.cfg['Directories']['Sample_ID']
timer = time.time()
metadata_dict = {'Height' : height,
'Width' : width,
'#chan' : numchan,
'all_channels' : channel_list,
'Mosaicx' : mosaicX,
'MosaicY' : mosaicY,
'ScaleX' : scalex,
'ScaleY': scaley,
'scope' : scope_name,
'session' : session_num,
'ribbon_length' : length,
'frame_number' : length*mosaicX*mosaicY,
'owner' : owner,
'project' : project,
'Time' : timer}
thestring = json.JSONEncoder().encode(metadata_dict)
# thestring = json.dumps(metadata_dict)
filename = os.path.join(outdir, 'session_metadata.json')
f = open(filename, 'w')
f.write(thestring)
f.close()
def autofocus_loop(self,hold_focus,wait,sleep):
attempts=0
if self.imgSrc.has_hardware_autofocus():
#wait till autofocus settles
time.sleep(wait)
while not self.imgSrc.is_hardware_autofocus_done():
time.sleep(sleep)
attempts+=1
if attempts>50:
print "not auto-focusing correctly.. giving up after 10 seconds"
break
if not hold_focus:
self.imgSrc.set_hardware_autofocus_state(False) #turn off autofocus
else:
score=self.imgSrc.image_based_autofocus(chan=self.channel_settings.map_chan)
print score
def multiDacq(self,success,outdir,chrome_correction,autofocus_trigger,triggerflag,x,y,current_z,slice_index,frame_index=0,hold_focus = False):
#print datetime.datetime.now().time()," starting multiDAcq, autofocus on"
if not hold_focus:
if self.imgSrc.has_hardware_autofocus():
self.imgSrc.set_hardware_autofocus_state(True)
#print datetime.datetime.now().time()," starting stage move"
self.imgSrc.move_stage(x,y)
if autofocus_trigger:
self.software_autofocus(acquisition_boolean=True)
stagexy = self.imgSrc.get_xy()
wx.Yield()
self.autofocus_loop(hold_focus,self.cfg['MosaicPlanner']['autofocus_wait'],self.cfg['MosaicPlanner']['autofocus_sleep'])
if self.cfg['MosaicPlanner']['do_second_autofocus_wait']:
self.autofocus_loop(hold_focus,self.cfg['MosaicPlanner']['second_autofocus_wait'],self.cfg['MosaicPlanner']['autofocus_sleep'])
if (self.dmi is not None) & (self.cfg['LeicaDMI']['take_afc_image']):
afc_image = self.dmi.get_AFC_image()
self.dmi.set_AFC_hold(True)
else:
afc_image = None
#print datetime.datetime.now().time()," starting multichannel acq"
current_z = self.imgSrc.get_z()
presentZ = current_z
#print 'flag is,',self.zstack_settings.zstack_flag
if self.zstack_settings.zstack_flag:
furthest_distance = self.zstack_settings.zstack_delta * (self.zstack_settings.zstack_number-1)/2
#furthest_distance =0
zplanes_to_visit = [(current_z-furthest_distance) + i*self.zstack_settings.zstack_delta for i in range(self.zstack_settings.zstack_number)]
else:
zplanes_to_visit = [current_z]
#print 'zplanes_to_visit : ',zplanes_to_visit
# num_chan, chrom_correction = self.summarize_channel_settings()
for k,ch in enumerate(self.channel_settings.channels):
if self.channel_settings.usechannels[ch]:
last_channel = ch
def software_acquire(presentZ):
# currZ=self.imgSrc.get_z()
# presentZ = currZ
for z_index, zplane in enumerate(zplanes_to_visit):
for k,ch in enumerate(self.channel_settings.channels):
# print datetime.datetime.now().time()," start channel",ch, " zplane", zplane
prot_name=self.channel_settings.prot_names[ch]
print prot_name
path=os.path.join(outdir,prot_name)
if self.channel_settings.usechannels[ch]:
#ti = time.clock()*1000
print time.clock(),'start'
if not hold_focus:
z = zplane + self.channel_settings.zoffsets[ch]
if not z == presentZ:
self.imgSrc.set_z(z)
z = presentZ
z = presentZ
self.imgSrc.set_exposure(self.channel_settings.exposure_times[ch])
self.imgSrc.set_channel(ch)
#t2 = time.clock()*1000
#print time.clock(),t2-ti, 'ms to get to snap image from start'
data=self.imgSrc.snap_image()
#t3 = time.clock()*1000
#print time.clock(),t3-t2, 'ms to snap image'
if ch == self.cfg['ChannelSettings']['focusscore_chan']:
calcFocus = True
else:
calcFocus = False
if ch is not last_channel:
self.dataQueue.put((slice_index,frame_index, z_index, prot_name,path,data,ch,stagexy[0],stagexy[1],z,False,calcFocus,None))
else:
self.dataQueue.put((slice_index,frame_index, z_index, prot_name,path,data,ch,stagexy[0],stagexy[1],z,triggerflag,calcFocus,afc_image))
def hardware_acquire(z=presentZ):
# currZ=self.imgSrc.get_z()
# presentZ = currZ
for z_index, zplane in enumerate(zplanes_to_visit):
z = zplane
if not hold_focus:
if not z == presentZ:
self.imgSrc.set_z(z)
presentZ = z
self.imgSrc.startHardwareSequence()
for k,ch in enumerate(self.channel_settings.channels):
#print datetime.datetime.now().time()," start channel",ch, " zplane", zplane
prot_name=self.channel_settings.prot_names[ch]
path=os.path.join(outdir,prot_name)
if self.channel_settings.usechannels[ch]:
data = self.imgSrc.get_image()
if ch == self.cfg['ChannelSettings']['focusscore_chan']:
calcFocus = True
else:
calcFocus = False
if ch is not last_channel:
self.dataQueue.put((slice_index,frame_index, z_index, prot_name,path,data,ch,stagexy[0],stagexy[1],z,False,calcFocus,None))
else:
self.dataQueue.put((slice_index,frame_index, z_index, prot_name,path,data,ch,stagexy[0],stagexy[1],z,triggerflag,calcFocus,afc_image))
if self.cfg['MosaicPlanner']['autofocus_toggle']:
print 'toggle autofocus'
self.imgSrc.set_hardware_autofocus_state(False,False)
if (self.cfg['MosaicPlanner']['hardware_trigger'] == True) and (chrome_correction == False) and (success != False) and (self.zstack_settings.zstack_flag == False):
hardware_acquire()
else:
software_acquire(presentZ)
if self.cfg['MosaicPlanner']['autofocus_toggle']:
self.imgSrc.set_hardware_autofocus_state(True,True)
if not hold_focus:
self.imgSrc.set_z(current_z)
if self.imgSrc.has_hardware_autofocus():
self.imgSrc.set_hardware_autofocus_state(True)
#self.imgSrc.set_hardware_autofocus_state(True)
def ResetPiezo(self):
do_stage_reset=self.cfg['StageResetSettings']['enableStageReset']
if do_stage_reset:
self.imgSrc.reset_piezo(self.cfg['StageResetSettings'])
def summarize_stage_settings(self):
do_stage_reset = self.cfg['StageResetSettings']['enableStageReset']
comp_stage = self.cfg['StageResetSettings']['compensationStage']
reset_stage = self.cfg['StageResetSettings']['resetStage']
min_threshold = self.cfg['StageResetSettings']['minThreshold']
max_threshold = self.cfg['StageResetSettings']['maxThreshold']
reset_position = self.cfg['StageResetSettings']['resetPosition']
invert_compensation = self.cfg['StageResetSettings']['invertCompensation']
Stage_Settings_Summary = {'Reset_enabled?' : do_stage_reset,
'Compensation Stage' : comp_stage,
'Reset Stage' : reset_stage,
'Reset Pos' : reset_position,
'Min' : min_threshold,
'Max' : max_threshold,
'Invert Comp' : invert_compensation}
return Stage_Settings_Summary
def summarize_channel_settings(self):
numchan = 0
chrom_correction = False
for ch in self.channel_settings.channels:
if self.channel_settings.usechannels[ch]:
numchan+=1
if (self.channel_settings.zoffsets[ch] != 0.0):
chrom_correction = True
return numchan,chrom_correction
def summarize_autofocus_settings(self):
auto_sleep = self.cfg['Mosaic Planner']['autofocus_sleep']
auto_wait = self.cfg['Mosaic Planner']['autofocus_wait']
Autofocus_settings = {'Sleep' : auto_sleep,
'Wait' : auto_wait}
return Autofocus_settings
def move_safe_to_start(self):
#step the stage back to the first position, position by position
#so as to not lose the immersion oil
(x,y)=self.imgSrc.get_xy()
currpos=self.posList.get_position_nearest(x,y)
#turn on autofocus
self.imgSrc.set_hardware_autofocus_state(True)
while currpos is not None:
self.ResetPiezo()
self.imgSrc.move_stage(currpos.x,currpos.y)
currpos=self.posList.get_prev_pos(currpos)
if currpos is not None:
if not currpos.activated:
break
wx.Yield()
def setup_progress_bar(self):
hasFrameList = self.posList.slicePositions[0].frameList is not None
numSections = len(self.posList.slicePositions)
if hasFrameList:
numFrames = len(self.posList.slicePositions[0].frameList.slicePositions)
else:
numFrames = 1
maxProgress = numSections*numFrames
self.progress = wx.ProgressDialog("A progress box", "Time remaining", maxProgress ,
style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
return numFrames,numSections
def get_output_dir(self,directory_settings):
assert(isinstance(directory_settings,DirectorySettings))
#gets output directory for session
cfg = self.cfg
path = directory_settings.create_directory(cfg,kind = 'data')
if path is not None:
dlg=wx.DirDialog(self, message="Pick output directory", defaultPath=path)
button_pressed = dlg.ShowModal()
if button_pressed == wx.ID_CANCEL:
wx.MessageBox("You didn't enter a save directory... \n Aborting acquisition")
return None
outdir = dlg.GetPath()
dlg.Destroy()
return outdir
else:
return None
def make_channel_directories(self,outdir):
#setup output directories
for k,ch in enumerate(self.channel_settings.channels):
if self.channel_settings.usechannels[ch]:
thedir=os.path.join(outdir,self.channel_settings.prot_names[ch])
if not os.path.isdir(thedir):
os.makedirs(thedir)
# def show_summary_dialog(self):
# binning=self.imgSrc.get_binning()
# caption = "about to capture %d sections, binning is %dx%d, numchannel is %d"%(len(self.posList.slicePositions),binning,binning,numchan)
# dlg = wx.MessageDialog(self,message=caption, style = wx.OK|wx.CANCEL)
# button_pressed = dlg.ShowModal()
# if button_pressed == wx.ID_CANCEL:
# return False
def slack_notify(self,message,notify=False):
if self.slacker is not None:
microscope = self.cfg['MosaicPlanner']['microscope_name']
if 'Jarvis'in microscope:
message="Ironman be aware: "+message
if 'Rosie' in microscope:
message="George!: "+message
if 'Igor' in microscope:
message="mmm Dr. Frankenstein...: "+message
if notify:
message=self.cfg['Slack']['notify_list']
self.slacker.chat.post_message(self.cfg['Slack']['slack_room'],'{} says: {}'.format(microscope,message))
def lookup_mountpoint(self,outdir):
drive,tail = os.path.splitdrive(outdir)
mountfile = os.path.join(drive,'mountpoint','mountpoint.json')
with open(mountfile,'r') as fp:
d=json.load(fp)
return d['mountpoint']
def get_initial_position(self,position):
for i in range(len(position.frameList.slicePositions)):
framepos = position.frameList.slicePositions[i]
if framepos.initial_trigger == True:
frameposx = framepos.x
frameposy = framepos.y
return [frameposx, frameposy]
elif i == (len(position.frameList.slicePositions)-1):
return None
else:
pass
def move_to_initial_and_focus(self,x,y):
self.imgSrc.move_stage(x,y)
stg = self.imgSrc.mmc.getXYStageDevice()
self.imgSrc.mmc.waitForDevice(stg)
# self.imgSrc.stop_hardware_triggering()
self.software_autofocus(acquisition_boolean= True)
# self.imgSrc.setup_hardware_triggering(channels,exp_times)
def on_run_acq(self,event="none"):
print "running"
from SetupAlerts import SetupAlertDialog
#dlg = SetupAlertDialog(self.cfg['smtp'])
#dlg.setModal(True)
#dlg.show()
#alert_settings = dlg.getSettings()
#self.channel_settings
#self.pos_list