class Tubes(wx.Panel):
    def __init__(self, parent=None):
        super(Tubes, self).__init__(parent)
        # Parameters
        self.parent = parent

        tubeBox = wx.StaticBox(self, -1, "Plate settings")

        mainSizer = wx.StaticBoxSizer(tubeBox, wx.VERTICAL)
        level1Sizer = wx.BoxSizer(wx.HORIZONTAL)
        level2Sizer = wx.BoxSizer(wx.HORIZONTAL)

        labelTube = wx.Button(self, name='labelTube', label='Go to tube #:', style=wx.TR_SINGLE)
        labelTube.Bind(wx.EVT_BUTTON, self.goto_tube)
        level1Sizer.Add(labelTube, 1, wx.RIGHT|wx.ALIGN_CENTER, 2)
        self.tubeNo = NumCtrl(self, name = 'gotoTube', value = 1, integerWidth = 2, allowNegative = False, min = 1, max = 99, 
                                fractionWidth = 0, groupDigits = False, autoSize = False, style = wx.TR_SINGLE|wx.CENTER, size = (29,-1))
        level1Sizer.Add(self.tubeNo, 1, wx.ALL|wx.ALIGN_CENTER, 2)
        mainSizer.Add(level1Sizer, 1, wx.ALL|wx.ALIGN_CENTER, 5)
        
        label_row = wx.StaticText(self, label='Rows', style=wx.TR_SINGLE)
        level2Sizer.Add(label_row, 2, wx.ALL|wx.ALIGN_CENTER, 2)
        self.tube_rows = NumCtrl(self, name = 'rowsTube', value = 12, integerWidth = 2, allowNegative = False, min = 1, max = 99, 
                                fractionWidth = 0, groupDigits = False, autoSize = False, style = wx.TR_SINGLE|wx.CENTER, size = (29,-1))
        level2Sizer.Add(self.tube_rows, 1, wx.ALL|wx.ALIGN_CENTER, 2)
        label_row = wx.StaticText(self, label='Columns', style=wx.TR_SINGLE)
        level2Sizer.Add(label_row, 2, wx.ALL|wx.ALIGN_CENTER, 2)
        self.tube_cols = NumCtrl(self, name = 'colsTube', value = 8, integerWidth = 2, allowNegative = False, min = 1, max = 99, 
                                fractionWidth = 0, groupDigits = False, autoSize = False, style = wx.TR_SINGLE|wx.CENTER, size = (29,-1))
        level2Sizer.Add(self.tube_cols, 1, wx.ALL|wx.ALIGN_CENTER, 2)
        mainSizer.Add(level2Sizer, 1, wx.ALL|wx.ALIGN_CENTER, 5)
        
        self.SetSizer(mainSizer)

    def goto_tube(self, event):
        rows = self.tube_rows.GetValue()
        cols = self.tube_cols.GetValue()
        tube = self.tubeNo.GetValue()-1
        if (tube+1 > rows*cols) or (tube < 0):
            return
        incX = self.parent.pos_param.setIncrementX.GetValue()
        incY = self.parent.pos_param.setIncrementY.GetValue()
        cols_step = int(tube/rows)
        rows_step = tube - (cols_step * rows)
        print(cols_step, rows_step)
        self.parent.control.move_abs(-rows_step*incX, cols_step*incY)
class ResampleNumBoxFrame(wx.Frame):
    def __init__(self, parent, values):
        wx.Frame.__init__(self, parent, \
                              title="Enter Resolution to Resample To", \
                              size = (350,100))

        panel = wx.Panel(self)

        sizer = wx.BoxSizer(wx.VERTICAL)

        flexsizer = wx.FlexGridSizer(cols=2, hgap=10, vgap=15)

        label1 = wx.StaticText(panel, -1, label='Resolution (in mm)')
        self.box1 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[0],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=False,
                            allowNone=True)

        flexsizer.Add(label1)
        flexsizer.Add(self.box1, 0, wx.ALIGN_RIGHT, 5)

        button = wx.Button(panel, -1, 'OK', size=(90, 30))
        button.Bind(wx.EVT_BUTTON, self.onButtonClick)
        sizer.Add(flexsizer, 1, wx.EXPAND | wx.ALL, 10)
        sizer.Add(button, 0, wx.ALIGN_CENTER)
        panel.SetSizer(sizer)

        self.Show()

    def onButtonClick(self, event):
        parent = self.Parent

        if type(self.box1.GetValue()) is not float:
            dlg = wx.MessageDialog(self, "Resolution must be a decimal " \
                                   "value, such as 2.5 or 3.0.",
                                   'Error!',
                               wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            val = self.box1.GetValue()
            parent.listbox.Append(str(val))
            self.Close()
Beispiel #3
0
class TextBoxFrame(wx.Frame):
    def __init__(self, parent, values):
        wx.Frame.__init__(self,
                          parent,
                          title="Enter Frequency Cutoffs (in Hz)",
                          size=(300, 140))

        panel = wx.Panel(self)

        sizer = wx.BoxSizer(wx.VERTICAL)

        flexsizer = wx.FlexGridSizer(cols=2, hgap=10, vgap=15)

        label1 = wx.StaticText(panel, -1, label='Low-frequency cutoff')
        self.box1 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[0],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=False,
                            allowNone=True)

        flexsizer.Add(label1)
        flexsizer.Add(self.box1, 0, wx.ALIGN_RIGHT, 5)

        label2 = wx.StaticText(panel, -1, label='High-frequency cutoff')
        self.box2 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[1],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=False,
                            allowNone=True)

        flexsizer.Add(label2, 0, wx.EXPAND, 2)
        flexsizer.Add(self.box2, 0, wx.ALIGN_RIGHT, 5)

        button = wx.Button(panel, -1, 'OK', size=(90, 30))
        button.Bind(wx.EVT_BUTTON, self.onButtonClick)
        sizer.Add(flexsizer, 1, wx.EXPAND | wx.ALL, 10)
        sizer.Add(button, 0, wx.ALIGN_CENTER)
        panel.SetSizer(sizer)

        self.Show()

    def onButtonClick(self, event):
        parent = self.Parent

        if self.box1.GetValue() and self.box2.GetValue():

            if self.box1.GetValue() >= self.box2.GetValue():
                dlg = wx.MessageDialog(
                    self, 'Lower Bound should be less than Upper Bound',
                    'Error!', wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
            else:
                val = [self.box1.GetValue(), self.box2.GetValue()]
                parent.listbox.Append(str(val))
                self.Close()
Beispiel #4
0
class ClipInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX )
        xLabel = wx.StaticText(self, -1,
                           "X",
                           pos=(120,5))
        yLabel = wx.StaticText(self, -1,
                           "Y",
                           pos=(180,5))
        centerLabel = wx.StaticText(self, -1,
                           "Enter min: ",
                           pos=(10,24))
        self.minxInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(90, 20), size=(100, -1))
        self.minyInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(150, 20), size=(100, -1))
        radiusLabel = wx.StaticText(self, -1,
                           "Enter max: ",
                           pos=(10,54))
        self.maxxInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(90, 50), size=(100, -1))
        self.maxyInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(150, 50), size=(100, -1))
        self.errorLabel = wx.StaticText(self, -1,
                                   "",
                                   pos=(90, 80))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 100), size=(100, 30))
        cancelBtn = wx.Button(self, -1, label='Cancel', pos=(120, 100), size=(100, 30))
        self.SetSize((230, 135))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        if self.minxInput.GetValue() < self.maxxInput.GetValue() and self.minyInput.GetValue() < self.maxyInput.GetValue():
            self.parent.canvas.min_x = self.minxInput.GetValue()
            self.parent.canvas.min_y = self.minyInput.GetValue()
            self.parent.canvas.max_x = self.maxxInput.GetValue()
            self.parent.canvas.max_y = self.maxyInput.GetValue()
            self.parent.canvas.draw()
            self.Show(False)
            self.parent.buttons[3] = True
        else:
            self.errorLabel.SetForegroundColour((255,0,0))
            self.errorLabel.SetLabel('Clipping Error')


    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[3] = True
Beispiel #5
0
class MyForm(wx.Frame):
 
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Background Reset Tutorial",size=wx.Size(500,500))
 
        # Add a panel so it looks the correct on all platforms
        self.panel = wx.Panel(self, wx.ID_ANY)

        #self.txt = wx.Button(self.panel,id=wx.ID_ANY,pos=(0,30),size=(100,30))
        sampleList = ['Input string', 'Input number','Checkbox','Dropdown','Toggle']
        self.txt = wx.ComboBox(self.panel, 500, "", (0,0), 
                         (170,50), sampleList,
                         wx.CB_DROPDOWN
                         #| wx.TE_PROCESS_ENTER
                         #| wx.CB_SORT
                         )
        Btn = wx.Button(self.panel, label="Submit")
        Btn.Bind(wx.EVT_BUTTON, self.onEnter)

        Btn1 = wx.Button(self.panel, label="Reset")
        Btn1.Bind(wx.EVT_BUTTON, self.onReset)

        topSizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        btnSizer.Add(Btn, 0, wx.ALL|wx.CENTER, 5)
        btnSizer.Add(Btn1, 0, wx.ALL|wx.LEFT, 5)
        topSizer.Add(self.txt, 0, wx.ALL|wx.CENTER, 10)
        
        
        
        topSizer.Add(btnSizer, 0, wx.CENTER)
        self.panel.SetSizer(topSizer)

    def onEnter(self, event):
        label = self.txt.GetValue()
        if label == "Input string":
            #print("Input string it's working")
            self.txtstring = wx.TextCtrl(self.panel,id=wx.ID_ANY,pos=(190,110))

            self.btn = wx.Button(self.panel,id=wx.ID_ANY,label="Show",pos=(350,110))
            self.btn.Bind(wx.EVT_BUTTON,self.onShow)
            self.static = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,240),style=wx.TE_READONLY)
        elif label == "Input number":
            #print("Input number it's working")
            self.txtnum = NumCtrl(self.panel,id=wx.ID_ANY,pos=(200,110))

            self.btn1 = wx.Button(self.panel,id=wx.ID_ANY,label="Show",pos=(350,110))
            self.btn1.Bind(wx.EVT_BUTTON,self.onShow1)
            self.static1 = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,100),style=wx.TE_READONLY)
        elif label  == "Checkbox":
            #print("Checkbox it's working")
            self.CB1 = wx.CheckBox(self.panel,id=wx.ID_ANY,label="Example1",pos=(200,110))
            self.CB2 = wx.CheckBox(self.panel,id=wx.ID_ANY,label="Exmaple2",pos=(200,130))
            self.Bind(wx.EVT_CHECKBOX,self.onShow2)
            self.static2 = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,100),style=wx.TE_READONLY)
        elif label == "Dropdown":
            #print("Dropdown it's working")
            sampleList1 = ['Sample1','Sample2','Sample3']
            self.dod = wx.ComboBox(self.panel, 500, "", (160,110), 
                         (170,50), sampleList1,
                         wx.CB_DROPDOWN
                         #| wx.TE_PROCESS_ENTER
                         #| wx.CB_SORT
                         )
            self.btn2 = wx.Button(self.panel,id=wx.ID_ANY,label="Show",pos=(350,110))
            self.btn2.Bind(wx.EVT_BUTTON,self.onShow3)
            self.static3 = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,100),style=wx.TE_READONLY)
        elif label == "Toggle":
            #print("Toggle it's working")
            self.Toggle = wx.ToggleButton(self.panel,id=1,label="default",pos=(200,110))
            self.Toggle.Bind(wx.EVT_TOGGLEBUTTON,self.onShow4)
            self.static4 = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,100),style=wx.TE_READONLY)
        #self.btn = wx.Button(self.panel,id=wx.ID_ANY,label="Show",pos=(350,110))
        #self.btn.Bind(wx.EVT_BUTTON,self.onShow)
        #self.static = wx.TextCtrl(self.panel,id=1,pos=(10,200),size=(460,100),style=wx.TE_READONLY)
    def onShow(self,event):
        value = self.txtstring.GetValue() 
        self.static.SetValue(value)
    def onShow1(self,event):
        value = self.txtnum.GetValue() 
        self.static1.SetValue(str(value))
    def onShow2(self,event):
        cb = event.GetEventObject() 
        lab = cb.GetLabel()
        self.static2.SetValue(lab)
    def onShow3(self,event):
        value = self.dod.GetValue()
        self.static3.SetValue(value)
    def onShow4(self,event):
        TO = self.Toggle.GetValue()
        self.static4.SetValue(str(TO))
    def onReset(self,event):
        pass
Beispiel #6
0
class SaveLayerDlg(wx.Dialog):
	def __init__(self, parent, model):
		wx.Dialog.__init__(self, parent, wx.ID_ANY, "Save Layer(s)")
		
		self.app = parent
		self.model = model
		self.layerText = self.getLayers()

		sizer = wx.BoxSizer(wx.VERTICAL)
		
		box = wx.BoxSizer(wx.HORIZONTAL)
		box.AddSpacer(10)
		
		self.lbStart = wx.ListBox(self, wx.ID_ANY, choices=self.layerText, style=wx.LB_SINGLE)
		self.lbStart.SetSelection(0)
		self.Bind(wx.EVT_LISTBOX, self.onLb, self.lbStart)
		b = wx.StaticBox(self, wx.ID_ANY, "Start Layer")
		sbox = wx.StaticBoxSizer(b, wx.VERTICAL)
		sbox.Add(self.lbStart)
		box.Add(sbox)
		box.AddSpacer(10)
		
		self.lbEnd = wx.ListBox(self, wx.ID_ANY, choices=self.layerText, style=wx.LB_SINGLE)
		self.lbEnd.SetSelection(len(self.layerText)-1)
		self.Bind(wx.EVT_LISTBOX, self.onLb, self.lbEnd)
		b = wx.StaticBox(self, wx.ID_ANY, "End Layer")
		sbox = wx.StaticBoxSizer(b, wx.VERTICAL)
		sbox.Add(self.lbEnd)
		box.Add(sbox)
		box.AddSpacer(10)
		
		vbox = wx.BoxSizer(wx.VERTICAL)
		vbox.AddSpacer(20)
		
		self.cbPreE = wx.CheckBox(self, wx.ID_ANY, "E Axis Reset")
		self.cbPreE.SetValue(True)
		vbox.Add(self.cbPreE)
		vbox.AddSpacer(20)
		
		self.cbZModify = wx.CheckBox(self, wx.ID_ANY, "Change height by")
		self.cbZModify.SetValue(True)
		self.Bind(wx.EVT_CHECKBOX, self.onCbZModify, self.cbZModify)
		self.cbZModify.SetValue(False)
		vbox.Add(self.cbZModify)
		vbox.AddSpacer(10)

		self.tcZDelta = NumCtrl(self, integerWidth=4, fractionWidth = 2)
		self.tcZDelta.Enable(False)
		vbox.Add(self.tcZDelta, 1, wx.ALIGN_CENTER_HORIZONTAL, 1)
		
		box.Add(vbox) #, 0, wx.GROW|wx.ALIGN_TOP)
		box.AddSpacer(10)

		sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)

		line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
		sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)

		btnsizer = wx.BoxSizer(wx.HORIZONTAL)

		self.bOk = wx.Button(self, wx.ID_ANY, "OK")
		self.bOk.SetHelpText("Save the chosen layer range")
		self.Bind(wx.EVT_BUTTON, self.onOK, self.bOk)
		btnsizer.Add(self.bOk)
		
		btnsizer.AddSpacer(20)

		btn = wx.Button(self, wx.ID_ANY, "Cancel")
		btn.SetHelpText("Exit without saving")
		btnsizer.Add(btn)
		self.Bind(wx.EVT_BUTTON, self.onCancel, btn)

		sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5)

		self.SetSizer(sizer)
		sizer.Fit(self)
		
	def onOK(self, evt):
		self.EndModal(wx.ID_OK)
		
	def onCancel(self, evt):
		self.EndModal(wx.ID_CANCEL)
		
	def onLb(self, evt):
		s = self.lbStart.GetSelection()
		e = self.lbEnd.GetSelection()
		self.bOk.Enable(s <= e)
		
	def onCbZModify(self, evt):
		self.tcZDelta.Enable(self.cbZModify.GetValue())
		
		
	def getValues(self):
		data = self.lbStart.GetSelection()
		try:
			slayer = int(data)
		except:
			slayer = 0
		
		data = self.lbEnd.GetSelection()
		try:
			elayer = int(data)
		except:
			elayer = 0
		
		return [slayer, elayer, self.cbPreE.GetValue(), self.cbZModify.GetValue(), self.tcZDelta.GetValue()]
		
	def getLayers(self):
		return ["%7.3f" % x.printHeight() for x in self.model]
Beispiel #7
0
class SpectroscopyGUI(wx.Frame):
    def __init__(self, parent=None, title="QuIN Lab Spectroscopy"):
        super(SpectroscopyGUI, self).__init__(parent,
                                              title=title,
                                              size=(1340, 690))
        self._filedir = os.getcwd() + "\\"
        self._truefilename = ""
        self._filename = ""
        self._lcvr_init = False
        self._zaber_init = False
        self._lcvr_swp = True
        self._zaber_swp = True

        main_panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        input_nb = wx.Notebook(main_panel)

        common_panel = wx.Panel(input_nb)
        common_sizer = wx.GridBagSizer()
        lcvr_swp_txt = wx.StaticText(common_panel,
                                     label="LCVR Mode:",
                                     size=(140, 20),
                                     style=wx.ALIGN_RIGHT)
        self._lcvr_swp_val = wx.Choice(common_panel,
                                       size=(-1, 20),
                                       choices=["Sweep", "Fixed"])
        self._lcvr_swp_val.Bind(wx.EVT_CHOICE, self._lcvr_swp_sel)
        zaber_swp_txt = wx.StaticText(common_panel,
                                      label="Zaber Mode:",
                                      size=(130, 20),
                                      style=wx.ALIGN_RIGHT)
        self._zaber_swp_val = wx.Choice(common_panel,
                                        size=(-1, 20),
                                        choices=["Sweep", "Fixed"])
        self._zaber_swp_val.Bind(wx.EVT_CHOICE, self._zaber_swp_sel)
        lcvr_label = wx.StaticText(common_panel,
                                   label="LCVR COM Port:",
                                   size=(140, 20),
                                   style=wx.ALIGN_RIGHT)
        self._lcvr_val = NumCtrl(common_panel,
                                 size=(-1, 20),
                                 style=wx.TE_PROCESS_ENTER)
        self._lcvr_val.SetAllowNegative(False)
        self._lcvr_val.SetBounds(1, 99)
        self._lcvr_val.SetFractionWidth(0)
        self._lcvr_val.SetIntegerWidth(2)
        self._lcvr_val.SetValue(6)
        self._lcvr_val.SetLimitOnFieldChange(True)
        self._lcvr_val.Bind(wx.EVT_KILL_FOCUS, self._lcvr_entry)
        lcvr_chan = wx.StaticText(common_panel,
                                  label="LCVR Channel:",
                                  size=(140, 20),
                                  style=wx.ALIGN_RIGHT)
        self._lcvr_ch = wx.Choice(common_panel,
                                  size=(-1, 20),
                                  choices=["1", "2", "3", "4"])
        zaber_txt = wx.StaticText(common_panel,
                                  label="Zaber COM Port:",
                                  size=(140, 20),
                                  style=wx.ALIGN_RIGHT)
        self._zaber_val = NumCtrl(common_panel,
                                  size=(-1, 20),
                                  style=wx.TE_PROCESS_ENTER)
        self._zaber_val.SetAllowNegative(False)
        self._zaber_val.SetBounds(1, 99)
        self._zaber_val.SetFractionWidth(0)
        self._zaber_val.SetIntegerWidth(2)
        self._zaber_val.SetValue(9)
        self._zaber_val.SetLimitOnFieldChange(True)
        self._zaber_val.Bind(wx.EVT_KILL_FOCUS, self._zaber_entry)
        wavelength_label = wx.StaticText(common_panel,
                                         label="Laser Wavelength (nm):",
                                         size=(130, 20),
                                         style=wx.ALIGN_RIGHT)
        self._wavelength_val = NumCtrl(common_panel,
                                       size=(-1, 20),
                                       style=wx.TE_PROCESS_ENTER)
        self._wavelength_val.SetAllowNegative(False)
        self._wavelength_val.SetBounds(400, 1100)
        self._wavelength_val.SetFractionWidth(0)
        self._wavelength_val.SetIntegerWidth(4)
        self._wavelength_val.SetValue(780)
        self._wavelength_val.SetLimitOnFieldChange(True)
        pow_label = wx.StaticText(common_panel,
                                  label="Laser Power (mW):",
                                  size=(130, 20),
                                  style=wx.ALIGN_RIGHT)
        self._pow_val = NumCtrl(common_panel,
                                size=(-1, 20),
                                style=wx.TE_PROCESS_ENTER)
        self._pow_val.SetAllowNegative(False)
        self._pow_val.SetBounds(0, 1000)
        self._pow_val.SetFractionWidth(2)
        self._pow_val.SetIntegerWidth(4)
        self._pow_val.SetValue(0)
        self._pow_val.SetLimitOnFieldChange(True)
        od_label = wx.StaticText(common_panel,
                                 label="OD:",
                                 size=(130, 20),
                                 style=wx.ALIGN_RIGHT)
        self._od_val = wx.Choice(common_panel,
                                 size=(-1, 20),
                                 choices=[
                                     "0", "0.5", "1", "1.5", "2", "2.5", "3",
                                     "3.5", "4", "4.5", "5"
                                 ])
        self._start_volt_txt = wx.StaticText(common_panel,
                                             label="Start Voltage (V):",
                                             size=(140, 20),
                                             style=wx.ALIGN_RIGHT)
        self._start_volt_val = NumCtrl(common_panel,
                                       size=(-1, 20),
                                       style=wx.TE_PROCESS_ENTER)
        self._start_volt_val.SetAllowNegative(False)
        self._start_volt_val.SetBounds(0, 10)
        self._start_volt_val.SetFractionWidth(2)
        self._start_volt_val.SetIntegerWidth(2)
        self._start_volt_val.SetValue(10)
        self._start_volt_val.SetLimitOnFieldChange(True)
        end_volt_label = wx.StaticText(common_panel,
                                       label="End Voltage (V):",
                                       size=(140, 20),
                                       style=wx.ALIGN_RIGHT)
        self._end_volt_val = NumCtrl(common_panel,
                                     size=(-1, 20),
                                     style=wx.TE_PROCESS_ENTER)
        self._end_volt_val.SetAllowNegative(False)
        self._end_volt_val.SetBounds(0, 10)
        self._end_volt_val.SetFractionWidth(2)
        self._end_volt_val.SetIntegerWidth(2)
        self._end_volt_val.SetValue(0)
        self._end_volt_val.SetLimitOnFieldChange(True)
        step_volt_label = wx.StaticText(common_panel,
                                        label="Absolute Step Voltage (V):",
                                        size=(140, 20),
                                        style=wx.ALIGN_RIGHT)
        self._step_volt_val = NumCtrl(common_panel,
                                      size=(-1, 20),
                                      style=wx.TE_PROCESS_ENTER)
        self._step_volt_val.SetAllowNegative(False)
        self._step_volt_val.SetBounds(0, 10)
        self._step_volt_val.SetFractionWidth(2)
        self._step_volt_val.SetIntegerWidth(2)
        self._step_volt_val.SetValue(0.1)
        self._step_volt_val.SetLimitOnFieldChange(True)
        self._dir_button = wx.Button(common_panel,
                                     label="Choose Save Location",
                                     size=(130, 20))
        self._dir_button.Bind(wx.EVT_BUTTON, self._dir_select)
        self._file_button = wx.Button(common_panel,
                                      label="Choose Save Filename",
                                      size=(130, 20))
        self._file_button.Bind(wx.EVT_BUTTON, self._file_select)
        self._go_button = wx.Button(common_panel,
                                    label="Start",
                                    size=(130, 20))
        self._go_button.SetForegroundColour(wx.Colour("GREEN"))
        self._go_button.Bind(wx.EVT_BUTTON, self._go)
        self._stop_button = wx.Button(common_panel,
                                      label="Stop",
                                      size=(130, 20))
        self._stop_button.Bind(wx.EVT_BUTTON, self._stop)
        self._stop_button.SetForegroundColour(wx.Colour("RED"))
        self._resume_button = wx.Button(common_panel,
                                        label="Resume",
                                        size=(130, 20))
        self._resume_button.Bind(wx.EVT_BUTTON, self._resume)
        self._pause_button = wx.Button(common_panel,
                                       label="Pause",
                                       size=(130, 20))
        self._pause_button.Bind(wx.EVT_BUTTON, self._pause)
        curr_dir_txt = wx.StaticText(common_panel,
                                     label="Current Directory:",
                                     size=(-1, 20),
                                     style=wx.ALIGN_RIGHT)
        self._curr_dir_disp = wx.StaticText(common_panel,
                                            label=self._filedir,
                                            size=(-1, 20))
        curr_file_txt = wx.StaticText(common_panel,
                                      label="Current Filename:",
                                      size=(-1, 20),
                                      style=wx.ALIGN_RIGHT)
        self._curr_file_disp = wx.StaticText(common_panel,
                                             label=self._filename,
                                             size=(-1, 20))
        common_sizer.Add(lcvr_label, (0, 0))
        common_sizer.Add(self._lcvr_val, (0, 1))
        common_sizer.Add(lcvr_chan, (1, 0))
        common_sizer.Add(self._lcvr_ch, (1, 1))
        common_sizer.Add(self._start_volt_txt, (2, 0))
        common_sizer.Add(self._start_volt_val, (2, 1))
        common_sizer.Add(end_volt_label, (3, 0))
        common_sizer.Add(self._end_volt_val, (3, 1))
        common_sizer.Add(step_volt_label, (4, 0))
        common_sizer.Add(self._step_volt_val, (4, 1))
        common_sizer.Add(zaber_txt, (5, 0))
        common_sizer.Add(self._zaber_val, (5, 1))
        common_sizer.Add(wavelength_label, (0, 2))
        common_sizer.Add(self._wavelength_val, (0, 3))
        common_sizer.Add(pow_label, (1, 2))
        common_sizer.Add(self._pow_val, (1, 3))
        common_sizer.Add(od_label, (2, 2))
        common_sizer.Add(self._od_val, (2, 3))
        common_sizer.Add(self._dir_button, (3, 2))
        common_sizer.Add(self._file_button, (3, 3))
        common_sizer.Add(self._go_button, (4, 2))
        common_sizer.Add(self._stop_button, (4, 3))
        common_sizer.Add(self._resume_button, (5, 2))
        common_sizer.Add(self._pause_button, (5, 3))
        common_sizer.Add(lcvr_swp_txt, (6, 0))
        common_sizer.Add(self._lcvr_swp_val, (6, 1))
        common_sizer.Add(zaber_swp_txt, (6, 2))
        common_sizer.Add(self._zaber_swp_val, (6, 3))
        common_sizer.Add(curr_dir_txt, (7, 0))
        common_sizer.Add(self._curr_dir_disp, (7, 1), wx.GBSpan(1, 3))
        common_sizer.Add(curr_file_txt, (8, 0))
        common_sizer.Add(self._curr_file_disp, (8, 1), wx.GBSpan(1, 3))
        common_panel.SetSizer(common_sizer)
        self._stop_button.Disable()
        self._pause_button.Disable()
        self._resume_button.Disable()

        self._zaber = ZaberLinearActuator()
        self._zaber_pnl = ZaberControlPanel(self._zaber, input_nb)
        self._zaber_pnl.disable_ui()

        self._lf = LightField("", True)
        self._lf.set_export(True)

        self._lfcontrol = LightFieldControlPanel(self._lf, input_nb)

        input_nb.InsertPage(0, common_panel, "Common Settings")
        input_nb.InsertPage(1, self._zaber_pnl, "Zaber Settings")
        input_nb.InsertPage(2, self._lfcontrol, "LightField Settings")

        copyright_str = "\u00a9 2016 QuIN Lab "
        copyright_str += "Developed by Hayden Jones"
        copyright_text = wx.StaticText(main_panel, label=copyright_str)

        self._img = wx.Image(1340, 400, True).ConvertToBitmap()
        self._display = wx.StaticBitmap(main_panel, -1, self._img,
                                        wx.DefaultPosition, wx.Size(1340, 400))
        self._display.SetBitmap(self._img)

        self._set_filename()
        self.update_file_display()

        main_sizer.Add(input_nb, 0, wx.ALL, 0)
        main_sizer.Add(self._display, 0, wx.ALL, 0)
        main_sizer.Add(copyright_text, 0, wx.ALL, 0)

        main_panel.SetSizer(main_sizer)
        main_panel.Layout()

        self.Bind(wx.EVT_CLOSE, self._on_close)

        self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
                            ^ wx.MAXIMIZE_BOX)
        self.Show()

    def _on_close(self, evt):
        if self._lcvr_init is True:
            self._lcvr.close()
        self._lf.close_lightfield()
        self._lf.close_matlab()
        evt.Skip()

    def disable_ui(self):
        self._zaber_val.Disable()
        self._lcvr_val.Disable()
        self._lcvr_ch.Disable()
        self._wavelength_val.Disable()
        self._pow_val.Disable()
        self._od_val.Disable()
        self._start_volt_val.Disable()
        self._end_volt_val.Disable()
        self._step_volt_val.Disable()
        self._dir_button.Disable()
        self._file_button.Disable()
        self._go_button.Disable()
        self._stop_button.Enable()
        self._resume_button.Disable()
        self._pause_button.Enable()
        self._zaber_pnl.disable_ui()
        self._lfcontrol.disable_ui()

    def enable_ui(self):
        self._zaber_val.Enable()
        self._lcvr_val.Enable()
        self._lcvr_ch.Enable()
        self._wavelength_val.Enable()
        self._pow_val.Enable()
        self._od_val.Enable()
        self._start_volt_val.Enable()
        self._end_volt_val.Enable()
        self._step_volt_val.Enable()
        self._dir_button.Enable()
        self._file_button.Enable()
        self._go_button.Enable()
        self._stop_button.Disable()
        self._resume_button.Disable()
        self._pause_button.Disable()
        self._zaber_pnl.enable_ui()
        self._lfcontrol.enable_ui()

    def get_od(self):
        return float(self._od_val.GetCurrentSelection() / 2)

    def get_wavelength(self):
        return self._wavelength_val.GetValue()

    def get_power(self):
        return self._pow_val.GetValue()

    def get_start_volt(self):
        return self._start_volt_val.GetValue()

    def get_end_volt(self):
        return self._end_volt_val.GetValue()

    def get_step_volt(self):
        return self._step_volt_val.GetValue()

    def get_lcvr_ch(self):
        return self._lcvr_ch.GetCurrentSelection() + 1

    def update_dir_display(self):
        self._curr_dir_disp.SetLabel(self._filedir)

    def update_file_display(self):
        self._curr_file_disp.SetLabel(self._filename)

    def _lcvr_swp_sel(self, evt):
        if self._lcvr_swp_val.GetCurrentSelection() == 0:
            self._lcvr_swp = True
        else:
            self._lcvr_swp = False

    def _zaber_swp_sel(self, evt):
        if self._zaber_swp_val.GetCurrentSelection() == 0:
            self._zaber_swp = True
        else:
            self._zaber_swp = False

    def _invalid_lcvr_warn(self):
        warning_message = "Invalid LCVR Controller Address/Connection!"
        warning = wx.GenericMessageDialog(None, warning_message, "Warning!",
                                          wx.OK, wx.DefaultPosition)
        warning.ShowModal()
        warning.Destroy()

    def _lcvr_entry(self, evt):
        if self._lcvr_init is True:
            return
        try:
            com_port = self._lcvr_val.GetValue()
            self._lcvr = MeadowlarkD3050Controller(com_port)
        except Exception:
            self._invalid_lcvr_warn()
            evt.Skip()
            return
        self._lcvr_init = True
        evt.Skip()

    def _invalid_zaber_warn(self):
        warning_message = "Invalid Zaber Address/Connection!"
        warning = wx.GenericMessageDialog(None, warning_message, "Warning!",
                                          wx.OK, wx.DefaultPosition)
        warning.ShowModal()
        warning.Destroy()

    def _zaber_entry(self, evt):
        if self._zaber_init is True:
            return
        try:
            com_port = self._zaber_val.GetValue()
            self._zaber.open(com_port)
        except Exception:
            self._invalid_zaber_warn()
            evt.Skip()
            return
        self._zaber_pnl.enable_ui()
        self._zaber_init = True
        evt.Skip()

    def _set_filename(self):
        self._filename = self._truefilename
        self._filename += "_OD" + str(self.get_od())
        self._filename += "_" + str(self.get_wavelength()) + "nm"
        self._filename += "_" + str(self.get_power()) + "mW"

    def _dir_select(self, evt):
        dir_dialog = wx.DirDialog(self, "Choose file save directory...", "",
                                  wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        if dir_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._filedir = dir_dialog.GetPath() + "\\"
        self.update_dir_display()
        dir_dialog.Destroy()

    def _file_select(self, evt):
        file_dialog = wx.TextEntryDialog(self, "Enter the file name...",
                                         "File Name Selection Dialog",
                                         self._truefilename)
        if file_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._truefilename = file_dialog.GetValue()
        self._set_filename()
        self.update_file_display()
        file_dialog.Destroy()

    def _go(self, evt):
        self._lcvr_entry(wx.EVT_BUTTON)
        self._zaber_entry(wx.EVT_BUTTON)
        if self._lcvr_init is False:
            self._invalid_lcvr_warn()
            return
        if self._zaber_init is False:
            self._invalid_zaber_warn()
            return
        self.disable_ui()
        self._kill_automation = False
        self._pause_automation = False
        _thread.start_new_thread(self._automation, (self.get_lcvr_ch(), ))

    def _stop(self, evt):
        self._kill_automation = True
        self._pause_automation = False
        self.enable_ui()

    def _resume(self, evt):
        self._od_val.Disable()
        self._resume_button.Disable()
        self._pause_button.Enable()
        self._pause_automation = False

    def _pause(self, evt):
        self._pause_automation = True
        self._od_val.Enable()
        self._resume_button.Enable()
        self._pause_button.Disable()

    def _automation(self, channel):
        self._lf.set_directory(self._filedir.rstrip("\\"))
        start_volt = self.get_start_volt()
        if self._lcvr_swp is True:
            end_volt = self.get_end_volt()
        else:
            end_volt = start_volt
        if start_volt > end_volt:
            step_volt = -self.get_step_volt()
        else:
            step_volt = self.get_step_volt()
        self._zaber.goto_pos(0, 324000)
        start_zaber = self._zaber_pnl.get_start()
        if self._zaber_swp is True:
            end_zaber = self._zaber_pnl.get_end()
            self._zaber.goto_pos(0, start_zaber)
        else:
            end_zaber = start_zaber
        if start_zaber > end_zaber:
            step_zaber = -self._zaber_pnl.get_step()
        else:
            step_zaber = self._zaber_pnl.get_step()
        self._lcvr.set_voltage(channel, start_volt)
        overlap_holder = []
        for i in range(int(start_volt * 1000), int((end_volt * 1000) + 1),
                       int(step_volt * 1000)):
            if self._kill_automation is True:
                break
            if self._pause_automation is True:
                i = overlap_holder[0]
                while self._pause_automation is True:
                    if self._kill_automation is True:
                        break
            overlap_holder.append(i)
            if len(overlap_holder) > 5:
                overlap_holder.pop(0)
            v = float(i / 1000)
            self._set_filename()
            self._lcvr.set_voltage(channel, v)
            self._filename += "_" + str(v) + "V"
            self._lf.set_filename(self._filename)
            for j in range(start_zaber, end_zaber + 1, step_zaber):
                if self._kill_automation is True:
                    break
                if self._pause_automation is True:
                    while self._pause_automation is True:
                        if self._kill_automation is True:
                            break
                self._filename += "_" + str(j) + "zaber"
                self._zaber.goby_dist(0, step_zaber)
                self._lf.set_filename(self._filename)
                self._lf.acquire(60)
                self._lf.set_filename(self._filename)
                newest_spe = max(glob.iglob(self._filedir + '*.spe'),
                                 key=os.path.getctime)
                spe2pngraw.spe2pngraw(self._filedir, newest_spe)
                newest_png = newest_spe.rstrip('.spe') + '.png'
                self._img = wx.Image(newest_png,
                                     wx.BITMAP_TYPE_ANY).ConvertToBitmap()
                wx.CallAfter(self._display.SetBitmap, self._img)
            sleep(1)
        wx.CallAfter(self._stop, wx.EVT_BUTTON)
class BETCoordinateFrame(wx.Frame):
    def __init__(self, parent, values):
        wx.Frame.__init__(self, parent, \
                              title="Enter Center of gravity coordinates", \
                              size = (450,150))

        panel = wx.Panel(self)

        sizer = wx.BoxSizer(wx.VERTICAL)

        flexsizer = wx.FlexGridSizer(cols=3, hgap=10, vgap=15)

        label1 = wx.StaticText(panel, -1, label='x-coordinate')
        self.box1 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[0],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=True,
                            allowNone=True)

        flexsizer.Add(label1)
        flexsizer.Add(self.box1, 0, wx.ALIGN_RIGHT, 5)

        label2 = wx.StaticText(panel, -1, label='y-coordinate')
        self.box2 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[1],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=True,
                            allowNone=True)

        flexsizer.Add(label2, 0, wx.EXPAND, 2)
        flexsizer.Add(self.box2, 0, wx.ALIGN_LEFT, 5)

        label3 = wx.StaticText(panel, -1, label='z-coordinate')
        self.box3 = NumCtrl(panel,
                            id=wx.ID_ANY,
                            value=values[2],
                            integerWidth=2,
                            fractionWidth=3,
                            allowNegative=True,
                            allowNone=True)

        flexsizer.Add(label3, 0, wx.EXPAND, 3)
        flexsizer.Add(self.box3, 0, wx.ALIGN_LEFT, 5)

        button = wx.Button(panel, -1, 'OK', size=(90, 30))
        button.Bind(wx.EVT_BUTTON, self.onButtonClick)
        sizer.Add(flexsizer, 1, wx.EXPAND | wx.ALL, 10)
        sizer.Add(button, 0, wx.ALIGN_CENTER)
        panel.SetSizer(sizer)

        self.Show()

    def onButtonClick(self, event):
        parent = self.Parent

        if type(self.box1.GetValue() or self.box2.GetValue()
                or self.box3.GetValue()) is not int:

            dlg = wx.MessageDialog(self, "the values should be int or long" \
                                       'Error!',
                                   wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            val = [
                self.box1.GetValue(),
                self.box2.GetValue(),
                self.box3.GetValue()
            ]
            parent.listbox.Append(str(val))
            self.Close()
Beispiel #9
0
class ScaleInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        sxLabel = wx.StaticText(self, -1, "Enter sx: ", pos=(10, 14))
        self.sxInput = NumCtrl(self,
                               value=0.0,
                               allowNegative=False,
                               integerWidth=2,
                               fractionWidth=2,
                               pos=(75, 10),
                               size=(100, -1))
        syLabel = wx.StaticText(self, -1, "Enter sy: ", pos=(10, 44))
        self.syInput = NumCtrl(self,
                               value=0.0,
                               allowNegative=False,
                               integerWidth=2,
                               fractionWidth=2,
                               pos=(75, 40),
                               size=(100, -1))
        angleLabel = wx.StaticText(self, -1, "Enter angle: ", pos=(10, 74))
        self.angleInput = NumCtrl(self,
                                  value=0.0,
                                  allowNegative=False,
                                  integerWidth=2,
                                  fractionWidth=2,
                                  pos=(75, 70),
                                  size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 100), size=(100, 20))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(10, 130),
                              size=(100, 20))
        self.SetSize((130, 170))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        sx = self.sxInput.GetValue()
        sy = self.syInput.GetValue()
        theta = self.angleInput.GetValue()
        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]
        self.parent.canvas.drawings.append(
            self.scale(points=self.parent.canvas.drawings[0],
                       sx=sx,
                       sy=sy,
                       theta=theta))

        self.Show(False)
        self.parent.buttons[10] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[10] = True

    def matrixMultiply(self, A, B):
        prod = list()
        for i in range(3):
            row = list()
            sm = 0
            for j in range(3):
                sm += A[i][j] * B[j][0]
            row.append(sm)
            prod.append(row)
        return prod

    def scale(self, points, sx, sy, theta):
        theta = radians(theta)
        translated_points = list()
        scale_mat = [[sx * cos(theta), -sy * sin(theta), 0],
                     [sx * sin(theta), sy * cos(theta), 0], [0, 0, 1]]
        for point in points:
            translated = self.matrixMultiply(scale_mat,
                                             [[point[0]], [point[1]], [1]])
            translated_points.append([translated[0][0], translated[1][0]])
        return translated_points
Beispiel #10
0
class ControlPanel(wx.Panel):
    def __init__(self, parent, size=(100, 100)):
        wx.Panel.__init__(self, parent=parent, size=size)

        self.signal_status_text = None
        self.dlg = wx.FileDialog(self,
                                 message="Choose a file",
                                 defaultDir=os.getcwd(),
                                 defaultFile="",
                                 wildcard=FILE_TYPES,
                                 style=wx.OPEN | wx.CHANGE_DIR
                                 | wx.FILE_MUST_EXIST)

        bandpass = self.buildBandpassBox()
        time_options = self.buildTimeOptions()
        test_signals = self.buildTestSignalsBox()
        output = self.buildOutput()

        left_vbox = wx.BoxSizer(wx.VERTICAL)
        left_vbox.Add(test_signals, proportion=0, flag=wx.EXPAND)
        left_vbox.Add(output, proportion=0, flag=wx.EXPAND)

        right_vbox = wx.BoxSizer(wx.VERTICAL)
        right_vbox.Add(bandpass, proportion=0, flag=wx.EXPAND)
        right_vbox.AddStretchSpacer(1)
        right_vbox.Add(time_options, proportion=0, flag=wx.EXPAND)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(left_vbox, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
        hbox.Add(right_vbox, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)

        self.SetSizer(hbox)

        self.Fit()
        self.SetMinSize(self.GetSize())

    def buildBandpassBox(self):
        bandpass_box = wx.StaticBox(self, label="Bandpass filter")
        text_start_fq = wx.StaticText(bandpass_box, label="Low cutoff:")
        self.input_start_fq = NumCtrl(bandpass_box,
                                      value=20,
                                      integerWidth=5,
                                      fractionWidth=0,
                                      allowNegative=False,
                                      min=20,
                                      max=20000)
        text_end_fq = wx.StaticText(bandpass_box, label="High cutoff:")
        self.input_end_fq = NumCtrl(bandpass_box,
                                    value=20000.0,
                                    integerWidth=5,
                                    fractionWidth=0,
                                    allowNegative=False,
                                    min=100,
                                    max=25000)
        button_apply_bandpass = wx.Button(bandpass_box,
                                          label="Apply bandpass filter")
        button_reset_bandpass = wx.Button(bandpass_box,
                                          label="Delete bandpass")

        button_apply_bandpass.Bind(wx.EVT_BUTTON, self.onApplyBandpass)
        button_reset_bandpass.Bind(wx.EVT_BUTTON, self.onResetBandpass)

        gridbag_sizer = wx.GridBagSizer(vgap=5, hgap=5)
        gridbag_sizer.Add(text_start_fq, pos=(0, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.input_start_fq, pos=(0, 2), flag=wx.EXPAND)
        gridbag_sizer.Add(text_end_fq, pos=(1, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.input_end_fq, pos=(1, 2), flag=wx.EXPAND)
        gridbag_sizer.Add(button_reset_bandpass, pos=(3, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(button_apply_bandpass, pos=(3, 2), flag=wx.EXPAND)

        gridbag_sizer.AddGrowableCol(1)
        # gridbag_sizer.AddGrowableRow(3)

        box_sizer = wx.StaticBoxSizer(bandpass_box, wx.VERTICAL)
        box_sizer.Add(gridbag_sizer, proportion=1, flag=wx.EXPAND)

        return box_sizer

    def buildTimeOptions(self):
        time_box = wx.StaticBox(self, label="Displayed time limits")
        text_start_time = wx.StaticText(time_box, label="Start:")
        self.input_start_time = NumCtrl(time_box,
                                        value=0.0,
                                        integerWidth=3,
                                        fractionWidth=2,
                                        allowNegative=False,
                                        min=0.00)
        text_end_time = wx.StaticText(time_box, label="End:")
        self.input_end_time = NumCtrl(time_box,
                                      value=1.0,
                                      integerWidth=3,
                                      fractionWidth=2,
                                      allowNegative=False,
                                      min=0.01)
        button_apply_time = wx.Button(time_box, label="Apply time limits")
        button_reset_time = wx.Button(time_box, label="Reset time limits")

        button_apply_time.Bind(wx.EVT_BUTTON, self.onApplyTime)
        button_reset_time.Bind(wx.EVT_BUTTON, self.onResetTime)

        gridbag_sizer = wx.GridBagSizer(vgap=5, hgap=5)
        gridbag_sizer.Add(text_start_time, pos=(0, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.input_start_time, pos=(0, 2), flag=wx.EXPAND)
        gridbag_sizer.Add(text_end_time, pos=(1, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.input_end_time, pos=(1, 2), flag=wx.EXPAND)
        gridbag_sizer.Add(button_reset_time, pos=(3, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(button_apply_time, pos=(3, 2), flag=wx.EXPAND)

        gridbag_sizer.AddGrowableCol(1)
        # gridbag_sizer.AddGrowableRow(3)

        box_sizer = wx.StaticBoxSizer(time_box, wx.VERTICAL)
        box_sizer.Add(gridbag_sizer, proportion=1, flag=wx.EXPAND)

        return box_sizer

    def buildTestSignalsBox(self):
        testsignals_box = wx.StaticBox(self, label="Generate test signals")

        text_freq = wx.StaticText(testsignals_box, label="Freq. (Hz):")
        self.input_freq = NumCtrl(testsignals_box,
                                  value=440.0,
                                  integerWidth=5,
                                  fractionWidth=1,
                                  allowNegative=False,
                                  min=1.0,
                                  max=50000.0)
        text_len = wx.StaticText(testsignals_box, label="Len. (s):")
        self.input_len = NumCtrl(testsignals_box,
                                 value=2.0,
                                 integerWidth=3,
                                 fractionWidth=2,
                                 allowNegative=False,
                                 min=0.10,
                                 max=100.00)
        text_amp = wx.StaticText(testsignals_box, label="Amp.:")
        self.input_amp = NumCtrl(testsignals_box,
                                 value=1.0,
                                 integerWidth=2,
                                 fractionWidth=2,
                                 allowNegative=False,
                                 min=0.01,
                                 max=10.00)
        text_fs = wx.StaticText(testsignals_box, label="Sample rate (Hz):")
        self.input_fs = NumCtrl(testsignals_box,
                                value=44100,
                                integerWidth=6,
                                fractionWidth=0,
                                allowNegative=False,
                                min=1.0,
                                max=200000.0)
        text_fft = wx.StaticText(testsignals_box, label="FFT size:")
        self.input_fft = wx.ComboBox(testsignals_box,
                                     value='1024',
                                     choices=[
                                         '16', '32', '64', '128', '256', '512',
                                         '1024', '2048', '4096', '8192',
                                         '16384', '32768', '65536'
                                     ])

        button_file = wx.Button(testsignals_box,
                                id=ID_FILE_SIGNAL,
                                label="Open file")
        button_sawtooth = wx.Button(testsignals_box,
                                    id=ID_SAWTOOTH_SIGNAL,
                                    label="Sawtooth")
        button_sine = wx.Button(testsignals_box,
                                id=ID_SINE_SIGNAL,
                                label="Sine")
        button_square = wx.Button(testsignals_box,
                                  id=ID_SQUARE_SIGNAL,
                                  label="Square")
        button_triangle = wx.Button(testsignals_box,
                                    id=ID_TRIANGLE_SIGNAL,
                                    label="Triangle")
        button_wnoise = wx.Button(testsignals_box,
                                  id=ID_WNOISE_SIGNAL,
                                  label="White noise")

        button_file.Bind(wx.EVT_BUTTON, self.onSignalButton, button_file)
        button_sawtooth.Bind(wx.EVT_BUTTON, self.onSignalButton,
                             button_sawtooth)
        button_sine.Bind(wx.EVT_BUTTON, self.onSignalButton, button_sine)
        button_square.Bind(wx.EVT_BUTTON, self.onSignalButton, button_square)
        button_triangle.Bind(wx.EVT_BUTTON, self.onSignalButton,
                             button_triangle)
        button_wnoise.Bind(wx.EVT_BUTTON, self.onSignalButton, button_wnoise)

        gridbag_sizer_top = wx.GridBagSizer(vgap=5, hgap=5)
        gridbag_sizer_top.Add(text_freq, pos=(0, 0), flag=wx.EXPAND)
        gridbag_sizer_top.Add(self.input_freq, pos=(0, 2), flag=wx.EXPAND)
        gridbag_sizer_top.Add(text_fs, pos=(1, 0), flag=wx.EXPAND)
        gridbag_sizer_top.Add(self.input_fs, pos=(1, 2), flag=wx.EXPAND)
        gridbag_sizer_top.Add(text_len, pos=(2, 0), flag=wx.EXPAND)
        gridbag_sizer_top.Add(self.input_len, pos=(2, 2), flag=wx.EXPAND)
        gridbag_sizer_top.Add(text_amp, pos=(3, 0), flag=wx.EXPAND)
        gridbag_sizer_top.Add(self.input_amp, pos=(3, 2), flag=wx.EXPAND)
        gridbag_sizer_top.Add(text_fft, pos=(5, 0), flag=wx.EXPAND)
        gridbag_sizer_top.Add(self.input_fft, pos=(5, 2), flag=wx.EXPAND)
        gridbag_sizer_top.AddGrowableCol(1)

        gridbag_sizer_bottom = wx.GridBagSizer(vgap=5, hgap=5)
        gridbag_sizer_bottom.Add(button_sine, pos=(0, 0), flag=wx.EXPAND)
        gridbag_sizer_bottom.Add(button_square, pos=(0, 1), flag=wx.EXPAND)
        gridbag_sizer_bottom.Add(button_sawtooth, pos=(0, 2), flag=wx.EXPAND)
        gridbag_sizer_bottom.Add(button_triangle, pos=(1, 0), flag=wx.EXPAND)
        gridbag_sizer_bottom.Add(button_wnoise, pos=(1, 1), flag=wx.EXPAND)
        gridbag_sizer_bottom.Add(button_file, pos=(1, 2), flag=wx.EXPAND)
        gridbag_sizer_bottom.AddGrowableCol(0)
        gridbag_sizer_bottom.AddGrowableCol(1)
        gridbag_sizer_bottom.AddGrowableCol(2)

        box_sizer = wx.StaticBoxSizer(testsignals_box, wx.VERTICAL)
        box_sizer.Add(gridbag_sizer_top, proportion=1, flag=wx.EXPAND)
        box_sizer.AddSpacer(5)
        box_sizer.Add(gridbag_sizer_bottom, proportion=0, flag=wx.EXPAND)

        return box_sizer

    def buildOutput(self):
        output_box = wx.StaticBox(self, label="Information output")
        text_fs = wx.StaticText(output_box, label="Sample rate:")
        self.output_fs = wx.StaticText(output_box, label="000000")
        text_len = wx.StaticText(output_box, label="Length:")
        self.output_len = wx.StaticText(output_box, label="0000")

        gridbag_sizer = wx.GridBagSizer(vgap=5, hgap=5)
        gridbag_sizer.Add(text_fs, pos=(0, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.output_fs, pos=(0, 2), flag=wx.EXPAND)
        gridbag_sizer.Add(text_len, pos=(1, 0), flag=wx.EXPAND)
        gridbag_sizer.Add(self.output_len, pos=(1, 2), flag=wx.EXPAND)

        # gridbag_sizer.AddGrowableCol(2)

        box_sizer = wx.StaticBoxSizer(output_box, wx.VERTICAL)
        box_sizer.Add(gridbag_sizer, proportion=1, flag=wx.EXPAND)

        return box_sizer

    def onApplyBandpass(self, event):
        if self.input_end_time.GetValue() <= self.input_start_time.GetValue():
            print("End time needs to be greater than start time")
            return
        parent = self.GetParent()
        parent.signal.low_cutoff = self.input_start_fq.GetValue()
        parent.signal.high_cutoff = self.input_end_fq.GetValue()
        if self.signal_status_text is None:
            self.signal_status_text = self.GetTopLevelParent(
            ).status_bar.GetStatusText()
        self.GetTopLevelParent().status_bar.SetStatusText(
            self.signal_status_text + " - Bandpass: Low: " +
            str(parent.signal.low_cutoff) + " Hz, "
            "High: " + str(parent.signal.high_cutoff) + " Hz")
        parent.plotSignal(parent.signal, parent.nfft)

    def onResetBandpass(self, event):
        parent = self.GetParent()
        parent.signal._low_cutoff = None
        parent.signal._high_cutoff = None
        if self.signal_status_text is None:
            self.signal_status_text = self.GetTopLevelParent(
            ).status_bar.GetStatusText()
        self.GetTopLevelParent().status_bar.SetStatusText(
            self.signal_status_text + " - Bandpass: None")
        parent.plotSignal(parent.signal, parent.nfft)

    def onApplyTime(self, event):
        dlg = wx.ProgressDialog(parent=self,
                                message="Processing...",
                                title="Processing info",
                                maximum=1)
        parent = self.GetParent()
        parent.matplot_panel1.setXLimits(
            (self.input_start_time.GetValue(), self.input_end_time.GetValue()))
        parent.matplot_panel1.plot(parent.signal)
        parent.matplot_panel3.setXLimits(
            (self.input_start_time.GetValue(), self.input_end_time.GetValue()))
        parent.matplot_panel3.plotSpectrogram(parent.signal, parent.nfft)
        dlg.Update(1, "Complete")
        dlg.Destroy()

    def onResetTime(self, event):
        dlg = wx.ProgressDialog(parent=self,
                                message="Processing...",
                                title="Processing info",
                                maximum=1)
        parent = self.GetParent()
        parent.matplot_panel1.setXLimits((0.0, 1.0))
        parent.matplot_panel1.plot(parent.signal)
        parent.matplot_panel3.resetXLimits()
        parent.matplot_panel3.plotSpectrogram(parent.signal, parent.nfft)
        dlg.Update(1, "Complete")
        dlg.Destroy()

    def onSignalButton(self, event):
        source = event.GetId()

        file_path = ""

        if source == ID_FILE_SIGNAL:
            if self.GetTopLevelParent().dlg.ShowModal() == wx.ID_OK:
                file_path = self.GetTopLevelParent().dlg.GetPath()
                signal = "File"
            else:
                file_path = None
                signal = None
        elif source == ID_SAWTOOTH_SIGNAL:
            signal = "Sawtooth"
        elif source == ID_SINE_SIGNAL:
            signal = "Sine"
        elif source == ID_SQUARE_SIGNAL:
            signal = "Square"
        elif source == ID_TRIANGLE_SIGNAL:
            signal = "Triangle"
        elif source == ID_WNOISE_SIGNAL:
            signal = "WNoise"
        else:
            signal = None
            print("Missing ID for event object")

        self.signal_status_text = None
        self.GetParent().nfft = int(self.input_fft.GetValue())
        self.GetParent().changeSignal(signal,
                                      f=self.input_freq.GetValue(),
                                      l=self.input_len.GetValue(),
                                      amp=self.input_amp.GetValue(),
                                      fs=self.input_fs.GetValue(),
                                      path=file_path)
Beispiel #11
0
class SecondSystemDialog(wx.Dialog):
    def __init__(self, parent, id, flag=None):
        #flag es una variable que indica si el calculo es de caida de presion o de diametro
        self.prevReturnCode = None
        self.systemValues = {}
        wx.Dialog.__init__(self, parent, id, self.secondSystemDialogGeneralText()["c1"],
                           size=(460, 350))
        self.panel = wx.Panel(self, -1)

        vbox = wx.BoxSizer(wx.VERTICAL)

        firstList = self.secondSystemDialogGeneralText()["c2"]
        self.radioBox1 = wx.RadioBox(self.panel, -1, self.secondSystemDialogGeneralText()["c3"],
                    (50, 10), (100, 70), firstList, 1, wx.RA_SPECIFY_COLS)
        secondList = self.secondSystemDialogGeneralText()["c4"]
        self.radioBox2 = wx.RadioBox(self.panel, -1, self.secondSystemDialogGeneralText()["c5"],
                                     (300, 10), (100, 70), secondList, 2, wx.RA_SPECIFY_COLS)
    ### flow label value and units
        self.flowLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c6"],
                                       pos=(10, 94))
        self.flowValue = NumCtrl(self.panel, -1, pos=(10, 110), integerWidth = 7,
                                 fractionWidth = 2)
        self.flowValue.SetMin(0.01)
        self.flowValue.SetValue(0.01)
        flowUnitList = self.secondSystemDialogGeneralText()["c7"]
        self.flowUnit = wx.Choice(self.panel, -1, (115, 110), choices=flowUnitList)

    ### temperature label value and units
        self.temperatureLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c8"],
                                              pos=(10, 140))
        self.temperatureValue = NumCtrl(self.panel, -1, pos=(10, 156), integerWidth = 7,
                                        fractionWidth = 2)#, SetMin=0.01, SetMax=373.94)
        self.temperatureValue.SetMin(0.01)
        self.temperatureValue.SetMax(373.94)
        self.temperatureValue.SetLimitOnFieldChange(True)
        self.temperatureValue.SetValue(0.01)
        temperatureUnitList = self.secondSystemDialogGeneralText()["c9"]
        self.temperatureUnit = wx.Choice(self.panel, -1, (115, 156), choices=temperatureUnitList)
        self.temperatureUnit.Bind(wx.EVT_CHOICE, self.onTemperatureUnitChange)

    ### density label value and units
        self.densityLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c10"],
                                          pos=(10, 186))
        self.densityValue = NumCtrl(self.panel, -1, pos=(10, 202), integerWidth = 4,
                                    fractionWidth = 2)
        self.densityValue.SetMin(0.01)
        self.densityValue.SetValue(0.01)
        densityUnitList = self.secondSystemDialogGeneralText()["c11"]
        self.densityUnit = wx.Choice(self.panel, -1, (115, 202), choices=densityUnitList)
        self.densityLabel.Enable(False)
        self.densityUnit.Enable(False)
        self.densityValue.Enable(False)

    ### viscosity label value and units
        self.viscosityLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c12"],
                                            pos=(10, 228))
        self.viscosityValue = NumCtrl(self.panel, -1, pos=(10, 244), integerWidth = 3,
                                      fractionWidth = 7)
        self.viscosityValue.SetMin(0.0000001)
        self.viscosityValue.SetValue(0.0000001)
        viscosityUnitList = self.secondSystemDialogGeneralText()["c13"]
        self.viscosityUnit = wx.Choice(self.panel, -1, (115, 244), choices=viscosityUnitList)
        self.viscosityLabel.Enable(False)
        self.viscosityUnit.Enable(False)
        self.viscosityValue.Enable(False)

    ### roughness label value and units
        self.roughnessLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c14"],
                                            pos=(260, 94))
        self.roughnessValue = NumCtrl(self.panel, -1, pos=(260, 110), integerWidth = 1,
                                     fractionWidth = 7)
        self.roughnessValue.SetMin(0.0000001)
        self.roughnessValue.SetValue(0.0000001)
        roughnessUnitList = self.secondSystemDialogGeneralText()["c15"]
        self.roughnessUnit = wx.Choice(self.panel, -1, (345, 110), choices=roughnessUnitList)
        self.roughnessLabel.Enable(False)
        self.roughnessUnit.Enable(False)
        self.roughnessValue.Enable(False)

    ### pressure drop label value and units
        self.pressureDropLabel = wx.StaticText(self.panel, -1, self.secondSystemDialogGeneralText()["c23"],
                                    pos=(260, 140))
        self.pressureDropValue = NumCtrl(self.panel, -1, pos=(260, 156), integerWidth = 7,
                                      fractionWidth = 3)
        self.pressureDropValue.SetMin(0.01)
        self.pressureDropValue.SetValue(0.01)
        pressureDropUnitList = self.secondSystemDialogGeneralText()["c24"]
        self.pressureDropUnit = wx.Choice(self.panel, -1, (370, 156), choices=pressureDropUnitList)
        if flag:
            self.pressureDropLabel.Enable(True)
            self.pressureDropUnit.Enable(True)
            self.pressureDropValue.Enable(True)
        else:
            self.pressureDropLabel.Enable(False)
            self.pressureDropUnit.Enable(False)
            self.pressureDropValue.Enable(False)

        self.radioBox1.Bind(wx.EVT_RADIOBOX, self.onRadioBox1)
        self.radioBox2.Bind(wx.EVT_RADIOBOX, self.onRadioBox2)

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        self.prevButton = wx.Button(self, -1, self.secondSystemDialogGeneralText()["c16"], size=(70, 30))
        self.cancelButton = wx.Button(self, -1, self.secondSystemDialogGeneralText()["c17"], size=(70, 30))
        self.nextButton = wx.Button(self, -1, self.secondSystemDialogGeneralText()["c18"], size=(70, 30))
        self.prevButton.Bind(wx.EVT_BUTTON, self.onPrev)
        self.cancelButton.Bind(wx.EVT_BUTTON, self.onCancel)
        self.nextButton.Bind(wx.EVT_BUTTON, self.onNext)

        hbox.Add(self.prevButton, 1 )
        hbox.Add(self.nextButton, 1, wx.LEFT, 5)
        hbox.Add(self.cancelButton, 1, wx.LEFT, 5)

        vbox.Add(self.panel)
        vbox.Add(hbox, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10)

        self.SetSizer(vbox)
        self.nextButton.SetDefault() #set the nextButton as default
        self.Bind(wx.EVT_CLOSE, self.onCancel) #bind the window close icon on the top right corner of the window

    def onTemperatureUnitChange(self, evt):
        unitSelected = self.temperatureUnit.GetStringSelection()
        if unitSelected == "F":
            self.temperatureValue.SetMin(32.02)
            self.temperatureValue.SetMax(705.1)
            self.temperatureValue.SetValue(32.02)
        elif unitSelected == "C":
            self.temperatureValue.SetMin(0.01)
            self.temperatureValue.SetMax(373.94)
            self.temperatureValue.SetValue(0.01)
        pass

    def onRadioBox1(self, evt):
        selected = self.radioBox1.GetSelection()
        if selected == 0:
            self.densityLabel.Enable(False)
            self.densityUnit.Enable(False)
            self.densityValue.Enable(False)
            self.viscosityLabel.Enable(False)
            self.viscosityUnit.Enable(False)
            self.viscosityValue.Enable(False)
            self.temperatureLabel.Enable()
            self.temperatureUnit.Enable()
            self.temperatureValue.Enable()
        elif selected == 1:
            self.temperatureLabel.Enable(False)
            self.temperatureUnit.Enable(False)
            self.temperatureValue.Enable(False)
            self.densityLabel.Enable()
            self.densityUnit.Enable()
            self.densityValue.Enable()
            self.viscosityLabel.Enable()
            self.viscosityUnit.Enable()
            self.viscosityValue.Enable()
        else:
            pass

    def onRadioBox2(self, evt):
        selected = self.radioBox2.GetSelection()
        if (selected == 0 or
            selected == 1 or
            selected == 2):
            self.roughnessLabel.Enable(False)
            self.roughnessUnit.Enable(False)
            self.roughnessValue.Enable(False)
        elif selected == 3:
            self.roughnessLabel.Enable()
            self.roughnessUnit.Enable()
            self.roughnessValue.Enable()
        else:
            pass

    def onCancel(self, evt):
        self.EndModal(wx.ID_CANCEL)

    def onPrev(self, evt):
        self.prevReturnCode = wx.NewId()
        self.EndModal(self.prevReturnCode)

    def onNext(self, evt):
        radioBox1Selection = self.radioBox1.GetSelection()
        radioBox2Selection = self.radioBox2.GetSelection()
        okToClose = [False, False, False]

        #begin segmento para la caida de presion
        if self.pressureDropValue.IsEnabled():
            #si el calculo es para diametro minimo
            if self.pressureDropUnit.GetSelection() == -1:
                #si no se ha especificado valor en las unidades de caida de presion
                dialog = wx.MessageDialog(self.panel, self.secondSystemDialogGeneralText()["c25"],
                                          self.secondSystemDialogGeneralText()["c26"],
                                          style=wx.OK | wx.ICON_EXCLAMATION)
                dialog.ShowModal()
                dialog.Destroy()
                okToClose[2] = False
            else:
                self.systemValues["pressure_drop"] = self.pressureDropValue.GetValue()
                self.systemValues["pressure_drop_unit"] = self.pressureDropUnit.GetStringSelection()
                okToClose[2] = True
        #end segmento para la caida de presion

        if radioBox1Selection == 0:
            if (self.flowUnit.GetSelection() == -1 or
                self.temperatureUnit.GetSelection() == -1):
                dialog = wx.MessageDialog(self.panel, self.secondSystemDialogGeneralText()["c19"],
                                          self.secondSystemDialogGeneralText()["c20"],
                                          style=wx.OK | wx.ICON_EXCLAMATION)
                dialog.ShowModal()
                dialog.Destroy()
                okToClose[0] = False
            else:
                self.systemValues["water"] = "yes"
                self.systemValues["flow"] = self.flowValue.GetValue()
                self.systemValues["flow_unit"] = self.flowUnit.GetStringSelection()
                self.systemValues["temperature"] = self.temperatureValue.GetValue()
                self.systemValues["temperature_unit"] = self.temperatureUnit.GetStringSelection()
                okToClose[0] = True

        elif radioBox1Selection == 1:
            if (self.flowUnit.GetSelection() == -1 or
                self.viscosityUnit.GetSelection() == -1 or
                self.densityUnit.GetSelection() == -1):
                dialog = wx.MessageDialog(self.panel, self.secondSystemDialogGeneralText()["c21"],
                                          self.secondSystemDialogGeneralText()["c20"],
                                          style=wx.OK | wx.ICON_EXCLAMATION)
                dialog.ShowModal()
                dialog.Destroy()
                okToClose[0] = False
            else:
                self.systemValues["water"] = "None"
                self.systemValues["flow"] = self.flowValue.GetValue()
                self.systemValues["flow_unit"] = self.flowUnit.GetStringSelection()
                self.systemValues["viscosity"] = self.viscosityValue.GetValue()
                self.systemValues["viscosity_unit"] = self.viscosityUnit.GetStringSelection()
                self.systemValues["density"] = self.densityValue.GetValue()
                self.systemValues["density_unit"] = self.densityUnit.GetStringSelection()
                okToClose[0] = True

        if radioBox2Selection == 0:
            self.systemValues["pipe_type"] = "CSP"
            okToClose[1] = True
        elif radioBox2Selection == 1:
            self.systemValues["pipe_type"] = "SSP"
            okToClose[1] = True
        elif radioBox2Selection == 2:
            self.systemValues["pipe_type"] = "PVC"
            okToClose[1] = True
        elif radioBox2Selection == 3:
            self.systemValues["pipe_type"] = "None"
            if self.roughnessUnit.GetSelection() == -1:
                dialog = wx.MessageDialog(self.panel, self.secondSystemDialogGeneralText()["c22"],
                                          self.secondSystemDialogGeneralText()["c20"],
                                          style=wx.OK | wx.ICON_EXCLAMATION)
                dialog.ShowModal()
                dialog.Destroy()
                okToClose[1] = False
            else:
                self.systemValues["roughness"] = self.roughnessValue.GetValue()
                self.systemValues["roughness_unit"] = self.roughnessUnit.GetStringSelection()
                okToClose[1] = True
                
        if self.pressureDropValue.IsEnabled():
            if okToClose[0] and okToClose[1] and okToClose[2]:
    #            print self.systemValues
                self.EndModal(wx.ID_OK)
        else:
            if okToClose[0] and okToClose[1]:
    #            print self.systemValues
                self.EndModal(wx.ID_OK)

    def secondSystemDialogGeneralText(self):
        text = Language()
        return text.secondSystemDialogGeneralText()
Beispiel #12
0
class ReflectInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX )
        self.rbox = wx.RadioBox(self,label = 'About', pos = (2,10), choices = ['X-axis', 'Y-axis', 'Origin', 'Line'], majorDimension = 1, style = wx.RA_SPECIFY_ROWS)
        slopeLabel = wx.StaticText(self, -1,
                           "Enter slope (m): ",
                           pos=(10,70))
        self.slopeInput = NumCtrl(self, value=0.0, integerWidth=3,fractionWidth=2, pos=(120, 70), size=(100, -1))
        cLabel = wx.StaticText(self, -1,
                           "Enter y-intercept (c): ",
                           pos=(10,100))
        self.cInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(120, 100), size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 130), size=(100, 30))
        cancelBtn = wx.Button(self, -1, label='Cancel', pos=(120, 130), size=(100, 30))
        self.SetSize((230, 170))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        selected = self.rbox.GetStringSelection()
        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.canvas.num_of_plots]

        if selected == 'X-axis':
            self.parent.canvas.drawings.append(self.reflect(points=self.parent.canvas.drawings[0], m=0, c=0, about='x'))
        elif selected == 'Y-axis':
            self.parent.canvas.drawings.append(self.reflect(points=self.parent.canvas.drawings[0], m=0, c=0, about='y'))
        elif selected == 'Origin':
            self.parent.canvas.drawings.append(self.reflect(points=self.parent.canvas.drawings[0], m=0, c=0, about='origin'))
        else:
            slope = min(100, self.slopeInput.GetValue())
            c = self.cInput.GetValue()
            self.parent.canvas.drawings.append(self.reflect(points=self.parent.canvas.drawings[0], m=slope, c=c, about='line'))


        self.Show(False)
        self.parent.buttons[8] = True
        self.parent.canvas.num_of_plots = min(9, len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[8] = True


    def matrixMultiply(self, A, B):
        prod = list()
        for i in range(3):
            row = list()
            sm = 0
            for j in range(3):
                sm += A[i][j] * B[j][0]
            row.append(sm)
            prod.append(row)
        return prod

    def matrixMultiply(self, A, B):
        prod = list()
        for i in range(3):
            row = list()
            sm = 0
            for j in range(3):
                sm += A[i][j] * B[j][0]
            row.append(sm)
            prod.append(row)
        return prod

    def reflect(self, points, m, c, about):
        translated_points = list()
        if about == 'x':
            reflect_mat = [[1, 0, 0],
                           [0, -1, 0],
                           [0, 0, 1]]

        elif about == 'y':
            reflect_mat = [[-1, 0, 0],
                           [0, 1, 0],
                           [0, 0, 1]]

        elif about == 'origin':
            reflect_mat = [[-1, 0, 0],
                           [0, -1, 0],
                           [0, 0, 1]]

        else:
            reflect_mat = [[cos(2 * atan(m)), sin(2 * atan(m)), -c * sin(2 * atan(m))],
                           [sin(2 * atan(m)), -cos(2 * atan(m)), c * 2 * (cos(atan(m)) ** 2)],
                           [0, 0, 1]]
        for point in points:
            translated = self.matrixMultiply(reflect_mat, [[point[0]], [point[1]], [1]])
            translated_points.append([translated[0][0], translated[1][0]])
        return translated_points
Beispiel #13
0
class LineInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        slopeLabel = wx.StaticText(self, -1, "Enter slope (m): ", pos=(10, 14))
        self.slopeInput = NumCtrl(self,
                                  value=0.0,
                                  integerWidth=3,
                                  fractionWidth=2,
                                  pos=(120, 10),
                                  size=(100, -1))
        cLabel = wx.StaticText(self,
                               -1,
                               "Enter y-intercept (c): ",
                               pos=(10, 44))
        self.cInput = NumCtrl(self,
                              value=0.0,
                              integerWidth=3,
                              fractionWidth=2,
                              pos=(120, 40),
                              size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 70), size=(100, 30))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(120, 70),
                              size=(100, 30))
        self.SetSize((230, 110))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        m = min(100, self.slopeInput.GetValue())
        c = self.cInput.GetValue()

        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]
        if m == 999.99:
            self.parent.canvas.drawings.append(
                self.lineDrawing(float('inf'), c))
        elif m == -999.99:
            self.parent.canvas.drawings.append(
                self.lineDrawing(float('-inf'), c))
        else:
            self.parent.canvas.drawings.append(self.lineDrawing(m, c))
        self.Show(False)
        self.parent.buttons[0] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[0] = True

    def lineDrawing(self, m, c):
        points = list()
        if m > 0:
            if m != float('inf'):
                start = [-1000, -1000 * m + c]
                end = [1000, 1000 * m + c]
            else:
                start = [c, -1000]
                end = [c, 1000]

        else:
            if m != float('-inf'):
                start = [1000, 1000 * m + c]
                end = [-1000, -1000 * m + c]
            else:
                start = [c, 1000]
                end = [c, -1000]
        x = start[0]
        y = start[1]
        dx = end[0] - start[0]
        dy = end[1] - start[1]
        if abs(dx) > abs(dy):
            stepsize = abs(dx)
        else:
            stepsize = abs(dy)
        if stepsize != float('inf') and stepsize != float('-inf'):
            x_inc = dx / stepsize
            y_inc = dy / stepsize
        else:
            x_inc = 0
            if stepsize == float('inf'):
                y_inc = 1
            else:
                y_inc = -1
        for _ in range(round(stepsize) // 1):
            points.append([x, y])
            x += x_inc
            y += y_inc
            points.append([x, y])
        return points
Beispiel #14
0
class CubicInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        aLabel = wx.StaticText(self, -1, "Enter a: ", pos=(10, 14))
        self.aInput = NumCtrl(self,
                              value=0.0,
                              integerWidth=2,
                              fractionWidth=2,
                              pos=(55, 10),
                              size=(100, -1))
        bLabel = wx.StaticText(self, -1, "Enter b: ", pos=(10, 44))
        self.bInput = NumCtrl(self,
                              value=0.0,
                              integerWidth=2,
                              fractionWidth=2,
                              pos=(55, 40),
                              size=(100, -1))
        cLabel = wx.StaticText(self, -1, "Enter c: ", pos=(10, 74))
        self.cInput = NumCtrl(self,
                              value=0.0,
                              integerWidth=2,
                              fractionWidth=2,
                              pos=(55, 70),
                              size=(100, -1))
        dLabel = wx.StaticText(self, -1, "Enter d: ", pos=(10, 104))
        self.dInput = NumCtrl(self,
                              value=0.0,
                              integerWidth=2,
                              fractionWidth=2,
                              pos=(55, 100),
                              size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 130), size=(100, 20))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(10, 160),
                              size=(100, 20))
        self.SetSize((120, 190))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        a = self.aInput.GetValue()
        b = self.bInput.GetValue()
        c = self.cInput.GetValue()
        d = self.dInput.GetValue()

        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]
        if a == 0 and b == 0:
            self.parent.canvas.drawings.append(self.lineDrawing(c, d))
        elif a == 0:
            self.parent.canvas.drawings.append(self.quadraticDrawing(b, c, d))
        else:
            self.parent.canvas.drawings.append(self.cubicDrawing(a, b, c, d))

        self.Show(False)
        self.parent.buttons[11] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[11] = True

    def cubicDrawing(self, a, b, c, d):
        points = list()
        for y in range(-1000, 1001):
            roots = list(np.roots([a, b, c, d - y]))
            for x in roots:
                if x.imag == 0:
                    points.append([x.real, y])
        return points

    def quadraticDrawing(self, a, b, c):
        points = list()
        for x in range(-1000, 1001):
            if b**2 - 4 * a * (c - x) >= 0:
                x1 = (-b + (b**2 - 4 * a * (c - x))**0.5) / 2 * a
                x2 = (-b - (b**2 - 4 * a * (c - x))**0.5) / 2 * a
                points.append([x1, x])
                points.append([x2, x])
        return points

    def lineDrawing(self, m, c):
        points = list()
        if m > 0:
            if m != float('inf'):
                start = [-1000, -1000 * m + c]
                end = [1000, 1000 * m + c]
            else:
                start = [c, -1000]
                end = [c, 1000]

        else:
            if m != float('-inf'):
                start = [1000, 1000 * m + c]
                end = [-1000, -1000 * m + c]
            else:
                start = [c, 1000]
                end = [c, -1000]
        x = start[0]
        y = start[1]
        dx = end[0] - start[0]
        dy = end[1] - start[1]
        if abs(dx) > abs(dy):
            stepsize = abs(dx)
        else:
            stepsize = abs(dy)
        if stepsize != float('inf') and stepsize != float('-inf'):
            x_inc = dx / stepsize
            y_inc = dy / stepsize
        else:
            x_inc = 0
            if stepsize == float('inf'):
                y_inc = 1
            else:
                y_inc = -1
        for _ in range(round(stepsize) // 1):
            points.append([x, y])
            x += x_inc
            y += y_inc
            points.append([x, y])
        return points
Beispiel #15
0
class ZaberControlPanel(wx.Panel):

    def __init__(self, zaber, *args):
        wx.Panel.__init__(self, *args)
        self._zaber = zaber
        
        self._home_button = wx.Button(
            self, label="Home Zaber", size=(100, 24))
        self._home_button.Bind(wx.EVT_BUTTON, self._home)
        self._center_button = wx.Button(
            self, label="Center Zaber", size=(100, 24))
        self._center_button.Bind(wx.EVT_BUTTON, self._center)
        
        self._start_txt = wx.StaticText(
            self, label="Start Position:",
            size=(100, 24), style=wx.ALIGN_RIGHT)
        self._start_val = NumCtrl(
            self, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._start_val.SetAllowNegative(False)
        self._start_val.SetBounds(0, 640000)
        self._start_val.SetFractionWidth(0)
        self._start_val.SetIntegerWidth(6)
        self._start_val.SetValue(294000)
        
        self._end_txt = wx.StaticText(
            self, label="End Position:",
            size=(100, 24), style=wx.ALIGN_RIGHT)
        self._end_val = NumCtrl(
            self, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._end_val.SetAllowNegative(False)
        self._end_val.SetBounds(0, 640000)
        self._end_val.SetFractionWidth(0)
        self._end_val.SetIntegerWidth(6)
        self._end_val.SetValue(354000)
        
        self._step_txt = wx.StaticText(
            self, label="Absolute Step Size:",
            size=(100, 24), style=wx.ALIGN_RIGHT)
        self._step_val = NumCtrl(
            self, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._step_val.SetAllowNegative(False)
        self._step_val.SetBounds(0, 640000)
        self._step_val.SetFractionWidth(0)
        self._step_val.SetIntegerWidth(6)
        self._step_val.SetValue(1500)
        
        self._go_abs_button = wx.Button(
            self, label="Go to Position \u2192", size=(100, 24))
        self._go_abs_button.Bind(wx.EVT_BUTTON, self._go_abs)
        self._goto_val = NumCtrl(
            self, size=(100, 20), style=wx.TE_PROCESS_ENTER)
        self._goto_val.SetBounds(0, 640000)
        self._goto_val.SetAllowNegative(False)
        self._goto_val.SetFractionWidth(0)
        self._goto_val.SetIntegerWidth(6)
        self._goto_val.SetValue(0)
        self._goto_val.SetLimitOnFieldChange(True)
        
        self._go_rel_button = wx.Button(
            self, label="Go by Distance \u2192", size=(100,24))
        self._go_rel_button.Bind(wx.EVT_BUTTON, self._go_rel)
        self._goby_val = NumCtrl(
            self, size=(100, 20), style=wx.TE_PROCESS_ENTER)
        self._goby_val.SetBounds(-640000, 640000)
        self._goby_val.SetAllowNegative(True)
        self._goby_val.SetFractionWidth(0)
        self._goby_val.SetIntegerWidth(6)
        self._goby_val.SetValue(0)
        self._goby_val.SetLimitOnFieldChange(True)
        
        self._pos_txt = wx.StaticText(
            self, label="Current Position:", 
            size=(-1, 24), style=wx.ALIGN_RIGHT)
        self._pos_val = wx.StaticText(self, label="0", size=(-1, 24))

        sizer = wx.GridBagSizer(5, 5)
        sizer.Add(self._home_button, (0, 2))
        sizer.Add(self._center_button, (0, 3))
        sizer.Add(self._start_txt, (0, 0))
        sizer.Add(self._start_val, (0, 1))
        sizer.Add(self._end_txt, (1, 0))
        sizer.Add(self._end_val, (1, 1))
        sizer.Add(self._step_txt, (2, 0))
        sizer.Add(self._step_val, (2, 1))
        sizer.Add(self._go_abs_button, (1, 2))
        sizer.Add(self._goto_val, (1, 3))
        sizer.Add(self._go_rel_button, (2, 2))
        sizer.Add(self._goby_val, (2, 3))
        sizer.Add(self._pos_txt, (3, 1))
        sizer.Add(self._pos_val, (3, 2))
        self.SetSizer(sizer)

    def disable_ui(self):
        self._home_button.Disable()
        self._center_button.Disable()
        self._start_val.Disable()
        self._end_val.Disable()
        self._step_val.Disable()
        self._go_abs_button.Disable()
        self._goto_val.Disable()
        self._go_rel_button.Disable()
        self._goby_val.Disable()
        
    def enable_ui(self):
        self._home_button.Enable()
        self._center_button.Enable()
        self._start_val.Enable()
        self._end_val.Enable()
        self._step_val.Enable()
        self._go_abs_button.Enable()
        self._goto_val.Enable()
        self._go_rel_button.Enable()
        self._goby_val.Enable()
        
    def get_start(self):
        return self._start_val.GetValue()
        
    def get_end(self):
        return self._end_val.GetValue()
        
    def get_step(self):
        return self._step_val.GetValue()
        
    def update_pos(self):
        self._pos_val.SetLabel(str(self._zaber.get_current_pos(0)[0][1]))
        
    def _home(self, evt):
        self._zaber.home(0)
        self.update_pos()
        
    def _center(self, evt):
        self._zaber.goto_pos(0, 324000)
        self.update_pos()

    def _go_abs(self, evt):
        self._zaber.goto_pos(0, self._goto_val.GetValue())
        self.update_pos()  

    def _go_rel(self, evt):
        curr_pos = int(self._pos_val.GetLabel())
        if curr_pos + self._goby_val.GetValue() > 640000:
            return
        self._zaber.goby_dist(0, self._goby_val.GetValue())
        self.update_pos()
class PolarizationExperimentGUI(wx.Frame):
    """The base object for the Polarization Experiment GUI.

    Parameters
    ----------
    parent : wx.Parent
        Parent for the superclass wx.Frame, usually None in most cases.
    title : str
        The title for the frame of the GUI.

    Methods
    -------
    disable_ui
        Disables the input on the UI, except enables the stop button.
    enable_ui
        Enables the input on the UI, except disables the stop button.
    serial_entry
        Intended for override by subclass, this is bound to the event
        on data entry into the serial number field.
    home_press
        Intended for override by subcless, this is bound to the event
        on pressing the Home Stage button.
    zero_press
        Intended for override by subclass, this is bound to the event
        on pressing the Zero Power Meter button.
    start_press
        Intended for override by subclass, this is bound to the event
        on pressing the Start button.
    stop_press
        Intended for override by subclass, this is bound to the event
        on pressing the Stop button.
    get_serial
        Return the value of the serial number input.
    set_pow_val
        Set value of current power reading.
    set_curr_angle_val
        Set value of current angle reading.
    get_start_angle
        Return start angle input value.
    get_end_angle
        Return end angle input value.
    get_step_size
        Return step size input value.
    set_curr_iter
        Set current iteration value.
    get_iter_val
        Return iteration input value.
    set_speed
        Set current speed value.
    set_moving
        Sets the motion status.
    get_speed
        Get speed input value.

    """
    def __init__(self,
                 parent=None,
                 title="Laser Polarization Detection Experiment"):
        # Creation of objects to be used only within the class
        # '_is_disabled' refers to whether the UI is disabled or enabled
        self._is_disabled = False
        self._program_font = wx.Font(13, wx.FONTFAMILY_SWISS,
                                     wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,
                                     False, "", wx.FONTENCODING_SYSTEM)
        self._title_font = wx.Font(15, wx.FONTFAMILY_SWISS,
                                   wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL,
                                   True, "", wx.FONTENCODING_SYSTEM)
        self._serial_val = wx.Object()
        self._curr_pow_val = wx.Object()
        self._curr_angle_val = wx.Object()
        self._start_angle_val = wx.Object()
        self._end_angle_val = wx.Object()
        self._step_size_val = wx.Object()
        self._curr_iter_val = wx.Object()
        self._set_iter_val = wx.Object()
        self._moving_val = wx.Object()
        self._curr_speed_val = wx.Object()
        self._set_speed_val = wx.Object()
        self._home_button = wx.Object()
        self._zero_button = wx.Object()
        self._start_button = wx.Object()
        self._stop_button = wx.Object()
        self._live_plt = Figure()
        self._live_plt.set_facecolor('w')
        axes_dim = [0.125, 0.125, 0.8, 0.8]
        # self._live_plt_axes = self._live_plt.add_axes(axes_dim)
        self._live_plt_axes = self._live_plt.add_axes(axes_dim, polar=True)
        self._live_plt_canvas = 0

        # Initialise the frame with title and fixed size
        super(PolarizationExperimentGUI, self).__init__(parent,
                                                        title=title,
                                                        size=(1200, 600))
        self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
                            ^ wx.MAXIMIZE_BOX)
        self._generate_dynamic_ui()
        self.Show()

    def _generate_dynamic_ui(self):
        """Create the elements for the interface."""
        # Create the panel for the widgets to be placed on
        program_panel = wx.Panel(self)
        program_sizer = wx.BoxSizer(wx.HORIZONTAL)

        # Create the panel for the controls
        control_panel = wx.Panel(program_panel)
        control_panel.SetSize(wx.Size(400, 600))
        control_panel.SetBackgroundColour(wx.WHITE)

        # Set the control panel sizer to be a vertical BoxSizer
        control_sizer = wx.BoxSizer(wx.VERTICAL)

        # Title object
        title_label = wx.StaticText(control_panel, -1, "Experiment Parameters",
                                    wx.DefaultPosition, wx.DefaultSize,
                                    wx.ALIGN_CENTER, "StaticTextNameStr")
        title_label.SetFont(self._title_font)

        # Serial panel objects
        serial_panel = wx.Panel(control_panel)
        serial_sizer = wx.FlexGridSizer(1, 2, 0, 0)

        serial_label = wx.StaticText(serial_panel, -1,
                                     "ThorLabs Serial: ", wx.DefaultPosition,
                                     wx.Size(200, 20), wx.ALIGN_RIGHT,
                                     "StaticTextNameStr")
        serial_label.SetFont(self._program_font)
        self._serial_val = wx.Choice(
            serial_panel,
            size=(200, 20),
            choices=["83843569", "83846179", "83845569"])
        serial_sizer.AddMany([serial_label, self._serial_val])
        serial_panel.SetSizer(serial_sizer)

        # Power panel objects
        power_panel = wx.Panel(control_panel)
        power_sizer = wx.FlexGridSizer(1, 2, 0, 0)

        curr_power_label = wx.StaticText(power_panel, -1,
                                         "Current Power (W): ",
                                         wx.DefaultPosition, wx.Size(200, 20),
                                         wx.ALIGN_RIGHT, "StaticTextNameStr")
        curr_power_label.SetFont(self._program_font)
        self._curr_pow_val = wx.StaticText(power_panel, -1,
                                           "", wx.DefaultPosition,
                                           wx.Size(200, 20), wx.ALIGN_LEFT,
                                           "StaticTextNameStr")
        self._curr_pow_val.SetFont(self._program_font)
        power_sizer.AddMany([curr_power_label, self._curr_pow_val])
        power_panel.SetSizer(power_sizer)

        # Angle panel objects
        angle_panel = wx.Panel(control_panel)
        angle_sizer = wx.FlexGridSizer(6, 2, 0, 0)
        curr_angle_label = wx.StaticText(angle_panel, -1,
                                         "Current Angle (\xb0): ",
                                         wx.DefaultPosition, wx.Size(200, 20),
                                         wx.ALIGN_RIGHT, "StaticTextNameStr")
        curr_angle_label.SetFont(self._program_font)
        self._curr_angle_val = wx.StaticText(angle_panel, -1, "",
                                             wx.DefaultPosition,
                                             wx.Size(200, 20), wx.ALIGN_LEFT,
                                             "StaticTextNameStr")
        self._curr_angle_val.SetFont(self._program_font)
        start_angle_label = wx.StaticText(angle_panel, -1,
                                          "Start Angle (\xb0): ",
                                          wx.DefaultPosition, wx.Size(200, 20),
                                          wx.ALIGN_RIGHT, "StaticTextNameStr")
        start_angle_label.SetFont(self._program_font)
        self._start_angle_val = NumCtrl(
            angle_panel, -1, 0, wx.DefaultPosition, wx.Size(-1, 20),
            wx.TE_PROCESS_TAB | wx.TE_PROCESS_ENTER, wx.DefaultValidator,
            "masked.num")
        self._start_angle_val.SetAllowNegative(False)
        self._start_angle_val.SetBounds(0, 359.9)
        self._start_angle_val.SetFractionWidth(1)
        self._start_angle_val.SetIntegerWidth(3)
        self._start_angle_val.SetValue(0)
        self._start_angle_val.SetLimited(True)
        self._start_angle_val.SetFont(self._program_font)
        end_angle_label = wx.StaticText(angle_panel, -1, "End Angle (\xb0): ",
                                        wx.DefaultPosition, wx.Size(200, 20),
                                        wx.ALIGN_RIGHT, "StaticTextNameStr")
        end_angle_label.SetFont(self._program_font)
        self._end_angle_val = NumCtrl(angle_panel, -1, 0, wx.DefaultPosition,
                                      wx.Size(-1, 20),
                                      wx.TE_PROCESS_TAB | wx.TE_PROCESS_ENTER,
                                      wx.DefaultValidator, "masked.num")
        self._end_angle_val.SetAllowNegative(False)
        self._end_angle_val.SetBounds(0, 360)
        self._end_angle_val.SetFractionWidth(1)
        self._end_angle_val.SetIntegerWidth(3)
        self._end_angle_val.SetValue(360)
        self._end_angle_val.SetLimited(True)
        self._end_angle_val.SetFont(self._program_font)
        step_size_label = wx.StaticText(angle_panel, -1, "Step Size (\xb0): ",
                                        wx.DefaultPosition, wx.Size(200, 20),
                                        wx.ALIGN_RIGHT, "StaticTextNameStr")
        step_size_label.SetFont(self._program_font)
        self._step_size_val = NumCtrl(angle_panel, -1, 0, wx.DefaultPosition,
                                      wx.Size(200, 20),
                                      wx.TE_PROCESS_TAB | wx.TE_PROCESS_ENTER,
                                      wx.DefaultValidator, "masked.num")
        self._step_size_val.SetAllowNegative(False)
        self._step_size_val.SetBounds(0, 360)
        self._step_size_val.SetFractionWidth(1)
        self._step_size_val.SetIntegerWidth(3)
        self._step_size_val.SetValue(1)
        self._step_size_val.SetLimited(True)
        self._step_size_val.SetFont(self._program_font)
        curr_iter_label = wx.StaticText(angle_panel, -1, "Current Iteration: ",
                                        wx.DefaultPosition, wx.Size(200, 20),
                                        wx.ALIGN_RIGHT, "StaticTextNameStr")
        curr_iter_label.SetFont(self._program_font)
        self._curr_iter_val = wx.StaticText(angle_panel, -1,
                                            "Not currently testing!",
                                            wx.DefaultPosition,
                                            wx.Size(200, 20), wx.ALIGN_LEFT,
                                            "StaticTextNameStr")
        self._curr_iter_val.SetFont(self._program_font)
        set_iter_label = wx.StaticText(angle_panel, -1,
                                       "Iterations: ", wx.DefaultPosition,
                                       wx.Size(200, 20), wx.ALIGN_RIGHT,
                                       "StaticTextNameStr")
        set_iter_label.SetFont(self._program_font)
        self._set_iter_val = NumCtrl(angle_panel, -1, 0, wx.DefaultPosition,
                                     wx.Size(200, 20),
                                     wx.TE_PROCESS_TAB | wx.TE_PROCESS_ENTER,
                                     wx.DefaultValidator, "masked.num")
        self._set_iter_val.SetAllowNegative(False)
        self._set_iter_val.SetBounds(1, 99)
        self._set_iter_val.SetFractionWidth(0)
        self._set_iter_val.SetIntegerWidth(2)
        self._set_iter_val.SetValue(10)
        self._set_iter_val.SetLimited(True)
        self._set_iter_val.SetFont(self._program_font)
        angle_sizer.AddMany([
            curr_power_label, self._curr_angle_val, start_angle_label,
            self._start_angle_val, end_angle_label, self._end_angle_val,
            step_size_label, self._step_size_val, curr_iter_label,
            self._curr_iter_val, set_iter_label, self._set_iter_val
        ])
        angle_panel.SetSizer(angle_sizer)

        # Velocity panel objects
        velocity_panel = wx.Panel(control_panel)
        velocity_sizer = wx.FlexGridSizer(3, 2, 0, 0)
        curr_speed_label = wx.StaticText(velocity_panel, -1,
                                         "Current Max Speed (\xb0/s): ",
                                         wx.DefaultPosition, wx.Size(200, 20),
                                         wx.ALIGN_RIGHT, "StaticTextNameStr")
        curr_speed_label.SetFont(self._program_font)
        self._curr_speed_val = wx.StaticText(velocity_panel, -1, "",
                                             wx.DefaultPosition,
                                             wx.Size(200, 20), wx.ALIGN_LEFT,
                                             "StaticTextNameStr")
        self._curr_speed_val.SetFont(self._program_font)
        moving_label = wx.StaticText(velocity_panel, -1,
                                     "Tracking: ", wx.DefaultPosition,
                                     wx.Size(200, 20), wx.ALIGN_RIGHT,
                                     "StaticTextNameStr")
        moving_label.SetFont(self._program_font)
        self._moving_val = wx.StaticText(velocity_panel, -1,
                                         "Resting", wx.DefaultPosition,
                                         wx.Size(200, 20), wx.ALIGN_LEFT,
                                         "StaticTextNameStr")
        self._moving_val.SetFont(self._program_font)
        set_speed_label = wx.StaticText(velocity_panel, -1,
                                        "Max Speed (\xb0/s): ",
                                        wx.DefaultPosition, wx.Size(200, 20),
                                        wx.ALIGN_RIGHT, "StaticTextNameStr")
        set_speed_label.SetFont(self._program_font)
        self._set_speed_val = NumCtrl(velocity_panel, -1, 0,
                                      wx.DefaultPosition, wx.Size(200, 20),
                                      wx.TE_PROCESS_TAB | wx.TE_PROCESS_ENTER,
                                      wx.DefaultValidator, "masked.num")
        self._set_speed_val.SetAllowNegative(False)
        self._set_speed_val.SetBounds(0.01, 25)
        self._set_speed_val.SetFractionWidth(2)
        self._set_speed_val.SetIntegerWidth(2)
        self._set_speed_val.SetValue(10)
        self._set_speed_val.SetLimited(True)
        self._set_speed_val.SetFont(self._program_font)
        velocity_sizer.AddMany([
            curr_speed_label, self._curr_speed_val, moving_label,
            self._moving_val, set_speed_label, self._set_speed_val
        ])
        velocity_panel.SetSizer(velocity_sizer)

        # Button panel
        button_panel = wx.Panel(control_panel)
        button_sizer = wx.FlexGridSizer(2, 2, 0, 0)
        self._home_button = wx.Button(button_panel, -1,
                                      "Home Stage", wx.DefaultPosition,
                                      wx.Size(200, 26), 0, wx.DefaultValidator,
                                      "ButtonNameStr")
        self._home_button.SetFont(self._program_font)
        self._zero_button = wx.Button(button_panel, -1,
                                      "Zero Power Meter", wx.DefaultPosition,
                                      wx.Size(200, 26), 0, wx.DefaultValidator,
                                      "ButtonNameStr")
        self._zero_button.SetFont(self._program_font)
        self._start_button = wx.Button(button_panel, -1, "Start",
                                       wx.DefaultPosition, wx.Size(200, 26), 0,
                                       wx.DefaultValidator, "ButtonNameStr")
        self._start_button.SetFont(self._program_font)
        self._start_button.SetForegroundColour(wx.Colour("GREEN"))
        self._stop_button = wx.Button(button_panel, -1,
                                      "Stop", wx.DefaultPosition,
                                      wx.Size(200, 26), 0, wx.DefaultValidator,
                                      "ButtonNameStr")
        self._stop_button.SetFont(self._program_font)
        self._stop_button.SetForegroundColour(wx.Colour("RED"))
        self._stop_button.Disable()
        button_sizer.AddMany([
            self._home_button, self._zero_button, self._start_button,
            self._stop_button
        ])
        button_panel.SetSizer(button_sizer)

        # Bind events to the buttons and the serial input
        self._serial_val.Bind(wx.EVT_CHOICE, self.serial_entry)
        self._home_button.Bind(wx.EVT_BUTTON, self.home_press)
        self._zero_button.Bind(wx.EVT_BUTTON, self.zero_press)
        self._start_button.Bind(wx.EVT_BUTTON, self.start_press)
        self._stop_button.Bind(wx.EVT_BUTTON, self.stop_press)

        # Add the objects/panels to the control panel
        control_sizer.Add(title_label, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM,
                          44)
        control_sizer.Add(serial_panel, 0, wx.BOTTOM, 33)
        control_sizer.Add(power_panel, 0, wx.BOTTOM, 32)
        control_sizer.Add(angle_panel, 0, wx.BOTTOM, 32)
        control_sizer.Add(velocity_panel, 0, wx.BOTTOM, 32)
        control_sizer.Add(button_panel, 0, wx.BOTTOM, 0)
        control_panel.SetSizer(control_sizer)

        # Create the blank live plot canvas
        self._live_plt_canvas = FigureCanvasWxAgg(program_panel, -1,
                                                  self._live_plt)
        plot_title = "Laser Power (mW) vs. Polarizing Filter Angle (\xb0)"
        self._live_plt_axes.set_title(plot_title)
        # self._live_plt_axes.set_ylabel("Power (mW)")
        # self._live_plt_axes.set_xlabel("Angle (\xb0)")
        # self._live_plt_axes.grid(True)

        # Add the control panel and live plot to the main program panel
        program_sizer.Add(control_panel)
        program_sizer.Add(self._live_plt_canvas, 1, wx.EXPAND)

        # Set program panel sizer to display control and graph panels
        program_panel.SetSizer(program_sizer)

    def disable_ui(self):
        """Disable the inputs of the GUI, but enable the stop button."""
        self._serial_val.Disable()
        self._start_angle_val.Disable()
        self._end_angle_val.Disable()
        self._step_size_val.Disable()
        self._set_iter_val.Disable()
        self._set_speed_val.Disable()
        self._home_button.Disable()
        self._zero_button.Disable()
        self._start_button.Disable()
        self._stop_button.Enable()
        self._is_disabled = True

    def enable_ui(self):
        """Enable the inputs of the GUI, but disable the stop button."""
        self._serial_val.Enable()
        self._start_angle_val.Enable()
        self._end_angle_val.Enable()
        self._step_size_val.Enable()
        self._set_iter_val.Enable()
        self._set_speed_val.Enable()
        self._home_button.Enable()
        self._zero_button.Enable()
        self._start_button.Enable()
        self._stop_button.Disable()
        self._is_disabled = False

    def serial_entry(self, evt):
        """Intended for override by subclass, this is bound to the event
        on data entry into the serial number field.

        Parameters
        ----------
        evt : wx.Event
            The event which called this method.

        """
        print(self.get_serial())
        evt.Skip()

    def home_press(self, evt):
        """Intended for override by subcless, this is bound to the event
        on pressing the Home Stage button.
        Parameters
        ----------
        evt : wx.Event
            The event which called this method.

        """
        evt.Skip()

    def zero_press(self, evt):
        """Intended for override by subclass, this is bound to the event
        on pressing the Zero Power Meter button.

        Parameters
        ----------
        evt : wx.Event
            The event which called this method.

        """
        evt.Skip()

    def start_press(self, evt):
        """Intended for override by subclass, this is bound to the event
        on pressing the Start button.

        Parameters
        ----------
        evt : wx.Event
            The event which called this method.

        """
        evt.Skip()

    def stop_press(self, evt):
        """Intended for override by subclass, this is bound to the event
        on pressing the Stop button.

        Parameters
        ----------
        evt : wx.Event
            The event which called this method.

        """
        evt.Skip()

    def get_serial(self):
        """Return the value of the serial number input.

        Returns
        -------
        int
            The serial number input value.

        """
        serials = {0: 83843569, 1: 83846179, 2: 83845569}
        return serials[self._serial_val.GetCurrentSelection()]

    def set_pow_val(self, power):
        """Set the value of the current power display.

        Parameters
        ----------
        power
            The power value to be displayed.

        """
        self._curr_pow_val.SetLabel(str(power))

    def set_curr_angle_val(self, angle):
        """Set the value of the current angle display.

        Parameters
        ----------
        angle
            The angle to be displayed.

        """
        self._curr_angle_val.SetLabel(str(angle))

    def get_start_angle(self):
        """Return the value of the start angle input.

        Returns
        -------
        float
            The start angle input value.

        """
        return self._start_angle_val.GetValue()

    def get_end_angle(self):
        """Return the value of the end angle input.

        Returns
        -------
        float
            The end angle input value.

        """
        return self._end_angle_val.GetValue()

    def get_step_size(self):
        """Return the value of the step size input.

        Returns
        -------
        float
            The step size input value.

        """
        return self._step_size_val.GetValue()

    def set_curr_iter(self, iteration):
        """Set the value of the current iteration display.

        If the GUI is currently disabled, "Not currently testing!"
        will be displayed instead of `iteration`.

        Parameters
        ----------
        iteration
            The iteration value to be displayed.

        """
        if self._is_disabled is False:
            self._curr_iter_val.SetLabel("Not currently testing!")
        else:
            self._curr_iter_val.SetLabel(str(iteration))

    def get_iter_val(self):
        """Return the value of the number of iterations input.

        Returns
        -------
        int
            The number of iterations input value.

        """
        return self._set_iter_val.GetValue()

    def set_speed(self, speed):
        """Set the value of the current maximum speed.

        Parameters
        ----------
        speed
            The speed to be displayed.

        """
        self._curr_speed_val.SetLabel(str(speed))

    def set_moving(self):
        """Set the value of whether or not the motor is moving."""
        if self._is_disabled is True:
            self._moving_val.SetLabel("Tracking")
        else:
            self._moving_val.SetLabel("Resting")

    def get_speed(self):
        """Return the value of the maximum speed input.

        Returns
        -------
        float
            The value of the maximum speed input.

        """
        return self._set_speed_val.GetValue()

    def clear_plt(self):
        """Clears the live plot."""
        self._live_plt_axes.clear()
        plot_title = "Laser Power (mW) vs. Polarizing Filter Angle (\xb0)"
        self._live_plt_axes.set_title(plot_title)
        # self._live_plt_axes.set_ylabel("Power (mW)")
        # self._live_plt_axes.set_xlabel("Angle (\xb0)")
        # self._live_plt_axes.grid(True)

    def old_update_plt(self, data):
        """Updates the plot using 'data' for x and y values.

        Parameters
        ----------
        data : list of tuple of float
            The data set of [x, y] tuples to be plotted.

        """
        x_data = np.array([])
        y_data = np.array([])
        for item in data:
            x_data = np.append(x_data, [item[0]])
            y_data = np.append(y_data, [item[1] * 1000])
        min_power = y_data.min() - 50
        max_power = y_data.max() + 50
        self._live_plt_axes.axis([
            self.get_start_angle(),
            self.get_end_angle(), min_power, max_power
        ])
        self._live_plt_axes.plot(x_data[-1], y_data[-1], 'rx')
        self._live_plt_canvas.draw()

    def update_plt(self, data):
        """Updates the plot using 'data' for angle and r values.

        Parameters
        ----------
        data : list of tuple of float
            The data set of [angle, r] tuples to be plotted.

        """
        angle_data = np.array([])
        r_data = np.array([])
        for item in data:
            angle_data = np.append(angle_data, [item[0]])
            r_data = np.append(r_data, [item[1] * 1000])
        min_power = r_data.min() - 50
        max_power = r_data.max() + 50
        self._live_plt_axes.set_ylim([min_power, max_power])
        self._live_plt_axes.plot(x_data[-1], y_data[-1], 'rx')
        self._live_plt_canvas.draw()
Beispiel #17
0
class PanelOne(wx.Panel):
    def __init__(self, parent):
        self.bot = painter_bot()
        self.bot.connect_camera([1, 0])
        # Initialize Welcome Screen
        wx.Panel.__init__(self, parent=parent)

        ####################  Welcome Screen Text ###################
        font1 = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.BOLD)
        txt = wx.StaticText(self,
                            label="Welcome to CARP MQP Painter Application",
                            pos=(20, 10))
        txt.SetFont(font1)
        self.txt2 = wx.StaticText(self,
                                  label="Please select an image to process",
                                  pos=(20, 45))

        # Button For selecting a Video File
        button = wx.Button(self, label="Choose Image...", pos=(20, 70))
        button.Bind(wx.EVT_BUTTON, self.onSelectFile)

        # Button for Going to the next panel -- Disabled until a video file has been chosen
        self.paint_button = wx.Button(self, label="Paint", pos=(150, 70))
        self.paint_button.Bind(wx.EVT_BUTTON, self.paint)
        self.paint_button.Disable()

        # Variable for central image
        self.main_image = ''

        # Place Image of CARP logo
        png = wx.Image('./painter_gui/carp.png',
                       wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, png, (530, 5), (120, 120))

        ################### Decomposition Section ###################
        CONTROLS_OFFSET_LEFT = 450
        DY = 110

        txt3 = wx.StaticText(self,
                             label="Decomposition",
                             pos=(CONTROLS_OFFSET_LEFT, DY))
        self.MAX_COLORS = 6

        txt31 = wx.StaticText(self,
                              label="# of Colors: ",
                              pos=(CONTROLS_OFFSET_LEFT, DY + 23))
        # self.decomp_num_colors = wx.TextCtrl(self, value=self.num_colors, pos=(CONTROLS_OFFSET_LEFT, 150))
        self.decomp_num_colors = NumCtrl(self,
                                         value=self.MAX_COLORS,
                                         size=(40, 20),
                                         pos=(CONTROLS_OFFSET_LEFT + 70,
                                              DY + 20),
                                         integerWidth=2,
                                         limitOnFieldChange=True,
                                         min=0,
                                         max=self.MAX_COLORS)
        self.decomp_num_colors.Bind(EVT_NUM, self.showColors)

        self.auto_colors_button = wx.Button(self,
                                            label="Auto",
                                            pos=(CONTROLS_OFFSET_LEFT + 110,
                                                 DY + 19))
        self.auto_colors_button.Bind(
            wx.EVT_BUTTON, lambda evt, var=False: self.decomp(evt, var))

        self.color_data = wx.ColourData()
        self.color_data.SetChooseFull(True)

        self.paint_colors = []

        # wx.ColourDialog(self, data=None)
        for i in range(self.MAX_COLORS):
            panel = wx.Panel(self,
                             name="color " + str(i + 1),
                             pos=(CONTROLS_OFFSET_LEFT + 30 * i, DY + 50),
                             style=wx.SIMPLE_BORDER)
            panel.BackgroundColour = wx.WHITE

            panel.Bind(wx.EVT_LEFT_UP,
                       lambda evt, index=i: self.pickColor(index))
            self.paint_colors.append(panel)

        panel = wx.Panel(self,
                         name="color " + str(self.MAX_COLORS + 1),
                         pos=(CONTROLS_OFFSET_LEFT + 90, DY + 80),
                         style=wx.SIMPLE_BORDER)
        panel.BackgroundColour = wx.WHITE
        panel.Bind(
            wx.EVT_LEFT_UP,
            lambda evt, index=self.MAX_COLORS: self.pickColor(self.MAX_COLORS))
        self.paint_colors.append(panel)

        self.canvas_checkbox = wx.CheckBox(self,
                                           label="Canvas:",
                                           pos=(CONTROLS_OFFSET_LEFT + 20,
                                                DY + 82))
        self.canvas_checkbox.SetValue(True)
        self.canvas_checkbox.Bind(
            wx.EVT_CHECKBOX,
            lambda evt, index=self.MAX_COLORS: self.paint_colors[
                self.MAX_COLORS].Show(self.canvas_checkbox.GetValue()))

        self.decomp_button_apply = wx.Button(self,
                                             label="Apply",
                                             pos=(CONTROLS_OFFSET_LEFT,
                                                  DY + 110))
        self.decomp_button_apply.Bind(wx.EVT_BUTTON, self.decomp)

        self.disable_decomp()

        ####################  Recomposition Section ###################
        RY = 260

        txt4 = wx.StaticText(self,
                             label="Recomposition",
                             pos=(CONTROLS_OFFSET_LEFT, RY))
        txt5 = wx.StaticText(self,
                             label="Select a Recomposition Method",
                             pos=(CONTROLS_OFFSET_LEFT, RY + 20))

        self.rb1 = wx.RadioButton(self,
                                  11,
                                  label='Iterative Erosion',
                                  pos=(CONTROLS_OFFSET_LEFT, RY + 50),
                                  style=wx.RB_GROUP)
        self.rb2 = wx.RadioButton(self,
                                  22,
                                  label='Skeleton',
                                  pos=(CONTROLS_OFFSET_LEFT, RY + 70))
        self.rb3 = wx.RadioButton(self,
                                  33,
                                  label='Blended Recomposition',
                                  pos=(CONTROLS_OFFSET_LEFT, RY + 90))

        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.rb1.GetId())
        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.rb2.GetId())
        self.Bind(wx.EVT_RADIOBUTTON, self.SetVal, id=self.rb3.GetId())

        txt31 = wx.StaticText(self,
                              label="Brush Radius: ",
                              pos=(CONTROLS_OFFSET_LEFT, RY + 123))
        self.recomp_brush_radius = NumCtrl(self,
                                           value=4,
                                           pos=(CONTROLS_OFFSET_LEFT + 80,
                                                RY + 120),
                                           integerWidth=2,
                                           limitOnFieldChange=True,
                                           min=1,
                                           max=99)

        self.recomp_button_apply = wx.Button(self,
                                             label="Apply",
                                             pos=(CONTROLS_OFFSET_LEFT,
                                                  RY + 150))
        self.recomp_button_apply.Bind(wx.EVT_BUTTON, self.recomp)

        self.disable_recomp()

    def disable_decomp(self):
        self.enable_decomp(False)

    def enable_decomp(self, value=True):
        self.decomp_num_colors.Enable(value)
        self.decomp_button_apply.Enable(value)
        self.auto_colors_button.Enable(value)
        for box in self.paint_colors:
            box.Enable(value)
        self.canvas_checkbox.Enable(value)

    def disable_recomp(self):
        self.enable_recomp(False)

    def enable_recomp(self, value=True):
        self.rb1.Enable(value)
        self.rb2.Enable(value)
        self.rb3.Enable(value)
        self.recomp_button_apply.Enable(value)
        self.recomp_brush_radius.Enable(value)

    def enable_paint(self, value=True):
        self.paint_button.Enable(value)

    def disable_paint(self):
        self.enable_paint(False)

    def pickColor(self, index):
        print "pick ", index
        # set the default color in the chooser
        self.color_data.SetColour(
            self.paint_colors[index].GetBackgroundColour())

        # construct the chooser
        dlg = wx.ColourDialog(self, self.color_data)

        if dlg.ShowModal() == wx.ID_OK:
            # set the panel background color
            self.color_data = dlg.GetColourData()
            color = dlg.GetColourData().Colour
            # self.bot.colors[index] = [color.Blue,color.Green,color.Red]
            self.paint_colors[index].SetBackgroundColour(color)
        dlg.Destroy()

        self.Refresh()

    def SetVal(self, event):
        state1 = str(self.rb1.GetValue())
        state2 = str(self.rb2.GetValue())
        state3 = str(self.rb3.GetValue())

        print "state1 ", state1
        print "state2 ", state2
        print "state3 ", state3

    # Method for calling function to paint
    def paint(self, event):
        print "Paint"

        self.bot.connect_eth(ip='192.168.178.7', port=1234)
        self.bot.paint()
        # bot.paint_with_feedback([4])

    # Method for performing decomp
    def decomp(self, event, usePallete=True):
        print "Decomp"

        self.disable_decomp()
        self.disable_recomp()
        self.disable_paint()

        pallete = []
        num_colors = self.decomp_num_colors.GetValue()

        if usePallete:
            for i in range(num_colors):
                color = self.paint_colors[i].GetBackgroundColour()
                pallete.append(
                    [int(color.Blue()),
                     int(color.Green()),
                     int(color.Red())])
            num_colors = 0

        canvas_color = None
        if self.canvas_checkbox.GetValue():
            color = self.paint_colors[self.MAX_COLORS].GetBackgroundColour()
            canvas_color = [
                int(color.Blue()),
                int(color.Green()),
                int(color.Red())
            ]

        self.bot.decompose(num_colors, pallete, canvas_color)

        for i in range(len(self.bot.colors)):
            color = self.bot.colors[i]
            self.paint_colors[i].BackgroundColour = wx.Colour(
                color[2], color[1], color[0])
            self.color_data.SetCustomColour(
                15 - i, wx.Colour(color[2], color[1], color[0]))
        i = i + 1
        if i < len(self.paint_colors):
            for j in range(i, len(self.paint_colors)):
                self.paint_colors[j].BackgroundColour = wx.Colour(
                    255, 255, 255)

        self.setImage(self.bot.segmentedImg)

        self.enable_decomp()
        self.enable_recomp()
        self.disable_paint()

    # Method for performing recomp
    def recomp(self, event):
        print "Recomp"
        self.disable_recomp()

        radius = self.recomp_brush_radius.GetValue()

        re_func = None

        if self.rb1.GetValue():
            re_func = iterativeErosionRecomp
        elif self.rb2.GetValue():
            re_func = medialAxisRecomp
        elif self.rb3.GetValue():
            re_func = iterativeBlendedRecomp

        self.bot.recompose([radius], recomp_fun=re_func)
        self.setImage(self.bot.lltImg)

        self.enable_recomp()
        self.enable_paint()

    def scale_bitmap(self, bitmap, width, height):
        image = wx.ImageFromBitmap(bitmap)
        image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
        result = wx.BitmapFromImage(image)
        return result

    def showColors(self, event):
        n = self.decomp_num_colors.GetValue()
        for i in range(self.MAX_COLORS):
            self.paint_colors[i].Show(i < n)

    def setImage(self, input_image):
        ideal = np.zeros([400, 400, 3])
        resized_image = resize_with_buffer(input_image,
                                           ideal,
                                           padding_color=[0, 0, 0])
        cv2.imwrite('./painter_gui/resized.png', resized_image)
        self.main_image = wx.Image('./painter_gui/resized.png',
                                   wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, self.main_image, (20, 110),
                        (resized_image.shape[0], resized_image.shape[1]))
        self.Refresh()

# Method for launching file dialog box

    def onSelectFile(self, event):

        # Launch Dialog Box
        dlg = wx.FileDialog(self, "Choose a file", user.home, "", "*.*")
        if dlg.ShowModal() == wx.ID_OK:
            # Save selected file name and directory
            dirname = dlg.GetDirectory()
            filename = dlg.GetFilename()

            # Display Image
            input_image = readImage(filename, dirname + "/")
            self.bot.setImage(input_image)
            self.setImage(self.bot.desiredImg)

            # Report file selected and enable decomp section
            self.txt2.SetLabel("Selected file: " + filename)
            self.enable_decomp()
            self.disable_recomp()
            self.disable_paint()

            self.Refresh()

        # On Completion destroy dialog box
        dlg.Destroy()
Beispiel #18
0
class ShearInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        self.rbox = wx.RadioBox(self,
                                label='Shear Axis',
                                pos=(50, 10),
                                choices=['X-axis', 'Y-axis'],
                                majorDimension=1,
                                style=wx.RA_SPECIFY_ROWS)
        sfLabel = wx.StaticText(self, -1, "Enter Shear Factor: ", pos=(10, 74))
        self.sfInput = NumCtrl(self,
                               value=0.0,
                               integerWidth=2,
                               fractionWidth=2,
                               pos=(115, 75),
                               size=(100, -1))
        refLabel = wx.StaticText(self, -1, "Enter ref: ", pos=(10, 104))
        self.refInput = NumCtrl(self,
                                value=0.0,
                                integerWidth=2,
                                fractionWidth=2,
                                pos=(115, 105),
                                size=(100, -1))

        okBtn = wx.Button(self, -1, label='OK', pos=(10, 140), size=(100, 30))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(120, 140),
                              size=(100, 30))
        self.SetSize((230, 180))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        sf = self.sfInput.GetValue()
        ref = self.refInput.GetValue()
        selected = self.rbox.GetStringSelection()
        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]
        if selected == 'X-axis':
            self.parent.canvas.drawings.append(
                self.shear(points=self.parent.canvas.drawings[0],
                           sf=sf,
                           ref=ref,
                           axis='x'))
        else:
            self.parent.canvas.drawings.append(
                self.shear(points=self.parent.canvas.drawings[0],
                           sf=sf,
                           ref=ref,
                           axis='y'))

        self.Show(False)
        self.parent.buttons[12] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[12] = True

    def matrixMultiply(self, A, B):
        prod = list()
        for i in range(3):
            row = list()
            sm = 0
            for j in range(3):
                sm += A[i][j] * B[j][0]
            row.append(sm)
            prod.append(row)
        return prod

    def shear(self, points, sf, ref, axis):
        translated_points = list()
        if axis == 'x':
            shear_mat = [[1, sf, -sf * ref], [0, 1, 0], [0, 0, 1]]

        elif axis == 'y':
            shear_mat = [[1, 0, 0], [sf, 1, -sf * ref], [0, 0, 1]]

        for point in points:
            translated = self.matrixMultiply(shear_mat,
                                             [[point[0]], [point[1]], [1]])
            translated_points.append([translated[0][0], translated[1][0]])
        return translated_points
class CreateGui(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'GUI')
        self.initUI()
        self.currentDirectory = os.getcwd()

    def initUI(self):

        ##init options to default to put data into
        options = OptionsG(None, default_args.STYLE_WEIGHT, default_args.STYLE_LAYER_WEIGHT_EXP, default_args.VGG_PATH, \
                        None, default_args.CONTENT_WEIGHT, default_args.CONTENT_WEIGHT_BLEND, None, default_args.ITERATIONS, \
                        None, default_args.STYLE_SCALE, None, None, 'cpop%s.jpg', False, False, \
                        default_args.TV_WEIGHT, default_args.LEARNING_RATE, default_args.BETA1, \
                        default_args.BETA2, default_args.EPSILON, default_args.POOLING, 100, 100, True, True)

        ##init gui panel
        panel = wx.Panel(self)
        guiBox = wx.BoxSizer(wx.VERTICAL)

        required = wx.StaticBox(panel, label='Required')
        requireds = wx.StaticBoxSizer(required, orient=wx.HORIZONTAL)
        #required variables
        contentB = wx.Button(panel, label='Content Image')
        contentB.Bind(wx.EVT_BUTTON, self.onOpenContentFile)
        styleB = wx.Button(panel, label='Style Image')
        styleB.Bind(wx.EVT_BUTTON, self.onOpenStyleFile)
        output = wx.Button(panel, label='Output')
        output.Bind(wx.EVT_BUTTON, self.onSaveFile)

        requireds.Add(contentB, 0, wx.ALL, 5)
        requireds.Add(styleB, 0, wx.ALL, 5)
        requireds.Add(output, 0, wx.ALL, 5)

        #optional settings (if not default)
        optional = wx.StaticBox(panel, label='Optional')
        optionals = wx.StaticBoxSizer(optional, orient=wx.HORIZONTAL)

        #col1 = wx.StaticBox(panel)
        col1s = wx.BoxSizer(wx.VERTICAL)

        _style_weightBox = wx.BoxSizer(wx.HORIZONTAL)
        _style_weightLabel = wx.StaticText(panel, label='style_weight')
        self._style_weight = wx.SpinCtrl(panel,
                                         value=str(options.style_weight),
                                         min=0,
                                         max=1000)
        _style_weightBox.Add(_style_weightLabel)
        _style_weightBox.Add(self._style_weight)
        #_style_weight.SetRange(0,1000)

        _style_layer_weight_expBox = wx.BoxSizer(wx.HORIZONTAL)
        _style_layer_weight_expLabel = wx.StaticText(
            panel, label='style_layer_weight_exp')
        self._style_layer_weight_exp = wx.SpinCtrl(
            panel, value=str(options.style_layer_weight_exp), min=0.0, max=2.0)
        _style_layer_weight_expBox.Add(_style_layer_weight_expLabel)
        _style_layer_weight_expBox.Add(self._style_layer_weight_exp)
        #_style_layer_weight_exp.SetRange(0.0,2.0)

        _networkBox = wx.BoxSizer(wx.HORIZONTAL)
        _networkB = wx.Button(panel, label='network')
        _networkB.Bind(wx.EVT_BUTTON, self.onOpenNetworkFile)
        _networkBox.Add(_networkB, 0, wx.ALL, 5)

        _content_weightBox = wx.BoxSizer(wx.HORIZONTAL)
        _content_weightLabel = wx.StaticText(panel, label='content_weight')
        self._content_weight = wx.SpinCtrl(panel,
                                           value=str(options.content_weight),
                                           min=0,
                                           max=10000)
        _content_weightBox.Add(_content_weightLabel)
        _content_weightBox.Add(self._content_weight)
        #_content_weight.SetRange(0,10000)

        _content_weight_blendBox = wx.BoxSizer(wx.HORIZONTAL)
        _content_weight_blendLabel = wx.StaticText(
            panel, label='content_weight_blend')
        self._content_weight_blend = wx.SpinCtrl(
            panel, value=str(options.content_weight_blend), min=0.0, max=1.0)
        _content_weight_blendBox.Add(_content_weight_blendLabel)
        _content_weight_blendBox.Add(self._content_weight_blend)
        #_content_weight_blend.SetRange(0.0,1.0)

        _iterationsBox = wx.BoxSizer(wx.HORIZONTAL)
        _iterationsLabel = wx.StaticText(panel, label='iterations')
        self._iterations = wx.SpinCtrl(panel,
                                       value=str(options.iterations),
                                       min=0,
                                       max=2000)
        _iterationsBox.Add(_iterationsLabel)
        _iterationsBox.Add(self._iterations)
        #_iterations.SetRange(0,2000)   #allow for 0/1 to check running

        col1s.Add(_style_weightBox)
        col1s.Add(_style_layer_weight_expBox)
        col1s.Add(_networkBox)
        col1s.Add(_content_weightBox)
        col1s.Add(_content_weight_blendBox)
        col1s.Add(_iterationsBox)

        #  col2 = wx.StaticBox(panel)
        col2s = wx.BoxSizer(wx.VERTICAL)

        _widthBox = wx.BoxSizer(wx.HORIZONTAL)
        _widthLabel = wx.StaticText(panel, label='width (pixels)')
        self._width = NumCtrl(panel)
        _widthBox.Add(_widthLabel)
        _widthBox.Add(self._width)

        _style_scaleBox = wx.BoxSizer(wx.HORIZONTAL)
        _style_scaleLabel = wx.StaticText(panel, label='style_scale')
        self._style_scale = wx.SpinCtrl(panel,
                                        value=str(options.style_scale),
                                        min=0.0,
                                        max=1.0)
        _style_scaleBox.Add(_style_scaleLabel)
        _style_scaleBox.Add(self._style_scale)
        #_style_scale.SetRange(0.0,1.0)

        _initial_noiseblendBox = wx.BoxSizer(wx.HORIZONTAL)
        _initial_noiseblendLabel = wx.StaticText(panel,
                                                 label='initial_noiseblend')
        self._initial_noiseblend = wx.SpinCtrl(panel,
                                               value=str(
                                                   options.initial_noiseblend),
                                               min=0.0,
                                               max=1.0)
        _initial_noiseblendBox.Add(_initial_noiseblendLabel)
        _initial_noiseblendBox.Add(self._initial_noiseblend)
        #_initial_noiseblend.SetRange(0.0,1.0)

        _overwriteBox = wx.BoxSizer(wx.HORIZONTAL)
        self._overwriteCB = wx.CheckBox(panel, label='overwrite')
        self._overwriteCB.SetValue(options.overwrite)
        self._overwriteCB.Bind(wx.EVT_CHECKBOX, self.overwriteToggle)
        _overwriteBox.Add(self._overwriteCB)

        _preserve_colorsBox = wx.BoxSizer(wx.HORIZONTAL)
        self._preserve_colorsCB = wx.CheckBox(panel, label='preserve_colors')
        self._preserve_colorsCB.SetValue(options.preserve_colors)
        self._preserve_colorsCB.Bind(wx.EVT_CHECKBOX, self.presColToggle)
        _preserve_colorsBox.Add(self._preserve_colorsCB)

        _tv_weightBox = wx.BoxSizer(wx.HORIZONTAL)
        _tv_weightLabel = wx.StaticText(panel, label='tv_weight')
        self._tv_weight = wx.SpinCtrl(panel,
                                      value=str(options.tv_weight),
                                      min=0,
                                      max=100)
        _tv_weightBox.Add(_tv_weightLabel)
        _tv_weightBox.Add(self._tv_weight)
        #_tv_weight.SetRange(0,100)

        col2s.Add(_widthBox)
        col2s.Add(_style_scaleBox)
        col2s.Add(_initial_noiseblendBox)
        col2s.Add(_overwriteBox)
        col2s.Add(_preserve_colorsBox)
        col2s.Add(_tv_weightBox)

        #    col3 = wx.StaticBox(panel)
        col3s = wx.BoxSizer(wx.VERTICAL)

        _learning_rateBox = wx.BoxSizer(wx.HORIZONTAL)
        _learning_rateLabel = wx.StaticText(panel, label='learning_rate')
        self._learning_rate = wx.SpinCtrl(panel,
                                          value=str(options.learning_rate),
                                          min=0,
                                          max=100)
        _learning_rateBox.Add(_learning_rateLabel)
        _learning_rateBox.Add(self._learning_rate)
        #_learning_rate.SetRange(0,100)

        _beta1Box = wx.BoxSizer(wx.HORIZONTAL)
        _beta1Label = wx.StaticText(panel, label='beta1')
        self._beta1 = wx.SpinCtrl(panel,
                                  value=str(options.beta1),
                                  min=0.000,
                                  max=1.000)
        _beta1Box.Add(_beta1Label)
        _beta1Box.Add(self._beta1)
        #_beta1.SetRange(0.000,1.000)

        _beta2Box = wx.BoxSizer(wx.HORIZONTAL)
        _beta2Label = wx.StaticText(panel, label='beta2')
        self._beta2 = wx.SpinCtrl(panel,
                                  value=str(options.beta2),
                                  min=0.000,
                                  max=1.000)
        _beta2Box.Add(_beta2Label)
        _beta2Box.Add(self._beta2)
        #_beta2.SetRange(0.000,1.000)

        _epsilonBox = wx.BoxSizer(wx.HORIZONTAL)
        _epsilonLabel = wx.StaticText(panel, label='epsilon')
        self._epsilon = NumCtrl(panel,
                                value=np.format_float_scientific(
                                    options.epsilon))
        _epsilonBox.Add(_epsilonLabel)
        _epsilonBox.Add(self._epsilon)

        poolOpts = ['max', 'avg']
        _poolingBox = wx.BoxSizer(wx.HORIZONTAL)
        _poolingLabel = wx.StaticText(panel, label='pooling')
        self._pooling = wx.ComboBox(panel,
                                    choices=poolOpts,
                                    style=wx.CB_READONLY)
        self._pooling.Bind(wx.EVT_COMBOBOX, self.onPoolSelect)
        _poolingBox.Add(_poolingLabel)
        _poolingBox.Add(self._pooling)

        _progress_plotBox = wx.BoxSizer(wx.HORIZONTAL)
        self._progress_plotCB = wx.CheckBox(panel, label='progress_plot')
        self._progress_plotCB.SetValue(options.progress_plot)
        _progress_plotBox.Add(self._progress_plotCB)

        _progress_writeBox = wx.BoxSizer(wx.HORIZONTAL)
        self._progress_writeCB = wx.CheckBox(panel, label='progress_write')
        self._progress_writeCB.SetValue(options.progress_write)
        _progress_writeBox.Add(self._progress_writeCB)

        col3s.Add(_learning_rateBox)
        col3s.Add(_beta1Box)
        col3s.Add(_beta2Box)
        col3s.Add(_epsilonBox)
        col3s.Add(_poolingBox)
        col3s.Add(_progress_plotBox)
        col3s.Add(_progress_writeBox)

        optionals.Add(col1s)
        optionals.Add(col2s)
        optionals.Add(col3s)

        #buttons + gui collect
        guiBox.Add(requireds, flag=wx.EXPAND)
        guiBox.Add(optionals)

        buttonsbox = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(panel, label="Go", size=(40, 40))
        button.Bind(wx.EVT_BUTTON, self.goButton)
        exitbutton = wx.Button(panel, label="Exit", size=(40, 40))
        exitbutton.Bind(wx.EVT_BUTTON, self.onExit)

        buttonsbox.Add(button)
        buttonsbox.Add(exitbutton)

        guiBox.Add(buttonsbox, border=5)

        guiBox.SetSizeHints(self)

        guiBox.Add(panel,
                   proportion=1,
                   flag=wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.ALL,
                   border=5)

        self.SetSizer(guiBox)

##http://www.blog.pythonlibrary.org/2010/06/26/the-dialogs-of-wxpython-part-1-of-2/ ##open/output

    def onOpenContentFile(self, event):
        """
        Create and show the Open FileDialog
        """
        dlg = wx.FileDialog(self,
                            message="Choose a file",
                            defaultDir=self.currentDirectory,
                            defaultFile=".jpg",
                            wildcard=wildcard,
                            style=wx.FD_OPEN | wx.FD_MULTIPLE
                            | wx.FD_CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            print "opened content"
            contentimg = dlg.GetFilename()
            options.content = sys.path[0] + "/examples/" + contentimg
            options.width = Image.open(contentimg).size[0]
            options.initial = options.content
            print options.content
        dlg.Destroy()

    def onOpenStyleFile(self, event):
        """
        Create and show the Open FileDialog
        """
        dlg = wx.FileDialog(self,
                            message="Choose a file",
                            defaultDir=self.currentDirectory,
                            defaultFile=".jpg",
                            wildcard=wildcard,
                            style=wx.FD_OPEN | wx.FD_MULTIPLE
                            | wx.FD_CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            print "opened style"
            styleimg = dlg.GetFilename()
            options.styles = sys.path[0] + "/examples/" + styleimg
            print options.styles
        dlg.Destroy()

    def onOpenNetworkFile(self, event):
        """
        Create and show the Open FileDialog
        """
        dlg = wx.FileDialog(self,
                            message="Choose a file",
                            defaultDir=self.currentDirectory,
                            defaultFile=".mat",
                            wildcard=wildcard,
                            style=wx.FD_OPEN | wx.FD_MULTIPLE
                            | wx.FD_CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            print "opened network"
            _network = dlg.GetFilename()
            options.network = sys.path[0] + '/' + _network
            print options.network
        dlg.Destroy()

    def onSaveFile(self, event):
        """
        Create and show the Save FileDialog
        """
        dlg = wx.FileDialog(self,
                            message="Save file as ...",
                            defaultDir=self.currentDirectory,
                            defaultFile=".jpg",
                            wildcard=wildcard,
                            style=wx.FD_SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            print "saved"
            outputimg = dlg.GetFilename()
            options.output = sys.path[0] + "/" + outputimg
            print options.output

        dlg.Destroy()

    def overwriteToggle(self, event):
        overwriteT = event.GetEventObject()
        isChecked = overwriteT.GetValue()

        if isChecked:
            self._overwriteCB = True
        else:
            self._overwriteCB = False

    def presColToggle(self, event):
        presColT = event.GetEventObject()
        isChecked = presColT.GetValue()

        if isChecked:
            self._preserve_colorsCB = True
        else:
            self._preserve_colorsCB = False

    def onPoolSelect(self, event):
        pool = event.GetString()
        self._pooling.SetValue(pool)


##----------------------------------------

    def goButton(self, event):
        #---------extra test set vars------------
        ##set options to be self
        ##options.styles = self.styles
        ##options.content = self.content
        ##options.output = self.output
        ##options._network = self.network.GetValue() #set in Network func
        ##options.initial = self._initial.GetValue() #initial = content
        options.style_weight = self._style_weight.GetValue()
        options.style_layer_weight_exp = self._style_layer_weight_exp.GetValue(
        )
        options.content_weight = self._content_weight.GetValue()
        options.content_weight_blend = self._content_weight_blend.GetValue()
        options.iterations = self._iterations.GetValue()
        options.style_scale = self._style_scale.GetValue()
        options.initial_noiseblend = self._initial_noiseblend.GetValue()
        options.preserve_colors = self._preserve_colorsCB.GetValue()
        options.overwrite = self._overwriteCB.GetValue()
        options.tv_weight = self._tv_weight.GetValue()
        options.learning_rate = self._learning_rate.GetValue()
        options.beta1 = self._beta1.GetValue()
        options.beta2 = self._beta2.GetValue()
        options.epsilon = self._epsilon.GetValue()
        options.pooling = self._pooling.GetValue()
        options.progress_plot = self._progress_plotCB.GetValue()
        options.progress_write = self._progress_writeCB.GetValue()
        #----------------------------------------
        #---set individually due to list setting causing segfault--
        #----------------------------------------
        #print options.overwrite #options.overwrite = True? Getting overriden in run()?
        #print os.getcwd() ##for debugging/checking path manually

        os.chdir(sys.path[0])
        print "Please wait..."

        run()

    def onExit(self, event):

        self.Close(True)
Beispiel #20
0
class SinInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        amplitudeLabel = wx.StaticText(self,
                                       -1,
                                       "Enter amplitude: ",
                                       pos=(10, 14))
        self.amplitudeInput = NumCtrl(self,
                                      value=0.0,
                                      integerWidth=3,
                                      fractionWidth=2,
                                      pos=(120, 10),
                                      size=(100, -1))
        phaseLabel = wx.StaticText(self, -1, "Enter phase: ", pos=(10, 44))
        self.phaseInput = NumCtrl(self,
                                  value=0.0,
                                  integerWidth=3,
                                  fractionWidth=2,
                                  pos=(120, 40),
                                  size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 70), size=(100, 30))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(120, 70),
                              size=(100, 30))
        self.SetSize((230, 110))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        amplitude = self.amplitudeInput.GetValue()
        phase = self.phaseInput.GetValue()

        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]

        self.parent.canvas.drawings.append(self.sinDrawing(amplitude, phase))
        self.Show(False)
        self.parent.buttons[4] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[4] = True

    def sinDrawing(self, amplitude, phase):
        points = list()
        y = 0
        while y <= 1:
            x = degrees(asin(y))
            points.append([(x + phase), y * amplitude])
            points.append([(180 + phase - x), y * amplitude])
            points.append([(180 + phase + x), -y * amplitude])
            points.append([(360 + phase - x), -y * amplitude])
            y += 0.0005
        return points
Beispiel #21
0
class PowerDependentGUI(wx.Frame):
    def __init__(self, parent=None, title="Power Dependent Imaging"):
        super(PowerDependentGUI, self).__init__(parent,
                                                title=title,
                                                size=(1000, 1000))
        self._filedir = ""
        self._truefilename = ""
        self._filename = ""
        self._lcvr_init = False

        main_panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)

        input_panel = wx.Panel(main_panel)
        input_sizer = wx.BoxSizer(wx.HORIZONTAL)

        common_panel = wx.Panel(input_panel)
        common_sizer = wx.FlexGridSizer(11, 2, 0, 0)
        lcvr_label = wx.StaticText(common_panel, -1,
                                   "LCVR COM Port: ", wx.DefaultPosition,
                                   wx.Size(125, 20), wx.ALIGN_RIGHT,
                                   "StaticTextNameStr")
        self._lcvr_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                 wx.Size(125, 20), wx.TE_PROCESS_TAB
                                 | wx.TE_PROCESS_ENTER, wx.DefaultValidator,
                                 "masked.num")
        self._lcvr_val.SetAllowNegative(False)
        self._lcvr_val.SetBounds(1, 99)
        self._lcvr_val.SetFractionWidth(0)
        self._lcvr_val.SetIntegerWidth(2)
        self._lcvr_val.SetValue(6)
        self._lcvr_val.SetLimitOnFieldChange(True)
        self._lcvr_val.Bind(wx.lib.masked.EVT_NUM, self._lcvr_entry)
        lcvr_chan = wx.StaticText(common_panel, -1,
                                  "LCVR Channel: ", wx.DefaultPosition,
                                  wx.Size(125, 20), wx.ALIGN_RIGHT,
                                  "StaticTextNameStr")
        self._lcvr_ch = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                wx.Size(125, 20), wx.TE_PROCESS_TAB
                                | wx.TE_PROCESS_ENTER, wx.DefaultValidator,
                                "masked.num")
        self._lcvr_ch.SetAllowNegative(False)
        self._lcvr_ch.SetBounds(1, 4)
        self._lcvr_ch.SetFractionWidth(0)
        self._lcvr_ch.SetIntegerWidth(1)
        self._lcvr_ch.SetValue(1)
        self._lcvr_ch.SetLimitOnFieldChange(True)
        wavelength_label = wx.StaticText(common_panel, -1,
                                         "Laser Wavelength (nm):",
                                         wx.DefaultPosition, wx.Size(150, 20),
                                         wx.ALIGN_RIGHT, "StaticTextNameStr")
        self._wavelength_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                       wx.Size(150, 20), wx.TE_PROCESS_TAB
                                       | wx.TE_PROCESS_ENTER,
                                       wx.DefaultValidator, "masked.num")
        self._wavelength_val.SetAllowNegative(False)
        self._wavelength_val.SetBounds(400, 1100)
        self._wavelength_val.SetFractionWidth(0)
        self._wavelength_val.SetIntegerWidth(4)
        self._wavelength_val.SetValue(780)
        self._wavelength_val.SetLimitOnFieldChange(True)
        pow_label = wx.StaticText(common_panel, -1,
                                  "Laser Power (mW):", wx.DefaultPosition,
                                  wx.Size(150, 20), wx.ALIGN_RIGHT,
                                  "StaticTextNameStr")
        self._pow_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                wx.Size(150, 20), wx.TE_PROCESS_TAB
                                | wx.TE_PROCESS_ENTER, wx.DefaultValidator,
                                "masked.num")
        self._pow_val.SetAllowNegative(False)
        self._pow_val.SetBounds(0, 1000)
        self._pow_val.SetFractionWidth(2)
        self._pow_val.SetIntegerWidth(4)
        self._pow_val.SetValue(0)
        self._pow_val.SetLimitOnFieldChange(True)
        od_label = wx.StaticText(common_panel, -1, "OD:", wx.DefaultPosition,
                                 wx.Size(150, 20), wx.ALIGN_RIGHT,
                                 "StaticTextNameStr")
        self._od_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                               wx.Size(150, 20), wx.TE_PROCESS_TAB
                               | wx.TE_PROCESS_ENTER, wx.DefaultValidator,
                               "masked.num")
        self._od_val.SetAllowNegative(False)
        self._od_val.SetBounds(0, 100)
        self._od_val.SetFractionWidth(0)
        self._od_val.SetIntegerWidth(4)
        self._od_val.SetValue(0)
        self._od_val.SetLimitOnFieldChange(True)
        start_volt_label = wx.StaticText(common_panel, -1,
                                         "Start Voltage (V):",
                                         wx.DefaultPosition, wx.Size(150, 20),
                                         wx.ALIGN_RIGHT, "StaticTextNameStr")
        self._start_volt_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                       wx.Size(150, 20), wx.TE_PROCESS_TAB
                                       | wx.TE_PROCESS_ENTER,
                                       wx.DefaultValidator, "masked.num")
        self._start_volt_val.SetAllowNegative(False)
        self._start_volt_val.SetBounds(0, 10)
        self._start_volt_val.SetFractionWidth(2)
        self._start_volt_val.SetIntegerWidth(2)
        self._start_volt_val.SetValue(0)
        self._start_volt_val.SetLimitOnFieldChange(True)
        end_volt_label = wx.StaticText(common_panel, -1,
                                       "End Voltage (V):", wx.DefaultPosition,
                                       wx.Size(150, 20), wx.ALIGN_RIGHT,
                                       "StaticTextNameStr")
        self._end_volt_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                     wx.Size(150, 20), wx.TE_PROCESS_TAB
                                     | wx.TE_PROCESS_ENTER,
                                     wx.DefaultValidator, "masked.num")
        self._end_volt_val.SetAllowNegative(False)
        self._end_volt_val.SetBounds(0, 10)
        self._end_volt_val.SetFractionWidth(2)
        self._end_volt_val.SetIntegerWidth(2)
        self._end_volt_val.SetValue(10)
        self._end_volt_val.SetLimitOnFieldChange(True)
        step_volt_label = wx.StaticText(common_panel, -1,
                                        "Absolute Step Voltage (V):",
                                        wx.DefaultPosition, wx.Size(150, 20),
                                        wx.ALIGN_RIGHT, "StaticTextNameStr")
        self._step_volt_val = NumCtrl(common_panel, -1, 0, wx.DefaultPosition,
                                      wx.Size(150, 20), wx.TE_PROCESS_TAB
                                      | wx.TE_PROCESS_ENTER,
                                      wx.DefaultValidator, "masked.num")
        self._step_volt_val.SetAllowNegative(False)
        self._step_volt_val.SetBounds(0, 10)
        self._step_volt_val.SetFractionWidth(2)
        self._step_volt_val.SetIntegerWidth(2)
        self._step_volt_val.SetValue(0.1)
        self._step_volt_val.SetLimitOnFieldChange(True)
        self._dir_button = wx.Button(common_panel, -1, "Choose Save Location",
                                     wx.DefaultPosition, wx.Size(150, 20), 0,
                                     wx.DefaultValidator, "ButtonNameStr")
        self._file_button = wx.Button(common_panel, -1, "Choose Save Filename",
                                      wx.DefaultPosition, wx.Size(150, 20), 0,
                                      wx.DefaultValidator, "ButtonNameStr")
        self._go_button = wx.Button(common_panel, -1,
                                    "Start", wx.DefaultPosition,
                                    wx.Size(150, 20), 0, wx.DefaultValidator,
                                    "ButtonNameStr")
        self._stop_button = wx.Button(common_panel, -1,
                                      "Stop", wx.DefaultPosition,
                                      wx.Size(150, 20), 0, wx.DefaultValidator,
                                      "ButtonNameStr")

        self._resume_button = wx.Button(common_panel, -1,
                                        "Resume", wx.DefaultPosition,
                                        wx.Size(150, 20), 0,
                                        wx.DefaultValidator, "ButtonNameStr")

        self._pause_button = wx.Button(common_panel, -1, "Pause",
                                       wx.DefaultPosition, wx.Size(150, 20), 0,
                                       wx.DefaultValidator, "ButtonNameStr")
        self._dir_button.Bind(wx.EVT_BUTTON, self._dir_select)
        self._file_button.Bind(wx.EVT_BUTTON, self._file_select)
        self._go_button.Bind(wx.EVT_BUTTON, self._go)
        self._stop_button.Bind(wx.EVT_BUTTON, self._stop)
        self._resume_button.Bind(wx.EVT_BUTTON, self._resume)
        self._pause_button.Bind(wx.EVT_BUTTON, self._pause)
        common_sizer.AddMany([
            lcvr_label, self._lcvr_val, lcvr_chan, self._lcvr_ch,
            wavelength_label, self._wavelength_val, pow_label, self._pow_val,
            od_label, self._od_val, start_volt_label, self._start_volt_val,
            end_volt_label, self._end_volt_val, step_volt_label,
            self._step_volt_val, self._dir_button, self._file_button,
            self._go_button, self._stop_button, self._resume_button,
            self._pause_button
        ])
        common_panel.SetSizer(common_sizer)
        self._stop_button.Disable()
        self._pause_button.Disable()
        self._resume_button.Disable()

        input_sizer.Add(common_panel, 0, wx.ALL, 10)

        input_panel.SetSizer(input_sizer)

        self._ccd = CCDPanel("", "", title, main_panel)

        copyright_str = "\u00a9 2016 QuIN Lab"
        copyright_str += "Developed by Hayden Jones"
        copyright_text = wx.StaticText(main_panel, label=copyright_str)

        main_sizer.Add(input_panel, 0, wx.ALL, 0)
        main_sizer.Add(self._ccd, 0, wx.ALL, 0)
        main_sizer.Add(copyright_text, 0, wx.ALL, 0)

        main_panel.SetSizer(main_sizer)

        self.Bind(wx.EVT_CLOSE, self._on_close)

        self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER
                            ^ wx.MAXIMIZE_BOX)
        self.Show()

    def _on_close(self, evt):
        if self._lcvr_init is True:
            self._lcvr.close()
        evt.Skip()

    def disable_ui(self):
        self._lcvr_val.Disable()
        self._lcvr_ch.Disable()
        self._wavelength_val.Disable()
        self._pow_val.Disable()
        self._od_val.Disable()
        self._start_volt_val.Disable()
        self._end_volt_val.Disable()
        self._step_volt_val.Disable()
        self._dir_button.Disable()
        self._file_button.Disable()
        self._go_button.Disable()
        self._stop_button.Enable()
        self._resume_button.Disable()
        self._pause_button.Enable()

    def enable_ui(self):
        self._lcvr_val.Enable()
        self._lcvr_ch.Enable()
        self._wavelength_val.Enable()
        self._pow_val.Enable()
        self._od_val.Enable()
        self._start_volt_val.Enable()
        self._end_volt_val.Enable()
        self._step_volt_val.Enable()
        self._dir_button.Enable()
        self._file_button.Enable()
        self._go_button.Enable()
        self._stop_button.Disable()
        self._resume_button.Disable()
        self._pause_button.Disable()

    def get_od(self):
        return self._od_val.GetValue()

    def get_wavelength(self):
        return self._wavelength_val.GetValue()

    def get_power(self):
        return self._pow_val.GetValue()

    def get_start_volt(self):
        return self._start_volt_val.GetValue()

    def get_end_volt(self):
        return self._end_volt_val.GetValue()

    def get_step_volt(self):
        return self._step_volt_val.GetValue()

    def get_lcvr_addr(self):
        return self._lcvr_ch.GetValue()

    def _invalid_lcvr_warn(self):
        warning_message = "Invalid LCVR Controller Address/Connection!"
        warning = wx.GenericMessageDialog(None, warning_message, "Warning!",
                                          wx.OK, wx.DefaultPosition)
        warning.ShowModal()
        warning.Destroy()

    def _lcvr_entry(self, evt):
        if self._lcvr_init is True or self.get_lcvr_addr() < 1:
            return
        try:
            com_port = self._lcvr_val.GetValue()
            self._lcvr = MeadowlarkD3050Controller(com_port)
        except:
            self._invalid_lcvr_warn()
            return
        self._lcvr_init = True

    def _set_filename(self):
        self._filename = self._truefilename
        self._filename += "_OD" + str(self.get_od())
        self._filename += "_" + str(self.get_wavelength()) + "nm"
        self._filename += "_" + str(self.get_power()) + "mW"

    def _dir_select(self, evt):
        dir_dialog = wx.DirDialog(self, "Choose file save directory...", "",
                                  wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        if dir_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._filedir = dir_dialog.GetPath() + "\\"
        dir_dialog.Destroy()

    def _file_select(self, evt):
        file_dialog = wx.TextEntryDialog(self, "Enter the file name...",
                                         "File Name Selection Dialog",
                                         self._truefilename)
        if file_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._truefilename = file_dialog.GetValue()
        file_dialog.Destroy()

    def _go(self, evt):
        if self._lcvr_init is False:
            return
        self.disable_ui()
        self._ccd.open_xcap()
        self._kill_automation = False
        self._pause_automation = False
        _thread.start_new_thread(self._automation, (self.get_lcvr_addr(), ))

    def _stop(self, evt):
        self._kill_automation = True
        self._pause_automation = False
        self._ccd.close_xcap()
        self.enable_ui()

    def _resume(self, evt):
        self._od_val.Disable()
        self._resume_button.Disable()
        self._pause_button.Enable()
        self._pause_automation = False

    def _pause(self, evt):
        self._pause_automation = True
        self._od_val.Enable()
        self._resume_button.Enable()
        self._pause_button.Disable()

    def _automation(self, channel):
        start_volt = self.get_start_volt()
        end_volt = self.get_end_volt()
        if start_volt > end_volt:
            step = -self.get_step_volt()
        else:
            step = self.get_step_volt()
        overlap_holder = []
        self._ccd.set_work_dir(self._filedir)
        for i in range(int(start_volt * 1000), int((end_volt + 0.01) * 1000),
                       int(step * 1000)):
            v = float(i / 1000)
            if self._kill_automation is True:
                break
            if self._pause_automation is True:
                i = overlap_holder[0]
                while self._pause_automation is True:
                    if self._kill_automation is True:
                        break
            overlap_holder.append(i)
            self._lcvr.set_voltage(channel, v)
            if len(overlap_holder) > 5:
                overlap_holder.pop(0)
            self._set_filename()
            self._filename += "_" + str(v) + "V.jpg"
            self._ccd.set_filename(self._filename)
            self._ccd.grab_frame()
            sleep(5)
        wx.CallAfter(self._stop, wx.EVT_BUTTON)
Beispiel #22
0
class contratos(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          title=u"Contratos",
                          pos=wx.DefaultPosition,
                          size=wx.Size(640, 542),
                          style=wx.CAPTION | wx.CLOSE_BOX | wx.NO_BORDER
                          | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)
        self.SetBackgroundColour(wx.Colour(58, 5, 19))

        bSizer12 = wx.BoxSizer(wx.VERTICAL)

        self.m_panel15 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel15.SetBackgroundColour(wx.Colour(251, 203, 159))

        gSizer11 = wx.GridSizer(0, 4, 0, 0)

        self.m_staticText26 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Contrato N° : ",
                                            wx.DefaultPosition, wx.DefaultSize,
                                            0)
        self.m_staticText26.Wrap(-1)
        gSizer11.Add(self.m_staticText26, 0, wx.ALL, 5)

        self.NumCtrlc = NumCtrl(self.m_panel15,
                                -1,
                                style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB)
        gSizer11.Add(self.NumCtrlc, 0, wx.ALL, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        self.m_staticText27 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Direccion:", wx.DefaultPosition,
                                            wx.DefaultSize, 0)
        self.m_staticText27.Wrap(-1)
        gSizer11.Add(self.m_staticText27, 0, wx.ALL, 5)

        m_comboBox5Choices = []
        i = 0
        while i < len(rcasas):
            m_comboBox5Choices.append(rcasas[i][1])
            i = i + 1
        self.m_comboBox5 = wx.ComboBox(self.m_panel15, wx.ID_ANY,
                                       wx.EmptyString, wx.DefaultPosition,
                                       (250, 23), m_comboBox5Choices, 0)
        gSizer11.Add(self.m_comboBox5, 0, wx.ALL, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        self.m_button21 = wx.Button(self.m_panel15, wx.ID_ANY, u"BUSCAR",
                                    wx.DefaultPosition, wx.DefaultSize, 0)
        gSizer11.Add(self.m_button21, 0, wx.ALL, 5)

        self.m_staticText28 = wx.StaticText(self.m_panel15, 3, u"Propietario:",
                                            wx.DefaultPosition, wx.DefaultSize,
                                            0)
        self.m_staticText28.Wrap(-1)
        gSizer11.Add(self.m_staticText28, 0, wx.ALL, 5)

        self.m_textCtrl20 = wx.TextCtrl(self.m_panel15, wx.ID_ANY,
                                        wx.EmptyString, wx.DefaultPosition,
                                        (250, 23), 0)
        self.m_textCtrl20.Enable(False)

        gSizer11.Add(self.m_textCtrl20, 0, wx.ALL, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        self.m_staticText29 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Inquilino:", wx.DefaultPosition,
                                            wx.DefaultSize, 0)
        self.m_staticText29.Wrap(-1)
        gSizer11.Add(self.m_staticText29, 0, wx.ALL, 5)

        m_comboBox6Choices = []
        i = 0
        while i < len(rinq1):
            m_comboBox6Choices.append(rinq1[i][0])
            i = i + 1
        self.m_comboBox6 = wx.ComboBox(self.m_panel15, wx.ID_ANY,
                                       wx.EmptyString, wx.DefaultPosition,
                                       (250, 23), m_comboBox6Choices, 0)
        self.m_comboBox6.Enable(False)

        gSizer11.Add(self.m_comboBox6, 0, wx.ALL, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        gSizer11.AddSpacer((0, 0), 1, wx.EXPAND, 5)

        self.m_staticText31 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Fecha Inicio:",
                                            wx.DefaultPosition, wx.DefaultSize,
                                            0)
        self.m_staticText31.Wrap(-1)
        gSizer11.Add(self.m_staticText31, 0, wx.ALL, 5)

        self.m_datePicker2 = wx.DatePickerCtrl(self.m_panel15, wx.ID_ANY,
                                               wx.DefaultDateTime,
                                               wx.DefaultPosition,
                                               wx.DefaultSize,
                                               wx.DP_DEFAULT | wx.DP_DROPDOWN)
        self.m_datePicker2.Enable(False)

        gSizer11.Add(self.m_datePicker2, 0, wx.ALL, 5)

        self.m_staticText32 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Fecha de Vencimiento",
                                            wx.DefaultPosition, wx.DefaultSize,
                                            0)
        self.m_staticText32.Wrap(-1)
        gSizer11.Add(self.m_staticText32, 0, wx.ALL, 5)

        self.m_datePicker3 = wx.DatePickerCtrl(self.m_panel15, wx.ID_ANY,
                                               wx.DefaultDateTime,
                                               wx.DefaultPosition,
                                               wx.DefaultSize, wx.DP_DROPDOWN)
        self.m_datePicker3.Enable(False)

        gSizer11.Add(self.m_datePicker3, 0, wx.ALL, 5)

        self.m_staticText34 = wx.StaticText(self.m_panel15, wx.ID_ANY,
                                            u"Comision:", wx.DefaultPosition,
                                            wx.DefaultSize, 0)
        self.m_staticText34.Wrap(-1)
        gSizer11.Add(self.m_staticText34, 0, wx.ALL, 5)

        self.NumCtrl1 = NumCtrl(self.m_panel15,
                                -1,
                                style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB)
        self.NumCtrl1.SetParameters(integerWidth=9)
        self.NumCtrl1.SetParameters(fractionWidth=2)
        self.NumCtrl1.SetGroupChar(';')
        self.NumCtrl1.SetDecimalChar(',')
        self.NumCtrl1.SetGroupChar('.')
        self.NumCtrl1.SetMin(0)
        self.NumCtrl1.SetMax(-1)
        self.NumCtrl1.SetAllowNegative(False)
        self.NumCtrl1.SetSelectOnEntry(False)
        self.NumCtrl1.Enable(False)

        gSizer11.Add(self.NumCtrl1, 0, wx.ALL, 5)

        self.m_panel15.SetSizer(gSizer11)
        self.m_panel15.Layout()
        gSizer11.Fit(self.m_panel15)
        bSizer12.Add(self.m_panel15, 1, wx.ALIGN_TOP | wx.ALL, 5)

        self.m_panel16 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel16.SetBackgroundColour(wx.Colour(251, 203, 159))

        gSizer12 = wx.GridSizer(0, 3, 0, 0)

        self.m_staticText36 = wx.StaticText(self.m_panel16, wx.ID_ANY,
                                            u"Descuentos:", wx.DefaultPosition,
                                            wx.DefaultSize, 0)
        self.m_staticText36.Wrap(-1)
        gSizer12.Add(self.m_staticText36, 0, wx.ALL, 5)
        i = 0
        m_comboBox7Choices = []
        while i < len(rdes1):
            m_comboBox7Choices.append(rdes1[i][0])
            i = i + 1
        self.m_comboBox7 = wx.ComboBox(self.m_panel16, wx.ID_ANY,
                                       wx.EmptyString, wx.DefaultPosition,
                                       (250, 23), m_comboBox7Choices, 0)
        self.m_comboBox7.Enable(False)

        gSizer12.Add(self.m_comboBox7, 0, wx.ALL, 5)

        self.NumCtrl2 = NumCtrl(self.m_panel16,
                                -1,
                                style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB)
        self.NumCtrl2.Enable(False)
        self.NumCtrl2.SetParameters(integerWidth=9)
        self.NumCtrl2.SetParameters(fractionWidth=2)
        self.NumCtrl2.SetGroupChar(';')
        self.NumCtrl2.SetDecimalChar(',')
        self.NumCtrl2.SetGroupChar('.')
        self.NumCtrl2.SetMin(0)
        self.NumCtrl2.SetMax(-1)
        self.NumCtrl2.SetAllowNegative(False)
        self.NumCtrl2.SetSelectOnEntry(False)
        self.NumCtrl2.Enable(False)

        gSizer12.Add(self.NumCtrl2, 0,
                     wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_LEFT | wx.ALL, 5)

        self.m_checkBox1 = wx.CheckBox(self.m_panel16, wx.ID_ANY,
                                       u"Imprime en Propietario",
                                       wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox1.Enable(False)

        gSizer12.Add(self.m_checkBox1, 0, wx.ALL, 5)

        self.m_checkBox2 = wx.CheckBox(self.m_panel16, wx.ID_ANY,
                                       u"Imprime en Inmobiliaria",
                                       wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox2.Enable(False)

        gSizer12.Add(self.m_checkBox2, 0, wx.ALL, 5)

        self.m_checkBox3 = wx.CheckBox(self.m_panel16, wx.ID_ANY,
                                       u"Imprime en Inquilino",
                                       wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_checkBox3.Enable(False)

        gSizer12.Add(self.m_checkBox3, 0, wx.ALL, 5)

        self.m_panel16.SetSizer(gSizer12)
        self.m_panel16.Layout()
        gSizer12.Fit(self.m_panel16)
        bSizer12.Add(self.m_panel16, 1, wx.ALIGN_TOP | wx.ALL | wx.EXPAND, 5)

        self.m_panel17 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel17.SetBackgroundColour(wx.Colour(251, 203, 159))

        bSizer14 = wx.BoxSizer(wx.VERTICAL)

        self.m_button24 = wx.Button(self.m_panel17, wx.ID_ANY, u"AGREGAR",
                                    wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_button24.Enable(False)

        bSizer14.Add(self.m_button24, 0,
                     wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, 5)

        self.m_panel17.SetSizer(bSizer14)
        self.m_panel17.Layout()
        bSizer14.Fit(self.m_panel17)
        bSizer12.Add(self.m_panel17, 1, wx.ALIGN_TOP | wx.ALL | wx.EXPAND, 5)

        self.m_panel18 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel18.SetBackgroundColour(wx.Colour(251, 203, 159))

        bSizer15 = wx.BoxSizer(wx.VERTICAL)

        m_listBox1Choices = []
        self.m_listBox1 = wx.ListBox(self.m_panel18, wx.ID_ANY,
                                     wx.DefaultPosition, wx.DefaultSize,
                                     m_listBox1Choices, 0)
        self.m_listBox1.Enable(False)

        bSizer15.Add(self.m_listBox1, 0,
                     wx.ALIGN_TOP | wx.ALL | wx.EXPAND | wx.TOP, 5)

        self.m_panel18.SetSizer(bSizer15)
        self.m_panel18.Layout()
        bSizer15.Fit(self.m_panel18)
        bSizer12.Add(self.m_panel18, 1, wx.ALIGN_TOP | wx.ALL | wx.EXPAND, 5)

        self.m_panel19 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel19.SetBackgroundColour(wx.Colour(251, 203, 159))

        bSizer17 = wx.BoxSizer(wx.VERTICAL)

        self.m_button25 = wx.Button(self.m_panel19, wx.ID_ANY, u"ELIMINAR",
                                    wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_button25.Enable(False)

        bSizer17.Add(self.m_button25, 0, wx.ALIGN_TOP | wx.ALL | wx.EXPAND, 5)

        self.m_panel19.SetSizer(bSizer17)
        self.m_panel19.Layout()
        bSizer17.Fit(self.m_panel19)
        bSizer12.Add(self.m_panel19, 1, wx.ALIGN_TOP | wx.ALL | wx.EXPAND, 5)

        self.m_panel20 = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition,
                                  wx.DefaultSize, wx.TAB_TRAVERSAL)
        self.m_panel20.SetBackgroundColour(wx.Colour(251, 203, 159))

        bSizer18 = wx.BoxSizer(wx.HORIZONTAL)

        self.m_button26 = wx.Button(self.m_panel20, wx.ID_ANY, u"GUARDAR",
                                    wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_button26.Enable(False)

        bSizer18.Add(self.m_button26, 0, wx.ALL, 5)

        self.m_button27 = wx.Button(self.m_panel20, wx.ID_ANY, u"CANCELAR",
                                    wx.DefaultPosition, wx.DefaultSize, 0)
        self.m_button27.Enable(False)

        bSizer18.Add(self.m_button27, 0, wx.ALIGN_RIGHT | wx.ALL, 5)

        self.m_panel20.SetSizer(bSizer18)
        self.m_panel20.Layout()
        bSizer18.Fit(self.m_panel20)
        bSizer12.Add(self.m_panel20, 1,
                     wx.ALIGN_CENTER | wx.ALIGN_TOP | wx.ALL, 5)

        self.SetSizer(bSizer12)
        self.Layout()

        self.Centre(wx.BOTH)

        # Connect Events
        self.m_button21.Bind(wx.EVT_BUTTON, self.buscar)
        self.m_button24.Bind(wx.EVT_BUTTON, self.agregar)
        self.m_button25.Bind(wx.EVT_BUTTON, self.eliminar)
        self.m_button26.Bind(wx.EVT_BUTTON, self.guardar)
        self.m_button27.Bind(wx.EVT_BUTTON, self.cancelar)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def buscar(self, event):
        self.m_comboBox6.Enable(True)
        self.m_datePicker2.Enable(True)
        self.m_datePicker3.Enable(True)
        self.NumCtrl1.Enable(True)
        self.m_comboBox7.Enable(True)
        self.NumCtrl2.Enable(True)
        self.m_checkBox1.Enable(True)
        self.m_checkBox2.Enable(True)
        self.m_checkBox3.Enable(True)
        self.m_listBox1.Enable(True)
        self.m_button24.Enable(True)
        self.m_button25.Enable(True)
        self.m_button26.Enable(True)
        self.m_button27.Enable(True)
        direccion = self.m_comboBox5.GetValue()
        Casa2 = Casa('', direccion, '', '', '')
        regp = Casa2.consultar(con1)
        self.m_textCtrl20.SetValue(regp[0])
        event.Skip()

    def agregar(self, event):
        desc = self.m_comboBox7.GetValue()
        monto = self.NumCtrl2.GetValue()
        monto = str(monto)
        if self.m_checkBox1.GetValue() == True:
            chek1 = "SI"
        else:
            chek1 = "NO"
        if self.m_checkBox2.GetValue() == True:
            chek2 = "SI"
        else:
            chek2 = "NO"
        if self.m_checkBox3.GetValue() == True:
            chek3 = "SI"
        else:
            chek3 = "NO"
        self.m_listBox1.Append(desc + " ," + monto + "," + chek1 + "," +
                               chek2 + "," + chek3)

        event.Skip()

    def eliminar(self, event):
        sel = self.m_listBox1.GetSelection()
        if sel != -1:
            self.m_listBox1.Delete(sel)
        event.Skip()

    def guardar(self, event):
        for i in range(self.m_listBox1.GetCount()):
            a = self.m_listBox1.GetString(i)
            lista = a.split(',')
            descripcion = lista[0]
            descuento1 = Descuentos('', descripcion)
            rd = descuento1.consultar(con1)
            monto = lista[1]
            monto = monto[0:len(monto)]
            impripro = lista[2]
            impripro = impripro[0:len(impripro)]
            imprinmo = lista[3]
            imprinmo = imprinmo[0:len(imprinmo)]
            imprinq = lista[4]
            imprinq = imprinq[0:len(imprinq)]
            ncontrato = self.NumCtrlc.GetValue()
            comision = self.NumCtrl1.GetValue()
            direccion = self.m_comboBox5.GetValue()
            propietario = self.m_textCtrl20.GetValue()
            inquilinos = self.m_comboBox6.GetValue()
            seleccion1 = self.m_datePicker2.GetValue()
            mes1 = 1 + seleccion1.Month
            mes = str(mes1)
            dia = str(seleccion1.Day)
            ano = str(seleccion1.Year)
            fechain = dia + "/" + mes + "/" + ano
            fechain = str(fechain)
            seleccion2 = self.m_datePicker3.GetValue()
            mes1 = seleccion2.Month + 1
            mes = str(mes1)
            dia = str(seleccion2.Day)
            ano = str(seleccion2.Year)
            fechavto = dia + "/" + mes + "/" + ano
            fechavto = str(fechavto)
            cont1 = Contrato(ncontrato, direccion, inquilinos, fechain,
                             fechavto, propietario, comision)
            cont1.agregar(con1, descripcion, monto, impripro, imprinmo,
                          imprinq, rd[1])
            Casa1.direccion = self.m_comboBox5.GetValue()
            Casa1.contrato = self.NumCtrlc.GetValue()
            Casa1.alquilar(con1)
        self.Destroy()

    def cancelar(self, event):
        self.Destroy()
        event.Skip()
class mainWindow(wx.Frame):
    def __init__(self, camera):

        #set up directory to save photos
        global current_directory
        current_directory = os.getcwd()

        #inheritence
        wx.Frame.__init__(self,
                          None,
                          style=wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX
                          | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX
                          | wx.CLIP_CHILDREN)
        self.Title = "webcam"
        #menubar
        menubar = wx.MenuBar()

        filemenu = wx.Menu()
        change_dir = filemenu.Append(-1, 'Change Directory',
                                     "Change the directory to save Photos")
        menubar.Append(filemenu, '&File')

        optionsmenu = wx.Menu()
        self.mirrorcheckbox = optionsmenu.AppendCheckItem(
            -1, 'Mirror Image', "Mirror")
        optionsmenu.Check(self.mirrorcheckbox.GetId(), True)
        resolutionsmenu = wx.Menu()
        self.sixforty = resolutionsmenu.AppendRadioItem(
            -1, '640x480', "640x480")
        self.ninteentwenty = resolutionsmenu.AppendRadioItem(
            -1, '1920x1080', "1920x1080")
        self.custom = resolutionsmenu.AppendRadioItem(-1, 'Custom', "Custom")
        resolutionsmenu.Check(self.ninteentwenty.GetId(), True)
        optionsmenu.AppendMenu(wx.ID_ANY, '&Resolutions', resolutionsmenu)
        menubar.Append(optionsmenu, '&Options')

        self.SetMenuBar(menubar)

        #main ui
        self.webcampanel = webcamPanel(self, camera)
        self.button = wx.Button(self, label="Take Picture!")

        main_window_sizer = wx.BoxSizer(wx.VERTICAL)

        main_window_sizer.Add(self.webcampanel, 7,
                              wx.CENTER | wx.BOTTOM | wx.EXPAND, 1)
        main_window_sizer.SetItemMinSize(self.webcampanel, (640, 480))
        main_window_sizer.Add(self.button, 1, wx.CENTER | wx.EXPAND)

        self.SetSizer(main_window_sizer)
        main_window_sizer.Fit(self)

        self.Bind(wx.EVT_MENU, self.change_dir, change_dir)
        self.Bind(wx.EVT_MENU, self.mirror, self.mirrorcheckbox)
        self.Bind(wx.EVT_MENU, self.resolution, self.sixforty)
        self.Bind(wx.EVT_MENU, self.resolution, self.ninteentwenty)
        self.Bind(wx.EVT_MENU, self.custom_resolution, self.custom)
        self.Bind(wx.EVT_BUTTON, self.take_picture, self.button)

    def change_dir(self, e):
        #declare global variables
        global current_directory
        global iteration
        #open the choose folder directory
        dialog = wx.DirDialog(None,
                              "Choose a directory:",
                              style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        #wait for the okay
        if dialog.ShowModal() == wx.ID_OK:
            #grab the new directory
            current_directory = dialog.GetPath()
        #close the window
        dialog.Destroy()
        #reset the count for files
        iteration = 1

    def mirror(self, e):
        global mirror
        mirror = self.mirrorcheckbox.IsChecked()

    def resolution(self, e):
        global width
        global height

        if self.sixforty.IsChecked() == True:
            width = 640
            height = 480
        elif self.ninteentwenty.IsChecked() == True:
            width = 1920
            height = 1080

    def custom_resolution(self, e):

        global width
        global height

        dlg = wx.Dialog(self, size=(300, 150))
        self.instructions = wx.StaticText(
            dlg, wx.ID_ANY,
            'Here you can input a custom resolution. Make sure your camera supports it.'
        )

        self.width = NumCtrl(dlg)
        self.width.SetAllowNegative(False)
        self.width.SetAllowNone(False)
        self.width.SetValue(width)
        self.placex = wx.StaticText(dlg, wx.ID_ANY, 'x')
        self.height = NumCtrl(dlg)
        self.height.SetAllowNegative(False)
        self.height.SetAllowNone(False)
        self.height.SetValue(height)

        self.enter = wx.Button(dlg, wx.ID_OK)
        self.cancel = wx.Button(dlg, wx.ID_CANCEL)

        wrap_sizer = wx.BoxSizer(wx.VERTICAL)
        instructions_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button_sizer = wx.BoxSizer(wx.HORIZONTAL)

        button_sizer.Add(self.enter, 0, wx.CENTER | wx.RIGHT, 5)
        button_sizer.Add(self.cancel, 0, wx.CENTER)
        instructions_sizer.Add(self.width, 1, wx.CENTER | wx.EXPAND)
        instructions_sizer.Add(self.placex, 0, wx.CENTER)
        instructions_sizer.Add(self.height, 1, wx.CENTER | wx.EXPAND)
        wrap_sizer.Add(self.instructions, 1,
                       wx.CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
        wrap_sizer.Add(instructions_sizer, 0, wx.CENTER | wx.EXPAND | wx.ALL,
                       10)
        wrap_sizer.Add(button_sizer, 0, wx.CENTER | wx.BOTTOM, 10)

        dlg.SetSizer(wrap_sizer)
        dlg.Centre()
        dlg.Show()

        if dlg.ShowModal() == wx.ID_OK:
            height = self.height.GetValue()
            width = self.width.GetValue()

    def take_picture(self, e):
        #declare global variables
        global current_directory
        global iteration
        global mirror
        global height
        global width

        #get current frame from camera
        camera.set(3, width)
        camera.set(4, height)

        return_value, image = camera.read()
        #check to see if you should mirror image
        if mirror:
            image = cv2.flip(image, 1)
        #get the directory to save it in.
        filename = current_directory + "/000" + str(iteration) + ".png"
        #update the count
        iteration += 1
        #save the image
        cv2.imwrite(filename, image)
        #read the image (this is backwards isn't it?!
        saved_image = cv2.imread(filename)

        if height > 500:
            multiplyer = float(500.0 / height)
            multiplyer = round(multiplyer, 3)
            height *= multiplyer
            height = int(height)
            width *= multiplyer
            width = int(width)

        saved_image = cv2.resize(saved_image, (width, height))
        #show the image in a new window!
        cv2.imshow('Snapshot!', saved_image)
        camera.set(3, 640)
        camera.set(4, 480)
Beispiel #24
0
 def _number_editor(self, settings, name):
     initial_value = settings[name]
     editor = NumCtrl(self, value=initial_value)
     editor.Bind(wx.EVT_TEXT,
                 lambda evt: settings.set(name, int(editor.GetValue())))
     return editor
Beispiel #25
0
class RotateInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX)
        xLabel = wx.StaticText(self, -1, "X", pos=(120, 5))
        yLabel = wx.StaticText(self, -1, "Y", pos=(180, 5))
        centerLabel = wx.StaticText(self, -1, "Enter center: ", pos=(10, 24))
        self.centerxInput = NumCtrl(self,
                                    value=0.0,
                                    integerWidth=3,
                                    fractionWidth=2,
                                    pos=(90, 20),
                                    size=(100, -1))
        self.centeryInput = NumCtrl(self,
                                    value=0.0,
                                    integerWidth=3,
                                    fractionWidth=2,
                                    pos=(150, 20),
                                    size=(100, -1))
        thetaLabel = wx.StaticText(self, -1, "Enter angle: ", pos=(10, 54))
        self.thetaInput = NumCtrl(self,
                                  value=0.0,
                                  integerWidth=3,
                                  fractionWidth=2,
                                  pos=(90, 50),
                                  size=(100, -1))

        okBtn = wx.Button(self, -1, label='OK', pos=(10, 110), size=(100, 30))
        cancelBtn = wx.Button(self,
                              -1,
                              label='Cancel',
                              pos=(120, 110),
                              size=(100, 30))
        self.SetSize((230, 145))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        xc = self.centerxInput.GetValue()
        yc = self.centeryInput.GetValue()
        theta = self.thetaInput.GetValue()
        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.
                                                                  canvas.
                                                                  num_of_plots]
        self.parent.canvas.drawings.append(
            self.rotate(xc, yc, theta, self.parent.canvas.drawings[0]))

        self.Show(False)
        self.parent.buttons[7] = True
        self.parent.canvas.num_of_plots = min(9,
                                              len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[7] = True

    def matrixMultiply(self, A, B):
        prod = list()
        for i in range(3):
            row = list()
            sm = 0
            for j in range(3):
                sm += A[i][j] * B[j][0]
            row.append(sm)
            prod.append(row)
        return prod

    def rotate(self, xc, yc, theta, points):
        translated_points = list()
        theta = math.radians(theta)
        rotate_mat = [[
            math.cos(theta), -math.sin(theta),
            -xc * math.cos(theta) + yc * math.sin(theta) + xc
        ],
                      [
                          math.sin(theta),
                          math.cos(theta),
                          -xc * math.sin(theta) - yc * math.cos(theta) + yc
                      ], [0, 0, 1]]
        for point in points:
            translated = self.matrixMultiply(rotate_mat,
                                             [[point[0]], [point[1]], [1]])
            translated_points.append([translated[0][0], translated[1][0]])
        return translated_points
class CircleInputPopup(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.PopupWindow.__init__(self, parent, style=wx.CLOSE_BOX )
        xLabel = wx.StaticText(self, -1,
                           "X",
                           pos=(120,5))
        yLabel = wx.StaticText(self, -1,
                           "Y",
                           pos=(180,5))
        centerLabel = wx.StaticText(self, -1,
                           "Enter center: ",
                           pos=(10,24))
        self.centerxInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(90, 20), size=(100, -1))
        self.centeryInput = NumCtrl(self, value=0.0, integerWidth=3, fractionWidth=2, pos=(150, 20), size=(100, -1))
        radiusLabel = wx.StaticText(self, -1,
                           "Enter radius: ",
                           pos=(10,54))
        self.radiusInput = NumCtrl(self, value=0.0, allowNegative = False, integerWidth=3, fractionWidth=2, pos=(90, 50), size=(100, -1))
        okBtn = wx.Button(self, -1, label='OK', pos=(10, 100), size=(100, 30))
        cancelBtn = wx.Button(self, -1, label='Cancel', pos=(120, 100), size=(100, 30))
        self.SetSize((230, 135))

        okBtn.Bind(wx.EVT_BUTTON, self.onOKClick)
        cancelBtn.Bind(wx.EVT_BUTTON, self.onCancelClick)

    def onOKClick(self, event):
        xc = self.centerxInput.GetValue()
        yc = self.centeryInput.GetValue()
        radius = self.radiusInput.GetValue()
        self.parent.canvas.drawings = self.parent.canvas.drawings[:self.parent.canvas.num_of_plots]
        self.parent.canvas.drawings.append(self.circleDrawing(xc, yc, radius))

        self.Show(False)
        self.parent.buttons[2] = True
        self.parent.canvas.num_of_plots = min(9, len(self.parent.canvas.drawings))
        self.parent.canvas.draw()

    def onCancelClick(self, event):
        self.Show(False)
        self.parent.buttons[2] = True


    def circleDrawing(self, xc, yc, r):
        points = list()

        x = 0
        y = r
        points.append([x + xc, y + yc])
        points.append([-x + xc, y + yc])
        points.append([x + xc, -y + yc])
        points.append([-x + xc, -y + yc])
        points.append([y + xc, x + yc])
        points.append([-y + xc, x + yc])
        points.append([y + xc, -x + yc])
        points.append([-y + xc,-x + yc])
        p = 5 / 4 - r

        while x < y:
            x += 1
            if p < 0:
                points.append([x + xc, y + yc])
                points.append([-x + xc, y + yc])
                points.append([x + xc, -y + yc])
                points.append([-x + xc, -y + yc])
                points.append([y + xc, x + yc])
                points.append([-y + xc, x + yc])
                points.append([y + xc, -x + yc])
                points.append([-y + xc,-x + yc])

                p += 2 * x + 1
            else:
                y -= 1
                points.append([x + xc, y + yc])
                points.append([-x + xc, y + yc])
                points.append([x + xc, -y + yc])
                points.append([-x + xc, -y + yc])
                points.append([y + xc, x + yc])
                points.append([-y + xc, x + yc])
                points.append([y + xc, -x + yc])
                points.append([-y + xc,-x + yc])
                p += 2 * (x - y) + 1
        return points
Beispiel #27
0
class LightFieldControlPanel(wx.Panel):
    
    def __init__(self, lightfield, *args):
        wx.Panel.__init__(self, *args)
        self._lf = lightfield
        
        subpanel = wx.Panel(self)
        sp_sizer = wx.FlexGridSizer(6, 4, 0, 0)
        
        exp_txt = wx.StaticText(
            subpanel, label="Exposure Time (ms):", 
            size=(115, 20), style=wx.ALIGN_RIGHT)
        self._exp_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._exp_val.SetAllowNegative(False)
        self._exp_val.SetFractionWidth(0)
        self._exp_val.SetIntegerWidth(9)
        self._exp_val.SetValue(100)
        self._exp_val.Bind(wx.EVT_KILL_FOCUS, self._exp_entry)
        
        frames_txt = wx.StaticText(
            subpanel, label="Number of Frames:", 
            size=(-1, 20), style=wx.ALIGN_RIGHT)
        self._frames_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._frames_val.SetAllowNegative(False)
        self._frames_val.SetFractionWidth(0)
        self._frames_val.SetIntegerWidth(9)
        self._frames_val.SetValue(1)
        self._frames_val.Bind(wx.EVT_KILL_FOCUS, self._frames_entry)
        
        adcqlty_txt = wx.StaticText(
            subpanel, label="ADC Quality:", 
            size=(-1, 20), style=wx.ALIGN_RIGHT)
        self._adcqlty_val = wx.Choice(
            subpanel, size=(-1, 20), style=wx.CB_SORT,
            choices=["High Capacity", "Low Noise"])
        self._adcqlty_val.Bind(wx.EVT_CHOICE, self._adcqlty_entry)
                
        adcspeed_txt = wx.StaticText(
            subpanel, label="ADC Speed:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._adcspeed_val = wx.Choice(
            subpanel, size=(-1, 20),
            choices=["4 MHz", "2 MHz", "1 MHz", "500 kHz", "200 kHz",
                     "100 kHz", "50 kHz"])
        self._adcspeed_val.Bind(wx.EVT_CHOICE, self._adcspeed_entry)
        
        adcgain_txt = wx.StaticText(
            subpanel, label="ADC Analog Gain:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._adcgain_val = wx.Choice(
            subpanel, size=(-1, 20), choices=["High", "Medium", "Low"])
        self._adcgain_val.Bind(wx.EVT_CHOICE, self._adcgain_entry)
        
        adcbits_txt = wx.StaticText(
            subpanel, label="ADC Bit Depth:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        bitdepth = self._lf.get_adcbitdepth()
        adcbits_val = wx.StaticText(
            subpanel, label="{0} bits".format(bitdepth), size=(-1, 20), 
            style=wx.ALIGN_LEFT)
            
        width_txt = wx.StaticText(
            subpanel, label="Sensor Bin Width:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._width_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._width_val.SetAllowNegative(False)
        self._width_val.SetBounds(1, 1340)
        self._width_val.SetFractionWidth(0)
        self._width_val.SetIntegerWidth(4)
        self._width_val.SetValue(1)
        self._width_val.SetLimitOnFieldChange(True)
        self._width_val.Bind(wx.EVT_KILL_FOCUS, self._width_entry)
                    
        height_txt = wx.StaticText(
            subpanel, label="Sensor Bin Height:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._height_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._height_val.SetAllowNegative(False)
        self._height_val.SetBounds(1, 400)
        self._height_val.SetFractionWidth(0)
        self._height_val.SetIntegerWidth(4)
        self._height_val.SetValue(1)
        self._height_val.SetLimitOnFieldChange(True)
        self._height_val.Bind(wx.EVT_KILL_FOCUS, self._height_entry)
        
        roi_txt = wx.StaticText(
            subpanel, label="Sensor Mode:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._roi_val = wx.Choice(
            subpanel, size=(-1, 20), 
            choices=["Full Sensor", "Line Sensor", "Binned Sensor"])
        self._roi_val.Bind(wx.EVT_CHOICE, self._roi_entry)
     
        grating_txt = wx.StaticText(
            subpanel, label="Grating Density:", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._grating_val = wx.Choice(
            subpanel, size=(-1, 20), 
            choices=["300 g/mm", "1200 g/mm", "1800 g/mm"])
        self._grating_val.Bind(wx.EVT_CHOICE, self._grating_entry)
        
        lambda_txt = wx.StaticText(
            subpanel, label="Center Wavelength (nm):", 
            size=(135, 20), style=wx.ALIGN_RIGHT)
        self._lambda_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._lambda_val.SetAllowNegative(False)
        self._lambda_val.SetFractionWidth(3)
        self._lambda_val.SetIntegerWidth(4)
        self._lambda_val.SetValue(780)
        self._lambda_val.Bind(wx.EVT_KILL_FOCUS, self._lambda_entry)
        
        slit_txt = wx.StaticText(
            subpanel, label="Slit Width (\u03BCm):", size=(-1, 20), 
            style=wx.ALIGN_RIGHT)
        self._slit_val = NumCtrl(
            subpanel, size=(-1, 20), style=wx.TE_PROCESS_ENTER)
        self._slit_val.SetAllowNegative(False)
        self._slit_val.SetBounds(10, 3000)
        self._slit_val.SetFractionWidth(0)
        self._slit_val.SetIntegerWidth(4)
        self._slit_val.SetValue(100)
        self._slit_val.SetLimitOnFieldChange(True)
        self._slit_val.Bind(wx.EVT_KILL_FOCUS, self._slit_entry)
        
        sp_sizer.AddMany(
            [exp_txt, self._exp_val, width_txt, self._width_val,
             frames_txt, self._frames_val, height_txt, self._height_val,
             adcqlty_txt, self._adcqlty_val, roi_txt, self._roi_val,
             adcspeed_txt, self._adcspeed_val, grating_txt, self._grating_val,
             adcgain_txt, self._adcgain_val, lambda_txt, self._lambda_val,
             adcbits_txt, adcbits_val, slit_txt, self._slit_val])
        subpanel.SetSizer(sp_sizer)
        
        overall_sizer = wx.BoxSizer()
        overall_sizer.Add(subpanel, 0, wx.ALL, 10)
        self.SetSizer(overall_sizer)
        
    def disable_ui(self):
        self._exp_val.Disable()
        self._frames_val.Disable()
        self._adcqlty_val.Disable()
        self._adcspeed_val.Disable()
        self._adcgain_val.Disable()
        self._width_val.Disable()
        self._height_val.Disable()
        self._roi_val.Disable()
        self._grating_val.Disable()
        self._lambda_val.Disable()
        self._slit_val.Disable()
        
    def enable_ui(self):
        self._exp_val.Enable()
        self._frames_val.Enable()
        self._adcqlty_val.Enable()
        self._adcspeed_val.Enable()
        self._adcgain_val.Enable()
        self._width_val.Enable()
        self._height_val.Enable()
        self._roi_val.Enable()
        self._grating_val.Enable()
        self._lambda_val.Enable()
        self._slit_val.Enable()

    def _exp_entry(self, evt):
        if self._exp_val.GetValue() < 1:
            return
        self._lf.set_exposure(self._exp_val.GetValue())
        evt.Skip()
        
    def _frames_entry(self, evt):
        if self._frames_val.GetValue() < 1:
            return
        self._lf.set_frames(self._frames_val.GetValue())
        evt.Skip()
    
    def _adcqlty_entry(self, evt):
        if self._adcqlty_val.GetCurrentSelection() == 0:
            self._lf.set_adcquality(2)
        else:
            self._lf.set_adcquality(1)
            
    def _adcspeed_entry(self, evt):
        speeds = {
            0: 4,
            1: 2,
            2: 1,
            3: 0.5,
            4: 0.2,
            5: 0.1,
            6: 0.05
        }
        self._lf.set_adcspeed(
            speeds[self._adcspeed_val.GetCurrentSelection()])
            
    def _adcgain_entry(self, evt):
        if self._adcgain_val.GetCurrentSelection() == 0:
            self._lf.set_adcanaloggain(3)
        elif self._adcgain_val.GetCurrentSelection() == 1:
            self._lf.set_adcanaloggain(2)
        else:
            self._lf.set_adcanaloggain(1)
            
    def _width_entry(self, evt):
        if self._width_val.GetValue() < 1:
            return
        self._lf.set_binwidth(self._width_val.GetValue())
        evt.Skip()
        
    def _height_entry(self, evt):
        if self._height_val.GetValue() < 1:
            return
        self._lf.set_binheight(self._height_val.GetValue())
        evt.Skip()
        
    def _roi_entry(self, evt):
        if self._roi_val.GetCurrentSelection() == 0:
            self._lf.set_roiselection(1)
        elif self._roi_val.GetCurrentSelection() == 1:
            self._lf.set_roiselection(3)
        else:
            self._lf.set_roiselection(2)
    
    def _grating_entry(self, evt):
        if self._grating_val.GetCurrentSelection() == 0:
            self._lf.set_grating(300)
        elif self._grating_val.GetCurrentSelection() == 1:
            self._lf.set_grating(1200)
        else:
            self._lf.set_grating(1800)
            
    def _lambda_entry(self, evt):
        if self._lambda_val.GetValue() < 1:
            return
        self._lf.set_centerwavelength(self._lambda_val.GetValue())
        evt.Skip()
        
    def _slit_entry(self, evt):
        if self._slit_val.GetValue() < 1:
            return
        self._lf.set_slitwidth(self._slit_val.GetValue())
        evt.Skip()
        
class LabGUI(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(LabGUI, self).__init__(*args, **kwargs)

        self.InitUI()

    def InitUI(self):
        menubar = wx.MenuBar()
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT, 'About', 'Display about information')
        menubar.Append(helpMenu, '&Help')
        self.SetMenuBar(menubar)
        self.Bind(wx.EVT_MENU, self.OnShowAbout, aboutItem)

        panel = wx.Panel(self, wx.ID_ANY)

        self.chooseDataButton = wx.Button(panel, label="Choose Data File")
        self.chooseDataButton.Bind(wx.EVT_BUTTON, self.OnChooseFile)
        self.dataFileName = wx.StaticText(panel, wx.ID_ANY, label="No Data File Chosen", style=wx.ALIGN_CENTER)

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(panel, -1, self.figure)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL) 
        l1 = wx.StaticText(panel, -1, "Data Start") 
        hbox1.Add(l1, 1, wx.EXPAND | wx.ALIGN_LEFT | wx.ALL,5) 
        self.dataStartText = NumCtrl(panel) 
        self.dataStartText.Disable()
        hbox1.Add(self.dataStartText,1,wx.EXPAND | wx.ALIGN_LEFT | wx.ALL,5) 

        self.runAnalysisButton = wx.Button(panel, label="Run Analysis")
        self.runAnalysisButton.Bind(wx.EVT_BUTTON, self.OnRunAnalysis)
        self.runAnalysisButton.Disable()

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.chooseDataButton)
        vbox.Add(self.dataFileName) 
        vbox.Add(hbox1) 
        vbox.Add(self.runAnalysisButton)
        vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        panel.SetSizer(vbox) 

        self.SetTitle('Analyzing Slowdown of Spinner')
        self.SetSize(640,480)
        self.Centre()

    def OnShowAbout(self, e):
        wx.MessageBox(info, 'About', wx.OK | wx.ICON_INFORMATION)

    def OnRunAnalysis(self, e):
        dataStart = int(self.dataStartText.GetValue())
        velocity = analyzeData.findVelocity(self.data[dataStart:])
        self.axes.clear()
        self.axes.plot(velocity)
        self.axes.relim()
        self.axes.autoscale_view()
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()


    def OnChooseFile(self, e):
        with wx.FileDialog(self, "Open XYZ file",
                       style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:

            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return    

            # Proceed loading the file chosen by the user
            pathname = fileDialog.GetPath()
            try:
                self.dataFileName.SetLabel('Loading file')
                self.data = np.loadtxt(pathname)
                self.axes.plot(self.data)
                self.axes.relim()
                self.axes.autoscale_view()
                self.figure.canvas.draw()
                self.figure.canvas.flush_events()
                self.dataStartText.Enable()
                self.runAnalysisButton.Enable()
                self.dataFileName.SetLabel(pathname)
            except IOError:
                wx.LogError("Cannot open file '%s'." % newfile)
Beispiel #29
0
class SettingsDialog(wx.Dialog):
    def __init__(self, parent, solver, solvergui, fom_string):
        '''__init__(self, parent, solver, fom_string, mut_schemes,\
                    current_mut_scheme)
                    
        parent - parent window, solver - the solver (Diffev alg.)
        fom_string - the fom function string
        '''
        wx.Dialog.__init__(self, parent, -1, 'Optimizer settings')
        #self.SetAutoLayout(True)
        self.solver = solver
        self.solvergui = solvergui
        self.apply_change = None

        col_sizer = wx.BoxSizer(wx.HORIZONTAL)
        row_sizer1 = wx.BoxSizer(wx.VERTICAL)

        # Make the Diff. Ev. box
        de_box = wx.StaticBox(self, -1, "Diff. Ev.")
        de_box_sizer = wx.StaticBoxSizer(de_box, wx.VERTICAL)
        de_grid = wx.GridBagSizer(2, 2)

        km_sizer = wx.BoxSizer(wx.HORIZONTAL)
        km_text = wx.StaticText(self, -1, 'k_m ')
        self.km_control = NumCtrl(self, value = self.solver.km,\
            fractionWidth = 2, integerWidth = 2)
        km_sizer.Add(km_text,0, \
                wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        km_sizer.Add(self.km_control,1, \
                wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        km_sizer.Add((10, 20), 0, wx.EXPAND)
        de_grid.Add(km_sizer, (0,0),\
                    flag = wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL,\
                    border = 5)

        kr_sizer = wx.BoxSizer(wx.HORIZONTAL)
        kr_sizer.Add((10, 20), 0, wx.EXPAND)
        kr_text = wx.StaticText(self, -1, 'k_r ')
        self.kr_control = NumCtrl(self, value = self.solver.kr,\
            fractionWidth = 2, integerWidth = 2)
        kr_sizer.Add(kr_text, 1, \
                wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        kr_sizer.Add(self.kr_control, 0, \
                wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        de_grid.Add(kr_sizer, (0,1), \
                    flag = wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL,\
                    border = 5)

        method_sizer = wx.BoxSizer(wx.HORIZONTAL)
        method_text = wx.StaticText(self, -1, 'Method ')
        mut_schemes = [f.__name__ for f in self.solver.mutation_schemes]
        self.method_choice = wx.Choice(self, -1,\
            choices = mut_schemes)
        self.method_choice.SetSelection(self.solver.get_create_trial(True))
        method_sizer.Add(method_text,0, \
            wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        method_sizer.Add(self.method_choice,0,\
            wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        de_grid.Add(method_sizer, (1,0),(1,2), \
                    flag = wx.ALIGN_CENTER|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,\
                    border = 5)

        de_box_sizer.Add(de_grid, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        row_sizer1.Add(de_box_sizer, 0, wx.EXPAND, 5)

        #FOM BOX SIZER
        fom_box = wx.StaticBox(self, -1, "FOM")
        fom_box_sizer = wx.StaticBoxSizer(fom_box, wx.VERTICAL)

        # FOM choice
        fom_sizer = wx.BoxSizer(wx.HORIZONTAL)
        fom_text = wx.StaticText(self, -1, 'Figure of merit ')
        self.fom_choice = wx.Choice(self, -1, choices=fom_funcs.func_names)
        self.fom_choice.SetSelection(fom_funcs.func_names.index(fom_string))
        fom_sizer.Add(fom_text,0, \
            wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        fom_sizer.Add(self.fom_choice,0,\
            wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border = 10)
        fom_box_sizer.Add(fom_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        cb_sizer = wx.BoxSizer(wx.HORIZONTAL)
        fom_box_sizer.Add(cb_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        # Check box for ignoring nans
        self.fom_ignore_nan_control = wx.CheckBox(self, -1, "Ignore Nan")
        cb_sizer.Add(self.fom_ignore_nan_control, 0, wx.ALIGN_CENTRE | wx.ALL,
                     5)
        self.fom_ignore_nan_control.SetValue(
            self.solvergui.parent.model.fom_ignore_nan)
        # Check box for ignoring infs
        self.fom_ignore_inf_control = wx.CheckBox(self, -1, "Ignore +/-Inf")
        cb_sizer.Add(self.fom_ignore_inf_control, 0, wx.ALIGN_CENTRE | wx.ALL,
                     5)
        self.fom_ignore_inf_control.SetValue(
            self.solvergui.parent.model.fom_ignore_inf)
        self.fom_ignore_inf_control.SetValue(
            self.solvergui.parent.model.fom_ignore_inf)

        # Errorbar level
        errorbar_sizer = wx.BoxSizer(wx.HORIZONTAL)
        errorbar_text = wx.StaticText(self, -1, 'Error bar level ')
        self.errorbar_control = NumCtrl(self, value =\
                        self.solvergui.fom_error_bars_level,\
                        fractionWidth = 2, integerWidth = 2)
        errorbar_sizer.Add(errorbar_text,0, \
                wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        errorbar_sizer.Add(self.errorbar_control,1, \
                wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        errorbar_sizer.Add((10, 20), 0, wx.EXPAND)
        fom_box_sizer.Add(errorbar_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        row_sizer1.Add(fom_box_sizer, 0, wx.EXPAND, 5)

        # Make the Fitting box
        fit_box = wx.StaticBox(self, -1, "Fitting")
        fit_box_sizer = wx.StaticBoxSizer(fit_box, wx.VERTICAL)

        # Make a sizer for the check boxes
        cb_sizer = wx.BoxSizer(wx.HORIZONTAL)
        fit_box_sizer.Add(cb_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        # Check box for start guess
        startguess_control = wx.CheckBox(self, -1, "Start guess")
        cb_sizer.Add(startguess_control, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        startguess_control.SetValue(self.solver.use_start_guess)
        self.startguess_control = startguess_control

        # Check box for using boundaries
        bound_control = wx.CheckBox(self, -1, "Use (Max, Min)")
        cb_sizer.Add(bound_control, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        bound_control.SetValue(self.solver.use_boundaries)
        self.bound_control = bound_control

        # Check box and integer input for autosave
        autosave_sizer = wx.BoxSizer(wx.HORIZONTAL)
        use_autosave_control = wx.CheckBox(self, -1, "Autosave, interval ")
        use_autosave_control.SetValue(self.solver.use_autosave)
        autosave_sc = wx.SpinCtrl(self)
        autosave_sc.SetRange(1, 1000)
        autosave_sc.SetValue(self.solver.autosave_interval)
        autosave_sc.Enable(True)
        autosave_sizer.Add(use_autosave_control, 0, \
            wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 5)
        autosave_sizer.Add(autosave_sc,0,\
            wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 5)
        self.autosave_sc = autosave_sc
        self.use_autosave_control = use_autosave_control
        fit_box_sizer.Add(autosave_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        # Checkbox for saving all evals
        save_sizer = wx.BoxSizer(wx.HORIZONTAL)
        save_all_control = wx.CheckBox(self, -1, "Save evals, buffer ")
        save_all_control.SetValue(self.solvergui.save_all_evals)
        buffer_sc = wx.SpinCtrl(self)
        buffer_sc.SetRange(1000, 100000000)
        buffer_sc.SetValue(self.solver.max_log)
        buffer_sc.Enable(True)
        save_sizer.Add(save_all_control, 0, \
            wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 5)
        save_sizer.Add(buffer_sc,0,\
            wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 5)
        self.buffer_sc = buffer_sc
        self.save_all_control = save_all_control
        fit_box_sizer.Add(save_sizer, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        row_sizer1.Add(fit_box_sizer, 1, wx.EXPAND, 5)

        col_sizer.Add(row_sizer1, 1, wx.ALIGN_CENTRE | wx.ALL, 5)

        row_sizer2 = wx.BoxSizer(wx.VERTICAL)

        # Make the Population box
        pop_box = wx.StaticBox(self, -1, "Population size")
        pop_box_sizer = wx.StaticBoxSizer(pop_box, wx.VERTICAL)
        pop_grid = wx.FlexGridSizer(0, 2, 0, 0)

        multsize_radio = wx.RadioButton(self, -1,  " Relative size ",\
                            style = wx.RB_GROUP )
        fixedsize_radio = wx.RadioButton(self, -1, " Fixed size ")

        multsize_sc = wx.SpinCtrl(self)
        multsize_sc.SetRange(1, 1000)
        multsize_sc.SetValue(self.solver.pop_mult)
        multsize_sc.Enable(self.solver.use_pop_mult)
        fixedsize_sc = wx.SpinCtrl(self)
        fixedsize_sc.SetRange(1, 1000)
        fixedsize_sc.SetValue(self.solver.pop_size)
        fixedsize_sc.Enable(not self.solver.use_pop_mult)

        self.pop_multsize_radio = multsize_radio
        self.pop_fixedsize_radio = fixedsize_radio
        self.pop_multsize_sc = multsize_sc
        self.pop_fixedsize_sc = fixedsize_sc

        pop_grid.Add(multsize_radio, 0,\
            wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        pop_grid.Add(multsize_sc, 0,\
            wx.ALIGN_RIGHT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        pop_grid.Add( fixedsize_radio, 0,\
            wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        pop_grid.Add(fixedsize_sc, 0,\
            wx.ALIGN_RIGHT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )

        pop_box_sizer.Add(pop_grid, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        row_sizer2.Add(pop_box_sizer, 1, wx.EXPAND, 5)
        self.Bind(wx.EVT_RADIOBUTTON, self.on_pop_select, multsize_radio)
        self.Bind(wx.EVT_RADIOBUTTON, self.on_pop_select, fixedsize_radio)
        multsize_radio.SetValue(self.solver.use_pop_mult)
        fixedsize_radio.SetValue(not self.solver.use_pop_mult)

        # Make the Generation box
        gen_box = wx.StaticBox(self, -1, "Max Generations")
        gen_box_sizer = wx.StaticBoxSizer(gen_box, wx.VERTICAL)
        gen_grid = wx.FlexGridSizer(0, 2, 0, 0)

        gen_multsize_radio = wx.RadioButton( self, -1, " Relative size ",\
                            style = wx.RB_GROUP )
        gen_fixedsize_radio = wx.RadioButton(self, -1, " Fixed size ")

        gen_multsize_sc = wx.SpinCtrl(self)
        gen_multsize_sc.SetRange(1, 10000)
        gen_multsize_sc.SetValue(self.solver.max_generation_mult)
        gen_multsize_sc.Enable(not self.solver.use_max_generations)
        gen_fixedsize_sc = wx.SpinCtrl(self)
        gen_fixedsize_sc.SetRange(1, 10000)
        gen_fixedsize_sc.SetValue(self.solver.max_generations)
        gen_fixedsize_sc.Enable(self.solver.use_max_generations)

        self.gen_multsize_radio = gen_multsize_radio
        self.gen_fixedsize_radio = gen_fixedsize_radio
        self.gen_multsize_sc = gen_multsize_sc
        self.gen_fixedsize_sc = gen_fixedsize_sc

        gen_grid.Add(gen_multsize_radio, 0,\
            wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        gen_grid.Add(gen_multsize_sc, 0,\
            wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        gen_grid.Add(gen_fixedsize_radio, 0,\
            wx.ALIGN_LEFT|wx.LEFT|wx.RIGHT|wx.TOP, 5 )
        gen_grid.Add(gen_fixedsize_sc, 0,\
            wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 )

        gen_box_sizer.Add(gen_grid, 0, wx.ALIGN_CENTRE | wx.ALL, 5)
        row_sizer2.Add(gen_box_sizer, 1, wx.EXPAND, 5)
        self.Bind(wx.EVT_RADIOBUTTON, self.on_gen_select, gen_multsize_radio)
        self.Bind(wx.EVT_RADIOBUTTON, self.on_gen_select, gen_fixedsize_radio)
        gen_fixedsize_radio.SetValue(self.solver.use_max_generations)
        gen_multsize_radio.SetValue(not self.solver.use_max_generations)

        ##
        # Make the parallel fitting box
        parallel_box = wx.StaticBox(self, -1, "Parallel processing")
        parallel_box_sizer = wx.StaticBoxSizer(parallel_box, wx.VERTICAL)

        use_parallel_control = wx.CheckBox(self, -1, "Parallel fitting")
        use_parallel_control.SetValue(self.solver.use_parallel_processing)
        use_parallel_control.Enable(diffev.__parallel_loaded__)
        self.use_parallel_control = use_parallel_control
        parallel_box_sizer.Add(use_parallel_control, 1,\
                    wx.ALIGN_CENTRE|wx.EXPAND, 5 )

        processes_sc = wx.SpinCtrl(self, size=(80, -1))
        processes_sc.SetRange(1, 100)
        processes_sc.SetValue(self.solver.processes)
        processes_sc.Enable(diffev.__parallel_loaded__)
        chunk_size_sc = wx.SpinCtrl(self, size=(80, -1))
        chunk_size_sc.SetRange(1, 100)
        chunk_size_sc.SetValue(self.solver.chunksize)
        chunk_size_sc.Enable(diffev.__parallel_loaded__)
        self.processes_sc = processes_sc
        self.chunk_size_sc = chunk_size_sc
        parallel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        p_text = wx.StaticText(self, -1, '# Processes')
        parallel_sizer.Add(p_text, 0, \
                wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        parallel_sizer.Add((10, 20), 1, wx.EXPAND)
        parallel_sizer.Add(processes_sc, 0, \
                wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        parallel_box_sizer.Add(parallel_sizer, 1, wx.ALIGN_CENTRE | wx.EXPAND,
                               10)
        parallel_sizer = wx.BoxSizer(wx.HORIZONTAL)
        p_text = wx.StaticText(self, -1, ' Chunk size ')
        parallel_sizer.Add(p_text, 0, \
                wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, border = 10)
        parallel_sizer.Add((10, 20), 1, wx.EXPAND)
        parallel_sizer.Add(chunk_size_sc, 0, \
                wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, border = 10)

        parallel_box_sizer.Add(parallel_sizer, 1, wx.EXPAND, 10)
        row_sizer2.Add(parallel_box_sizer, 1, wx.EXPAND, 5)

        col_sizer.Add(row_sizer2, 1, wx.ALIGN_CENTRE | wx.ALL, 5)
        ##

        # Add the Dialog buttons
        button_sizer = wx.StdDialogButtonSizer()
        okay_button = wx.Button(self, wx.ID_OK)
        okay_button.SetDefault()
        button_sizer.AddButton(okay_button)
        apply_button = wx.Button(self, wx.ID_APPLY)
        apply_button.SetDefault()
        button_sizer.AddButton(apply_button)
        button_sizer.AddButton(wx.Button(self, wx.ID_CANCEL))
        button_sizer.Realize()
        # Add some eventhandlers
        self.Bind(wx.EVT_BUTTON, self.on_apply_change, okay_button)
        self.Bind(wx.EVT_BUTTON, self.on_apply_change, apply_button)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(col_sizer, 1, wx.GROW | wx.ALIGN_CENTER_HORIZONTAL, 20)
        #sizer.Add(col_sizer, 1, wx.GROW|wx.ALL|wx.EXPAND, 20)
        line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL)
        sizer.Add(line, 0, wx.GROW | wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, 20)

        sizer.Add(button_sizer,0,\
                flag = wx.ALIGN_RIGHT, border = 20)
        self.SetSizer(sizer)

        sizer.Fit(self)
        self.Layout()

    def on_pop_select(self, event):
        '''on_pop_select(self, event) --> None
        
        callback for selction of a radio button in the population group
        '''
        radio_selected = event.GetEventObject()

        if radio_selected is self.pop_fixedsize_radio:
            self.pop_fixedsize_sc.Enable(True)
            self.pop_multsize_sc.Enable(False)
        else:
            self.pop_fixedsize_sc.Enable(False)
            self.pop_multsize_sc.Enable(True)

    def on_gen_select(self, event):
        '''on_pop_select(self, event) --> None
        
        callback for selection of a radio button in the Generation group
        '''
        radio_selected = event.GetEventObject()

        if radio_selected is self.gen_fixedsize_radio:
            self.gen_fixedsize_sc.Enable(True)
            self.gen_multsize_sc.Enable(False)
        else:
            self.gen_fixedsize_sc.Enable(False)
            self.gen_multsize_sc.Enable(True)

    def get_fom_string(self):
        return self.fom_choice.GetStringSelection()

    def on_apply_change(self, event):
        self.solver.kr = self.kr_control.GetValue()
        self.solver.km = self.km_control.GetValue()
        self.solver.max_generation_mult = self.gen_multsize_sc.GetValue()
        self.solver.max_generations = self.gen_fixedsize_sc.GetValue()
        self.solver.pop_mult = self.pop_multsize_sc.GetValue()
        self.solver.pop_size = self.pop_fixedsize_sc.GetValue()
        self.solver.use_max_generations = self.gen_fixedsize_radio.GetValue()
        self.solver.use_pop_mult = self.pop_multsize_radio.GetValue()
        self.solver.use_start_guess = self.startguess_control.GetValue()
        self.solver.use_boundaries = self.bound_control.GetValue()
        self.solver.set_create_trial(self.method_choice.GetStringSelection())
        self.solver.use_parallel_processing = self.use_parallel_control.GetValue(
        )
        self.solver.processes = self.processes_sc.GetValue()
        self.solver.chunksize = self.chunk_size_sc.GetValue()
        self.solvergui.parent.model.set_fom_ignore_inf(
            self.fom_ignore_inf_control.GetValue())
        self.solvergui.parent.model.set_fom_ignore_nan(
            self.fom_ignore_nan_control.GetValue())
        self.solvergui.fom_error_bars_level = self.errorbar_control.GetValue()
        self.solver.use_autosave = self.use_autosave_control.GetValue()
        self.solver.autosave_interval = self.autosave_sc.GetValue()
        self.solvergui.save_all_evals = self.save_all_control.GetValue()
        self.solver.max_log = self.buffer_sc.GetValue()
        if self.apply_change:
            self.apply_change(self)

        event.Skip()

    def set_apply_change_func(self, func):
        '''set_apply_change_func(self, func) --> None
        
        Set the apply_change function. Is executed when the apply or ok button
        is clicked.
        '''
        self.apply_change = func
Beispiel #30
0
class OrderForm(wx.Panel):
    def __init__(self, parent=None, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.parent = parent
        self.pnl = self.parent.pnl
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.cleaned_data = {
            'OrderType': 'LMT',
            'Action': 'BUY',
            'Symbol': '',
            'Quantity': 0,
            'LmtPrice': 0
        }
        self.createControls()
        self.bindEvents()
        self.doLayout()

    def createControls(self):
        self.OrderType = wx.RadioBox(self.pnl,
                                     label='OrderType',
                                     pos=(80, 30),
                                     choices=["LMT", "MKT"],
                                     majorDimension=1,
                                     style=wx.RA_SPECIFY_ROWS)
        self.Action = wx.RadioBox(self.pnl,
                                  label='Action',
                                  pos=(60, 30),
                                  choices=["BUY", "SELL"],
                                  majorDimension=1,
                                  style=wx.RA_SPECIFY_ROWS)
        self.hbox1 = wx.BoxSizer(wx.VERTICAL)
        l1 = wx.StaticText(self.pnl, -1, "Symbol")
        self.hbox1.Add(l1, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        self.Symbol = wx.TextCtrl(self.pnl)
        self.hbox1.Add(self.Symbol)

        self.hbox2 = wx.BoxSizer(wx.VERTICAL)
        l2 = wx.StaticText(self.pnl, -1, "Quantity")
        self.hbox2.Add(l2, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        self.Quantity = IntCtrl(self.pnl)
        self.hbox2.Add(self.Quantity)

        self.hbox3 = wx.BoxSizer(wx.VERTICAL)
        l3 = wx.StaticText(self.pnl, -1, "LmtPrice")
        self.hbox3.Add(l3, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        self.LmtPrice = NumCtrl(self.pnl, fractionWidth=2, min=0, max=None)
        self.hbox3.Add(self.LmtPrice)

    def bindEvents(self):
        for control, event, handler in \
             [(self.OrderType, wx.EVT_RADIOBOX, self.OnRadioBox1),
             (self.Action, wx.EVT_RADIOBOX, self.OnRadioBox2),
             (self.Symbol, wx.EVT_TEXT, self.OnSymbol),
             (self.Quantity, wx.EVT_TEXT, self.OnQuantity),
             (self.LmtPrice, wx.EVT_TEXT, self.OnLmtPrice)]:
            control.Bind(event, handler)

    def doLayout(self):
        self.sizer.AddMany(
            [self.OrderType, self.Action, self.hbox1, self.hbox2, self.hbox3])

    def OnRadioBox1(self, e):
        self.cleaned_data['OrderType'] = self.OrderType.GetStringSelection()
        self.parent.SetStatusText('{} is clicked from Radio Box'.format(
            self.OrderType.GetStringSelection()))

    def OnRadioBox2(self, e):
        self.cleaned_data['Action'] = self.Action.GetStringSelection()
        self.parent.SetStatusText('{} is clicked from Radio Box'.format(
            self.Action.GetStringSelection()))

    def OnSymbol(self, e):
        self.cleaned_data['Symbol'] = self.Symbol.GetValue()
        self.parent.SetStatusText("Entered Symbol: {}".format(
            self.Symbol.GetValue()))

    def OnQuantity(self, e):
        self.cleaned_data['Quantity'] = self.Quantity.GetValue()
        self.parent.SetStatusText("Entered Quantity: {}".format(
            self.Quantity.GetValue()))

    def OnLmtPrice(self, e):
        self.parent.SetStatusText("Entered Limit Price: {}".format(
            self.LmtPrice.GetValue()))
        if self.OrderType.GetStringSelection() == "LMT":
            # Only do something if both fields are valid so far.
            if not self.LmtPrice.GetValue():
                wx.MessageBox('Please Fill in the Limit Price', 'Error', wx.OK)
            else:
                self.cleaned_data["LmtPrice"] = self.LmtPrice.GetValue()
        if self.OrderType.GetStringSelection() == "MKT":
            self.LmtPrice.SetValue(0)
            self.cleaned_data["LmtPrice"] = 0