Beispiel #1
0
class AlignRotationCenterDialog(wx.Dialog):
        def __init__(self, parent):
                self.node = parent.node

                wx.Dialog.__init__(self, parent, -1, 'Align Rotation Center')

                self.measure = wx.Button(self, -1, 'Align')
                self.Bind(wx.EVT_BUTTON, self.onMeasureButton, self.measure)

                szbutton = wx.GridBagSizer(5, 5)
                szbutton.Add(self.measure, (0, 0), (1, 1), wx.EXPAND)

                sbsz = wx.GridBagSizer(5, 5)

                label = wx.StaticText(self, -1, 'Defocus 1:')
                self.d1value = FloatEntry(self, -1, allownone=False, chars=5, value='-2e-6')
                sbsz.Add(label, (0,0), (1,1))
                sbsz.Add(self.d1value, (0,1), (1,1))
                label = wx.StaticText(self, -1, 'Defocus 2:')
                self.d2value = FloatEntry(self, -1, allownone=False, chars=5, value='-4e-6')
                sbsz.Add(label, (1,0), (1,1))
                sbsz.Add(self.d2value, (1,1), (1,1))

                self.sizer = wx.GridBagSizer(5, 5)
                self.sizer.Add(sbsz, (0, 0), (1, 1), wx.EXPAND|wx.ALL, 10)
                self.sizer.Add(self.measure, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.ALL, 10)

                self.SetSizerAndFit(self.sizer)

        def onMeasureButton(self, evt):
                self.Close()
                d1 = self.d1value.GetValue()
                d2 = self.d2value.GetValue()
                threading.Thread(target=self.node.alignRotationCenter, args=(d1,d2,)).start()
class ReproTestDialog(wx.Dialog):
    def __init__(self, parent):
        self.node = parent.node

        wx.Dialog.__init__(self, parent, -1, 'Test Reproducibiltiy')

        self.measure = wx.Button(self, -1, 'Run')
        self.Bind(wx.EVT_BUTTON, self.onMeasureButton, self.measure)

        szbutton = wx.GridBagSizer(5, 5)
        szbutton.Add(self.measure, (0, 0), (1, 1), wx.EXPAND)

        sbsz = wx.GridBagSizer(5, 5)

        label = wx.StaticText(self, -1, 'Label:')
        self.labvalue = Entry(self, -1, chars=20, value='test1')
        sbsz.Add(label, (0, 0), (1, 1))
        sbsz.Add(self.labvalue, (0, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Moves:')
        self.movesvalue = IntEntry(self,
                                   -1,
                                   allownone=False,
                                   chars=5,
                                   value='10')
        sbsz.Add(label, (1, 0), (1, 1))
        sbsz.Add(self.movesvalue, (1, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Distance:')
        self.distvalue = FloatEntry(self,
                                    -1,
                                    allownone=False,
                                    chars=5,
                                    value='1e-5')
        sbsz.Add(label, (2, 0), (1, 1))
        sbsz.Add(self.distvalue, (2, 1), (1, 1))

        label = wx.StaticText(self, -1, 'Angle:')
        self.angvalue = FloatEntry(self, -1, allownone=True, chars=5, value='')
        sbsz.Add(label, (3, 0), (1, 1))
        sbsz.Add(self.angvalue, (3, 1), (1, 1))

        self.sizer = wx.GridBagSizer(5, 5)
        self.sizer.Add(sbsz, (0, 0), (1, 1), wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(self.measure, (1, 0), (1, 1),
                       wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 10)

        self.SetSizerAndFit(self.sizer)

    def onMeasureButton(self, evt):
        self.Close()
        label = self.labvalue.GetValue()
        moves = self.movesvalue.GetValue()
        distance = self.distvalue.GetValue()
        angle = self.angvalue.GetValue()
        threading.Thread(target=self.node.move_away_move_back,
                         args=(label, moves, distance, angle)).start()
Beispiel #3
0
class GuessShiftDialog(wx.Dialog):
	#==================
	def __init__(self, parent):
		self.parent = parent
		wx.Dialog.__init__(self, self.parent.frame, -1, "Guess Initial Shift")

		inforow = wx.FlexGridSizer(3, 2, 15, 15)

		gammastr = "%3.3f" % self.parent.data['gamma']
		label = wx.StaticText(self, -1, "Tilt axis angle (degrees): ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		self.tiltaxis = FloatEntry(self, -1, allownone=False, chars=5, value=gammastr)
		inforow.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add(self.tiltaxis, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 3)

		label = wx.StaticText(self, -1, "Vertical is 0 degrees",
			style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add((1,1), 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

		thetastr = "%3.3f" % self.parent.data['theta']
		label = wx.StaticText(self, -1, "Tilt angle: ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		self.tiltangle = FloatEntry(self, -1, allownone=False, chars=5, value=thetastr)
		inforow.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add(self.tiltangle, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 3)

		label = wx.StaticText(self, -1, "negative tilted on left, positive tilted or right",
			style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add(label, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
		inforow.Add((1,1), 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

		self.cancelguess = wx.Button(self, wx.ID_CANCEL, '&Cancel')
		self.runguess = wx.Button(self, wx.ID_OK, '&Run')
		self.Bind(wx.EVT_BUTTON, self.onRunGuessShift, self.runguess)
		buttonrow = wx.GridSizer(1,2)
		buttonrow.Add(self.cancelguess, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
		buttonrow.Add(self.runguess, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)

		self.sizer = wx.FlexGridSizer(2,1)
		self.sizer.Add(inforow, 0, wx.EXPAND|wx.ALL, 10)
		self.sizer.Add(buttonrow, 0, wx.EXPAND|wx.ALL, 5)
		self.SetSizerAndFit(self.sizer)

	#==================
	def onRunGuessShift(self, evt):
		tiltaxis = self.tiltaxis.GetValue()
		tiltangle = self.tiltangle.GetValue()
		self.parent.data['theta'] = tiltangle
		self.parent.data['gamma'] = tiltaxis
		self.parent.data['phi']   = tiltaxis
		self.Close()
		self.parent.onGuessShift(evt)
class TemplateBScrolledSettings(leginon.gui.wx.Settings.ScrolledDialog):
    def initialize(self):
        leginon.gui.wx.Settings.ScrolledDialog.initialize(self)

        sbsztemplate = wx.GridBagSizer(5, 5)
        lab = wx.StaticText(self, -1, 'Test Angle (degrees)')
        self.testangle = FloatEntry(self,
                                    -1,
                                    allownone=False,
                                    chars=5,
                                    value='0.0')
        sbsztemplate.Add(lab, (0, 0), (1, 1))
        sbsztemplate.Add(self.testangle, (0, 1), (1, 1))
        sbsztemplate.AddGrowableCol(0)

        self.btest = wx.Button(self, -1, 'Make Template B')
        szbutton = wx.GridBagSizer(5, 5)
        szbutton.Add(self.btest, (0, 0), (1, 1),
                     wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        szbutton.AddGrowableCol(0)

        self.Bind(wx.EVT_BUTTON, self.onButton, self.btest)

        return [sbsztemplate, szbutton]

    def onButton(self, evt):
        self.dialog.setNodeSettings()
        angle = self.testangle.GetValue()
        self.node.makeTemplateB(angle)
class EditFocusCalibrationDialog(
        leginon.gui.wx.MatrixCalibrator.EditMatrixDialog):
    def __init__(self,
                 parent,
                 matrix,
                 rotation_center,
                 eucentric_focus,
                 title,
                 subtitle='Focus Calibration'):
        self.rotation_center = rotation_center
        self.eucentric_focus = eucentric_focus
        leginon.gui.wx.MatrixCalibrator.EditMatrixDialog.__init__(
            self, parent, matrix, title, subtitle='Focus Calibration')

    def onInitialize(self):
        matrix = leginon.gui.wx.MatrixCalibrator.EditMatrixDialog.onInitialize(
            self)
        row = 1

        label = wx.StaticText(self, -1, 'Rotation Center:')
        self.sz.Add(label, (row + 2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.rotation_center_entries = {}
        for i, axis in enumerate(('x', 'y')):
            label = wx.StaticText(self, -1, axis)
            self.sz.Add(label, (row + 1, i + 1), (1, 1),
                        wx.ALIGN_CENTER | wx.ALIGN_BOTTOM)
            entry = FloatEntry(self, -1, chars=9)
            if self.rotation_center is not None:
                try:
                    entry.SetValue(self.rotation_center[axis])
                except KeyError:
                    pass
            self.rotation_center_entries[axis] = entry
            self.sz.Add(entry, (row + 2, i + 1), (1, 1),
                        wx.ALIGN_CENTER | wx.FIXED_MINSIZE)

        label = wx.StaticText(self, -1, 'Eucentric Focus:')
        self.sz.Add(label, (row + 3, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.eucentric_focus_entry = FloatEntry(self, -1, chars=9)
        self.sz.Add(self.eucentric_focus_entry, (row + 3, 1), (1, 2),
                    wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        self.eucentric_focus_entry.SetValue(self.eucentric_focus)

    def getFocusCalibration(self):
        matrix = leginon.gui.wx.MatrixCalibrator.EditMatrixDialog.getMatrix(
            self)
        rotation_center = {}
        for axis, entry in self.rotation_center_entries.items():
            value = entry.GetValue()
            if value is None:
                raise ValueError
            rotation_center[axis] = value

        eucentric_focus = self.eucentric_focus_entry.GetValue()
        if value is None:
            raise ValueError

        return matrix, rotation_center, eucentric_focus
Beispiel #6
0
class CameraPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        sb = wx.StaticBox(self, -1, 'Camera Configuration')
        self.sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        self.size = None
        self.binmethod = 'exact'
        self.geometry = None
        self.binnings = {'x': [1, 2, 3, 4, 6, 8], 'y': [1, 2, 3, 4, 6, 8]}
        self.defaultexptime = 1000.0
        self.defaultsaveframes = False
        self.defaultframetime = 200
        self.defaultalignframes = False
        self.defaultalignfilter = 'None'
        self.defaultuseframes = ''
        self.defaultreadoutdelay = 0
        self.common = {}
        self.setfuncs = {
            'exposure time': self._setExposureTime,
            'save frames': self._setSaveFrames,
            'frame time': self._setFrameTime,
            'align frames': self._setAlignFrames,
            'align filter': self._setAlignFilter,
            'use frames': self._setUseFrames,
            'readout delay': self._setReadoutDelay,
        }
        self.getfuncs = {
            'exposure time': self._getExposureTime,
            'save frames': self._getSaveFrames,
            'frame time': self._getFrameTime,
            'align frames': self._getAlignFrames,
            'align filter': self._getAlignFilter,
            'use frames': self._getUseFrames,
            'readout delay': self._getReadoutDelay,
        }

        # geometry
        self.ccommon = wx.Choice(self, -1, choices=['(None)'])
        self.ccommon.SetSelection(0)
        bcustom = wx.Button(self, -1, 'Custom...')

        std = wx.StaticText(self, -1, 'Dimension:')
        self.stdimension = wx.StaticText(self, -1, '')

        sto = wx.StaticText(self, -1, 'Offset:')
        self.stoffset = wx.StaticText(self, -1, '')

        stb = wx.StaticText(self, -1, 'Binning:')
        self.stbinning = wx.StaticText(self, -1, '')

        self.szmain = wx.GridBagSizer(3, 3)

        sz = wx.GridBagSizer(5, 5)
        sz.Add(self.ccommon, (0, 0), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        sz.Add(bcustom, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.AddGrowableRow(0)
        sz.AddGrowableCol(0)
        sz.AddGrowableCol(1)
        self.szmain.Add(sz, (0, 0), (1, 2), wx.EXPAND)

        self.szmain.Add(std, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stdimension, (1, 1), (1, 1), wx.ALIGN_CENTER)

        self.szmain.Add(sto, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stoffset, (2, 1), (1, 1), wx.ALIGN_CENTER)

        self.szmain.Add(stb, (3, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(self.stbinning, (3, 1), (1, 1), wx.ALIGN_CENTER)

        # exposure time
        stet = wx.StaticText(self, -1, 'Exposure time:')
        self.feexposuretime = FloatEntry(self, -1, min=0.0, chars=7)
        stms = wx.StaticText(self, -1, 'ms')

        self.szmain.Add(stet, (4, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz = wx.GridBagSizer(0, 3)
        sz.Add(self.feexposuretime, (0, 0), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        sz.Add(stms, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.szmain.Add(sz, (4, 1), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        sb = wx.StaticBox(self, -1, 'Camera with Movie Mode')
        ddsb = wx.StaticBoxSizer(sb, wx.VERTICAL)
        ddsz = wx.GridBagSizer(5, 5)
        # save frames
        self.saveframes = wx.CheckBox(self, -1, 'Save frames')
        ddsz.Add(self.saveframes, (0, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # frame time
        stet = wx.StaticText(self, -1, 'Exposure time per Frame:')
        self.frametime = FloatEntry(self, -1, min=0.01, chars=7)
        stms = wx.StaticText(self, -1, 'ms')

        ddsz.Add(stet, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ftsz = wx.GridBagSizer(0, 3)
        ftsz.Add(self.frametime, (0, 0), (1, 1),
                 wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        ftsz.Add(stms, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ddsz.Add(ftsz, (1, 1), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)
        # use raw frames
        label = wx.StaticText(self, -1, 'Frames to use:')
        self.useframes = Entry(self, -1)
        ddsz.Add(label, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        ddsz.Add(self.useframes, (2, 1), (1, 1), wx.ALIGN_CENTER | wx.EXPAND)

        # readout delay
        strd = wx.StaticText(self, -1, 'Readout delay:')
        self.readoutdelay = IntEntry(self, -1, chars=7)
        stms = wx.StaticText(self, -1, 'ms')
        sz = wx.BoxSizer(wx.HORIZONTAL)
        sz.Add(strd)
        sz.Add(self.readoutdelay)
        sz.Add(stms)
        ddsz.Add(sz, (3, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # align frames box
        sb = wx.StaticBox(self, -1, 'Frame-Aligning Camera Only')
        afsb = wx.StaticBoxSizer(sb, wx.VERTICAL)
        afsz = wx.GridBagSizer(3, 3)
        # align frames
        self.alignframes = wx.CheckBox(self, -1, 'Align frames')
        afsz.Add(self.alignframes, (0, 0), (1, 2), wx.ALIGN_CENTER | wx.EXPAND)

        # align frame filter
        label = wx.StaticText(self, -1, 'c-correlation filter:')
        self.alignfilter = wx.Choice(self, -1, choices=self.getAlignFilters())
        self.alignfilter.SetSelection(0)
        afsz.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        afsz.Add(self.alignfilter, (1, 1), (1, 1), wx.ALIGN_CENTER | wx.EXPAND)
        afsb.Add(afsz, 0, wx.EXPAND | wx.ALL, 2)

        ddsz.Add(afsb, (4, 0), (3, 2), wx.ALIGN_CENTER | wx.EXPAND)

        ddsb.Add(ddsz, 0, wx.EXPAND | wx.ALL, 2)
        self.szmain.Add(ddsb, (7, 0), (1, 3), wx.ALIGN_CENTER | wx.EXPAND)

        ddsz.AddGrowableCol(1)
        self.szmain.AddGrowableCol(1)
        self.szmain.AddGrowableCol(2)

        self.sbsz.Add(self.szmain, 0, wx.EXPAND | wx.ALL, 2)

        self.SetSizerAndFit(self.sbsz)

        self.Bind(wx.EVT_CHOICE, self.onCommonChoice, self.ccommon)
        self.Bind(wx.EVT_BUTTON, self.onCustomButton, bcustom)
        self.Bind(EVT_ENTRY, self.onExposureTime, self.feexposuretime)
        self.Bind(wx.EVT_CHECKBOX, self.onSaveFrames, self.saveframes)
        self.Bind(EVT_ENTRY, self.onFrameTime, self.frametime)
        self.Bind(EVT_ENTRY, self.onUseFrames, self.useframes)
        self.Bind(EVT_ENTRY, self.onReadoutDelay, self.readoutdelay)
        self.Bind(EVT_SET_CONFIGURATION, self.onSetConfiguration)

        #self.Enable(False)

    def setGeometryLimits(self, limitdict):
        if limitdict is None:
            self.setSize(None)
        if 'binnings' in limitdict.keys():
            self.binnings['x'] = limitdict['binnings']
            self.binnings['y'] = limitdict['binnings']
        if 'binmethod' in limitdict.keys():
            self.binmethod = limitdict['binmethod']
        if 'size' in limitdict.keys():
            self.setSize(limitdict['size'])
        else:
            self.setSize(None)

    def setSize(self, size):
        if size is None:
            self.size = None
            self.Freeze()
            self.choices, self.common = None, None
            self.ccommon.Clear()
            self.ccommon.Append('(None)')
            self.szmain.Layout()
            #self.Enable(False)
            self.Thaw()
        else:
            self.size = dict(size)
            self.Freeze()
            self.choices, self.common = self.getCenteredGeometries()
            self.ccommon.Clear()
            self.ccommon.AppendItems(self.choices)
            if self.geometry is None or not self.validateGeometry():
                self.ccommon.SetSelection(len(self.choices) - 1)
                self.setGeometry(
                    self.common[self.ccommon.GetStringSelection()])
            else:
                self.setCommonChoice()
            if self.feexposuretime.GetValue() is None:
                self.feexposuretime.SetValue(self.defaultexptime)
            #self.Enable(True)
            self.szmain.Layout()
            self.Thaw()

    def clear(self):
        if self.size is None:
            return
        self.Freeze()
        self.ccommon.SetSelection(len(self.choices) - 1)
        self.setGeometry(self.common[self.ccommon.GetStringSelection()])
        self.feexposuretime.SetValue(self.defaultexptime)
        self.saveframes.SetValue(self.defaultsaveframes)
        self.frametime.SetValue(self.defaultframetime)
        self.alignframes.SetValue(self.defaultalignframes)
        self.alignfilter.SetValue(self.defaultalignfilter)
        self.useframes.SetValue(self.defaultuseframes)
        self.readoutdelay.SetValue(self.defaultreadoutdelay)
        #self.Enable(False)
        self.Thaw()

    def onConfigurationChanged(self):
        evt = ConfigurationChangedEvent(self.getConfiguration(), self)
        self.GetEventHandler().AddPendingEvent(evt)

    def onExposureTime(self, evt):
        self.onConfigurationChanged()

    def onSaveFrames(self, evt):
        self.onConfigurationChanged()

    def onFrameTime(self, evt):
        self.onConfigurationChanged()

    def onUseFrames(self, evt):
        self.onConfigurationChanged()

    def onReadoutDelay(self, evt):
        self.onConfigurationChanged()

    def setCommonChoice(self):
        for key, geometry in self.common.items():
            flag = True
            for i in ['dimension', 'offset', 'binning']:
                if self.geometry[i] != geometry[i]:
                    flag = False
                    break
            if flag:
                self.ccommon.SetStringSelection(key)
                return
        if self.ccommon.FindString('(Custom)') is wx.NOT_FOUND:
            self.ccommon.Insert('(Custom)', 0)
            self.ccommon.SetSelection(0)

    def _getDimension(self):
        return self.geometry['dimension']

    def _setDimension(self, value):
        self.geometry['dimension'] = value
        self.setCommonChoice()

    def _getOffset(self):
        return self.geometry['offset']

    def _setOffset(self, value):
        self.geometry['offset'] = value
        self.setCommonChoice()

    def _getBinning(self):
        return self.geometry['binning']

    def _setBinning(self, value):
        self.geometry['binning'] = value
        self.setCommonChoice()

    def _getExposureTime(self):
        return self.feexposuretime.GetValue()

    def _setExposureTime(self, value):
        self.feexposuretime.SetValue(value)

    def _getSaveFrames(self):
        return self.saveframes.GetValue()

    def _setSaveFrames(self, value):
        value = bool(value)
        self.saveframes.SetValue(value)

    def _getFrameTime(self):
        return self.frametime.GetValue()

    def _setFrameTime(self, value):
        self.frametime.SetValue(value)

    def _getAlignFrames(self):
        return self.alignframes.GetValue()

    def _setAlignFrames(self, value):
        value = bool(value)
        self.alignframes.SetValue(value)

    def getAlignFilters(self):
        return [
            'None', 'Hanning Window (default)', 'Bandpass Filter (default)',
            'Sobel Filter (default)', 'Combined Filter (default)'
        ]

    def _getAlignFilter(self):
        return self.alignfilter.GetStringSelection()

    def _setAlignFilter(self, value):
        if value:
            value = str(value)
        else:
            value = 'None'
        self.alignfilter.SetStringSelection(value)

    def _getUseFrames(self):
        frames_str = self.useframes.GetValue()
        numbers = re.split('\D+', frames_str)
        numbers = filter(None, numbers)
        if numbers:
            numbers = map(int, numbers)
            numbers = tuple(numbers)
        else:
            numbers = ()
        return numbers

    def _setUseFrames(self, value):
        if value:
            value = str(value)
        else:
            value = ''
        self.useframes.SetValue(value)

    def _getReadoutDelay(self):
        return self.readoutdelay.GetValue()

    def _setReadoutDelay(self, value):
        return self.readoutdelay.SetValue(value)

    def onCommonChoice(self, evt):
        key = evt.GetString()
        if key == '(Custom)' or key.startswith('-'):
            return
        if self.setGeometry(self.common[key]):
            self.onConfigurationChanged()
        n = self.ccommon.FindString('(Custom)')
        if n is not wx.NOT_FOUND:
            self.ccommon.Delete(n)

    def onCustomButton(self, evt):
        dialog = CustomDialog(self, self.getGeometry())
        if dialog.ShowModal() == wx.ID_OK:
            if self.setGeometry(dialog.getGeometry()):
                self.onConfigurationChanged()
            self.setCommonChoice()
        dialog.Destroy()

    def getCenteredGeometry(self, dimension, binning):
        offset = {}
        for axis in ['x', 'y']:
            offset[axis] = int((self.size[axis] / binning - dimension) / 2)

        geometry = {
            'dimension': {
                'x': dimension,
                'y': dimension
            },
            'offset': {
                'x': offset['x'],
                'y': offset['y']
            },
            'binning': {
                'x': binning,
                'y': binning
            }
        }
        return geometry

    def getFullGeometry(self, binning):
        if self.binmethod == 'exact' and ((self.size['x'] % binning) or
                                          (self.size['y'] % binning)):
            return None
        dimx = self.size['x'] / binning
        dimy = self.size['y'] / binning
        geometry = {
            'dimension': {
                'x': dimx,
                'y': dimy
            },
            'offset': {
                'x': 0,
                'y': 0
            },
            'binning': {
                'x': binning,
                'y': binning
            }
        }
        return geometry

    def getCenteredGeometries(self):
        geometries = {}
        keys = []
        show_sections = False
        if self.size['x'] != self.size['y']:
            show_sections = True
            keys.append('--- Full ---')
            for binning in self.binnings['x']:
                dimx = self.size['x'] / binning
                dimy = self.size['y'] / binning
                key = '%d x %d bin %d' % (dimx, dimy, binning)
                geo = self.getFullGeometry(binning)
                if geo is not None:
                    geometries[key] = geo
                    keys.append(key)
        if self.binnings['x'] != self.binnings['y']:
            return geometries
        self.minsize = min(self.size['x'], self.size['y'])
        dimensions = [int(self.minsize / float(b)) for b in self.binnings['x']]

        def good(dim):
            return not bool(numpy.modf(dim)[1] - dim)

        def filtergood(input, mask):
            result = []
            for i, inval in enumerate(input):
                if mask[i]:
                    result.append(inval)
            return result

        if self.binmethod == 'exact':
            mask = [good(dim) for dim in dimensions]
        else:
            mask = [True for dim in dimensions]
        dimensions = filtergood(dimensions, mask)

        def minsize(size):
            return size >= self.minsize / max(self.binnings['x'])

        dimensions = filter(minsize, dimensions)
        dimensions = map((lambda x: primefactor.getAllEvenPrimes(x)[-1]),
                         dimensions)
        binnings = filtergood(self.binnings['x'], mask)
        dimensions.reverse()
        if show_sections:
            keys.append('--- Center ---')
        for d in dimensions:
            for b in self.binnings['x']:
                if d * b <= self.minsize:
                    key = '%d x %d bin %d' % (d, d, b)
                    geometries[key] = self.getCenteredGeometry(d, b)
                    keys.append(key)
                else:
                    break
        return keys, geometries

    def validateGeometry(self, geometry=None):
        if geometry is None:
            geometry = self.geometry
        for a in ['x', 'y']:
            try:
                if geometry['dimension'][a] < 1 or geometry['offset'][a] < 0:
                    return False
                if geometry['binning'][a] not in self.binnings[a]:
                    return False
                size = geometry['dimension'][a] + geometry['offset'][a]
                size *= geometry['binning'][a]
                if size > self.size[a]:
                    return False
            except:
                return False
        return True

    def cmpGeometry(self, geometry):
        if self.geometry == geometry:
            return True
        for g in ['dimension', 'offset', 'binning']:
            try:
                for a in ['x', 'y']:
                    if self.geometry[g][a] != geometry[g][a]:
                        return False
            except (KeyError, TypeError):
                return False
        return True

    def setGeometry(self, geometry):
        if self.cmpGeometry(geometry):
            return False

        if self.size is not None and not self.validateGeometry(geometry):
            raise ValueError

        self._setGeometry(geometry)

        return True

    def getGeometry(self):
        return self.geometry

    def getConfiguration(self):
        g = self.getGeometry()
        if g is None:
            return None
        c = copy.deepcopy(g)
        for key, func in self.getfuncs.items():
            c[key] = func()
        return c

    def _setGeometry(self, geometry):
        if self.geometry is None:
            self.geometry = {}
        else:
            self.geometry = copy.deepcopy(self.geometry)
        self.Freeze()
        for g in ['dimension', 'offset', 'binning']:
            if g not in self.geometry:
                self.geometry[g] = {}
            try:
                self.geometry[g].update(dict(geometry[g]))
                if g == 'offset':
                    label = '(%d, %d)'
                else:
                    #label = '%d × %d'
                    label = '%d x %d'
                label = label % (self.geometry[g]['x'], self.geometry[g]['y'])
                getattr(self, 'st' + g).SetLabel(label)
            except:
                pass
        self.szmain.Layout()
        self.Thaw()
        return True

    def _setConfiguration(self, value):
        for key, func in self.setfuncs.items():
            if key in value:
                func(value[key])
        self._setGeometry(value)
        self.setCommonChoice()

    def setConfiguration(self, value):
        for key, func in self.setfuncs.items():
            if key in value:
                func(value[key])
        self.setGeometry(value)
        if self.size is not None:
            self.setCommonChoice()
        #if not self.IsEnabled():
        #       self.Enable(True)

    def onSetConfiguration(self, evt):
        self.setConfiguration(evt.configuration)
Beispiel #7
0
class ManualFocusDialog(wx.Frame):
        def __init__(self, parent, node, title='Manual Focus'):
                wx.Frame.__init__(self, parent, -1, title, size=(650,600),
                        style=wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER)
                self.node = node
                self.center = (256,256)
                self.toolbar = wx.ToolBar(self, -1)

                bitmap = leginon.gui.wx.Icons.icon('settings')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_SETTINGS, bitmap, shortHelpString='Settings')

                self.toolbar.AddSeparator()

                bitmap = leginon.gui.wx.Icons.icon('play')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_PLAY, bitmap, shortHelpString='Play')
                bitmap = leginon.gui.wx.Icons.icon('pause')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_PAUSE, bitmap, shortHelpString='Pause')
                bitmap = leginon.gui.wx.Icons.icon('stop')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_STOP, bitmap, shortHelpString='Stop')

                self.toolbar.AddSeparator()

                self.initParameterChoice()
                self.toolbar.AddControl(self.parameter_choice)
                bitmap = leginon.gui.wx.Icons.icon('plus')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_PLUS, bitmap,
                        shortHelpString='Increment up')
                bitmap = leginon.gui.wx.Icons.icon('minus')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_MINUS, bitmap,
                        shortHelpString='Increment down')

                self.toolbar.AddSeparator()

                self.value = FloatEntry(self.toolbar, -1, allownone=False, chars=6, value='0.0')
                self.toolbar.AddControl(self.value)
                # size is defined because some wxPython installation lack good wxDefaultSize
                self.toolbar.AddControl(wx.StaticText(self.toolbar, -1, ' m',size=(20,20)))
                bitmap = leginon.gui.wx.Icons.icon('instrumentset')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_VALUE, bitmap,
                        shortHelpString='Set instrument')

                self.toolbar.AddSeparator()

                bitmap = leginon.gui.wx.Icons.icon('instrumentsetnew')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_RESET, bitmap,
                        shortHelpString='Reset Defocus')

                self.toolbar.AddSeparator()

                bitmap = leginon.gui.wx.Icons.icon('instrumentget')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_GET_INSTRUMENT, bitmap,
                        shortHelpString='Eucentric from instrument')

                bitmap = leginon.gui.wx.Icons.icon('instrumentset')
                self.toolbar.AddTool(leginon.gui.wx.ToolBar.ID_SET_INSTRUMENT, bitmap,
                        shortHelpString='Eucentric to instrument')

                self.moreToolbar()

                self.SetToolBar(self.toolbar)
                self.toolbar.Realize()

                self.imagepanel = leginon.gui.wx.TargetPanel.FFTTargetImagePanel(self, -1,imagesize=(512,512))

                self.imagepanel.addTypeTool('Image', display=True)
                self.imagepanel.addTypeTool('Power', display=True)
                self.imagepanel.selectiontool.setDisplayed('Power', True)

                self.statusbar = wx.StatusBar(self, -1)
                self.SetStatusBar(self.statusbar)

                self.Fit()
                #self.SetAutoLayout(True)

                self.settingsdialog = ManualFocusSettingsDialog(self, 'Manual Focus Settings', 'Settings')

                self.Bind(leginon.gui.wx.Events.EVT_PLAYER, self.onPlayer)
                self.Bind(wx.EVT_TOOL, self.onSettingsTool, id=leginon.gui.wx.ToolBar.ID_SETTINGS)
                self.Bind(wx.EVT_TOOL, self.onPlayTool, id=leginon.gui.wx.ToolBar.ID_PLAY)
                self.Bind(wx.EVT_TOOL, self.onPauseTool, id=leginon.gui.wx.ToolBar.ID_PAUSE)
                self.Bind(wx.EVT_TOOL, self.onStopTool, id=leginon.gui.wx.ToolBar.ID_STOP)
                self.Bind(wx.EVT_TOOL, self.onPlusTool, id=leginon.gui.wx.ToolBar.ID_PLUS)
                self.Bind(wx.EVT_TOOL, self.onMinusTool, id=leginon.gui.wx.ToolBar.ID_MINUS)
                self.Bind(wx.EVT_TOOL, self.onValueTool, id=leginon.gui.wx.ToolBar.ID_VALUE)
                self.Bind(wx.EVT_TOOL, self.onResetTool, id=leginon.gui.wx.ToolBar.ID_RESET)
                self.Bind(wx.EVT_TOOL, self.onGetInstrumentTool, id=leginon.gui.wx.ToolBar.ID_GET_INSTRUMENT)
                self.Bind(wx.EVT_TOOL, self.onSetInstrumentTool, id=leginon.gui.wx.ToolBar.ID_SET_INSTRUMENT)
                self.Bind(wx.EVT_CLOSE, self.onClose)
                self.Bind(leginon.gui.wx.Events.EVT_SET_IMAGE, self.onSetImage)
                self.Bind(leginon.gui.wx.Events.EVT_MANUAL_UPDATED, self.onManualUpdated)
                self.Bind(leginon.gui.wx.ImagePanelTools.EVT_SHAPE_FOUND, self.onShapeFound, self.imagepanel)
                self.Bind(leginon.gui.wx.ImagePanelTools.EVT_IMAGE_CLICKED, self.onImageClicked,
                                                        self.imagepanel)
                self.parameter_choice.Bind(wx.EVT_CHOICE, self.onParameterChoice)
                self.moreOnInit()

        def moreToolbar(self):
                pass

        def moreOnInit(self):
                self.beamtilt = False
                pass

        def initParameterChoice(self):
                self.parameter_choice = Choice(self.toolbar, -1, choices=['Defocus', 'Stage Z'])
                par = 'Defocus'
                self.parameter_choice.SetStringSelection(par)
                threading.Thread(target=self.node.setParameterChoice, args=(par,)).start()

        def onParameterChoice(self,evt):
                par = self.parameter_choice.GetStringSelection()
                threading.Thread(target=self.node.setParameterChoice, args=(par,)).start()

        def onSettingsTool(self, evt):
                self.settingsdialog.maskradius.SetValue(self.node.maskradius)
                self.settingsdialog.increment.SetValue(self.node.increment)
                print 'set increment to ',self.node.increment
                #self.MakeModal(False)
                if self.settingsdialog.ShowModal() == wx.ID_OK:
                        self.node.maskradius = self.settingsdialog.maskradius.GetValue()
                        self.node.increment = self.settingsdialog.increment.GetValue()
                        self.node.increment = self.settingsdialog.increment.GetValue()
                #self.MakeModal(True)

        def onPlayTool(self, evt):
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, False)
                self.node.manualplayer.play()

        def onPauseTool(self, evt):
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, False)
                self.node.manualplayer.pause()

        def onStopTool(self, evt):
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, False)
                self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, False)
                self.node.manualplayer.stop()

        def onPlayer(self, evt):
                if evt.state == 'play':
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, False)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, True)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, True)
                elif evt.state == 'pause':
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, True)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, False)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, True)
                elif evt.state == 'stop':
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PLAY, True)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_PAUSE, True)
                        self.toolbar.EnableTool(leginon.gui.wx.ToolBar.ID_STOP, False)

        def _manualEnable(self, enable):
                self.toolbar.Enable(enable)

        def onManualUpdated(self, evt):
                self._manualEnable(True)

        def manualUpdated(self):
                evt = leginon.gui.wx.Events.ManualUpdatedEvent()
                self.GetEventHandler().AddPendingEvent(evt)

        def onPlusTool(self, evt):
                self._manualEnable(False)
                par = self.parameter_choice.GetStringSelection()
                threading.Thread(target=self.node.onFocusUp, args=(par,)).start()

        def onMinusTool(self, evt):
                self._manualEnable(False)
                par = self.parameter_choice.GetStringSelection()
                threading.Thread(target=self.node.onFocusDown, args=(par,)).start()

        def onValueTool(self, evt):
                self._manualEnable(False)
                value = self.value.GetValue()
                threading.Thread(target=self.node.setFocus, args=(value,)).start()

        def onResetTool(self, evt):
                self._manualEnable(False)
                threading.Thread(target=self.node.onResetDefocus).start()

        def onGetInstrumentTool(self, evt):
                self._manualEnable(False)
                threading.Thread(target=self.node.onEucentricFromScope).start()

        def onSetInstrumentTool(self, evt):
                self._manualEnable(False)
                threading.Thread(target=self.node.onChangeToEucentric).start()

        def onClose(self, evt):
                self.node.manualplayer.stop()

        def onSetImage(self, evt):
                self.imagepanel.setImageType(evt.typename, evt.image)

        def onNewPixelSize(self, pixelsize,center,hightension):
                idcevt = leginon.gui.wx.ImagePanelTools.ImageNewPixelSizeEvent(self.imagepanel, pixelsize,center,hightension)
                self.imagepanel.GetEventHandler().AddPendingEvent(idcevt)
                self.center = center
                self.pixelsize = pixelsize
                self.hightension = hightension

        def onShapeFound(self, evt):
                centers = [(self.center['y'],self.center['x']),]
                idcevt = leginon.gui.wx.ImagePanelTools.ShapeNewCenterEvent(self.imagepanel, centers)
                self.imagepanel.GetEventHandler().AddPendingEvent(idcevt)
                threading.Thread(target=self.node.estimateAstigmation, args=(evt.params,)).start()

        def onImageClicked(self, evt):
                if not self.imagepanel.selectiontool.isDisplayed('Power'):
                        return
                resolution = 1/math.sqrt(((evt.xy[0]-self.center['x'])*self.pixelsize['x'])**2+((evt.xy[1]-self.center['y'])*self.pixelsize['y'])**2)
                defocus = fftfun.calculateDefocus(self.hightension,1/resolution)
                self.node.increment = defocus
                self.settingsdialog.increment.SetValue(self.node.increment)
Beispiel #8
0
class EditDialog(wx.Dialog):
    def __init__(self, parent, mag, ps, comment):
        wx.Dialog.__init__(self, parent, -1, 'Edit Pixel Size')
        sb = wx.StaticBox(self, -1, 'Pixel Size')
        sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)

        self.stmag = wx.StaticText(self, -1)
        self.stmag.SetLabel(str(mag))
        self.feps = FloatEntry(self, -1, min=0.0, chars=9)
        self.feps.SetValue(ps)
        self.tccomment = wx.TextCtrl(self,
                                     -1,
                                     'Manual entry',
                                     style=wx.TE_MULTILINE)
        self.tccomment.SetValue(comment)

        szedit = wx.GridBagSizer(5, 5)
        label = wx.StaticText(self, -1, 'Magnification:')
        szedit.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szedit.Add(self.stmag, (0, 1), (1, 1),
                   wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        label = wx.StaticText(self, -1, 'Pixel size:')
        szedit.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szedit.Add(
            self.feps, (1, 1), (1, 1),
            wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
        label = wx.StaticText(self, -1, 'm/pixel')
        szedit.Add(label, (1, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'Comment:')
        szedit.Add(label, (2, 0), (1, 3), wx.ALIGN_CENTER_VERTICAL)
        szedit.Add(self.tccomment, (3, 0), (1, 3), wx.EXPAND)

        szedit.AddGrowableRow(3)
        szedit.AddGrowableRow(0)
        szedit.AddGrowableCol(0)
        szedit.AddGrowableCol(1)
        szedit.AddGrowableCol(2)

        sbsz.Add(szedit, 1, wx.EXPAND | wx.ALL, 5)

        self.bsave = wx.Button(self, wx.ID_OK, 'Save')
        self.bcancel = wx.Button(self, wx.ID_CANCEL, 'Cancel')

        if ps is None:
            self.bsave.Enable(False)
        else:
            self.bsave.Enable(True)

        szbutton = wx.GridBagSizer(5, 5)
        szbutton.Add(self.bsave, (0, 0), (1, 1),
                     wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        szbutton.Add(self.bcancel, (0, 1), (1, 1), wx.ALIGN_CENTER)
        szbutton.AddGrowableCol(0)

        sz = wx.GridBagSizer(5, 5)
        sz.Add(sbsz, (0, 0), (1, 1), wx.EXPAND | wx.ALL, 10)
        sz.Add(szbutton, (1, 0), (1, 1), wx.EXPAND | wx.ALL, 10)
        self.SetSizerAndFit(sz)

        self.Bind(wx.EVT_BUTTON, self.validate, self.bsave)
        self.Bind(leginon.gui.wx.Entry.EVT_ENTRY, self.onPixelSizeEntry,
                  self.feps)

    def onPixelSizeEntry(self, evt):
        if evt.GetValue() is None:
            self.bsave.Enable(False)
        else:
            self.bsave.Enable(True)

    def validate(self, evt):
        self.mag = int(self.stmag.GetLabel())
        self.ps = self.feps.GetValue()
        if None in [self.mag, self.ps]:
            dialog = wx.MessageDialog(self, 'Pixel size entry', 'Error',
                                      wx.OK | wx.ICON_ERROR)
            dialog.ShowModal()
            dialog.Destroy()
        else:
            evt.Skip()
Beispiel #9
0
class DogPickerDialog(wx.Dialog):
    #==================
    def __init__(self, parent):
        self.parent = parent
        wx.Dialog.__init__(self, self.parent.frame, -1,
                           "DoG Auto Particle Picker")

        inforow = wx.FlexGridSizer(3, 3, 10, 10)

        inforow.Add((1, 1), 0, 3)
        inforow.Add((1, 1), 0, 3)
        inforow.Add((1, 1), 0, 3)

        ### standard options
        box = wx.StaticBox(self, -1, 'Standard Options')
        boxrow = wx.StaticBoxSizer(box, wx.VERTICAL)

        hbox1 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Particle diameter (pixels): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.diam = FloatEntry(self,
                               -1,
                               allownone=False,
                               chars=5,
                               value="100.0")
        hbox1.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox1.Add(
            self.diam, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_HORIZONTAL
            | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox1.AddGrowableCol(0)
        boxrow.Add(hbox1, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        boxrow.Add((3, 3), 0)

        hbox2 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Min Threshold: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.minthresh = FloatEntry(self,
                                    -1,
                                    allownone=False,
                                    chars=5,
                                    value="0.7")
        hbox2.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox2.Add(self.minthresh, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox2.AddGrowableCol(0)
        boxrow.Add(hbox2, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        boxrow.Add((3, 3), 0)

        label = wx.StaticText(self,
                              -1,
                              "Particle contrast: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        boxrow.Add(label, 0,
                   wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 3)

        hbox8 = wx.FlexGridSizer(1, 2, 10, 10)
        self.whitePart = wx.RadioButton(self,
                                        -1,
                                        'Light on Dark (stain)', (10, 10),
                                        style=wx.RB_GROUP)
        self.blackPart = wx.RadioButton(self, -1, 'Dark on Light (ice)',
                                        (10, 30))
        self.Bind(wx.EVT_RADIOBUTTON,
                  self.partContrast,
                  id=self.whitePart.GetId())
        self.Bind(wx.EVT_RADIOBUTTON,
                  self.partContrast,
                  id=self.blackPart.GetId())
        self.partContrast(True)
        hbox8.Add(self.whitePart, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox8.Add(self.blackPart, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        boxrow.Add(hbox8, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        boxrow.Add((3, 3), 0)

        inforow.Add((1, 1), 0, 3)
        inforow.Add(
            boxrow, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
            3)
        inforow.Add((1, 1), 0, 3)
        ### end standard options

        ### advanced options
        box = wx.StaticBox(self, -1, 'Advanded Options')
        boxrow = wx.StaticBoxSizer(box, wx.VERTICAL)

        hbox3 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Diameter range (pixels): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.srange = FloatEntry(self,
                                 -1,
                                 allownone=False,
                                 chars=5,
                                 value="20.0")
        hbox3.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox3.Add(self.srange, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox3.AddGrowableCol(0)
        boxrow.Add(hbox3, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        hbox4 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Number of sizes: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.numslices = IntEntry(self,
                                  -1,
                                  allownone=False,
                                  chars=3,
                                  value="2")
        hbox4.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox4.Add(self.numslices, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox4.AddGrowableCol(0)
        boxrow.Add(hbox4, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        hbox5 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Max threshold: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.maxthresh = FloatEntry(self,
                                    -1,
                                    allownone=False,
                                    chars=5,
                                    value="1.5")
        hbox5.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox5.Add(self.maxthresh, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox5.AddGrowableCol(0)
        boxrow.Add(hbox5, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        hbox6 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Max peak area (% πr^2): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.peakarea = FloatEntry(self,
                                   -1,
                                   allownone=False,
                                   chars=5,
                                   value="0.3")
        hbox6.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox6.Add(self.peakarea, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox6.AddGrowableCol(0)
        boxrow.Add(hbox6, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        hbox9 = wx.FlexGridSizer(1, 2, 10, 10)
        label = wx.StaticText(self,
                              -1,
                              "Max peaks: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.maxpeaks = IntEntry(self,
                                 -1,
                                 allownone=False,
                                 chars=5,
                                 value="500")
        hbox9.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        hbox9.Add(self.maxpeaks, 0,
                  wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 3)
        hbox9.AddGrowableCol(0)
        boxrow.Add(hbox9, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)

        boxrow.Add((3, 3), 0)

        inforow.Add((1, 1), 0, 3)
        inforow.Add(
            boxrow, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
            3)
        inforow.Add((1, 1), 0, 3)
        ### end advanced options

        self.canceldog = wx.Button(self, wx.ID_CANCEL, '&Cancel')
        self.rundog = wx.Button(self, wx.ID_OK, '&Run')
        self.Bind(wx.EVT_BUTTON, self.onRunDogPicker, self.rundog)
        buttonrow = wx.FlexGridSizer(1, 2, 10, 10)
        buttonrow.Add(self.canceldog, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,
                      10)
        buttonrow.Add(self.rundog, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,
                      10)

        self.sizer = wx.FlexGridSizer(3, 1, 10, 10)
        self.sizer.Add(inforow, 0, wx.ALIGN_CENTER_HORIZONTAL, border=10)
        self.sizer.Add(buttonrow, 0, wx.ALIGN_CENTER_HORIZONTAL, border=10)
        label = wx.StaticText(self,
                              -1,
                              "Check command line after running",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.sizer.Add(label, 0, wx.EXPAND, 5)

        self.SetSizerAndFit(self.sizer)

    #==================
    def partContrast(self, evt):
        if self.whitePart.GetValue() is True:
            return False
        return True

    #==================
    def onRunDogPicker(self, evt):
        apDisplay.printColor("===============\nRunning experimental DoGPicker",
                             "cyan")

        ### remove existing maps
        lefts = glob.glob("maps/leftimage.dogmap*.jpg")
        for imgname in lefts:
            apFile.removeFile(imgname, warn=False)
        rights = glob.glob("maps/rightimage.dogmap*.jpg")
        for imgname in rights:
            apFile.removeFile(imgname, warn=False)

        pixdiam = self.diam.GetValue()
        sizerange = self.srange.GetValue()
        minthresh = self.minthresh.GetValue()
        maxthresh = self.maxthresh.GetValue()
        peakarea = self.peakarea.GetValue()
        invert = self.partContrast(None)
        maxpeaks = self.maxpeaks.GetValue()
        numslices = self.numslices.GetValue()

        if invert is True:
            apDisplay.printMsg(
                "Picking dark particles on light backgound, i.e. ice")
        else:
            apDisplay.printMsg(
                "Picking light particles on dark backgound, i.e. stain")

        self.Close()

        apParam.createDirectory("maps")
        #1. set DoG parameters / hack to use existing pipeline function
        dogparams = {
            'apix': 1.0,  # set to 1 because we are using pixels
            'bin': 1.0,  # set to 1 because we are using pixels
            'diam': pixdiam,  # diameter of particles
            'sizerange': sizerange,  # diameter range of particles
            'numslices': numslices,  # number of slices to perform
            'kfactor': 1.2,  # does not matter
            'overlapmult': 1.5,
            'rundir': os.getcwd(),
            'maxpeaks': maxpeaks,
            'maxthresh': maxthresh,
            'thresh': minthresh,
            'maxsize': peakarea,
            'peaktype': 'maximum',
            'background': False,
            'doubles': False,
        }

        #2a. get image 1
        img1 = numpy.asarray(self.parent.panel1.imagedata, dtype=numpy.float32)
        if invert is True:
            img1 = apImage.invertImage(img1)

        #3a. run DoG picker on image 1
        dogarrays1 = apDog.diffOfGaussParam(img1, dogparams)

        #4a: threshold & find peaks image 1
        imgdict1 = {
            'filename': 'leftimage',
            'image': img1,
        }
        peaktree1 = apPeaks.findPeaks(imgdict1,
                                      dogarrays1,
                                      dogparams,
                                      maptype="dogmap",
                                      pikfile=False)

        #5a: insert into self.parent.picks1
        self.parent.picks1 = self.peaktreeToPicks(peaktree1)

        #===

        #2b: get image 2
        img2 = numpy.asarray(self.parent.panel2.imagedata, dtype=numpy.float32)
        if invert is True:
            img2 = apImage.invertImage(img2)

        #3b. run DoG picker on image 2
        dogarrays2 = apDog.diffOfGaussParam(img2, dogparams)

        #4b: threshold & find peaks image 2
        imgdict2 = {
            'filename': 'rightimage',
            'image': img2,
        }
        peaktree2 = apPeaks.findPeaks(imgdict2,
                                      dogarrays2,
                                      dogparams,
                                      maptype="dogmap",
                                      pikfile=False)

        #5b: insert into self.parent.picks2
        self.parent.picks2 = self.peaktreeToPicks(peaktree2)

        self.parent.onImportPicks(None, pixdiam, showmaps=True)
        apDisplay.printColor("Finished DoGPicker\n===================", "cyan")

    #==================
    def peaktreeToPicks(self, peaktree):
        picks = []
        for p in peaktree:
            picks.append((p['xcoord'], p['ycoord']))
        npicks = numpy.asarray(picks, dtype=numpy.float32)
        return npicks
Beispiel #10
0
class FitAllDialog(wx.Dialog):
    #==================
    def __init__(self, parent):
        self.parent = parent
        wx.Dialog.__init__(self, self.parent.frame, -1,
                           "Least Squares Optimization")
        self.lsfit = None

        inforow = wx.FlexGridSizer(5, 4, 15, 15)

        thetastr = "%3.3f" % self.parent.data['theta']
        label = wx.StaticText(self,
                              -1,
                              "Tilt angle (theta): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        #self.tiltvalue = wx.StaticText(self, -1, thetastr, style=wx.ALIGN_CENTER|wx.ALIGN_CENTER_VERTICAL)
        self.thetavalue = FloatEntry(self,
                                     -1,
                                     allownone=False,
                                     chars=8,
                                     value=thetastr)
        label2 = wx.StaticText(self,
                               -1,
                               "degrees",
                               style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.thetatog = wx.ToggleButton(self, -1, "Refine")
        self.Bind(wx.EVT_TOGGLEBUTTON, self.onToggleTheta, self.thetatog)
        #self.thetavalue.Enable(False)
        #self.thetatog.SetValue(1)
        inforow.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(
            self.thetavalue, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)
        inforow.Add(label2, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.thetatog, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        gammastr = "%3.3f" % self.parent.data['gamma']
        label = wx.StaticText(self,
                              -1,
                              "Image 1 Rotation (gamma): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.gammavalue = FloatEntry(self,
                                     -1,
                                     allownone=False,
                                     chars=8,
                                     value=gammastr)
        label2 = wx.StaticText(self,
                               -1,
                               "degrees",
                               style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.gammatog = wx.ToggleButton(self, -1, "Refine")
        self.Bind(wx.EVT_TOGGLEBUTTON, self.onToggleGamma, self.gammatog)
        inforow.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.gammavalue, 0,
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(label2, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.gammatog, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        phistr = "%3.3f" % self.parent.data['phi']
        label = wx.StaticText(self,
                              -1,
                              "Image 2 Rotation (phi): ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.phivalue = FloatEntry(self,
                                   -1,
                                   allownone=False,
                                   chars=8,
                                   value=phistr)
        label2 = wx.StaticText(self,
                               -1,
                               "degrees",
                               style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.phitog = wx.ToggleButton(self, -1, "Refine")
        self.Bind(wx.EVT_TOGGLEBUTTON, self.onTogglePhi, self.phitog)
        inforow.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.phivalue, 0,
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(label2, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.phitog, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        scalestr = "%3.3f" % self.parent.data['scale']
        label = wx.StaticText(self,
                              -1,
                              "Scaling factor: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.scalevalue = FloatEntry(self,
                                     -1,
                                     allownone=False,
                                     chars=8,
                                     value=scalestr)
        label2 = wx.StaticText(self,
                               -1,
                               " ",
                               style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.scaletog = wx.ToggleButton(self, -1, "Locked")
        self.Bind(wx.EVT_TOGGLEBUTTON, self.onToggleScale, self.scaletog)
        self.scalevalue.Enable(False)
        self.scaletog.SetValue(1)
        inforow.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.scalevalue, 0,
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(label2, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.scaletog, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        shiftxstr = "%3.3f" % self.parent.data['shiftx']
        shiftystr = "%3.3f" % self.parent.data['shifty']
        label = wx.StaticText(self,
                              -1,
                              "Shift (x,y) pixels: ",
                              style=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        self.shiftxvalue = FloatEntry(self,
                                      -1,
                                      allownone=False,
                                      chars=8,
                                      value=shiftxstr)
        self.shiftyvalue = FloatEntry(self,
                                      -1,
                                      allownone=False,
                                      chars=8,
                                      value=shiftystr)
        self.shifttog = wx.ToggleButton(self, -1, "Refine")
        self.Bind(wx.EVT_TOGGLEBUTTON, self.onToggleShift, self.shifttog)
        #self.shiftxvalue.Enable(False)
        #self.shiftyvalue.Enable(False)
        #self.shifttog.SetValue(1)
        inforow.Add(label, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.shiftxvalue, 0,
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.shiftyvalue, 0,
                    wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(self.shifttog, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        summaryrow = wx.GridSizer(1, 4)
        label = wx.StaticText(self,
                              -1,
                              "RMSD (pixels): ",
                              style=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        self.rmsdlabel = wx.StaticText(self,
                                       -1,
                                       " unknown ",
                                       style=wx.ALIGN_LEFT
                                       | wx.ALIGN_CENTER_VERTICAL)
        summaryrow.Add(label, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        summaryrow.Add(self.rmsdlabel, 0,
                       wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        label = wx.StaticText(self,
                              -1,
                              "Iterations: ",
                              style=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        self.iterlabel = wx.StaticText(self,
                                       -1,
                                       " none ",
                                       style=wx.ALIGN_LEFT
                                       | wx.ALIGN_CENTER_VERTICAL)
        summaryrow.Add(label, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
        summaryrow.Add(self.iterlabel, 0,
                       wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)

        self.cancelfitall = wx.Button(self, wx.ID_CANCEL, '&Cancel')
        self.applyfitall = wx.Button(self, wx.ID_APPLY, '&Apply')
        self.runfitall = wx.Button(self, -1, '&Run')
        self.Bind(wx.EVT_BUTTON, self.onRunLeastSquares, self.runfitall)
        self.Bind(wx.EVT_BUTTON, self.onApplyLeastSquares, self.applyfitall)
        buttonrow = wx.GridSizer(1, 3)
        buttonrow.Add(self.cancelfitall, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        buttonrow.Add(self.applyfitall, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        buttonrow.Add(self.runfitall, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)

        self.sizer = wx.FlexGridSizer(3, 1)
        self.sizer.Add(inforow, 0, wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(summaryrow, 0, wx.EXPAND | wx.ALL, 5)
        self.sizer.Add(buttonrow, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizerAndFit(self.sizer)

        self.onToggleScale(True)

    #==================
    def onToggleTheta(self, evt):
        if self.thetatog.GetValue() is True:
            self.thetavalue.Enable(False)
            self.thetatog.SetLabel("Locked")
        else:
            self.thetavalue.Enable(True)
            self.thetatog.SetLabel("Refine")

    #==================
    def onToggleGamma(self, evt):
        if self.gammatog.GetValue() is True:
            self.gammavalue.Enable(False)
            self.gammatog.SetLabel("Locked")
        else:
            self.gammavalue.Enable(True)
            self.gammatog.SetLabel("Refine")

    #==================
    def onTogglePhi(self, evt):
        if self.phitog.GetValue() is True:
            self.phivalue.Enable(False)
            self.phitog.SetLabel("Locked")
        else:
            self.phivalue.Enable(True)
            self.phitog.SetLabel("Refine")

    #==================
    def onTogglePhi(self, evt):
        if self.phitog.GetValue() is True:
            self.phivalue.Enable(False)
            self.phitog.SetLabel("Locked")
        else:
            self.phivalue.Enable(True)
            self.phitog.SetLabel("Refine")

    #==================
    def onToggleScale(self, evt):
        if self.scaletog.GetValue() is True:
            self.scalevalue.Enable(False)
            self.scaletog.SetLabel("Locked")
        else:
            self.scalevalue.Enable(True)
            self.scaletog.SetLabel("Refine")

    #==================
    def onToggleShift(self, evt):
        if self.shifttog.GetValue() is True:
            self.shiftxvalue.Enable(False)
            self.shiftyvalue.Enable(False)
            self.shifttog.SetLabel("Locked")
        else:
            self.shiftxvalue.Enable(True)
            self.shiftyvalue.Enable(True)
            self.shifttog.SetLabel("Refine")

    #==================
    def onRunLeastSquares(self, evt):
        theta = self.thetavalue.GetValue()
        gamma = self.gammavalue.GetValue()
        phi = self.phivalue.GetValue()
        scale = self.scalevalue.GetValue()
        shiftx = self.shiftxvalue.GetValue()
        shifty = self.shiftyvalue.GetValue()
        #SET XSCALE
        xscale = numpy.array((
            not self.thetatog.GetValue(),
            not self.gammatog.GetValue(),
            not self.phitog.GetValue(),
            not self.scaletog.GetValue(),
            not self.shifttog.GetValue(),
            not self.shifttog.GetValue(),
        ),
                             dtype=numpy.float32)
        #GET TARGETS
        targets1 = self.parent.panel1.getTargets('Picked')
        a1 = self.parent.targetsToArray(targets1)
        targets2 = self.parent.panel2.getTargets('Picked')
        a2 = self.parent.targetsToArray(targets2)
        if len(a1) > len(a2):
            print "shorten a1"
            a1 = a1[0:len(a2), :]
        elif len(a2) > len(a1):
            print "shorten a2"
            a2 = a2[0:len(a1), :]
        self.lsfit = apTiltTransform.willsq(a1, a2, theta, gamma, phi, scale,
                                            shiftx, shifty, xscale)
        #pprint.pprint(self.lsfit)
        self.thetavalue.SetValue(round(self.lsfit['theta'], 5))
        self.gammavalue.SetValue(round(self.lsfit['gamma'], 5))
        self.phivalue.SetValue(round(self.lsfit['phi'], 5))
        self.scalevalue.SetValue(round(self.lsfit['scale'], 5))
        self.shiftxvalue.SetValue(round(self.lsfit['shiftx'], 5))
        self.shiftyvalue.SetValue(round(self.lsfit['shifty'], 5))
        self.rmsdlabel.SetLabel(str(round(self.lsfit['rmsd'], 5)))
        self.iterlabel.SetLabel(str(self.lsfit['iter']))

    #==================
    def onApplyLeastSquares(self, evt):
        self.Close()
        self.parent.data['leastsqfitdata'] = self.lsfit
        self.parent.data['theta'] = self.thetavalue.GetValue()
        self.parent.data['gamma'] = self.gammavalue.GetValue()
        self.parent.data['phi'] = self.phivalue.GetValue()
        self.parent.data['scale'] = self.scalevalue.GetValue()
        self.parent.data['shiftx'] = self.shiftxvalue.GetValue()
        self.parent.data['shifty'] = self.shiftyvalue.GetValue()
        self.parent.data['rmsd'] = self.lsfit['rmsd']
        self.parent.data['point1'] = self.lsfit['point1']
        self.parent.data['point2'] = self.lsfit['point2']
        self.parent.data['optimrun'] = True
        self.parent.onUpdate(evt)
Beispiel #11
0
class PartCutoffDialog(wx.Dialog):
    #==================
    def __init__(self, parent):
        self.parent = parent

        ### get stats
        rmsd = self.parent.getRmsdArray()
        worstvalstr = "%.3f" % (rmsd.max())
        meanvalstr = "%.3f +/- %.3f" % (rmsd.mean(), rmsd.std())
        minworsterrstr = "%.3f" % (self.parent.minworsterr)

        ### create dialog
        wx.Dialog.__init__(self, self.parent.frame, -1,
                           "Particle Cutoff Removal")

        ### create input area
        inforow = wx.FlexGridSizer(3, 2, 15, 15)

        meanlabel = wx.StaticText(self,
                                  -1,
                                  "Current mean RMSD: ",
                                  style=wx.ALIGN_LEFT
                                  | wx.ALIGN_CENTER_VERTICAL)
        meanvalue = wx.StaticText(self,
                                  -1,
                                  meanvalstr,
                                  style=wx.ALIGN_CENTER
                                  | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(meanlabel, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(
            meanvalue, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)

        worstlabel = wx.StaticText(self,
                                   -1,
                                   "Current worst RMSD: ",
                                   style=wx.ALIGN_LEFT
                                   | wx.ALIGN_CENTER_VERTICAL)
        worstvalue = wx.StaticText(self,
                                   -1,
                                   worstvalstr,
                                   style=wx.ALIGN_CENTER
                                   | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(worstlabel, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(
            worstvalue, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)

        cutofflabel = wx.StaticText(self,
                                    -1,
                                    "RMSD cutoff: ",
                                    style=wx.ALIGN_LEFT
                                    | wx.ALIGN_CENTER_VERTICAL)
        self.cutoffvalue = FloatEntry(self,
                                      -1,
                                      allownone=False,
                                      chars=8,
                                      value=minworsterrstr)
        inforow.Add(cutofflabel, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)
        inforow.Add(
            self.cutoffvalue, 0,
            wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)

        ### create button area
        cancelcutoff = wx.Button(self, wx.ID_CANCEL, '&Cancel')
        self.applycutoff = wx.Button(self, wx.ID_APPLY, '&Apply')
        self.Bind(wx.EVT_BUTTON, self.onApplyCutoff, self.applycutoff)
        buttonrow = wx.GridSizer(1, 2)
        buttonrow.Add(cancelcutoff, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)
        buttonrow.Add(self.applycutoff, 0,
                      wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 0)

        ### merge input and button areas
        self.sizer = wx.FlexGridSizer(2, 1)
        self.sizer.Add(inforow, 0, wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(buttonrow, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizerAndFit(self.sizer)

    #==================
    def onApplyCutoff(self, evt):
        ### get values
        cutoff = self.cutoffvalue.GetValue()
        a1 = self.parent.getArray1()
        a2 = self.parent.getArray2()
        rmsd = self.parent.getRmsdArray()

        ### must set a lower bound
        if cutoff < rmsd.mean():
            self.Destroy()
            dialog = wx.MessageDialog(
                self.parent.frame,
                "Particle Cutoff must be greater than the mean error", 'Error',
                wx.OK | wx.ICON_ERROR)
            dialog.ShowModal()
            dialog.Destroy()
            return

        ### find good particles
        g1 = []
        g2 = []
        for i, val in enumerate(rmsd):
            if val < cutoff:
                g1.append(a1[i])
                g2.append(a2[i])

        ### replace existing particles with only good ones
        apDisplay.printMsg("Eliminated " + str(len(a1) - len(g1)) +
                           " particles")
        self.parent.panel1.setTargets('Worst', [])
        self.parent.panel2.setTargets('Worst', [])
        self.parent.panel1.setTargets('Picked', g1)
        self.parent.panel2.setTargets('Picked', g2)
        self.parent.onUpdate(None)
        self.parent.statbar.PushStatusText(
            "Removed " + str(len(a1) - len(g1)) + " particles", 0)

        self.Destroy()
        return
Beispiel #12
0
class MeasureComafreeDialog(wx.Dialog):
        def __init__(self, parent):
                self.node = parent.node
                self.panel = parent

                wx.Dialog.__init__(self, parent, -1, 'Measure Coma-free Beam Tilt')

                self.measure = wx.Button(self, -1, 'Measure')
                self.correctshift = wx.CheckBox(self, -1, 'Correct image-shift-induced beam tilt')
                self.correct = wx.Button(self, -1, 'Correct Beam Tilt')
                self.correct.Enable(False)
                self.Bind(wx.EVT_BUTTON, self.onMeasureButton, self.measure)
                self.Bind(wx.EVT_BUTTON, self.onCorrectButton, self.correct)

                szbutton = wx.GridBagSizer(5, 5)
                szbutton.Add(self.correctshift, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
                szbutton.Add(self.measure, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
                szbutton.Add(self.correct, (2, 0), (1, 1), wx.EXPAND)

                sbsz = wx.GridBagSizer(5, 5)

                tiltlabel = wx.StaticText(self, -1, 'Tilt (radian):')
                self.tiltvalue = FloatEntry(self, -1, allownone=False, chars=5, value='0.005')
                sbsz.Add(tiltlabel, (0,0), (1,1))
                sbsz.Add(self.tiltvalue, (0,1), (1,1))

                self.labels = {}
                self.labels['comatilt'] = {}
                for axis in ('x', 'y'):
                        self.labels['comatilt'][axis] = wx.StaticText(self, -1, '(Not measured)')

                szresult = wx.GridBagSizer(5, 5)
                label = wx.StaticText(self, -1, 'Beam Tilt Adjustment')
                szresult.Add(label, (0, 0), (1, 2), wx.ALIGN_CENTER_VERTICAL)
                label = wx.StaticText(self, -1, 'x')
                szresult.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
                szresult.Add(self.labels['comatilt']['x'], (1, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
                label = wx.StaticText(self, -1, 'y')
                szresult.Add(label, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
                szresult.Add(self.labels['comatilt']['y'], (2, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
                szresult.AddGrowableRow(0)
                szresult.AddGrowableRow(1)
                szresult.AddGrowableRow(2)
                szresult.AddGrowableCol(1)

                self.sizer = wx.GridBagSizer(5, 5)
                self.sizer.Add(sbsz, (0, 0), (1, 2), wx.EXPAND|wx.ALL, 10)
                self.sizer.Add(szresult, (1, 0), (2, 2), wx.EXPAND|wx.ALL, 10)
                self.sizer.Add(szbutton, (3, 0), (2, 2), wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL, 10)

                self.SetSizerAndFit(self.sizer)

        def onMeasureButton(self, evt):
                btilt = self.tiltvalue.GetValue()
                correctshift = self.correctshift.GetValue()
                self.panel._calibrationEnable(False)
                threading.Thread(target=self.node.measureComaFree, args=(btilt,correctshift)).start()

        def onCorrectButton(self, evt):
                self.panel.instrumentEnable(False)
                threading.Thread(target=self.node.correctComaTilt).start()
Beispiel #13
0
class EditPlanDialog(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent.GetParent(), -1, 'Edit Plan')
        self.parent = parent
        self.plan = parent.plan

        strows = wx.StaticText(self, -1, 'Bad rows:')
        stcolumns = wx.StaticText(self, -1, 'Bad columns:')
        stpixels = wx.StaticText(self, -1, 'Bad Pixel (x,y):')

        pixels = ', '.join(map(str, self.plan['pixels']))
        rows = ', '.join(map(str, self.plan['rows']))
        columns = ', '.join(map(str, self.plan['columns']))

        self.tcrows = wx.TextCtrl(self, -1, rows)
        self.tccolumns = wx.TextCtrl(self, -1, columns)
        self.tcpixels = wx.TextCtrl(self, -1, pixels)

        self.cdespike = wx.CheckBox(self, -1, 'Despike images')
        self.cdespike_size = IntEntry(self, -1, min=1, chars=4)
        self.cdespike_threshold = FloatEntry(self, -1, min=0, chars=4)
        self.cdespike.SetValue(self.plan['despike'])
        self.cdespike_size.SetValue(self.plan['despike size'])
        self.cdespike_threshold.SetValue(self.plan['despike threshold'])

        szdespike = wx.GridBagSizer(5, 5)
        szdespike.Add(self.cdespike, (0, 0), (1, 2), wx.ALIGN_CENTER_VERTICAL)
        label = wx.StaticText(self, -1, 'Neighborhood size:')
        szdespike.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szdespike.Add(
            self.cdespike_size, (1, 1), (1, 1),
            wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        label = wx.StaticText(self, -1, 'Threshold:')
        szdespike.Add(label, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szdespike.Add(
            self.cdespike_threshold, (2, 1), (1, 1),
            wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE)
        szdespike.AddGrowableCol(1)

        bsave = wx.Button(self, wx.ID_OK, 'Save')
        bcancel = wx.Button(self, wx.ID_CANCEL, 'Cancel')
        szbutton = wx.GridBagSizer(5, 5)
        szbutton.Add(bsave, (0, 0), (1, 1), wx.ALIGN_CENTER)
        szbutton.Add(bcancel, (0, 1), (1, 1), wx.ALIGN_CENTER)

        szplan = wx.GridBagSizer(5, 5)
        szplan.Add(strows, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(self.tcrows, (0, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(stcolumns, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(self.tccolumns, (1, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(stpixels, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(self.tcpixels, (2, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szplan.Add(szdespike, (3, 0), (1, 2), wx.EXPAND)

        sz = wx.GridBagSizer(5, 5)
        sz.Add(szplan, (0, 0), (1, 1), wx.ALIGN_RIGHT | wx.ALL, border=5)
        sz.Add(szbutton, (1, 0), (1, 1), wx.ALIGN_RIGHT | wx.ALL, border=5)

        self.SetSizerAndFit(sz)

        self.Bind(wx.EVT_BUTTON, self.onSave, bsave)

    def onSave(self, evt):
        try:
            rows = str2plan(self.tcrows.GetValue())
            columns = str2plan(self.tccolumns.GetValue())
            pixels = str2pixels(self.tcpixels.GetValue())
        except ValueError:
            dialog = wx.MessageDialog(self, 'Invalid plan', 'Error',
                                      wx.OK | wx.ICON_ERROR)
            dialog.ShowModal()
            dialog.Destroy()
        else:
            self.plan = {
                'rows': rows,
                'columns': columns,
                'pixels': pixels,
                'despike': self.cdespike.GetValue(),
                'despike size': self.cdespike_size.GetValue(),
                'despike threshold': self.cdespike_threshold.GetValue()
            }
            evt.Skip()
Beispiel #14
0
class DoseScrolledSettings(leginon.gui.wx.Settings.ScrolledDialog):
    def initialize(self):
        leginon.gui.wx.Settings.ScrolledDialog.initialize(self)
        sb = wx.StaticBox(self, -1, 'Main Screen')
        sbszscreen = wx.StaticBoxSizer(sb, wx.VERTICAL)
        sb = wx.StaticBox(self, -1, 'Dose Measurement')
        sbsz = wx.StaticBoxSizer(sb, wx.VERTICAL)
        sb = wx.StaticBox(self, -1, 'Camera Sensitivity')
        sbszcam = wx.StaticBoxSizer(sb, wx.VERTICAL)

        self.bscreenup = wx.Button(self, -1, 'Up')
        self.bscreendown = wx.Button(self, -1, 'Down')

        szscreen = wx.GridBagSizer(5, 5)
        szscreen.Add(self.bscreenup, (0, 0), (1, 1), wx.ALIGN_CENTER)
        szscreen.Add(self.bscreendown, (0, 1), (1, 1), wx.ALIGN_CENTER)
        szscreen.AddGrowableCol(0)
        szscreen.AddGrowableCol(1)

        sbszscreen.Add(szscreen, 0, wx.EXPAND | wx.ALL, 5)

        self.stbeamcurrent = wx.StaticText(self, -1, '')
        self.stscreenmag = wx.StaticText(self, -1, '')
        self.stdoserate = wx.StaticText(self, -1, '')
        self.widgets['beam diameter'] = FloatEntry(self, -1, chars=6)
        self.widgets['scale factor'] = FloatEntry(self, -1, chars=6)
        self.bmeasuredose = wx.Button(self, -1, 'Measure Dose')

        sz = wx.GridBagSizer(5, 5)

        label = wx.StaticText(self, -1, 'Beam current:')
        sz.Add(label, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.Add(self.stbeamcurrent, (0, 1), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        label = wx.StaticText(self, -1, 'amps')
        sz.Add(label, (0, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'Screen magnification:')
        sz.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.Add(self.stscreenmag, (1, 1), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        label = wx.StaticText(self, -1, 'Dose rate:')
        sz.Add(label, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.Add(self.stdoserate, (2, 1), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        label = wx.StaticText(self, -1, 'e/A^2/s')
        sz.Add(label, (2, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'Beam diameter:')
        sz.Add(label, (3, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.Add(self.widgets['beam diameter'], (3, 1), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE | wx.ALIGN_RIGHT)
        label = wx.StaticText(self, -1, 'meters')
        sz.Add(label, (3, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        label = wx.StaticText(self, -1, 'Screen to beam current scale factor:')
        sz.Add(label, (4, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        sz.Add(self.widgets['scale factor'], (4, 1), (1, 1),
               wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE | wx.ALIGN_RIGHT)

        sz.Add(self.bmeasuredose, (5, 0), (1, 3),
               wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)

        sz.AddGrowableCol(1)

        sbsz.Add(sz, 0, wx.EXPAND | wx.ALL, 5)

        self.szdose = sz

        self.sensitivity = FloatEntry(self, -1, chars=6)
        self.setsensitivity = wx.Button(self, -1, 'Save')
        self.bcalibratesensitivity = wx.Button(self, -1, 'Calibrate')

        szcam = wx.GridBagSizer(5, 5)
        szcam.Add(self.bcalibratesensitivity, (0, 0), (1, 4),
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
        szcam.AddGrowableCol(0)
        label = wx.StaticText(self, -1, 'Sensitivity:')
        szcam.Add(label, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        szcam.Add(self.sensitivity, (1, 1), (1, 1),
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        label = wx.StaticText(self, -1, 'counts/e')
        szcam.Add(label, (1, 2), (1, 1),
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
        szcam.Add(self.setsensitivity, (1, 3), (1, 1),
                  wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)

        sbszcam.Add(szcam, 1, wx.EXPAND | wx.ALL, 5)

        self.Bind(wx.EVT_BUTTON, self.onScreenUpButton, self.bscreenup)
        self.Bind(wx.EVT_BUTTON, self.onScreenDownButton, self.bscreendown)
        self.Bind(wx.EVT_BUTTON, self.onMeasureDoseButton, self.bmeasuredose)
        self.Bind(wx.EVT_BUTTON, self.onSetSensitivityButton,
                  self.setsensitivity)
        self.Bind(wx.EVT_BUTTON, self.onCalibrateSensitivityButton,
                  self.bcalibratesensitivity)

        return [sbszscreen, sbsz, sbszcam]

    def onScreenUpButton(self, evt):
        threading.Thread(target=self.node.screenUp).start()
        #self.node.screenUp()

    def onScreenDownButton(self, evt):
        threading.Thread(target=self.node.screenDown).start()
        #self.node.screenDown()

    def _setDoseResults(self, results):
        try:
            self.stbeamcurrent.SetLabel('%.5g' % results['beam current'])
            self.stscreenmag.SetLabel(str(results['screen magnification']))
            self.stdoserate.SetLabel('%.5g' % (results['dose rate'] / 1e20))
        except KeyError:
            self.stbeamcurrent.SetLabel('')
            self.stscreenmag.SetLabel('')
            self.stdoserate.SetLabel('')
        self.dialog.szmain.Layout()
        self.Fit()

    def onMeasureDoseButton(self, evt):
        threading.Thread(target=self.node.uiMeasureDoseRate).start()
        #self.node.uiMeasureDoseRate()
        #self._setDoseResults(self.node.results)

    def _setSensitivityResults(self, results):
        if results is None:
            self.sensitivity.SetValue(0)
        else:
            self.sensitivity.SetValue(results)
        self.dialog.szmain.Layout()
        self.Fit()

    def onSetSensitivityButton(self, evt):
        self.node.onSetSensitivity(self.sensitivity.GetValue())

    def onCalibrateSensitivityButton(self, evt):
        threading.Thread(target=self.node.uiCalibrateCamera).start()
Beispiel #15
0
class PixelToPixelDialog(leginon.gui.wx.Dialog.Dialog):
    def __init__(self, parent, title):
        self.node = parent.node
        leginon.gui.wx.Dialog.Dialog.__init__(self,
                                              parent,
                                              title,
                                              style=wx.DEFAULT_DIALOG_STYLE)

    def onInitialize(self):
        mag1lab = wx.StaticText(self, -1, 'Mag 1:')
        self.mag1 = IntEntry(self, -1, chars=8)
        mag2lab = wx.StaticText(self, -1, 'Mag 2:')
        self.mag2 = IntEntry(self, -1, chars=8)
        p1lab = wx.StaticText(self, -1, 'Pixel 1:')
        self.p1row = FloatEntry(self, -1, chars=4)
        self.p1col = FloatEntry(self, -1, chars=4)
        p2lab = wx.StaticText(self, -1, 'Pixel 2:')
        self.p2row = FloatEntry(self, -1, chars=4)
        self.p2col = FloatEntry(self, -1, chars=4)

        angle1lab = wx.StaticText(self, -1, 'Angle 1')
        self.angle1 = wx.StaticText(self, -1, '')
        len1lab = wx.StaticText(self, -1, 'Length 1')
        self.len1 = wx.StaticText(self, -1, '')
        angle2lab = wx.StaticText(self, -1, 'Angle 2')
        self.angle2 = wx.StaticText(self, -1, '')
        len2lab = wx.StaticText(self, -1, 'Length 2')
        self.len2 = wx.StaticText(self, -1, '')

        calcp1 = wx.Button(self, -1, 'Calculate')
        self.Bind(wx.EVT_BUTTON, self.calcp1, calcp1)
        calcp2 = wx.Button(self, -1, 'Calculate')
        self.Bind(wx.EVT_BUTTON, self.calcp2, calcp2)

        self.sz.Add(mag1lab, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.mag1, (0, 1), (1, 2), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(mag2lab, (0, 3), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.mag2, (0, 4), (1, 2), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(p1lab, (1, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.p1row, (1, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.p1col, (1, 2), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(p2lab, (1, 3), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.p2row, (1, 4), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.p2col, (1, 5), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        self.sz.Add(angle1lab, (2, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.angle1, (2, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(angle2lab, (2, 3), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.angle2, (2, 4), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(len1lab, (3, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.len1, (3, 1), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(len2lab, (3, 3), (1, 1), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(self.len2, (3, 4), (1, 1), wx.ALIGN_CENTER_VERTICAL)

        self.sz.Add(calcp1, (4, 0), (1, 3), wx.ALIGN_CENTER_VERTICAL)
        self.sz.Add(calcp2, (4, 3), (1, 3), wx.ALIGN_CENTER_VERTICAL)

    def calcp1(self, evt):
        p2row = self.p2row.GetValue()
        p2col = self.p2col.GetValue()
        mag1 = self.mag1.GetValue()
        mag2 = self.mag2.GetValue()
        p2 = p2row, p2col
        p1 = self.node.pixelToPixel(mag2, mag1, p2)
        self.p1row.SetValue(p1[0])
        self.p1col.SetValue(p1[1])
        a, n = self.angle_len(p1)
        self.angle1.SetLabel(str(a))
        self.len1.SetLabel(str(n))

    def calcp2(self, evt):
        p1row = self.p1row.GetValue()
        p1col = self.p1col.GetValue()
        mag1 = self.mag1.GetValue()
        mag2 = self.mag2.GetValue()
        p1 = p1row, p1col
        p2 = self.node.pixelToPixel(mag1, mag2, p1)
        self.p2row.SetValue(p2[0])
        self.p2col.SetValue(p2[1])
        a, n = self.angle_len(p2)
        self.angle2.SetLabel(str(a))
        self.len2.SetLabel(str(n))

    def angle_len(self, vect):
        angle = numpy.arctan2(*tuple(vect))
        angle = math.degrees(angle)
        len = numpy.hypot(*tuple(vect))
        return angle, len
class MeasureTiltAxisDialog(wx.Dialog):
        def __init__(self, parent):
                self.node = parent.node

                wx.Dialog.__init__(self, parent, -1, "Measure Stage Tilt Axis Location")
                sb = wx.StaticBox(self, -1, 'Tilt Axis Params')
                sbsz2 = wx.StaticBoxSizer(sb, wx.VERTICAL)

                sbsz = wx.GridBagSizer(3,6)

                row = int(0)
                label = wx.StaticText(self, -1, "Tilt angle: ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                self.tiltvalue = FloatEntry(self, -1, allownone=False, chars=5, value='15.0')
                label2 = wx.StaticText(self, -1, " degrees", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(label, (row,0), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(self.tiltvalue, (row,1), (1,1), wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(label2, (row,2), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

                row += 1
                self.tilttwice = wx.CheckBox(self, -1, "Tilt both directions")
                sbsz.Add(self.tilttwice, (row,0), (1,3), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

                row += 1
                label = wx.StaticText(self, -1, "Average ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                label2 = wx.StaticText(self, -1, " tilts", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                self.numtilts = IntEntry(self, -1, allownone=False, chars=1, value='1')
                sbsz.Add(label, (row,0), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(self.numtilts, (row,1), (1,1), wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(label2, (row,2), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

                row += 1
                label = wx.StaticText(self, -1, "SNR cutoff: ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                self.snrvalue = FloatEntry(self, -1, allownone=False, chars=5, value='10.0')
                label2 = wx.StaticText(self, -1, " levels")
                sbsz.Add(label, (row,0), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(self.snrvalue, (row,1), (1,1), wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(label2, (row,2), (1,1), wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

                row += 1
                label = wx.StaticText(self, -1, "Correlation: ", style=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
                self.phasecorr = wx.RadioButton(self, -1, "Phase", style=wx.RB_GROUP|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
                self.crosscorr = wx.RadioButton(self, -1, "Cross", style=wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL)
                sbsz.Add(label, (row,0), (1,1))
                sbsz.Add(self.phasecorr, (row,1), (1,1))
                sbsz.Add(self.crosscorr, (row,2), (1,1))

                row += 1
                self.medfilt = wx.CheckBox(self, -1, "Median filter phase correlation")
                self.medfilt.SetValue(True)
                sbsz.Add(self.medfilt, (row,0), (1,3), wx.EXPAND|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)

                self.measurecancel = wx.Button(self, wx.ID_CANCEL, 'Cancel')
                self.measureinit = wx.Button(self,  -1, 'Initial\nOffset')
                self.Bind(wx.EVT_BUTTON, self.onMeasureButtonInit, self.measureinit)
                self.measureupdate = wx.Button(self,  -1, 'Update\nOffset')
                self.Bind(wx.EVT_BUTTON, self.onMeasureButtonUpdate, self.measureupdate)

                sbsz2.Add(sbsz, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 1)

                buttonrow = wx.GridSizer(1,3)
                self.measurecancel.SetMinSize((85, 46))
                self.measureinit.SetMinSize((85, 46))
                self.measureupdate.SetMinSize((85, 46))
                buttonrow.Add(self.measurecancel, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
                buttonrow.Add(self.measureinit, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 0)
                buttonrow.Add(self.measureupdate, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 0)

                self.sizer = wx.FlexGridSizer(3,1)
                sbsz2.SetMinSize((270, 200))
                self.sizer.Add(sbsz2, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 3)
                #self.sizer.Add((10, 10), 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE|wx.ALL, 3)
                self.sizer.Add(buttonrow, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE|wx.ALL, 3)

                self.SetSizerAndFit(self.sizer)

        def onMeasureButtonInit(self, evt):
                self.node.logger.info('Obtain new beam tilt axis')
                self.onMeasure(evt, update=False)

        def onMeasureButtonUpdate(self, evt):
                self.node.logger.info('Updating beam tilt axis')
                self.onMeasure(evt, update=True)

        def onMeasure(self, evt, update):
                self.Close()
                atilt = self.tiltvalue.GetValue()
                asnr  = self.snrvalue.GetValue()
                if asnr <= 0:
                        self.node.logger.error('SNR cannot be less than or equal to zero')
                        return
                amedfilt = self.medfilt.GetValue()
                anumtilts = self.numtilts.GetValue()
                if(self.crosscorr.GetValue() and not self.phasecorr.GetValue()):
                        acorr = 'cross'
                else:
                        acorr = 'phase'
                atilttwice = self.tilttwice.GetValue()
                #RUN THE Measurement
                threading.Thread(target=self.node.measureTiltAxis, args=(atilt, anumtilts, atilttwice, update, asnr, acorr, amedfilt)).start()