示例#1
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()
示例#2
0
class ContExpDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        self.database = "funct/database.pype"
        self.contExpValues = {}
        self.listOfIds = []
        for x in range(17):
            NewId = wx.NewId()
            self.listOfIds.append(NewId)

        wx.Dialog.__init__(self, parent, id, title, size=(300, 265))
        self.firstPanel = wx.Panel(self, self.listOfIds[0])
        self.secondPanel = wx.Panel(
            self, self.listOfIds[1],
            style=wx.SUNKEN_BORDER)  #self.scrolledWindow(self)
        self.thirdPanel = wx.Panel(self, self.listOfIds[2])
        mainBox = wx.BoxSizer(wx.VERTICAL)

        radioBoxList = self.contExpDialogGeneralText()["e1"]
        self.radioBox = wx.RadioBox(self.firstPanel, self.listOfIds[3],
                                    self.contExpDialogGeneralText()["e2"],
                                    (50, 5), (200, 65), radioBoxList, 1,
                                    wx.RA_SPECIFY_COLS)

        self.setMiddlePanel(self.secondPanel)
        #        self.secondPanel.Enable(False)

        self.okButton = wx.Button(self.thirdPanel,
                                  wx.ID_OK,
                                  self.contExpDialogGeneralText()["e3"],
                                  size=(70, 30),
                                  pos=(220, 2))
        self.closeButton = wx.Button(self.thirdPanel,
                                     wx.ID_CANCEL,
                                     self.contExpDialogGeneralText()["e4"],
                                     size=(70, 30),
                                     pos=(145, 2))

        mainBox.Add(self.firstPanel, 9, wx.EXPAND)
        mainBox.Add(self.secondPanel, 15, wx.EXPAND)
        mainBox.Add(self.thirdPanel, 4, wx.EXPAND)

        self.radioBox.Bind(wx.EVT_RADIOBOX, self.analizeSelection)
        self.SetSizer(mainBox)

        self.okButton.Bind(wx.EVT_BUTTON, self.onOkButton)
        self.closeButton.Bind(wx.EVT_BUTTON, self.onClose)
        self.okButton.SetDefault()
        self.lastSegmentValues = self.setDisabledWidget()

        self.Centre()

    def typeOfPipe(self, pipeTypeAcron):
        if pipeTypeAcron == "CSP":
            pipeType = "Commercial_Steel_Pipe_c"
        elif pipeTypeAcron == "SSP":
            pipeType = "Stainless_Steel_Pipe_c"
        elif pipeTypeAcron == "PVC":
            pipeType = "PVC_Pipe_c"
        else:
            pipeType = "None"
#            msg = self.pipeDialogGeneralText()["d14"]
#            raise Exception, msg
        return pipeType

    def dataBaseConsult(self, sched, pipeType):
        #        ID = []
        OD = []
        NPS = []
        flag = 0

        if (sched == "STD" or sched == "XS" or sched == "DXS"):
            typeOfPipe = pipeType[:-1]
        else:
            typeOfPipe = pipeType

            connection = sqlite3.connect("funct/database.pype")
            cursor = connection.cursor()
            sqlcommand = """SELECT Nominal_Pipe_size, Outside_Diameter FROM %s""" % typeOfPipe + sched
            cursor.execute(sqlcommand)
            system_data = cursor.fetchall()
            connection.close()

            for value in system_data:
                #                print value
                if flag:
                    NPS.append(str(value[0]))
                    OD.append(str(value[1]))
#                    ID.append(str(value[2]))
                else:
                    flag += 1

            return NPS, OD
#        print system_data

    def onClose(self, evt):
        self.Destroy()

    def onOkButton(self, evt):
        okToClose = False
        #        print self.lastSegmentValues
        schedule = self.lastSegmentValues[0][1]
        NPS = self.lastSegmentValues[0][2]
        OD = self.lastSegmentValues[0][3]
        #        ID = self.lastSegmentValues[0][4]
        minimunDiameter = self.lastSegmentValues[0][5]

        if schedule != "None":
            #si la cedula fue especificada en el segmento anterior

            if self.NPSChoice.IsEnabled():
                #si la casilla de NPS esta habilitada
                selected = float(self.NPSChoice.GetStringSelection())
                if self.radioBox.GetSelection() == 0:
                    #si se selecciona expansion
                    self.contExpValues["type"] = "sudden_expansion"
                    if selected > NPS:
                        self.contExpValues["D_2"] = selected
                        self.contExpValues["D_2_type"] = "NPS"
                        okToClose = True
                    else:
                        text = self.contExpDialogGeneralText(
                        )["e5"] + " %s" % NPS
                        dialog = wx.MessageDialog(
                            self,
                            text,
                            self.contExpDialogGeneralText()["e6"],
                            style=wx.OK | wx.ICON_EXCLAMATION)
                        dialog.ShowModal()
                        dialog.Destroy()
                        okToClose = False

                elif self.radioBox.GetSelection() == 1:
                    #si se selecciona contraccion
                    self.contExpValues["type"] = "sudden_contraction"
                    if selected < NPS:
                        self.contExpValues["D_2"] = selected
                        self.contExpValues["D_2_type"] = "NPS"
                        okToClose = True
                    else:
                        text = self.contExpDialogGeneralText(
                        )["e7"] + " %s" % NPS
                        dialog = wx.MessageDialog(
                            self,
                            text,
                            self.contExpDialogGeneralText()["e6"],
                            style=wx.OK | wx.ICON_EXCLAMATION)
                        dialog.ShowModal()
                        dialog.Destroy()
                        okToClose = False

            elif self.ODChoice.IsEnabled():
                #si la casilla de OD esta habilitada
                selected = float(self.ODChoice.GetStringSelection())
                if self.radioBox.GetSelection() == 0:
                    #si se selecciona expansion
                    self.contExpValues["type"] = "sudden_expansion"
                    if selected > OD:
                        self.contExpValues["D_2"] = selected
                        self.contExpValues["D_2_type"] = "OD"
                        okToClose = True
                    else:
                        text = self.contExpDialogGeneralText(
                        )["e8"] + " %s" % OD
                        dialog = wx.MessageDialog(
                            self,
                            text,
                            self.contExpDialogGeneralText()["e6"],
                            style=wx.OK | wx.ICON_EXCLAMATION)
                        dialog.ShowModal()
                        dialog.Destroy()
                        okToClose = False

                elif self.radioBox.GetSelection() == 1:
                    #si se selecciona contraccion
                    self.contExpValues["type"] = "sudden_contraction"
                    if selected < OD:
                        self.contExpValues["D_2"] = selected
                        self.contExpValues["D_2_type"] = "OD"
                        okToClose = True
                    else:
                        text = self.contExpDialogGeneralText(
                        )["e9"] + " %s" % OD
                        dialog = wx.MessageDialog(
                            self,
                            text,
                            self.contExpDialogGeneralText()["e6"],
                            style=wx.OK | wx.ICON_EXCLAMATION)
                        dialog.ShowModal()
                        dialog.Destroy()
                        okToClose = False

#            elif self.IDChoice.IsEnabled():
#                #si la casilla de ID esta habilitada
#                selected = float(self.IDChoice.GetStringSelection())
#                if self.radioBox.GetSelection() == 0:
#                    #si se selecciona expansion
#                    self.contExpValues["type"] = "sudden_expansion"
#                    if selected > ID:
#                        self.contExpValues["D_2"] = selected
#                        self.contExpValues["D_2_type"] = "ID"
#                        okToClose = True
#                    else:
#                        text = "El valor de ID elegido\ndebe ser mayor a %s" % ID
#                        dialog = wx.MessageDialog(self, text,
#                                                  "titulo", style=wx.OK | wx.ICON_EXCLAMATION)
#                        dialog.ShowModal()
#                        dialog.Destroy()
#                        okToClose = False
#
#                elif self.radioBox.GetSelection() == 1:
#                    #si se selecciona contraccion
#                    self.contExpValues["type"] = "sudden_contraction"
#                    if selected < ID:
#                        self.contExpValues["D_2"] = selected
#                        self.contExpValues["D_2_type"] = "ID"
#                        okToClose = True
#                    else:
#                        text = "El valor de ID elegido\ndebe ser menor a %s" % ID
#                        dialog = wx.MessageDialog(self, text,
#                                                  "titulo", style=wx.OK | wx.ICON_EXCLAMATION)
#                        dialog.ShowModal()
#                        dialog.Destroy()
#                        okToClose = False

            else:
                #la condicion "else" no deberia darse pero por si acaso
                msg = "se cumplio condicion else en calculo de expansion/contraccion\nmodulo: onOkButton"
                raise Exception, msg

        else:
            #si no fue especificada la cedula se esta trabajando con el diametro minimo
            selected = self.minimumDiamValue.GetValue()
            units = self.minimumDiamUnit.GetStringSelection()
            if self.radioBox.GetSelection() == 0:
                #si se selecciona expansion
                self.contExpValues["type"] = "sudden_expansion"
                minimumDiameterOtherUnit = f.DistanceConvert(
                    minimunDiameter, "m", units)
                if selected > minimumDiameterOtherUnit:
                    self.contExpValues["minimum_diameter"] = selected
                    self.contExpValues["minimum_diameter_unit"] = units
                    okToClose = True
                else:
                    text = self.contExpDialogGeneralText(
                    )["e10"] + " %s %s" % (minimumDiameterOtherUnit, units)
                    dialog = wx.MessageDialog(
                        self,
                        text,
                        self.contExpDialogGeneralText()["e6"],
                        style=wx.OK | wx.ICON_EXCLAMATION)
                    dialog.ShowModal()
                    dialog.Destroy()
                    okToClose = False

            elif self.radioBox.GetSelection() == 1:
                #si se selecciona contraccion
                self.contExpValues["type"] = "sudden_contraction"
                minimumDiameterOtherUnit = f.DistanceConvert(
                    minimunDiameter, "m", units)
                if selected < minimumDiameterOtherUnit:
                    self.contExpValues["minimum_diameter"] = selected
                    self.contExpValues["minimum_diameter_unit"] = units
                    okToClose = True
                else:
                    text = self.contExpDialogGeneralText(
                    )["e11"] + " %s %s" % (minimumDiameterOtherUnit, units)
                    dialog = wx.MessageDialog(
                        self,
                        text,
                        self.contExpDialogGeneralText()["e6"],
                        style=wx.OK | wx.ICON_EXCLAMATION)
                    dialog.ShowModal()
                    dialog.Destroy()
                    okToClose = False

        if okToClose:
            #            print self.contExpValues
            self.EndModal(wx.ID_OK)
#        print self.contExpValues

    def analizeSelection(self, evt):
        """Modulo que activa y desactiva widgets
        dependiendo de las seleciones de los radiobox
        """
        schedule = self.lastSegmentValues[0][1]
        #        NPS = self.lastSegmentValues[0][2]
        #        OD  = self.lastSegmentValues[0][3]
        #        ID = self.lastSegmentValues[0][4]
        #        minimunDiameter = self.lastSegmentValues[0][5]

        if schedule != "None":
            #si la cedula fue especificada en el segmento anterior
            #            NPSselection = self.NPSChoice.GetStringSelection()
            #            ODselection = self.ODChoice.GetStringSelection()
            #            IDselection =self.IDChoice.GetStringSelection()

            if self.middlePanelRadioBox.GetSelection() == 0:
                #si se selecciona NPS para usar
                self.NPSChoice.Enable(True)
                self.ODChoice.Enable(False)
#                self.IDChoice.Enable(False)
#            if NPSselection != -1:
#                self.contExpValues["D_2"] = NPSselection
#                self.contExpValues["D_2_type"] = "NPS"

            elif self.middlePanelRadioBox.GetSelection() == 1:
                #si se selecciona OD para usar
                self.NPSChoice.Enable(False)
                self.ODChoice.Enable(True)
#                self.IDChoice.Enable(False)
#            if ODselection != -1:
#                self.contExpValues["D_2"] = ODselection
#                self.contExpValues["D_2_type"] = "OD"

            elif self.middlePanelRadioBox.GetSelection() == 2:
                #si se selecciona ID para usar
                self.NPSChoice.Enable(False)
                self.ODChoice.Enable(False)
#                self.IDChoice.Enable(True)
#            if IDselection != -1:
#                self.contExpValues["D_2"] = IDselection
#                self.contExpValues["D_2_type"] = "ID"

        else:
            #si no fue especificada la cedula se esta trabajando con el diametro minimo
            pass
#    def onAny(self, evt):
#        schedule = self.lastSegmentValues[0][1]

#        if schedule != "None":
#            #si la cedula fue especificada en el segmento anterior
#
#            if self.radioBox.GetSelection() == 0:
#                #si se selecciona expansion
##                self.contExpValues["type"] = "sudden_expansion"
##                self.analizeSelection(self)
#                pass
#
#            elif self.radioBox.GetSelection() == 1:
#                #si se selecciona una contraccion
##                self.contExpValues["type"] = "sudden_contraction"
##                self.analizeSelection(self)
#                pass
#        else:
#            #si no fue especificada la cedula se esta trabajando con el diametro minimo
#            if self.radioBox.GetSelection() == 0:
#                #si se selecciona expansion
##                self.contExpValues["type"] = "sudden_expansion"
#                "foo"
#
#            elif self.radioBox.GetSelection() == 1:
#                #si se selecciona una contraccion
##                self.contExpValues["type"] = "sudden_contraction"
#                "baar"

    def setMiddlePanel(self, parent):

        sizer = wx.GridBagSizer(hgap=0, vgap=5)

        self.textLabel = wx.StaticText(parent,
                                       self.listOfIds[16],
                                       self.contExpDialogGeneralText()["e12"],
                                       size=(150, 30))
        sizer.Add(self.textLabel, pos=(0, 0), span=(1, 2), flag=wx.EXPAND)

        radioBoxChoices = ["NPS", "OD"]
        self.middlePanelRadioBox = wx.RadioBox(
            parent,
            self.listOfIds[13],
            self.contExpDialogGeneralText()["e13"],
            size=(100, 40),
            choices=radioBoxChoices,
            majorDimension=3,
            style=wx.RA_SPECIFY_COLS)
        self.middlePanelRadioBox.Bind(wx.EVT_RADIOBOX, self.analizeSelection)
        sizer.Add(self.middlePanelRadioBox,
                  pos=(0, 2),
                  span=(1, 2),
                  flag=wx.EXPAND)

        self.NPSLabel = wx.StaticText(parent,
                                      self.listOfIds[14],
                                      "NPS",
                                      size=(150, 21))
        sizer.Add(self.NPSLabel, pos=(1, 0), span=(1, 2), flag=wx.EXPAND)
        self.NPSChoice = wx.Choice(
            parent,
            self.listOfIds[15],
            choices=self.contExpDialogGeneralText()["e14"],
            size=(145, 21))
        self.NPSChoice.Bind(wx.EVT_CHOICE, self.analizeSelection)
        sizer.Add(self.NPSChoice, pos=(1, 2), span=(1, 2), flag=wx.EXPAND)

        self.ODLabel = wx.StaticText(parent,
                                     self.listOfIds[4],
                                     "OD",
                                     size=(150, 21))
        sizer.Add(self.ODLabel, pos=(2, 0), span=(1, 2), flag=wx.EXPAND)
        self.ODChoice = wx.Choice(
            parent,
            self.listOfIds[5],
            choices=self.contExpDialogGeneralText()["e14"],
            size=(145, 21))
        self.ODChoice.Bind(wx.EVT_CHOICE, self.analizeSelection)
        sizer.Add(self.ODChoice, pos=(2, 2), span=(1, 2), flag=wx.EXPAND)

        #        self.IDLabel = wx.StaticText(parent, self.listOfIds[6], "ID", size=(150, 21))
        #        sizer.Add(self.IDLabel, pos=(3,0), span=(1,2), flag=wx.EXPAND)
        #        self.IDChoice = wx.Choice(parent, self.listOfIds[7], choices=["on", "off"], size=(145, 21))
        #        self.IDChoice.Bind(wx.EVT_CHOICE, self.analizeSelection)
        #        sizer.Add(self.IDChoice, pos=(3,2), span=(1,2), flag=wx.EXPAND)

        self.minimumDiamLabel = wx.StaticText(
            parent,
            self.listOfIds[10],
            self.contExpDialogGeneralText()["e15"],
            size=(75, 21))
        sizer.Add(self.minimumDiamLabel, pos=(3, 0))
        self.minimumDiamValue = NumCtrl(parent,
                                        self.listOfIds[11],
                                        integerWidth=7,
                                        fractionWidth=0,
                                        size=(145, 21),
                                        autoSize=False)
        sizer.Add(self.minimumDiamValue,
                  pos=(3, 1),
                  span=(1, 2),
                  flag=wx.EXPAND)
        self.minimumDiamUnit = wx.Choice(
            parent,
            self.listOfIds[12],
            choices=self.contExpDialogGeneralText()["e14"],
            size=(75, 21))
        self.minimumDiamUnit.Bind(wx.EVT_CHOICE, self.analizeSelection)
        sizer.Add(self.minimumDiamUnit, pos=(3, 3))

        sizer.AddGrowableCol(0)
        sizer.AddGrowableCol(1)
        sizer.AddGrowableCol(2)
        sizer.AddGrowableCol(3)
        #        sizer.AddGrowableCol(4)
        parent.SetSizer(sizer)
        parent.Fit()

    def setDisabledWidget(self):
        connection = sqlite3.connect("custom.pype")
        cursor = connection.cursor()
        command = """SELECT rowid, schedule, NPS, OD, ID, minimum_diameter_metric FROM segments ORDER BY rowid DESC LIMIT 1"""
        cursor.execute(command)
        data = cursor.fetchall()
        schedule = data[0][1]
        command = """SELECT pipe_type FROM system WHERE rowid=1"""
        cursor.execute(command)
        pipeType = cursor.fetchall()[0][0]
        data.append(pipeType)
        connection.close()
        #        print data

        if schedule != "None":
            #si la cedula fue especificada en el segmento anterior
            self.NPSLabel.Enable(True)
            self.NPSChoice.Enable(True)
            self.ODLabel.Enable(False)
            self.ODChoice.Enable(False)
            #            self.IDLabel.Enable(False)
            #            self.IDChoice.Enable(False)
            self.minimumDiamLabel.Enable(False)
            self.minimumDiamValue.Enable(False)
            self.minimumDiamUnit.Enable(False)
            pipe_type = self.typeOfPipe(pipeType)
            NPS, OD = self.dataBaseConsult(schedule, pipe_type)

            self.NPSChoice.SetItems(NPS)
            self.ODChoice.SetItems(OD)


#            self.IDChoice.SetItems(ID)

        else:
            #si no fue especificada la cedula se esta trabajando con el diametro minimo
            self.NPSLabel.Enable(False)
            self.NPSChoice.Enable(False)
            self.ODLabel.Enable(False)
            self.ODChoice.Enable(False)
            #            self.IDLabel.Enable(False)
            #            self.IDChoice.Enable(False)
            self.minimumDiamLabel.Enable(True)
            self.minimumDiamValue.Enable(True)
            self.minimumDiamUnit.Enable(True)

        return data

    def contExpDialogGeneralText(self):
        text = Language()
        return text.contExpDialogGeneralText()
示例#3
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)
示例#4
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)
示例#5
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 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)
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()
示例#8
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()
示例#9
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()
示例#10
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]
示例#11
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()
        
示例#12
0
class LCVRCalibrationGUI(wx.Frame):
    def __init__(self, parent=None, title="LCVR Calibration"):
        super(LCVRCalibrationGUI, self).__init__(
            parent,
            title=title,
            size=(815, 520),
            style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)
        self._max = "Not yet tested."
        self._min = "Not yet tested."
        self._pm_init = False
        self._lcvr_init = False
        self._data_set = []
        self._filename = "LCVR Calibration.csv"
        self._kill_calibration = True
        self._saved_data = True

        # make panel for frame
        overall_panel = wx.Panel(self)
        overall_sizer = wx.GridBagSizer()

        # make panel for top
        top_panel = wx.Panel(overall_panel)
        top_sizer = wx.BoxSizer(wx.VERTICAL)

        # make panel for main stuff
        main_panel = wx.Panel(top_panel)
        main_sizer = wx.FlexGridSizer(11, 2, 0, 0)

        newport_label = wx.StaticText(main_panel,
                                      label="Newport GPIB Port: ",
                                      size=(140, 20),
                                      style=wx.ALIGN_RIGHT)
        self._newport_val = NumCtrl(main_panel,
                                    size=(140, 20),
                                    style=wx.TE_PROCESS_ENTER)
        self._newport_val.SetAllowNegative(False)
        self._newport_val.SetBounds(1, 99)
        self._newport_val.SetFractionWidth(0)
        self._newport_val.SetIntegerWidth(2)
        self._newport_val.SetValue(4)
        self._newport_val.SetLimitOnFieldChange(True)

        meadowlark_label = wx.StaticText(main_panel,
                                         label="Meadowlark COM Port: ",
                                         size=(140, 20),
                                         style=wx.ALIGN_RIGHT)
        self._meadowlark_val = NumCtrl(main_panel,
                                       size=(140, 20),
                                       style=wx.TE_PROCESS_ENTER)
        self._meadowlark_val.SetAllowNegative(False)
        self._meadowlark_val.SetBounds(1, 99)
        self._meadowlark_val.SetFractionWidth(0)
        self._meadowlark_val.SetIntegerWidth(2)
        self._meadowlark_val.SetValue(6)
        self._meadowlark_val.SetLimitOnFieldChange(True)

        meadowlark_chan = wx.StaticText(main_panel,
                                        label="Meadowlark Channel: ",
                                        size=(140, 20),
                                        style=wx.ALIGN_RIGHT)
        self._meadowlark_ch = wx.Choice(main_panel,
                                        size=(140, 20),
                                        choices=["1", "2", "3", "4"])

        laser_label = wx.StaticText(main_panel,
                                    label="Laser Wavelength (nm): ",
                                    size=(140, 20),
                                    style=wx.ALIGN_RIGHT)
        self._laser_lambda = NumCtrl(main_panel,
                                     size=(140, 20),
                                     style=wx.TE_PROCESS_ENTER)
        self._laser_lambda.SetAllowNegative(False)
        self._laser_lambda.SetBounds(400, 1100)
        self._laser_lambda.SetFractionWidth(0)
        self._laser_lambda.SetIntegerWidth(4)
        self._laser_lambda.SetValue(780)
        self._laser_lambda.SetLimitOnFieldChange(True)

        start_volt_label = wx.StaticText(main_panel,
                                         label="Start Voltage (V):",
                                         size=(140, 20),
                                         style=wx.ALIGN_RIGHT)
        self._start_volt_val = NumCtrl(main_panel,
                                       size=(140, 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(main_panel,
                                       label="End Voltage (V):",
                                       size=(140, 20),
                                       style=wx.ALIGN_RIGHT)
        self._end_volt_val = NumCtrl(main_panel,
                                     size=(150, 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(main_panel,
                                        label="Absolute Step Voltage (V):",
                                        size=(140, 20),
                                        style=wx.ALIGN_RIGHT)
        self._step_volt_val = NumCtrl(main_panel,
                                      size=(140, 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._run_button = wx.Button(main_panel,
                                     label="Run Calibration",
                                     size=(140, 20))
        self._run_button.SetForegroundColour(wx.Colour("GREEN"))

        self._stop_button = wx.Button(main_panel,
                                      label="Stop Calibration",
                                      size=(140, 20))
        self._stop_button.SetForegroundColour(wx.Colour("RED"))
        self._stop_button.Disable()

        max_label = wx.StaticText(main_panel,
                                  label="Max Power Setting (V): ",
                                  size=(140, 20),
                                  style=wx.ALIGN_RIGHT)
        self._max_value = wx.StaticText(main_panel,
                                        label=self._max,
                                        size=(140, 20),
                                        style=wx.ALIGN_LEFT)
        min_label = wx.StaticText(main_panel,
                                  label="Min Power Setting (V): ",
                                  size=(140, 20),
                                  style=wx.ALIGN_RIGHT)
        self._min_value = wx.StaticText(main_panel,
                                        label=self._min,
                                        size=(140, 20),
                                        style=wx.ALIGN_LEFT)

        self._newport_val.Bind(wx.EVT_KILL_FOCUS, self._newport_entry)
        self._meadowlark_val.Bind(wx.EVT_KILL_FOCUS, self._meadowlark_entry)
        self._laser_lambda.Bind(wx.EVT_KILL_FOCUS, self._lambda_entry)

        self._save_button = wx.Button(main_panel,
                                      label="Save Values",
                                      size=(140, 20))
        self._load_button = wx.Button(main_panel,
                                      label="Load Values",
                                      size=(140, 20))

        self._save_button.Bind(wx.EVT_BUTTON, self._save_press)
        self._load_button.Bind(wx.EVT_BUTTON, self._load_press)
        self._run_button.Bind(wx.EVT_BUTTON, self._run_press)
        self._stop_button.Bind(wx.EVT_BUTTON, self._stop_press)

        main_sizer.AddMany([
            newport_label, self._newport_val, meadowlark_label,
            self._meadowlark_val, meadowlark_chan, self._meadowlark_ch,
            laser_label, self._laser_lambda, start_volt_label,
            self._start_volt_val, end_volt_label, self._end_volt_val,
            step_volt_label, self._step_volt_val, self._run_button,
            self._stop_button, max_label, self._max_value, min_label,
            self._min_value, self._save_button, self._load_button
        ])
        main_panel.SetSizer(main_sizer)
        self.Bind(wx.EVT_CLOSE, self._on_close)

        self._output_display = wx.TextCtrl(top_panel,
                                           size=(280, 180),
                                           style=wx.TE_MULTILINE
                                           | wx.TE_READONLY)

        top_sizer.Add(main_panel, 0, wx.ALL, 10)
        top_sizer.Add(self._output_display, 0, wx.ALL, 10)
        top_panel.SetSizer(top_sizer)

        plt_panel = wx.Panel(overall_panel, size=(500, 500))
        plt_sizer = wx.BoxSizer()
        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_canvas = FigureCanvasWxAgg(plt_panel, -1,
                                                  self._live_plt)
        plot_title = "Laser Power (mW) vs. LCVR Voltage (V)"
        self._live_plt_axes.set_title(plot_title)
        self._live_plt_axes.set_ylabel("Power (mW)")
        self._live_plt_axes.set_xlabel("Voltage (V)")
        self._live_plt_axes.grid(True)
        plt_sizer.Add(self._live_plt_canvas)
        plt_panel.SetSizer(plt_sizer)

        copyright_str = "\u00a9 2016 QuIN Lab "
        copyright_str += "Developed by Hayden Jones"
        copyright = wx.StaticText(overall_panel,
                                  label=copyright_str,
                                  style=wx.ALIGN_RIGHT)

        overall_sizer.Add(top_panel, (0, 0))
        overall_sizer.Add(plt_panel, (0, 1), (2, 1))
        overall_sizer.Add(copyright, (1, 0))
        overall_panel.SetSizer(overall_sizer)
        overall_panel.Layout()
        self.Show()

    def _on_close(self, evt):
        if self._lcvr_init is True:
            self._lcvr.close()
        if self._pm_init is True:
            self._pm.close()
        if self._saved_data is False:
            if self._dataloss_warn() == wx.ID_NO:
                return
        evt.Skip()

    def disable_ui(self):
        self._newport_val.Disable()
        self._meadowlark_val.Disable()
        self._meadowlark_ch.Disable()
        self._laser_lambda.Disable()
        self._run_button.Disable()
        self._stop_button.Enable()
        self._save_button.Disable()
        self._load_button.Disable()

    def enable_ui(self):
        self._newport_val.Enable()
        self._meadowlark_val.Enable()
        self._meadowlark_ch.Enable()
        self._laser_lambda.Enable()
        self._run_button.Enable()
        self._stop_button.Disable()
        self._save_button.Enable()
        self._load_button.Enable()

    def get_pm_addr(self):
        return self._newport_val.GetValue()

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

    def get_lcvr_ch(self):
        channels = {0: 1, 1: 2, 2: 3, 3: 4}
        return channels[self._meadowlark_ch.GetCurrentSelection()]

    def get_wavelength(self):
        return self._laser_lambda.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_max(self):
        return self._max

    def get_min(self):
        return self._min

    def set_max(self):
        if self._max == self._min:
            return
        self._max_value.SetLabel(str(self._max))

    def set_min(self):
        if self._min == self._max:
            return
        self._min_value.SetLabel(str(self._min))

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

    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 _overwrite_warn(self):
        warning_message = "Do you want to overwrite previous calibration?"
        warning = wx.GenericMessageDialog(None, warning_message, "Warning!",
                                          wx.YES_NO, wx.DefaultPosition)
        result = warning.ShowModal()
        warning.Destroy()
        return result

    def _dataloss_warn(self):
        warning_message = "Do you want to exit without saving data?"
        warning = wx.GenericMessageDialog(None, warning_message, "Warning!",
                                          wx.YES_NO, wx.DefaultPosition)
        result = warning.ShowModal()
        warning.Destroy()
        return result

    def _newport_entry(self, evt):
        # change line 308 to turn off attenuator
        if self._pm_init is True:
            return
        try:
            self._pm = Newport1830C(self.get_pm_addr())
        except:
            self._invalid_pm_warn()
            return
        self._pm_init = True
        self._pm.attenuator_on()
        evt.Skip()

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

    def _lambda_entry(self, evt):
        if self._laser_lambda.IsInBounds() is False:
            return
        if self._pm_init is True:
            self._pm.set_wavelength(self.get_wavelength())
        evt.Skip()

    def _run_press(self, evt):
        if self._data_set != []:
            if self._overwrite_warn() == wx.ID_NO:
                return
        self._meadowlark_entry(wx.EVT_BUTTON)
        self._newport_entry(wx.EVT_BUTTON)
        if self._pm_init is False:
            return
        if self._lcvr_init is False:
            return
        self.disable_ui()
        self._kill_calibration = False
        self._saved_data = False
        self._data_set = []
        self._output_display.Clear()
        _thread.start_new_thread(self._calibration, (self.get_lcvr_ch(), ))

    def _stop_press(self, evt):
        self.enable_ui()
        self._kill_calibration = True

    def _save_press(self, evt):
        file_type = "Comma Separated Values file (*.csv)|*.csv"
        save_dialog = wx.FileDialog(self, "Save calibration data as...", "",
                                    self._filename, file_type, wx.FD_SAVE)
        if save_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._filename = save_dialog.GetPath()
        save_dialog.Destroy()
        with open(self._filename, 'w') as f:
            writer = csv.writer(f, lineterminator='\n')
            writer.writerow(["Date:", strftime("_%Y_%m_%d_%H-%M-%S")])
            writer.writerow(["Wavelength:", self.get_wavelength()])
            writer.writerows(self._data_set)
        self._saved_data = True

    def _load_press(self, evt):
        file_type = "Comma Separated Values file (*.csv)|*.csv"
        open_dialog = wx.FileDialog(self, "Open calibration data...", "",
                                    self._filename, file_type, wx.FD_OPEN)
        if open_dialog.ShowModal() == wx.ID_CANCEL:
            return
        self._filename = open_dialog.GetPath()
        open_dialog.Destroy()
        with open(self._filename, 'r') as f:
            reader = csv.reader(f)
            reader = list(reader)
            self._laser_lambda.SetValue(int(reader[1][1]))
            self._data_set = reader[2:]
        self._data_set = [[float(x[0]), float(x[1])] for x in self._data_set]
        self._start_volt_val.SetValue(self._data_set[0][0])
        self._end_volt_val.SetValue(self._data_set[-1][0])
        self._step_volt_val.SetValue(
            abs(self._data_set[1][0] - self._data_set[0][0]))
        for item in self._data_set:
            v = round(item[0], 3)
            p = round(item[1], 6)
            data_string = "Voltage (V):{0} Power (W):{1}\n".format(v, p)
            self._output_display.AppendText(data_string)
        self._analyze()
        self.set_max()
        self.set_min()
        self._update_plt(self._data_set)

    def _clear_plt(self):
        self._live_plt_axes.clear()
        plot_title = "Laser Power (mW) vs. LCVR Voltage (V)"
        self._live_plt_axes.set_title(plot_title)
        self._live_plt_axes.set_ylabel("Power (mW)")
        self._live_plt_axes.set_xlabel("Voltage (V)")
        self._live_plt_axes.grid(True)

    def _update_plt(self, data):
        self._clear_plt()
        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() - y_data.min() / 20
        max_power = y_data.max() + y_data.max() / 100
        start_v = self.get_start_volt()
        end_v = self.get_end_volt()
        if start_v > end_v:
            temp = end_v
            end_v = start_v
            start_v = temp
        self._live_plt_axes.axis([start_v, end_v, min_power, max_power])
        self._live_plt_axes.plot(x_data, y_data, 'rx')
        self._live_plt_canvas.draw()

    def _calibration(self, channel):
        start_v = self.get_start_volt()
        end_v = self.get_end_volt()
        if start_v > end_v:
            step = -self.get_step_volt()
        else:
            step = self.get_step_volt()
        for i in range(int(start_v * 1000), int((end_v + 0.01) * 1000),
                       int(step * 1000)):
            if self._kill_calibration is True:
                break
            v = i / 1000
            self._lcvr.set_voltage(channel, v)
            sleep(0.1)
            p = self._pm.get_power()
            self._data_set.append([v, p])
            v = round(v, 3)
            p = round(p, 6)
            data_string = "Voltage (V):{0} Power (W):{1}\n".format(v, p)
            wx.CallAfter(self._output_display.AppendText, data_string)
            wx.CallAfter(self._update_plt, self._data_set)
        wx.CallAfter(self._stop_press, wx.EVT_BUTTON)
        wx.CallAfter(self._analyze)

    def _analyze(self):
        # Uses median absolute deviation (MAD) to remove outliers
        pow_arr = np.array([x[1] for x in self._data_set])
        d = np.abs(pow_arr - np.median(pow_arr))
        mdev = np.median(d)
        s = d / mdev if mdev else 0
        pow_arr = list(pow_arr[s < 20])
        min_index = pow_arr.index(min(pow_arr))
        max_index = pow_arr.index(max(pow_arr))
        self._min = self._data_set[min_index][0]
        self._max = self._data_set[max_index][0]
        self.set_max()
        self.set_min()
示例#13
0
class concam ( wx.Frame ):
	
	def __init__( self, parent ):
		wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Consulta de Cotrantos", pos = wx.DefaultPosition, size = wx.Size( 580,548 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.NO_BORDER|wx.TAB_TRAVERSAL )
		
		self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
		self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOWFRAME ) )
		
		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( 181, 249, 162 ) )
		
		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 )
		
		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 )
		
		
		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 )
		
		self.m_textCtrl32 = wx.TextCtrl( self.m_panel15, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, (250, 23), 0 )
		self.m_textCtrl32.Enable( False )
		
		gSizer11.Add( self.m_textCtrl32, 0, wx.ALL, 5 )
		
		
		gSizer11.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
		
		
		gSizer11.AddSpacer( ( 0, 0), 1, wx.EXPAND, 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 )
		
		self.m_textCtrl33 = wx.TextCtrl( self.m_panel15, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, (250, 23), 0 )
		gSizer11.Add( self.m_textCtrl33, 0, wx.ALL, 5 )
		self.m_textCtrl33.Enable(False)
		
		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_textCtrl26 = wx.TextCtrl( self.m_panel15, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
		gSizer11.Add( self.m_textCtrl26, 0, wx.ALL, 5 )
		self.m_textCtrl26.Enable(False)
		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_textCtrl27 = wx.TextCtrl( self.m_panel15, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
		gSizer11.Add( self.m_textCtrl27, 0, wx.ALL, 5 )
		self.m_textCtrl27.Enable(False)
		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.NumCtrl3 = NumCtrl(self.m_panel15,-1,style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB)
		self.NumCtrl3.Enable( False )
		self.NumCtrl3.SetParameters( integerWidth = 9) 
		self.NumCtrl3.SetParameters( fractionWidth = 2) 
		self.NumCtrl3.SetGroupChar(';')
		self.NumCtrl3.SetDecimalChar(',') 
		self.NumCtrl3.SetGroupChar('.') 
		self.NumCtrl3.SetMin(0) 
		self.NumCtrl3.SetMax(-1) 
		self.NumCtrl3.SetAllowNegative(False) 
		self.NumCtrl3.SetSelectOnEntry(False) 
		self.NumCtrl3.Enable( False )
		
		gSizer11.Add( self.NumCtrl3, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_LEFT|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( 181, 249, 162 ) )
		
		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 )
		a=0
		m_comboBox7Choices = []
		while a < len(rdes1):
			m_comboBox7Choices.append(rdes1[a][0])
			a = a + 1
		self.m_comboBox7 = wx.ComboBox( self.m_panel16, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 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( 184, 249, 162 ) )
		
		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( 191, 255, 162 ) )
		
		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( 181, 255, 162 ) )
		
		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( 181, 255, 162 ) )
		
		bSizer18 = wx.BoxSizer( wx.HORIZONTAL )
		
		self.m_button53 = wx.Button( self.m_panel20, wx.ID_ANY, u"EDITAR CONTRATO", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_button53.Enable( False )
		
		bSizer18.Add( self.m_button53, 0, wx.ALL, 5 )
		
		self.m_button54 = wx.Button( self.m_panel20, wx.ID_ANY, u"ELIMINAR CONTRATO", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_button54.Enable( False )
		
		bSizer18.Add( self.m_button54, 0, wx.ALL, 5 )
		
		self.m_button26 = wx.Button( self.m_panel20, wx.ID_ANY, u"GUARDAR", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_button26.Enable( False )
		self.m_button26.Hide()
		
		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 )
		self.m_button27.Hide()
		
		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_button53.Bind( wx.EVT_BUTTON, self.edcontrato )
		self.m_button54.Bind( wx.EVT_BUTTON, self.eliminarcontrato )
	
	def __del__( self ):
		pass
	
	
	# Virtual event handlers, overide them in your derived class
	def buscar( self, event ):
		cont1.numero=str(self.NumCtrlc.GetValue())

		a=cont1.consultar(con1)
		if len(a)==0:
			wx.MessageBox('Este contrato no existe', 'Info', wx.OK | wx.ICON_INFORMATION)
		else:	
			self.NumCtrlc.Enable(False)
			self.m_button21.Enable(False)
			self.m_button53.Enable(True)
			self.m_button54.Enable(True)
			for i in range (len(a)):
				descuento=a[i][1]
				monto=str(a[i][10])
				imprimep=a[i][7]
				imprimei=a[i][8] 
				imprimeinq=a[i][9] 
				self.m_listBox1.Append(descuento  + " ,"+monto + "," + imprimep + ","+ imprimei + ","+ imprimeinq )

			self.m_textCtrl26.Enable(True)
			self.m_textCtrl27.Enable(True)
			self.NumCtrl3.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_button24.Enable(True)
			self.m_listBox1.Enable(True)
			self.m_button25.Enable(True)
			self.m_textCtrl32.SetValue(a[0][2])
			self.m_textCtrl20.SetValue(a[0][6])
			self.m_textCtrl33.SetValue(a[0][3])
			self.m_textCtrl26.SetValue(a[0][4])
			self.m_textCtrl27.SetValue(a[0][5])
			self.NumCtrl3.SetValue(a[0][11])
		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 edcontrato( self, event ):
		cont1.direccion=self.m_textCtrl32.GetValue()
		cont1.inquilinos=self.m_textCtrl33.GetValue()
		cont1.fechain=self.m_textCtrl26.GetValue()
		cont1.fechavto=self.m_textCtrl27.GetValue()
		cont1.propietario=self.m_textCtrl20.GetValue()
		cont1.comision=self.NumCtrl3.GetValue()
		cont1.eliminar(con1)
		for i in range(self.m_listBox1.GetCount()):
			a = self.m_listBox1.GetString(i)
			lista=a.split(',')
			descripcion=lista[0]
			des1.descuento=lista[0]
			rd=des1.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)]
	
			cont1.agregar(con1,descripcion,monto,impripro,imprinmo,imprinq,rd[1])
		self.Destroy()
		event.Skip()
	
	def eliminarcontrato( self, event ):
		Casa1.contrato='0'
		Casa1.direccion=self.m_textCtrl32.GetValue()
		Casa1.desalquilar(con1)
		cont1.eliminar(con1)
		self.Destroy()
		event.Skip()