当前位置: 首页>>代码示例>>Python>>正文


Python NavigationToolbar2QTAgg.actions方法代码示例

本文整理汇总了Python中matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg.actions方法的典型用法代码示例。如果您正苦于以下问题:Python NavigationToolbar2QTAgg.actions方法的具体用法?Python NavigationToolbar2QTAgg.actions怎么用?Python NavigationToolbar2QTAgg.actions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg的用法示例。


在下文中一共展示了NavigationToolbar2QTAgg.actions方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: NeuralNetworkWidget

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class NeuralNetworkWidget(QWidget, Ui_Widget):
  def __init__(self, plugin, parent=None):
    QWidget.__init__(self, parent)
    self.setupUi(self)

    self.plugin = plugin
    self.inputs = plugin.inputs
    self.settings = QSettings("NextGIS", "MOLUSCE")

    # init plot for learning curve
    self.figure = Figure()
    self.axes = self.figure.add_subplot(111)
    self.figure.suptitle(self.tr("Neural Network learning curve"))
    self.canvas = FigureCanvas(self.figure)
    self.mpltoolbar = NavigationToolbar(self.canvas, None)
    lstActions = self.mpltoolbar.actions()
    self.mpltoolbar.removeAction(lstActions[7])
    self.layoutPlot.addWidget(self.canvas)
    self.layoutPlot.addWidget(self.mpltoolbar)

    # and configure matplotlib params
    rcParams['font.serif'] = "Verdana, Arial, Liberation Serif"
    rcParams['font.sans-serif'] = "Tahoma, Arial, Liberation Sans"
    rcParams['font.cursive'] = "Courier New, Arial, Liberation Sans"
    rcParams['font.fantasy'] = "Comic Sans MS, Arial, Liberation Sans"
    rcParams['font.monospace'] = "Courier New, Liberation Mono"

    self.btnTrainNetwork.clicked.connect(self.trainNetwork)

    self.manageGui()

  def manageGui(self):
    self.spnNeigbourhood.setValue(int(self.settings.value("ui/ANN/neighborhood", 1)))
    self.spnLearnRate.setValue(float(self.settings.value("ui/ANN/learningRate", 0.1)))
    self.spnMaxIterations.setValue(int(self.settings.value("ui/ANN/maxIterations", 1000)))
    self.leTopology.setText(self.settings.value("ui/ANN/topology", "10"))
    self.spnMomentum.setValue(float(self.settings.value("ui/ANN/momentum", 0.05)))
    self.btnStop.setEnabled(False)

  def trainNetwork(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    if self.leTopology.text() == "":
      QMessageBox.warning(self.plugin,
                          self.tr("Wrong network topology"),
                          self.tr("Network topology is undefined. Please define it and try again")
                         )
      return

    self.settings.setValue("ui/ANN/neighborhood", self.spnNeigbourhood.value())
    self.settings.setValue("ui/ANN/learningRate", self.spnLearnRate.value())
    self.settings.setValue("ui/ANN/maxIterations", self.spnMaxIterations.value())
    self.settings.setValue("ui/ANN/topology", self.leTopology.text())
    self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

    self.btnStop.setEnabled(True)
    self.btnTrainNetwork.setEnabled(False)

    self.plugin.logMessage(self.tr("Init ANN model"))

    model = MlpManager(ns=self.spnNeigbourhood.value())
    self.inputs["model"] = model
    model.createMlp(self.inputs["initial"],
                         self.inputs["factors"].values(),
                         self.inputs["changeMap"],
                         [int(n) for n in self.leTopology.text().split(" ")]
                        )

    self.plugin.logMessage(self.tr("Set training data"))
    model.setTrainingData(self.inputs["initial"],
                               self.inputs["factors"].values(),
                               self.inputs["changeMap"],
                               mode=self.inputs["samplingMode"],
                               samples=self.plugin.spnSamplesCount.value()
                              )

    model.setEpochs(self.spnMaxIterations.value())
    model.setValPercent(20)
    model.setLRate(self.spnLearnRate.value())
    model.setMomentum(self.spnMomentum.value())
    model.setContinueTrain()
#.........这里部分代码省略.........
开发者ID:stupidrabbit,项目名称:molusce,代码行数:103,代码来源:neuralnetworkwidget.py

示例2: ProfilefromPointsDialog

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class ProfilefromPointsDialog(QDialog, Ui_ProfilefromPoints):
    def __init__(self,iface):
        QDialog.__init__(self)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.iface = iface
        
        self.setupUi(self)
        
        # add matplotlib figure to dialog
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)
        
        self.mpltoolbar = NavigationToolbar(self.canvas, self.widgetPlot)
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction(lstActions[7])
        self.layoutPlot.addWidget(self.canvas)
        self.layoutPlot.addWidget(self.mpltoolbar)
        self.figure.patch.set_visible(False)
        
        # and configure matplotlib params
        rcParams["font.serif"] = "Verdana, Arial, Liberation Serif"
        rcParams["font.sans-serif"] = "Tahoma, Arial, Liberation Sans"
        rcParams["font.cursive"] = "Courier New, Arial, Liberation Sans"
        rcParams["font.fantasy"] = "Comic Sans MS, Arial, Liberation Sans"
        rcParams["font.monospace"] = "Courier New, Liberation Mono"

        self.values = None

        self.btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.uPointLayer.currentIndexChanged.connect(self.reloadFields)
        self.uLineLayer.currentIndexChanged.connect(self.checkSelectedLine)
        self.uCopytoClip.clicked.connect(self.copyClipboard)


        self.manageGui()

        
        
    def manageGui(self):
        print 'manageGui'
        self.uPointLayer.clear()
        self.uPointLayer.addItems(utils.getPointLayerNames())
        self.uLineLayer.clear()
        self.uLineLayer.addItems(utils.getLineLayerNames())

    
    def reloadFields(self):
        print 'reload fields'
        self.uZfield.clear()
        self.uOrderField.clear()

        self.axes.clear()

        point_layer = processing.getObject(str(self.uPointLayer.currentText()))
        if point_layer.selectedFeatureCount() != 0:
            self.uSelectedPoints.setCheckState(Qt.Checked)
        else:
            self.uSelectedPoints.setCheckState(Qt.Unchecked)
        
        self.uZfield.addItems(utils.getFieldNames(point_layer, [QVariant.Int, QVariant.Double]))
        self.uOrderField.addItems(utils.getFieldNames(point_layer, [QVariant.Int, QVariant.Double]))

    def checkSelectedLine(self):
        print 'check if line layer selected'
        line_layer = processing.getObject(str(self.uLineLayer.currentText()))
        if line_layer:
            if line_layer.selectedFeatureCount() != 0:
                self.uSelectedLine.setCheckState(Qt.Checked)
            else:
                self.uSelectedLine.setCheckState(Qt.Unchecked)

             
    def accept(self):
        print 'accepted'
        
        self.axes.clear()

        point_layer = processing.getObject(self.uPointLayer.currentText())
        line_layer = processing.getObject(self.uLineLayer.currentText())
        z_field=(self.uZfield.currentText())
        order_field=str(self.uOrderField.currentText())
        if str(self.uOrder.currentText())=='Ascending':
            sort = 'ASC'
        else:
            sort = 'DESC'
        buff=float(self.uBuffer.displayText())
        
        if self.utabWidget.currentIndex()==0:
            createLine=True        
        else:
            createLine=False
        

#.........这里部分代码省略.........
开发者ID:msweier,项目名称:QGIS-Profile-from-Points-Plugin,代码行数:103,代码来源:profilefrompointsdialog.py

示例3: ApplicationWindow

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]

#.........这里部分代码省略.........
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())
        self.propertiesDisplay.setColumnCount(2)
        self.propertiesDisplay.setHorizontalHeaderLabels(["Property","Value"])
        header=self.propertiesDisplay.horizontalHeader()
        header.setStretchLastSection(True)
        dock.setHidden(True)
        
        dock = QtGui.QDockWidget("Log", self)
        self.Log = QtGui.QTextEdit(dock)
        dock.setWidget(self.Log)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())
        self.Log.setReadOnly(True)
        
        dock = QtGui.QDockWidget("Fit Log", self)
        self.fitLog = QtGui.QTextEdit(dock)
        dock.setWidget(self.fitLog)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())
        self.fitLog.setReadOnly(True)
        
            
        
    def createImageDock(self):   
        dock = QtGui.QDockWidget("Image & Preview", self)
        self.imageWidget=QtGui.QMainWindow()
        self.imageWidget.setParent(dock)
        dock.setWidget(self.imageWidget)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())
        self.canvas = MPLCanvas(dock)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.imageWidget,coordinates=False)
        actlist= self.mpl_toolbar.actions()
        names=["Save","Customize","Subplots"]
        for action in actlist:
            if str(action.text()) in names:
                self.mpl_toolbar.removeAction(action)
        self.previewCheck=QtGui.QCheckBox("Preview")
        self.previewCheck.stateChanged.connect(self.previewCheckBoxChanged)
        self.mpl_toolbar.addWidget(self.previewCheck)
        self.mpl_toolbar.setMovable(False)
        self.imageWidget.addToolBar(self.mpl_toolbar)
        self.imageWidget.setCentralWidget(self.canvas)
        self.imageWidget.setMinimumSize(600,450)        
        
    def createWireOptions(self):
        dock = QtGui.QDockWidget("Wire Options", self)
        dock.setMaximumWidth(340)
        dock.setMinimumWidth(280)
        widget=QtGui.QWidget()
        dock.setWidget(widget)
        self.wireOptionsLayout=QtGui.QGridLayout()
        widget.setLayout(self.wireOptionsLayout)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
        self.viewMenu.addAction(dock.toggleViewAction())
        self.modeCombo=QtGui.QComboBox()
        self.wireOptionsLayout.addWidget(self.modeCombo,0,0)
        self.modeCombo.insertItem(0,"manual")
        self.modeCombo.insertItem(0,"select")
        self.modeCombo.insertItem(0,"auto")
        self.modeCombo.setEnabled(False)
        self.wireCombo=QtGui.QComboBox()
        self.wireOptionsLayout.addWidget(self.wireCombo,0,1)
        self.wireCombo.setEnabled(False)
        self.wireCombo.activated.connect(self.wireChanged)
开发者ID:drueffer,项目名称:apage_rom,代码行数:70,代码来源:GUIContact.py

示例4: createToolbar

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
def createToolbar(canvas, widget):
    toolbar = NavigationToolbar(canvas, widget)
    lstActions = toolbar.actions()
    toolbar.removeAction(lstActions[7])
    return toolbar
开发者ID:feuchner,项目名称:seismicsource-toolkit,代码行数:7,代码来源:plots.py

示例5: plotsqlitewindow

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class plotsqlitewindow(QtGui.QMainWindow, customplot_ui_class):
    def __init__(self, parent, msettings):#, parent as second arg?
        self.ms = msettings
        self.ms.loadSettings()
        QtGui.QDialog.__init__(self, parent)        
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setupUi( self )#due to initialisation of Ui_MainWindow instance
        self.initUI()
        self.LoadTablesFromDB()
        self.LastSelections()#fill comboboxes etc with last selected values
        #on close:
        #del self.axes.collections[:]#this should delete all plot objects related to axes and hence not intefere with following tsplots
        
    def initUI(self):
        self.table_ComboBox_1.clear()  
        self.table_ComboBox_2.clear()  
        self.table_ComboBox_3.clear()  
        for i in range (1,3):
            self.clearthings(1)
        # function partial due to problems with currentindexChanged and Combobox
        #self.connect(self.table_ComboBox_1, QtCore.SIGNAL("currentIndexChanged(int)"), partial(self.Table1Changed))#currentIndexChanged caused unnecessary signals when scrolling in combobox
        self.connect(self.table_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Table1Changed))  
        self.connect(self.Filter1_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_1Changed))
        #self.connect(self.Filter1_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.FilterChanged(1,1)))
        self.connect(self.Filter2_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_1Changed)) 
        self.connect(self.table_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Table2Changed)) 
        self.connect(self.Filter1_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_2Changed))
        self.connect(self.Filter2_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_2Changed)) 
        self.connect(self.table_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Table3Changed)) 
        self.connect(self.Filter1_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_3Changed))
        self.connect(self.Filter2_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_3Changed)) 
        self.PlotChart_QPushButton.clicked.connect(self.drawPlot)
        self.Redraw_pushButton.clicked.connect( self.refreshPlot )
        
        # Create a plot window with one single subplot
        self.custplotfigure = plt.figure() 
        self.axes = self.custplotfigure.add_subplot( 111 )
        self.canvas = FigureCanvas( self.custplotfigure )
        self.mpltoolbar = NavigationToolbar( self.canvas, self.widgetPlot )
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction( lstActions[ 7 ] )
        self.layoutplot.addWidget( self.canvas )
        self.layoutplot.addWidget( self.mpltoolbar )
        
        self.show()
        
    def drawPlot(self):
        QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))#show the user this may take a long time...

        self.axes.clear()
        My_format = [('date_time', datetime.datetime), ('values', float)] #Define (with help from function datetime) a good format for numpy array
        
        myconnection = utils.dbconnection()
        myconnection.connect2db()
        curs = myconnection.conn.cursor()

        i = 0
        nop=0# nop=number of plots
        self.p=[]
        self.plabels=[]
                
        if not (self.table_ComboBox_1.currentText() == '' or self.table_ComboBox_1.currentText()==' ') and not (self.xcol_ComboBox_1.currentText()== '' or self.xcol_ComboBox_1.currentText()==' ') and not (self.ycol_ComboBox_1.currentText()== '' or self.ycol_ComboBox_1.currentText()==' '): #if anything is to be plotted from tab 1
            self.ms.settingsdict['custplot_maxtstep'] = self.spnmaxtstep.value()   # if user selected a time step bigger than zero than thre may be discontinuous plots
            plottable1='y'
            filter1 = unicode(self.Filter1_ComboBox_1.currentText())
            filter1list = []
            filter2list = []
            filter1list = self.Filter1_QListWidget_1.selectedItems()
            filter2 = unicode(self.Filter2_ComboBox_1.currentText())
            filter2list= self.Filter2_QListWidget_1.selectedItems()
            nop += max(len(filter1list),1)*max(len(filter2list),1)
            #self.p= [None]*nop#list for plot objects
            self.p.extend([None]*nop)#list for plot objects
            self.plabels.extend([None]*nop)# List for plot labels
            while i < len(self.p):
                if not (filter1 == '' or filter1==' ' or filter1list==[]) and not (filter2== '' or filter2==' ' or filter2list==[]):
                    for item1 in filter1list:
                        for item2 in filter2list:
                            sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ where """ + filter1 + """='""" + unicode(item1.text())+ """' and """ + filter2 + """='""" + unicode(item2.text())+ """' order by """ + unicode(self.xcol_ComboBox_1.currentText())
                            self.plabels[i] = unicode(item1.text()) + """, """ + unicode(item2.text())
                            self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
                            i += 1
                elif not (filter1 == '' or filter1==' ' or filter1list==[]):
                    for item1 in filter1list:
                        sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ where """ + filter1 + """='""" + unicode(item1.text())+ """' order by """ + unicode(self.xcol_ComboBox_1.currentText())
                        self.plabels[i] = unicode(item1.text()) 
                        self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
                        i += 1
                elif not (filter2 == '' or filter2==' ' or filter2list==[]):
                    for item2 in filter2list:
                        sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ where """ + filter2 + """='""" + unicode(item2.text())+ """' order by """ + unicode(self.xcol_ComboBox_1.currentText())
                        self.plabels[i] = unicode(item2.text())
                        self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
                        i += 1            
                else:
                    sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ order by """ + unicode(self.xcol_ComboBox_1.currentText())
                    self.plabels[i] = unicode(self.ycol_ComboBox_1.currentText())+""", """+unicode(self.table_ComboBox_1.currentText())
                    self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
                    i += 1

#.........这里部分代码省略.........
开发者ID:qgisbrasil,项目名称:qgis-midvatten-plugin-pt_BR,代码行数:103,代码来源:customplot.py

示例6: calibrlogger

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class calibrlogger(PyQt4.QtGui.QMainWindow, Calibr_Ui_Dialog): # An instance of the class Calibr_Ui_Dialog is created same time as instance of calibrlogger is created

    def __init__(self, parent, settingsdict1={}, obsid=''):
        PyQt4.QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))#show the user this may take a long time...
        self.obsid = obsid
        self.log_pos = None
        self.y_pos = None
        self.meas_ts = None
        self.head_ts = None
        self.level_masl_ts = None
        self.loggerpos_masl_or_offset_state = 1

        self.settingsdict = settingsdict1
        PyQt4.QtGui.QDialog.__init__(self, parent)        
        self.setAttribute(PyQt4.QtCore.Qt.WA_DeleteOnClose)
        self.setupUi(self) # Required by Qt4 to initialize the UI
        self.setWindowTitle("Calibrate logger") # Set the title for the dialog
        self.connect(self.pushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.calibrateandplot)
        self.INFO.setText("Select the observation point with logger data to be calibrated.")
        self.log_calc_manual.setText("<a href=\"https://sites.google.com/site/midvattenpluginforqgis/usage/3-edit-data?pli=1#TOC-Calibrate-water-level-measurements-from-data-logger-\">Midvatten manual</a>")
      
        # Create a plot window with one single subplot
        self.calibrplotfigure = plt.figure() 
        self.axes = self.calibrplotfigure.add_subplot( 111 )
        self.canvas = FigureCanvas( self.calibrplotfigure )
        self.mpltoolbar = NavigationToolbar( self.canvas, self.widgetPlot )
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction( lstActions[ 7 ] )
        self.layoutplot.addWidget( self.canvas )
        self.layoutplot.addWidget( self.mpltoolbar )
        self.show()

        self.cid =[]
                
        self.connect(self.pushButtonFrom, PyQt4.QtCore.SIGNAL("clicked()"), self.set_from_date_from_x)
        self.connect(self.pushButtonTo, PyQt4.QtCore.SIGNAL("clicked()"), self.set_to_date_from_x)
        self.connect(self.pushButtonupdateplot, PyQt4.QtCore.SIGNAL("clicked()"), self.update_plot)
        self.connect(self.loggerpos_masl_or_offset, PyQt4.QtCore.SIGNAL("clicked()"), self.loggerpos_masl_or_offset_change)
        self.connect(self.pushButtonLpos, PyQt4.QtCore.SIGNAL("clicked()"), self.calibrate_from_plot_selection)
        self.connect(self.pushButtonCalcBestFit, PyQt4.QtCore.SIGNAL("clicked()"), self.calc_best_fit)

        self.connect(self.pushButton_delete_logger, PyQt4.QtCore.SIGNAL("clicked()"), lambda: self.delete_selected_range(u'w_levels_logger'))
        self.connect(self.pushButton_delete_meas, PyQt4.QtCore.SIGNAL("clicked()"), lambda: self.delete_selected_range(u'w_levels'))

        self.get_tolerance()

        # Populate combobox with obsid from table w_levels_logger
        self.load_obsid_from_db()

        PyQt4.QtGui.QApplication.restoreOverrideCursor()#now this long process is done and the cursor is back as normal

    def load_obsid_from_db(self):
        self.combobox_obsid.clear()
        myconnection = utils.dbconnection()
        if myconnection.connect2db() == True:
            # skapa en cursor
            curs = myconnection.conn.cursor()
            rs=curs.execute("""select distinct obsid from w_levels_logger order by obsid""")
            self.combobox_obsid.addItem('')
            for row in curs:
                self.combobox_obsid.addItem(row[0])
            rs.close()
            myconnection.closedb()

    def load_obsid_and_init(self):
        """ Checks the current obsid and reloads all ts.
        :return: obsid

        Info: Before, some time series was only reloaded when the obsid was changed, but this caused a problem if the
        data was changed in the background in for example spatialite gui. Now all time series are reloaded always.
        It's rather fast anyway.
        """
        obsid = unicode(self.combobox_obsid.currentText())
        if not obsid:
            utils.pop_up_info("ERROR: no obsid is chosen")

        meas_sql = r"""SELECT date_time, level_masl FROM w_levels WHERE obsid = '""" + obsid + """' ORDER BY date_time"""
        self.meas_ts = self.sql_into_recarray(meas_sql)
        head_sql = r"""SELECT date_time as 'date [datetime]', head_cm / 100 FROM w_levels_logger WHERE obsid = '""" + obsid + """' ORDER BY date_time"""
        self.head_ts = self.sql_into_recarray(head_sql)
        self.obsid = obsid
        level_masl_ts_sql = r"""SELECT date_time as 'date [datetime]', level_masl FROM w_levels_logger WHERE obsid = '""" + self.obsid + """' ORDER BY date_time"""
        self.level_masl_ts = self.sql_into_recarray(level_masl_ts_sql)
        return obsid

    def getlastcalibration(self):
        obsid = self.load_obsid_and_init()
        if not obsid=='':
            sql = """SELECT MAX(date_time), loggerpos FROM (SELECT date_time, (level_masl - (head_cm/100)) as loggerpos FROM w_levels_logger WHERE level_masl > -990 AND obsid = '"""
            sql += obsid
            sql += """')"""
            self.lastcalibr = utils.sql_load_fr_db(sql)[1]
            if self.lastcalibr[0][1] and self.lastcalibr[0][0]:
                text = """Last pos. for logger in """
                text += obsid
                text += """\nwas """ + str(self.lastcalibr[0][1]) + """ masl\nat """ +  str(self.lastcalibr[0][0])
            else:
                text = """There is no earlier known\nposition for the logger\nin """ + unicode(self.combobox_obsid.currentText())#self.obsid[0]
            self.INFO.setText(text)

#.........这里部分代码省略.........
开发者ID:mirouml,项目名称:qgis-midvatten-plugin,代码行数:103,代码来源:wlevels_calc_calibr.py

示例7: NeuralNetworkWidget

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class NeuralNetworkWidget(QWidget, Ui_Widget):
  def __init__(self, plugin, parent=None):
    QWidget.__init__(self, parent)
    self.setupUi(self)

    self.plugin = plugin
    self.inputs = plugin.inputs
    self.settings = QSettings("NextGIS", "MOLUSCE")

    # init plot for learning curve
    self.figure = Figure()
    self.axes = self.figure.add_subplot(111)
    self.axes.grid(True)
    self.figure.suptitle(self.tr("Neural Network learning curve"))
    self.canvas = FigureCanvas(self.figure)
    self.mpltoolbar = NavigationToolbar(self.canvas, None)
    lstActions = self.mpltoolbar.actions()
    self.mpltoolbar.removeAction(lstActions[7])
    self.layoutPlot.addWidget(self.canvas)
    self.layoutPlot.addWidget(self.mpltoolbar)

    # and configure matplotlib params
    rcParams['font.serif'] = "Verdana, Arial, Liberation Serif"
    rcParams['font.sans-serif'] = "Tahoma, Arial, Liberation Sans"
    rcParams['font.cursive'] = "Courier New, Arial, Liberation Sans"
    rcParams['font.fantasy'] = "Comic Sans MS, Arial, Liberation Sans"
    rcParams['font.monospace'] = "Courier New, Liberation Mono"

    self.chkCreateReport.toggled.connect(self.__toggleLineEdit)
    self.chkSaveSamples.toggled.connect(self.__toggleLineEdit)

    self.btnSelectReport.clicked.connect(self.__selectFile)
    self.btnSelectSamples.clicked.connect(self.__selectFile)

    self.btnTrainNetwork.clicked.connect(self.trainNetwork)

    self.manageGui()

  def manageGui(self):
    self.spnNeigbourhood.setValue(self.settings.value("ui/ANN/neighborhood", 1).toInt()[0])
    self.spnLearnRate.setValue(self.settings.value("ui/ANN/learningRate", 0.1).toFloat()[0])
    self.spnMaxIterations.setValue(self.settings.value("ui/ANN/maxIterations", 1000).toInt()[0])
    self.leTopology.setText(self.settings.value("ui/ANN/topology", "10").toString())
    self.spnMomentum.setValue(self.settings.value("ui/ANN/momentum", 0.05).toFloat()[0])

    self.chkCreateReport.setChecked(self.settings.value("ui/ANN/createReport", False).toBool())
    self.chkSaveSamples.setChecked(self.settings.value("ui/ANN/saveSamples", False).toBool())

  def trainNetwork(self):
    self.settings.setValue("ui/ANN/neighborhood", self.spnNeigbourhood.value())
    self.settings.setValue("ui/ANN/learningRate", self.spnLearnRate.value())
    self.settings.setValue("ui/ANN/maxIterations", self.spnMaxIterations.value())
    self.settings.setValue("ui/ANN/topology", self.leTopology.text())
    self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

    self.settings.setValue("ui/ANN/createReport", self.chkCreateReport.isChecked())
    self.settings.setValue("ui/ANN/saveSamples", self.chkSaveSamples.isChecked())

    self.model = MlpManager(ns=self.spnNeigbourhood.value())
    self.model.createMlp(self.inputs["initial"],
                         self.inputs["factors"].values(),
                         self.inputs["changeMap"],
                         [int(n) for n in self.leTopology.text().split(" ")]
                        )

    self.model.setTrainingData(self.inputs["initial"],
                               self.inputs["factors"].values(),
                               self.inputs["final"],
                               mode=self.inputs["samplingMode"],
                               samples=self.plugin.spnSamplesCount.value()
                              )

    self.model.setEpochs(self.spnMaxIterations.value())
    self.model.setValPercent(20)
    self.model.setLRate(self.spnLearnRate.value())
    self.model.setMomentum(self.spnMomentum.value())
    self.model.setContinueTrain()

    self.dataTrain = [1]
    self.dataVal = [1]
    self.plotTrain = self.axes.plot(self.dataTrain,
                                    linewidth=1,
                                    color="green",
                                   )[0]
    self.plotVal = self.axes.plot(self.dataVal,
                                  linewidth=1,
                                  color="red",
                                 )[0]

    self.model.moveToThread(self.plugin.workThread)

    self.plugin.workThread.started.connect(self.model.startTrain)
    self.model.updateGraph.connect(self.__updateGraph)
    self.model.updateDeltaRMS.connect(self.__updateRMS)
    self.model.updateMinValErr.connect(self.__updateValidationError)
    self.model.processFinished.connect(self.__trainFinished)
    self.model.processFinished.connect(self.plugin.workThread.quit)

    self.plugin.workThread.start()

#.........这里部分代码省略.........
开发者ID:asiaairsurvey,项目名称:molusce,代码行数:103,代码来源:neuralnetworkwidget.py

示例8: StatistDialog

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class StatistDialog(QDialog, Ui_StatistDialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        # add matplotlib figure to dialog
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)
        self.mpltoolbar = NavigationToolbar(self.canvas, self.widgetPlot)
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction(lstActions[7])
        self.layoutPlot.addWidget(self.canvas)
        self.layoutPlot.addWidget(self.mpltoolbar)

        # and configure matplotlib params
        rcParams["font.serif"] = "Verdana, Arial, Liberation Serif"
        rcParams["font.sans-serif"] = "Tahoma, Arial, Liberation Sans"
        rcParams["font.cursive"] = "Courier New, Arial, Liberation Sans"
        rcParams["font.fantasy"] = "Comic Sans MS, Arial, Liberation Sans"
        rcParams["font.monospace"] = "Courier New, Liberation Mono"

        self.values = None

        self.btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.cmbLayers.currentIndexChanged.connect(self.reloadFields)
        self.chkUseTextFields.stateChanged.connect(self.reloadFields)

        self.chkShowGrid.stateChanged.connect(self.refreshPlot)
        self.chkAsPlot.stateChanged.connect(self.refreshPlot)
        self.btnRefresh.clicked.connect(self.refreshPlot)

        self.manageGui()
        self.axes.set_title(self.tr("Frequency distribution"))

    def manageGui(self):
        self.cmbLayers.clear()
        self.cmbLayers.addItems(utils.getVectorLayerNames())

        self.btnRefresh.setEnabled(False)

    def reloadFields(self):
        self.cmbFields.clear()

        self.axes.clear()
        self.lstStatistics.clearContents()
        self.lstStatistics.setRowCount(0)

        self.spnMinX.setValue(0.0)
        self.spnMaxX.setValue(0.0)

        layer = utils.getVectorLayerByName(self.cmbLayers.currentText())

        if layer.selectedFeatureCount() != 0:
            self.chkUseSelected.setCheckState(Qt.Checked)
        else:
            self.chkUseSelected.setCheckState(Qt.Unchecked)

        if self.chkUseTextFields.checkState():
            self.cmbFields.addItems(utils.getFieldNames(layer, [QVariant.String]))
        else:
            self.cmbFields.addItems(utils.getFieldNames(layer, [QVariant.Int, QVariant.Double]))

    def accept(self):
        self.axes.clear()
        self.spnMinX.setValue(0.0)
        self.spnMaxX.setValue(0.0)
        self.lstStatistics.clearContents()
        self.lstStatistics.setRowCount(0)

        layer = utils.getVectorLayerByName(self.cmbLayers.currentText())

        if self.chkUseSelected.isChecked() and \
                layer.selectedFeatureCount() == 0:
            QMessageBox.warning(self,
                                self.tr('No selection'),
                                self.tr('There is no selection in input '
                                        'layer. Uncheck corresponding option '
                                        'or select some features before '
                                        'running analysis'))
            return

        self.workThread = statistthread.StatistThread(layer,
                                                      self.cmbFields.currentText(),
                                                      self.chkUseSelected.isChecked()
                                                     )
        self.workThread.rangeChanged.connect(self.setProgressRange)
        self.workThread.updateProgress.connect(self.updateProgress)
        self.workThread.processFinished.connect(self.processFinished)
        self.workThread.processInterrupted.connect(self.processInterrupted)

        self.btnOk.setEnabled(False)
        self.btnClose.setText(self.tr("Cancel"))
        self.buttonBox.rejected.disconnect(self.reject)
        self.btnClose.clicked.connect(self.stopProcessing)

        self.workThread.start()
#.........这里部分代码省略.........
开发者ID:ePublicHealth,项目名称:statist,代码行数:103,代码来源:statistdialog.py

示例9: MainWindow

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent = None):
        #QtGui.QMainWindow.__init__(self, parent)#the line below is for some reason preferred
        super(MainWindow, self).__init__(parent)#for some reason this is supposed to be better than line above
        #QDialog.__init__( self ) #if not working with an application with mainwindow
        #self.iface = iface

        #self=Ui_MainWindow()#new
                
        self.setupUi( self )#due to initialisation of Ui_MainWindow instance
        self.initUI()
        self.maxtstep = 0
        #self.database = ''
        #self.table1 = ''
        #self.database_pyqt4provider = QtSql.QSqlDatabase.addDatabase("QSQLITE","db1")
        
    def initUI(self):
        self.table_ComboBox_1.clear()  
        self.table_ComboBox_2.clear()  
        self.table_ComboBox_3.clear()  
        for i in range (1,3):
            self.clearthings(1)
        self.quit_Qaction.triggered.connect(self.quit_app)
        self.actionAbout.triggered.connect(self.about)          
        self.selectDB_QAction.triggered.connect(self.selectFile)          
        self.selectDB_QPushButton.clicked.connect(self.selectFile)          
        # whenever Time Series Table is changed, the column-combobox must be updated and TableCheck must be performed (function partial due to problems with currentindexChanged and Combobox)
        #self.connect(self.table_ComboBox_1, QtCore.SIGNAL("currentIndexChanged(int)"), partial(self.Table1Changed))#currentIndexChanged caused unnecessary signals when scrolling in combobox
        self.connect(self.table_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Table1Changed))  
        self.connect(self.Filter1_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_1Changed))
        self.connect(self.Filter2_ComboBox_1, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_1Changed)) 
        self.connect(self.table_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Table2Changed)) 
        self.connect(self.Filter1_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_2Changed))
        self.connect(self.Filter2_ComboBox_2, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_2Changed)) 
        self.connect(self.table_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Table3Changed)) 
        self.connect(self.Filter1_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Filter1_3Changed))
        self.connect(self.Filter2_ComboBox_3, QtCore.SIGNAL("activated(int)"), partial(self.Filter2_3Changed)) 
        self.PlotChart_QPushButton.clicked.connect(self.drawPlot)
        self.Redraw_pushButton.clicked.connect( self.refreshPlot )
        
        # Create a plot window with one single subplot
        self.figure = plt.figure() 
        self.axes = self.figure.add_subplot( 111 )
        self.canvas = FigureCanvas( self.figure )
        self.mpltoolbar = NavigationToolbar( self.canvas, self.widgetPlot )
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction( lstActions[ 7 ] )
        self.layoutplot.addWidget( self.canvas )
        self.layoutplot.addWidget( self.mpltoolbar )

        # Search for saved settings and load as preset values
        self.settings = QtCore.QSettings('foo','foo')
        self.readsettings()

        self.show()
        
    def quit_app(self):
        self.close()
        #QtSql.QSqlDatabase.removeDatabase("db1")
        QtCore.QCoreApplication.instance().quit()

    def drawPlot(self):
        QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))#show the user this may take a long time...

        self.storesettings()    #db, table, x-col and y-col are saved as default values when user clicks 'plot chart'
        self.axes.clear()
        My_format = [('date_time', datetime.datetime), ('values', float)] #Define (with help from function datetime) a good format for numpy array
        
        conn = sqlite.connect(unicode(self.selected_database_QLineEdit.text()),detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)#should be cross-platform
        # skapa en cursor
        curs = conn.cursor()

        i = 0
        nop=0# nop=number of plots
        self.p=[]
        self.plabels=[]
        if not (self.table1 == '' or self.table1==' ') and not (self.xcol1== '' or self.xcol1==' ') and not (self.ycol1== '' or self.ycol1==' '): #if anything is to be plotted from tab 1
            self.maxtstep = self.spnmaxtstep.value()   # if user selected a time step bigger than zero than thre may be discontinuous plots
            plottable1='y'
            filter1 = unicode(self.Filter1_ComboBox_1.currentText())
            filter1list = self.Filter1_QListWidget_1.selectedItems()
            filter2 = unicode(self.Filter2_ComboBox_1.currentText())
            filter2list= self.Filter2_QListWidget_1.selectedItems()
            nop += max(len(filter1list),1)*max(len(filter2list),1)
            #self.p= [None]*nop#list for plot objects
            self.p.extend([None]*nop)#list for plot objects
            self.plabels.extend([None]*nop)# List for plot labels
            while i < len(self.p):
                if not (filter1 == '' or filter1==' ') and not (filter2== '' or filter2==' '):
                    for item1 in filter1list:
                        for item2 in filter2list:
                            sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ where """ + filter1 + """='""" + unicode(item1.text())+ """' and """ + filter2 + """='""" + unicode(item2.text())+ """' order by """ + unicode(self.xcol_ComboBox_1.currentText())
                            self.plabels[i] = unicode(item1.text()) + """, """ + unicode(item2.text())
                            self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
                            i += 1
                elif not (filter1 == '' or filter1==' '):
                    for item1 in filter1list:
                        sql = r""" select """ + unicode(self.xcol_ComboBox_1.currentText()) + """, """ + unicode(self.ycol_ComboBox_1.currentText()) + """ from """ + unicode(self.table_ComboBox_1.currentText()) + """ where """ + filter1 + """='""" + unicode(item1.text())+ """' order by """ + unicode(self.xcol_ComboBox_1.currentText())
                        self.plabels[i] = unicode(item1.text()) 
                        self.createsingleplotobject(sql,i,My_format,curs,self.PlotType_comboBox_1.currentText())
#.........这里部分代码省略.........
开发者ID:sebastopol,项目名称:plotsqlite,代码行数:103,代码来源:plotsqlite.py

示例10: ProfileFromPointsDialog

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class ProfileFromPointsDialog(QtGui.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(ProfileFromPointsDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        
        # add matplotlib figure to dialog
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
#        self.figure.subplots_adjust(left=.1, bottom=0.15, right=.78, top=.9, wspace=None)
        self.mplCanvas = FigureCanvas(self.figure)
        
        self.mpltoolbar = NavigationToolbar(self.mplCanvas, self.toolbarWidget)
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction(lstActions[7])
        self.layoutPlot.addWidget(self.mplCanvas)
        self.layoutPlot.addWidget(self.mpltoolbar)
        self.figure.patch.set_visible(False)
        self.layoutPlot.minimumSize() 

        
        
        ##connections      
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.uPointLayer.currentIndexChanged.connect(self.reloadFields)
 
        self.uLineLayer.currentIndexChanged.connect(self.checkSelectedLine)
        self.uCopytoClip.clicked.connect(self.copyClipboard)


        self.manageGui()
        
    def manageGui(self):
        print 'manageGui'
        self.uPointLayer.clear()
        self.uPointLayer.addItems(utils.getPointLayerNames())
        self.uLineLayer.clear()
        self.uLineLayer.addItems(utils.getLineLayerNames())

    def reloadFields(self):
        print 'reload fields'
        self.uZfield.clear()
        self.uPointID.clear()
        self.uOrderField.clear()

        self.axes.clear()

        point_layer = processing.getObject(str(self.uPointLayer.currentText()))
        if point_layer.selectedFeatureCount() != 0:
            self.uSelectedPoints.setCheckState(Qt.Checked)
        else:
            self.uSelectedPoints.setCheckState(Qt.Unchecked)
        
        self.uZfield.addItems(utils.getFieldNames(point_layer, [QVariant.Int, QVariant.Double]))
        self.uOrderField.addItems(utils.getFieldNames(point_layer, [QVariant.Int, QVariant.Double]))
        self.uPointID.addItems(utils.getFieldNames(point_layer, [QVariant.Int, QVariant.Double, 10]))# 10 is for string
        
    def checkSelectedLine(self):
        ###print 'check if line layer selected'
        line_layer = processing.getObject(str(self.uLineLayer.currentText()))
        if line_layer:
            if line_layer.selectedFeatureCount() != 0:
                self.uSelectedLine.setCheckState(Qt.Checked)             
            else:
                self.uSelectedLine.setCheckState(Qt.Unchecked)
                
    def copyClipboard (self):
        if self.values is None:
            return
        else:
            clipboard = QApplication.clipboard()
            if self.uNoHeader.isChecked():
                clipboard.setText('\n'.join('%s\t%s' % x for x in zip(self.values[0],self.values[1])))
            else:
                clipboard.setText('distance\televation\tpointID\n'+'\n'.join('%s\t%s\t%s' % x for x in zip(self.values[0],self.values[1],self.values[2])))
            

    def restoreGui(self):
        self.buttonBox.rejected.connect(self.reject)
        self.btnClose.clicked.disconnect(self.stopProcessing)
        self.btnClose.setText(self.tr("Close"))
        self.btnOk.setEnabled(True)
        self.uprogressBar.setMaximum(100)

    def refreshPlot(self):
        self.axes.clear()

        if self.values is None:
            return

        self.axes.plot(np.array(self.values[0]),np.array(self.values[1]))
        
        ###to draw labels from jorgealmerio 
        if self.uPointIDlabels.isChecked():
#.........这里部分代码省略.........
开发者ID:msweier,项目名称:ProfileFromPoints,代码行数:103,代码来源:profileFromPoints_dialog.py

示例11: calibrlogger

# 需要导入模块: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg [as 别名]
# 或者: from matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg import actions [as 别名]
class calibrlogger(PyQt4.QtGui.QMainWindow, Calibr_Ui_Dialog): # An instance of the class Calibr_Ui_Dialog is created same time as instance of calibrlogger is created

    def __init__(self, parent, settingsdict1={}, obsid=''):
        #self.obsid = obsid
        self.settingsdict = settingsdict1
        PyQt4.QtGui.QDialog.__init__(self, parent)        
        self.setAttribute(PyQt4.QtCore.Qt.WA_DeleteOnClose)
        self.setupUi(self) # Required by Qt4 to initialize the UI
        self.setWindowTitle("Calibrate logger") # Set the title for the dialog
        self.connect(self.pushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.calibrateandplot)
        self.INFO.setText("Select the observation point with logger data to be calibrated.")

        # Create a plot window with one single subplot
        self.calibrplotfigure = plt.figure() 
        self.axes = self.calibrplotfigure.add_subplot( 111 )
        self.canvas = FigureCanvas( self.calibrplotfigure )
        self.mpltoolbar = NavigationToolbar( self.canvas, self.widgetPlot )
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction( lstActions[ 7 ] )
        self.layoutplot.addWidget( self.canvas )
        self.layoutplot.addWidget( self.mpltoolbar )
        self.show()

        # Populate combobox with obsid from table w_levels_logger
        self.load_obsid_from_db()

    def load_obsid_from_db(self):
        self.combobox_obsid.clear()
        myconnection = utils.dbconnection()
        if myconnection.connect2db() == True:
            # skapa en cursor
            curs = myconnection.conn.cursor()
            rs=curs.execute("""select distinct obsid from w_levels_logger order by obsid""")
            self.combobox_obsid.addItem('')
            for row in curs:
                self.combobox_obsid.addItem(row[0])
            rs.close()
            myconnection.closedb()        

    def getlastcalibration(self):
        obsid = unicode(self.combobox_obsid.currentText())
        if not obsid=='':
            sql = """SELECT MAX(date_time), loggerpos FROM (SELECT date_time, (level_masl - (head_cm/100)) as loggerpos FROM w_levels_logger WHERE level_masl > 0 AND obsid = '"""
            sql += obsid
            sql += """')"""
            self.lastcalibr = utils.sql_load_fr_db(sql)[1]
            if self.lastcalibr[0][1] and self.lastcalibr[0][0]:
                text = """Last pos. for logger in """
                text += obsid
                text += """\nwas """ + str(self.lastcalibr[0][1]) + """ masl\nat """ +  str(self.lastcalibr[0][0])
            else:
                text = """There is no earlier known\nposition for the logger\nin """ + unicode(self.combobox_obsid.currentText())#self.obsid[0]
            self.INFO.setText(text)

    def calibrateandplot(self):
        obsid = unicode(self.combobox_obsid.currentText())
        if not obsid=='':
            sanity1sql = """select count(obsid) from w_levels_logger where obsid = '""" +  obsid[0] + """'"""
            sanity2sql = """select count(obsid) from w_levels_logger where head_cm not null and head_cm !='' and obsid = '""" +  obsid[0] + """'"""
            if utils.sql_load_fr_db(sanity1sql)[1] == utils.sql_load_fr_db(sanity2sql)[1]: # This must only be done if head_cm exists for all data
                fr_d_t = self.FromDateTime.dateTime().toPyDateTime()
                to_d_t = self.ToDateTime.dateTime().toPyDateTime()
                newzref = self.LoggerPos.text()
                if len(newzref)>0:
                    sql =r"""UPDATE w_levels_logger SET level_masl = """
                    sql += str(newzref)
                    sql += """ + head_cm / 100 WHERE obsid = '"""
                    sql += obsid   
                    sql += """' AND date_time >= '"""
                    sql += str(fr_d_t)
                    sql += """' AND date_time <= '"""
                    sql += str(to_d_t)
                    sql += """' """
                    dummy = utils.sql_alter_db(sql)
                self.CalibrationPlot(obsid)
                self.getlastcalibration()
            else:
                utils.pop_up_info("Calibration aborted!!\nThere must not be empty cells or\nnull values in the 'head_cm' column!")
        else:
            self.INFO.setText("Select the observation point with logger data to be calibrated.")

    def CalibrationPlot(self,obsid):
        self.axes.clear()
        
        conn = sqlite.connect(self.settingsdict['database'],detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES)
        # skapa en cursor
        curs = conn.cursor()
        # Create a plot window with one single subplot
        #fig = plt.figure()  # causes conflict with plugins "statist" and "chartmaker"
        #ax = fig.add_subplot(111)
        
        p=[None]*2 # List for plot objects
        My_format = [('date_time', datetime.datetime), ('values', float)] #Define (with help from function datetime) a good format for numpy array 
        
        # Load manual reading (full time series) for the obsid
        sql =r"""SELECT date_time, level_masl FROM w_levels WHERE obsid = '"""
        sql += obsid   
        sql += """' ORDER BY date_time"""
        rs = curs.execute(sql) #Send SQL-syntax to cursor
        recs = rs.fetchall()  # All data are stored in recs
#.........这里部分代码省略.........
开发者ID:qgisbrasil,项目名称:qgis-midvatten-plugin-pt_BR,代码行数:103,代码来源:wlevels_calc_calibr.py


注:本文中的matplotlib.backends.backend_qt4agg.NavigationToolbar2QTAgg.actions方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。